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: stop showing sites Tauri's global API, which DeepSeek reads as an unofficial client
Tw93b3e1c8b9d930
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.mdindex 1badfa89..a9cce76f 100644--- a/.claude/rules/tauri-runtime.md+++ b/.claude/rules/tauri-runtime.md@@ -8,6 +8,7 @@ paths:- Native IPC is gated by the application command manifest in `src-tauri/build.rs`. Keep every registered app command in that manifest and grant only its required permissions. The packaged capability is local-only; `PakeConfig::remote_capability` grants the same permission set to exact configured entry origins (scheme, host, and port) before webviews load. Navigation flags, login redirects, subdomains, and restored URLs must not expand that grant. Keep local pages, secondary windows, loopback/IPv6 URLs, and literal hostname handling covered. ACL-denied downloads may fall back to browser attachments, but transient download anchors must bypass the IPC click interceptor to avoid recursion. Fullscreen must acquire native permission before mutating the player DOM; untrusted frame messages must never gain a top-level navigation fallback. Run `cargo test --lib` and `node tests/integration/ipc-security.mjs` (real macOS WebView); hiding `window.__TAURI__` or narrowing plugin capabilities alone does not gate application commands.- Injected CSS uses `src-tauri/src/inject/styles.js`: preserve DOM stylesheet order on ordinary pages; use constructable sheets only when CSP blocks the style element. `replaceSync` silently drops `@import`, so keep import-bearing CSS on its original DOM path, including escaped/case-insensitive at-keywords. Strict CSP plus imports remains unsupported. Run `node tests/browser/style-injection.mjs` with an installed Playwright runtime; mock CSSStyleSheet tests do not validate CSP or cascade behavior.- The `runtime-template` Cargo feature builds a prebuilt runtime that a separate builder customizes without a compiler: at launch it reads `pake-runtime/{pake.json, app.json, custom.js?, tray.png?}` from `Contents/Resources` on macOS or next to the executable elsewhere, and applies app.json's `identifier` and `productName` to the Tauri context before build. The CLI never enables the feature, so CLI-built apps keep their compiled configuration even if such a folder appears. A present but invalid override exits with a `[Pake]` message instead of falling back to the template's identity. A runtime app keys its WebView profile folder under the config dir (`%APPDATA%\<identifier>\EBWebView` on Windows) by identifier instead of product name (`data_dir_name`), so a rename keeps logins and a generated name cannot share another program's folder; CLI apps keep the product-name folder. On Windows a runtime app also sets the process AppUserModelID to its identifier before any window exists, so shortcuts carrying that ID group with the running window and toasts are attributed to it. Logic and tests live in `src-tauri/src/util.rs` (`apply_runtime_override`, `data_dir_name`, `set_app_user_model_id`); `PakeConfig::runtime_app` is the single runtime-app flag, and `run_app` copies the overridden identity from the returned Tauri config into the context; keep `cargo clippy` and `cargo test --lib` green both with and without `--features runtime-template`.+- The app is built with `withGlobalTauri: false`: a page can read `window.__TAURI__`, and DeepSeek's front end shows "Abnormal usage environment" when `"__TAURI__" in window` holds (measured on a real bundle, 2026-11-18; its other tests are a user agent naming Tauri or Electron). Injected scripts reach the native side only through `window.__PAKE_NATIVE__` from `src-tauri/src/inject/bridge.js`, which keeps the shape they used (`core.invoke`, `shell.open` and `window.getCurrentWindow()` with the nine window commands the capability grants) over `__TAURI_INTERNALS__`; a new window call is added there with the command and argument names Tauri's own API sends, and needs its permission in the capability. Tauri decides the global API at compile time, so a prebuilt runtime cannot switch it per app: the user's own code, a bundled local page or an injected script that names `__TAURI__`, gets the name pointed at the bridge instead (`global_api_name_script` in `window.rs`): a local app only on its own `tauri:` pages, so a site it links out to stays clean, while an app with such a script shows the name to its site again. The rest of Tauri's global API (events, paths, DPI types) is gone for such code; the capability never granted a page most of it. `isTauri`, `__TAURI_INTERNALS__` and the plugins' `__TAURI_PLUGIN_*` names remain and are not configurable from a script; hiding them means patching the tauri crate, to do only when a site is shown to read them. `tests/unit/native-bridge.test.js` holds the scripts and the config to this.- A page's `alert()`, `confirm()` and `prompt()` show nothing in a WKWebView unless its UI delegate implements the three `runJavaScript…Panel` methods, and Wry 0.54.2's does not: `alert` returned at once, `confirm` returned false and `prompt` null in a millisecond, so a site that confirms before logging out did nothing (a user's report, 2026-11-17; WebView2 and WebKitGTK show their own). `src-tauri/src/app/script_dialogs.rs` adds the three methods to the delegate's class where it lacks them, for every webview from `build_window`, and then sets the same delegate on the webview again: WebKit records which methods a delegate answers when it is set, and without the reset the added methods are never called. Each panel is an NSAlert sheet on the page's window whose completion calls WebKit's handler exactly once (WebKit raises on zero or two calls), which keeps the script waiting as a browser does. The sheet goes on the window even when it is hidden, as a closed window is with hide-on-close: AppKit then shows the window with its sheet (measured: a window hidden with Cmd+W came back on screen when its page called `confirm()`), where an app-modal panel would float over whatever else the user is doing; only a webview with no window falls back to `runModal`. Cancel carries an explicit Escape key equivalent, because AppKit gives Escape only to a button titled Cancel and the Chinese title is 取消. Verify on a real bundle with a page that calls all three and writes what it got back: OK gives `true`, Cancel `false`, a prompt its field's text or `null`, and each wait is seconds, not a millisecond. Send the keys with a CGEvent tool of your own: Escape must give `false` and `null`, Return `true`. Cover it with `tests/unit/macos-script-dialogs.test.ts` and the `script_panel_encodings_match_their_selectors` Rust test, which keeps each selector's colons and its type encoding in step.- `navigation_buttons` is a runtime-only macOS window field (no CLI flag; the paid apps set it, off by default): `src-tauri/src/app/nav_buttons.rs` adds Back and Forward to the title bar in a leading accessory beside the traffic lights, for people with a plain mouse who have neither the swipe nor Cmd-[. The buttons call `history_step`, the native step the Navigation menu uses, so they work on a blank error page; their action lives on the window's class as `tab_bar.rs`'s does. Enabled state follows the WKWebView's `canGoBack` and `canGoForward` by key-value observing; do not poll. The webview owns the observer through an associated object, which means the observer drops only while the webview is deallocating, when a weak reference to it already reads nil: removal in `Drop` never runs, so the observer unregisters on `NSWindowWillCloseNotification`, behind one flag because removing an unregistered observer raises (`auth.rs`'s delegate still has only the `Drop` removal). Alignment is to ink, checked on a 2x capture: each chevron's middle goes on the close button's centre line, read from `standardWindowButton:` (the lights sit 16 points down a 32 point bar on macOS 26) and from the cell's `imageRectForBounds:` (NSButton sets a 16 point image half a point above a 22 point button's middle), and redone on resize and around full screen. The chevrons are drawn, not `chevron.left`, because that symbol sits on a text baseline 1.5 points high. Labels are the system's own, 返回 and 前进, 上一頁 and 下一頁, through `UiLanguage`. A real-bundle check measures the rows of the red light and of each chevron in a `screencapture -l` PNG, whose centres must be equal, and opens then closes a Cmd+N window with the app still running. Under `hide_title_bar` the buttons sit over the page beside the lights, and the per-site `immersive` paddings in `style.js` clear only the lights' width. Cover it with `tests/unit/macos-navigation-buttons.test.ts` and the `navigation_buttons_are_opt_in` Rust test.- `transparent_title_bar` is a runtime-only macOS window field (no CLI flag; the paid apps set it): Tauri's `Transparent` title bar keeps the page below the bar, and `src-tauri/src/inject/title_bar.js` paints the window background with the page's top-edge color through `set_title_bar_color`. `hide_title_bar` keeps precedence and its overlay behavior. The color is the majority of three top-edge samples, resolved through a canvas so `oklch()`/`color()` values work; do not skip sampling for `document.hidden`, or windows revealed after load stay uncolored. Cover it with `tests/unit/title-bar-color.test.js`; when checking a real bundle, window captures carry the display profile, so convert the sRGB page color before comparing pixels.diff --git a/docs/advanced-usage.md b/docs/advanced-usage.mdindex 41e2d35c..5ed33a91 100644--- a/docs/advanced-usage.md+++ b/docs/advanced-usage.md@@ -72,6 +72,8 @@ window.__TAURI__.core.invoke("handle_scroll", {});```+`window.__TAURI__` exists only for your own code, a bundled local page or a script you inject with `--inject` that names it, and carries what a page is allowed to call: `core.invoke`, `shell.open` and `window.getCurrentWindow()` with `close`, `minimize`, `maximize`, `toggleMaximize`, `setResizable`, `startDragging`, `isFullscreen`, `setFullscreen` and `theme`. A packaged website sees no such object, because some sites, DeepSeek among them, treat it as an unofficial client and show a warning.+**Container Side (Rust):**```rustdiff --git a/docs/advanced-usage_CN.md b/docs/advanced-usage_CN.mdindex a3cbf27a..2246a8f0 100644--- a/docs/advanced-usage_CN.md+++ b/docs/advanced-usage_CN.md@@ -72,6 +72,8 @@ window.__TAURI__.core.invoke("handle_scroll", {});```+`window.__TAURI__` 只留给你自己的代码,打包的本地页面里一直有,用 `--inject` 注入的脚本里写到它时也有,提供页面有权限调用的那部分,`core.invoke`、`shell.open` 和 `window.getCurrentWindow()` 的 `close`、`minimize`、`maximize`、`toggleMaximize`、`setResizable`、`startDragging`、`isFullscreen`、`setFullscreen`、`theme`。打包的网站看不到这个对象,因为 DeepSeek 等网站会把它当成非官方客户端并弹出提示。+**容器端(Rust):**```rustdiff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex d6deed3b..fc076a44 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -259,6 +259,26 @@ fn popup_build_url(target_url: &Url) -> Url {}}+/// The app carries no Tauri global API object, since a site can see it and+/// some treat it as an unofficial client. The user's own code may still call+/// it, as the docs showed for years: a bundled local page, or an injected+/// script that names it. Those get the name back, pointing at Pake's bridge+/// (`core.invoke` and the current window).+const GLOBAL_API_NAME: &str =+ "if (!window.__TAURI__) { window.__TAURI__ = window.__PAKE_NATIVE__; }";+/// A local app's own pages only: a site it links out to stays without the name.+const GLOBAL_API_NAME_ON_LOCAL_PAGES: &str = "if (!window.__TAURI__ && (location.protocol === 'tauri:' || location.hostname === 'tauri.localhost')) { window.__TAURI__ = window.__PAKE_NATIVE__; }";++fn global_api_name_script(url_type: &str, custom_js: &str) -> Option<&'static str> {+ if custom_js.contains("__TAURI__") {+ Some(GLOBAL_API_NAME)+ } else if url_type == "local" {+ Some(GLOBAL_API_NAME_ON_LOCAL_PAGES)+ } else {+ None+ }+}+/// Whether a page's new-window request gets a window of its own: always with/// `--new-window`, and without it for a blank popup and for one that asks for/// a size.@@ -268,7 +288,10 @@ fn builds_requested_popup(allow_new_window: bool, target_url: &Url, sized: bool)#[cfg(test)]mod popup_tests {- use super::{builds_requested_popup, is_blank_popup_url, popup_build_url};+ use super::{+ builds_requested_popup, global_api_name_script, is_blank_popup_url, popup_build_url,+ GLOBAL_API_NAME, GLOBAL_API_NAME_ON_LOCAL_PAGES,+ };use tauri::Url;#[test]@@ -298,6 +321,35 @@ mod popup_tests {assert!(script.contains("window.addEventListener(\"click\", openUnhandledBlankLink);"));}+ #[test]+ fn a_site_sees_no_tauri_global_api_and_the_users_own_code_keeps_the_name() {+ // DeepSeek reads `"__TAURI__" in window` and warns of an abnormal+ // environment, so Tauri must not define it; Pake's own scripts are+ // held to that in tests/unit/native-bridge.test.js.+ let conf: serde_json::Value =+ serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap();+ assert_eq!(conf["app"]["withGlobalTauri"], serde_json::json!(false));+ assert_eq!(global_api_name_script("web", ""), None);+ assert_eq!(global_api_name_script("web", "document.title = 'x';"), None);+ let calls_it = "window.__TAURI__.core.invoke('set_zoom', { percent: 90 });";+ assert_eq!(+ global_api_name_script("web", calls_it),+ Some(GLOBAL_API_NAME)+ );+ assert_eq!(+ global_api_name_script("local", calls_it),+ Some(GLOBAL_API_NAME)+ );+ // A bundled local page is the user's own code, with no site to object;+ // a site that page links out to is still a site.+ assert_eq!(+ global_api_name_script("local", ""),+ Some(GLOBAL_API_NAME_ON_LOCAL_PAGES)+ );+ assert!(GLOBAL_API_NAME_ON_LOCAL_PAGES.contains("location.protocol === 'tauri:'"));+ assert!(GLOBAL_API_NAME.contains("window.__TAURI__ = window.__PAKE_NATIVE__"));+ }+#[test]fn a_popup_web_view_is_built_blank_so_the_engine_loads_its_address_once() {let google = Url::parse("https://accounts.google.com/gsi/select?client_id=1").unwrap();@@ -798,7 +850,9 @@ fn build_window(// so only inject its ~700 lines when the feature is on. Avoids parsing the// find UI on every page load in the common (find-off) case. Matches the// enable_find gating already applied to the Find menu item.- window_builder = window_builder.initialization_script(include_str!("../inject/styles.js"));+ window_builder = window_builder+ .initialization_script(include_str!("../inject/bridge.js"))+ .initialization_script(include_str!("../inject/styles.js"));if window_config.enable_find {window_builder = window_builder.initialization_script(include_str!("../inject/find.js"));@@ -825,12 +879,14 @@ fn build_window(window_builder.initialization_script(include_str!("../inject/title_bar.js"));}- window_builder = window_builder.initialization_script(- config- .runtime_custom_js- .as_deref()- .unwrap_or(include_str!("../inject/custom.js")),- );+ let custom_js = config+ .runtime_custom_js+ .as_deref()+ .unwrap_or(include_str!("../inject/custom.js"));+ if let Some(script) = global_api_name_script(&window_config.url_type, custom_js) {+ window_builder = window_builder.initialization_script(script);+ }+ window_builder = window_builder.initialization_script(custom_js);#[cfg(target_os = "windows")]let mut windows_browser_args = String::from("--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --disable-blink-features=AutomationControlled");diff --git a/src-tauri/src/inject/bridge.js b/src-tauri/src/inject/bridge.jsnew file mode 100644index 00000000..1b385937--- /dev/null+++ b/src-tauri/src/inject/bridge.js@@ -0,0 +1,59 @@+// Pake's own handle on the native side, for the injected scripts that follow.+//+// The app is built without Tauri's global API object: a site can see that+// object and some treat its presence as an unofficial client (DeepSeek showed+// "Abnormal usage environment" on every packaged app). This keeps what the+// capability allows a page to call anyway, `invoke`, the window commands and+// opening a link in the system browser, under Pake's name and in the shape+// the global API had, so the user's own code can be handed it under the old+// name.+(function () {+ if (window.__PAKE_NATIVE__) return;++ function internals() {+ return window.__TAURI_INTERNALS__;+ }++ function invoke(command, args, options) {+ const native = internals();+ if (!native || typeof native.invoke !== "function") {+ return Promise.reject(new Error("[Pake] native bridge unavailable"));+ }+ return native.invoke(command, args, options);+ }++ // The commands and argument names Tauri's own window API sends.+ function windowCommand(name, value) {+ const native = internals();+ const label =+ native && native.metadata && native.metadata.currentWindow+ ? native.metadata.currentWindow.label+ : undefined;+ const args = { label };+ if (value !== undefined) args.value = value;+ return invoke("plugin:window|" + name, args);+ }++ const currentWindow = Object.freeze({+ close: () => windowCommand("close"),+ startDragging: () => windowCommand("start_dragging"),+ isFullscreen: () => windowCommand("is_fullscreen"),+ setFullscreen: (fullscreen) => windowCommand("set_fullscreen", fullscreen),+ toggleMaximize: () => windowCommand("toggle_maximize"),+ maximize: () => windowCommand("maximize"),+ minimize: () => windowCommand("minimize"),+ setResizable: (resizable) => windowCommand("set_resizable", resizable),+ theme: () => windowCommand("theme"),+ });++ Object.defineProperty(window, "__PAKE_NATIVE__", {+ value: Object.freeze({+ core: Object.freeze({ invoke }),+ window: Object.freeze({ getCurrentWindow: () => currentWindow }),+ shell: Object.freeze({+ open: (path, openWith) =>+ invoke("plugin:shell|open", { path, with: openWith }),+ }),+ }),+ });+})();diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.jsindex 4bb65a04..0e2eac60 100644--- a/src-tauri/src/inject/event.js+++ b/src-tauri/src/inject/event.js@@ -2,7 +2,7 @@// on blank error shells (no JS context). Falls back to history/location when// the IPC bridge is unavailable.function nativeNavigate(action) {- const invoke = window.__TAURI__?.core?.invoke;+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;if (invoke) {invoke("webview_navigate", { action }).catch(() => {fallbackNavigate(action);@@ -41,7 +41,7 @@ function setZoom(zoom) {// on macOS. Native zoom recalculates layout exactly like a browser does.const zoomPercent = normalizeZoomPercent(zoom);const normalizedZoom = `${zoomPercent}%`;- const invoke = window.__TAURI__?.core?.invoke;+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;if (invoke) {invoke("set_zoom", { percent: zoomPercent }).catch(() => {});}@@ -89,11 +89,11 @@ function handleShortcut(event) {// and Ctrl+L. A browser keeps all three for itself, so no page relies on them.function closeCurrentWindow() {// close() raises the window's close request, so hide-on-close still applies.- window.__TAURI__?.window?.getCurrentWindow?.()?.close?.();+ window.__PAKE_NATIVE__?.window?.getCurrentWindow?.()?.close?.();}function quitApp() {- window.__TAURI__?.core?.invoke?.("quit_app")?.catch?.(() => {});+ window.__PAKE_NATIVE__?.core?.invoke?.("quit_app")?.catch?.(() => {});}function copyPageAddress() {@@ -194,7 +194,7 @@ function handleWindowFullscreenShortcut(event) {return;}- const appWindow = window.__TAURI__?.window?.getCurrentWindow?.();+ const appWindow = window.__PAKE_NATIVE__?.window?.getCurrentWindow?.();if (!appWindow) {return;}@@ -742,7 +742,7 @@ window.addEventListener("pagehide", () => {});document.addEventListener("DOMContentLoaded", () => {- const tauri = window.__TAURI__;+ const tauri = window.__PAKE_NATIVE__;const appWindow = tauri.window.getCurrentWindow();const invoke = tauri.core.invoke;const pakeConfig = window["pakeConfig"] || {};@@ -1504,7 +1504,7 @@ document.addEventListener("DOMContentLoaded", () => {// for DOMContentLoaded so feature-detection on Notification/setAppBadge// returns the polyfill before site scripts run.(function () {- const invoke = window.__TAURI__?.core?.invoke;+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;if (!invoke) return;if (typeof EventTarget !== "function" || typeof Event !== "function") return;diff --git a/src-tauri/src/inject/fullscreen.js b/src-tauri/src/inject/fullscreen.jsindex fb637599..84b375c7 100644--- a/src-tauri/src/inject/fullscreen.js+++ b/src-tauri/src/inject/fullscreen.js@@ -10,12 +10,12 @@window.__PAKE_FULLSCREEN_POLYFILL__ = true;function initFullscreenPolyfill() {- if (!window.__TAURI__ || !document.head) {+ if (!window.__PAKE_NATIVE__ || !document.head) {setTimeout(initFullscreenPolyfill, 100);return;}- const appWindow = window.__TAURI__.window.getCurrentWindow();+ const appWindow = window.__PAKE_NATIVE__.window.getCurrentWindow();let fullscreenElement = null;let actualFullscreenElement = null;let originalStyles = null;diff --git a/src-tauri/src/inject/theme_refresh.js b/src-tauri/src/inject/theme_refresh.jsindex 78f39b8c..b7fdedb2 100644--- a/src-tauri/src/inject/theme_refresh.js+++ b/src-tauri/src/inject/theme_refresh.js@@ -31,8 +31,8 @@ document.addEventListener("DOMContentLoaded", () => {else if (isLight) mode = "light";// Only invoke Rust command if an explicit theme override is detected- if (mode && window.__TAURI__?.core) {- window.__TAURI__.core.invoke("update_theme_mode", { mode });+ if (mode && window.__PAKE_NATIVE__?.core) {+ window.__PAKE_NATIVE__.core.invoke("update_theme_mode", { mode });}};diff --git a/src-tauri/src/inject/title_bar.js b/src-tauri/src/inject/title_bar.jsindex 398fd33d..7c65e132 100644--- a/src-tauri/src/inject/title_bar.js+++ b/src-tauri/src/inject/title_bar.js@@ -75,7 +75,7 @@if (!color) return;const key = `${color.red},${color.green},${color.blue}`;if (key === lastSent) return;- const invoke = window.__TAURI__?.core?.invoke;+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;if (!invoke) return;lastSent = key;// Pages outside the configured origin have no IPC grant; warn once anddiff --git a/src-tauri/src/inject/toast.js b/src-tauri/src/inject/toast.jsindex a55609b9..0a07492b 100644--- a/src-tauri/src/inject/toast.js+++ b/src-tauri/src/inject/toast.js@@ -11,7 +11,7 @@ document.addEventListener("DOMContentLoaded", () => {if (action) {m.style.cursor = "pointer";m.addEventListener("click", function () {- const invoke = window.__TAURI__?.core?.invoke;+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;if (invoke) invoke(action).catch(function () {});});}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 413a4b72..5460e59d 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -3,7 +3,7 @@"identifier": "com.pake.weekly","version": "3.19.4","app": {- "withGlobalTauri": true,+ "withGlobalTauri": false,"trayIcon": {"iconPath": "png/weekly_512.png","iconAsTemplate": false,diff --git a/tests/browser/fullscreen.mjs b/tests/browser/fullscreen.mjsindex 00bee108..bed0b4b5 100644--- a/tests/browser/fullscreen.mjs+++ b/tests/browser/fullscreen.mjs@@ -32,7 +32,7 @@ test("native fullscreen preserves the player subtree and F11 exits its top layervalue: { platform: "Windows" },});window.pakeConfig = { url: "https://video.example.com/" };- window.__TAURI__ = {+ window.__PAKE_NATIVE__ = {core: { invoke: () => Promise.resolve() },window: {getCurrentWindow: () => ({@@ -112,7 +112,7 @@ for (const target of ["html", "body", "#player"]) {<section id="player"><video></video><button id="controls">Pause</button></section><video id="preview"></video>`);await page.evaluate(() => {let fullscreen = false;- window.__TAURI__ = {+ window.__PAKE_NATIVE__ = {window: {getCurrentWindow: () => ({setFullscreen: async (value) => {@@ -193,7 +193,7 @@ test("denied polyfill fullscreen leaves the player in its original layout", asyn'<main><section id="player"><video></video><button>Pause</button></section></main>',);await page.evaluate(() => {- window.__TAURI__ = {+ window.__PAKE_NATIVE__ = {window: {getCurrentWindow: () => ({setFullscreen: async () => {diff --git a/tests/browser/notification-bridge.mjs b/tests/browser/notification-bridge.mjsindex 506a12c6..bffbdfc6 100644--- a/tests/browser/notification-bridge.mjs+++ b/tests/browser/notification-bridge.mjs@@ -45,7 +45,7 @@ for (const legacy of [false, true]) {}};}- window.__TAURI__ = {+ window.__PAKE_NATIVE__ = {core: { invoke: () => Promise.resolve({ nativeClick: true }) },};for (const script of source) (0, eval)(script);diff --git a/tests/browser/popup-routing.mjs b/tests/browser/popup-routing.mjsindex 21124119..0c0a02a3 100644--- a/tests/browser/popup-routing.mjs+++ b/tests/browser/popup-routing.mjs@@ -35,7 +35,7 @@ async function fixture(frame, run, config = {}) {({ source, config }) => {window.opened = [];window.pakeConfig = { url: "https://mail.example.com/", ...config };- window.__TAURI__ = {+ window.__PAKE_NATIVE__ = {core: {invoke: (cmd, args) => {if (cmd === "plugin:shell|open") window.opened.push(args.path);@@ -62,7 +62,7 @@ async function fixture(frame, run, config = {}) {/^https?:\/\//.test(node.href) &&node.target === "_blank") {- window.__TAURI__.core.invoke("plugin:shell|open", {+ window.__PAKE_NATIVE__.core.invoke("plugin:shell|open", {path: node.href,});event.preventDefault();diff --git a/tests/browser/protocol-links.mjs b/tests/browser/protocol-links.mjsindex 4e215e15..e8752222 100644--- a/tests/browser/protocol-links.mjs+++ b/tests/browser/protocol-links.mjs@@ -38,7 +38,7 @@ for (const frame of [false, true]) {({ source }) => {window.opened = [];window.pakeConfig = { url: "https://mail.example.com/" };- window.__TAURI__ = {+ window.__PAKE_NATIVE__ = {core: {invoke: (cmd, args) => {if (cmd === "plugin:shell|open")diff --git a/tests/integration/ipc-security.mjs b/tests/integration/ipc-security.mjsindex 2d8135b5..ff025294 100644--- a/tests/integration/ipc-security.mjs+++ b/tests/integration/ipc-security.mjs@@ -25,7 +25,7 @@ function page(stage, origin) {return `<!doctype html><meta charset="utf-8"><title>Pake IPC security probe</title><body>Testing ${stage} origin permissions<main><section id="player"><video></video><button>Pause</button></section></main><script>(async () => {- const invoke = window.__TAURI__.core.invoke;+ const invoke = window.__PAKE_NATIVE__.core.invoke;const check = async (command, args) => {try { await invoke(command, args); return "allowed"; }catch (error) { return "denied: " + String(error); }diff --git a/tests/integration/last-url.mjs b/tests/integration/last-url.mjsindex 627fbe6d..01e3697e 100644--- a/tests/integration/last-url.mjs+++ b/tests/integration/last-url.mjs@@ -53,7 +53,7 @@ const server = http.createServer(async (request, response) => {cookie:document.cookie})});await new Promise(resolve => setTimeout(resolve, 300));- await window.__TAURI__.core.invoke("plugin:window|close", {label:"pake"});+ await window.__PAKE_NATIVE__.core.invoke("plugin:window|close", {label:"pake"});})();</script>`);});diff --git a/tests/unit/event-clipboard-shortcuts.test.js b/tests/unit/event-clipboard-shortcuts.test.jsindex 929c13b9..c7428e39 100644--- a/tests/unit/event-clipboard-shortcuts.test.js+++ b/tests/unit/event-clipboard-shortcuts.test.js@@ -114,7 +114,7 @@ function loadEventHelpers({isAuthLink: () => false,isAuthPopup: () => false,pakeConfig: {},- __TAURI__: {+ __PAKE_NATIVE__: {core: {invoke: (command, payload) => {invokeCalls.push([command, payload]);diff --git a/tests/unit/event-fullscreen-shortcuts.test.js b/tests/unit/event-fullscreen-shortcuts.test.jsindex baf956d6..1861873c 100644--- a/tests/unit/event-fullscreen-shortcuts.test.js+++ b/tests/unit/event-fullscreen-shortcuts.test.js@@ -112,7 +112,7 @@ function loadEventHelpers({hide_title_bar: hideTitleBar,hide_window_decorations: hideWindowDecorations,},- __TAURI__: {+ __PAKE_NATIVE__: {core: {invoke: (command, payload) => {invokeCalls.push(command);diff --git a/tests/unit/event-ime-enter-guard.test.js b/tests/unit/event-ime-enter-guard.test.jsindex 654cd142..1e52c989 100644--- a/tests/unit/event-ime-enter-guard.test.js+++ b/tests/unit/event-ime-enter-guard.test.js@@ -97,7 +97,7 @@ function loadEventHelpers({isAuthLink: () => false,isAuthPopup: () => false,pakeConfig: {},- __TAURI__: {+ __PAKE_NATIVE__: {core: { invoke: () => Promise.resolve() },window: {getCurrentWindow: () => ({diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.jsindex fbe70f7d..c74256a9 100644--- a/tests/unit/event-link-guard.test.js+++ b/tests/unit/event-link-guard.test.js@@ -128,7 +128,7 @@ function loadEventHelpers({context.window.navigator = context.navigator;context.window.top = topWindow || context.window;if (withTauri) {- context.window.__TAURI__ = {+ context.window.__PAKE_NATIVE__ = {core: { invoke },window: {getCurrentWindow: () => ({diff --git a/tests/unit/native-bridge.test.js b/tests/unit/native-bridge.test.jsnew file mode 100644index 00000000..a60067bc--- /dev/null+++ b/tests/unit/native-bridge.test.js@@ -0,0 +1,92 @@+import fs from "node:fs";+import path from "node:path";+import vm from "node:vm";+import { describe, expect, it } from "vitest";++const source = fs.readFileSync(+ path.join(process.cwd(), "src-tauri/src/inject/bridge.js"),+ "utf-8",+);++function load(internals) {+ const window = {};+ if (internals) window.__TAURI_INTERNALS__ = internals;+ vm.runInNewContext(source, { window });+ return window;+}++describe("Pake's native bridge", () => {+ it("leaves no Tauri global API name for a page to find", () => {+ const window = load({ invoke: () => Promise.resolve() });++ expect("__TAURI__" in window).toBe(false);+ expect(Object.keys(window)).toEqual(["__TAURI_INTERNALS__"]);+ expect(typeof window.__PAKE_NATIVE__.core.invoke).toBe("function");+ });++ it("is the only way Pake's injected scripts reach the native side", () => {+ const dir = path.join(process.cwd(), "src-tauri/src/inject");+ const scripts = fs+ .readdirSync(dir)+ .filter((name) => name.endsWith(".js") && name !== "custom.js");++ expect(scripts.length).toBeGreaterThan(10);+ for (const name of scripts) {+ const script = fs.readFileSync(path.join(dir, name), "utf-8");+ expect(script.includes("__TAURI__"), name).toBe(false);+ }+ const conf = JSON.parse(+ fs.readFileSync(+ path.join(process.cwd(), "src-tauri/tauri.conf.json"),+ "utf-8",+ ),+ );+ expect(conf.app.withGlobalTauri).toBe(false);+ });++ it("sends the window commands Tauri's own API sends", async () => {+ const calls = [];+ const window = load({+ metadata: { currentWindow: { label: "pake-2" } },+ invoke: (command, args) => {+ calls.push([command, args]);+ return Promise.resolve(command.endsWith("is_fullscreen"));+ },+ });+ const appWindow = window.__PAKE_NATIVE__.window.getCurrentWindow();++ await appWindow.startDragging();+ await appWindow.setFullscreen(false);+ await appWindow.close();+ expect(await appWindow.isFullscreen()).toBe(true);+ await appWindow.toggleMaximize();+ await appWindow.maximize();+ await appWindow.minimize();+ await appWindow.setResizable(true);+ await appWindow.theme();+ await window.__PAKE_NATIVE__.shell.open("https://example.com");+ await window.__PAKE_NATIVE__.core.invoke("set_zoom", { percent: 90 });++ expect(calls).toEqual([+ ["plugin:window|start_dragging", { label: "pake-2" }],+ ["plugin:window|set_fullscreen", { label: "pake-2", value: false }],+ ["plugin:window|close", { label: "pake-2" }],+ ["plugin:window|is_fullscreen", { label: "pake-2" }],+ ["plugin:window|toggle_maximize", { label: "pake-2" }],+ ["plugin:window|maximize", { label: "pake-2" }],+ ["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 }],+ ["set_zoom", { percent: 90 }],+ ]);+ });++ it("rejects instead of throwing where the page has no native side", async () => {+ const window = load();++ await expect(+ window.__PAKE_NATIVE__.core.invoke("set_zoom", { percent: 90 }),+ ).rejects.toThrow("native bridge unavailable");+ });+});diff --git a/tests/unit/notification-bridge.test.js b/tests/unit/notification-bridge.test.jsindex 8008e3d2..33e7758c 100644--- a/tests/unit/notification-bridge.test.js+++ b/tests/unit/notification-bridge.test.js@@ -80,7 +80,7 @@ function loadNotificationBridge({isAuthLink: () => false,isAuthPopup: () => false,pakeConfig: {},- __TAURI__: {+ __PAKE_NATIVE__: {core: {invoke: (command, payload) => {invokeCalls.push({ command, payload });diff --git a/tests/unit/title-bar-color.test.js b/tests/unit/title-bar-color.test.jsindex 61994fd1..bbc8a10a 100644--- a/tests/unit/title-bar-color.test.js+++ b/tests/unit/title-bar-color.test.js@@ -74,7 +74,7 @@ function loadTitleBar({ columns, width = 1000, metas = [], matching = [] }) {addEventListener() {},matchMedia: (query) => ({ matches: matching.includes(query) }),getComputedStyle: (node) => ({ backgroundColor: node.background }),- __TAURI__: {+ __PAKE_NATIVE__: {core: {invoke(command, args) {calls.push({ command, args });