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: restrict native IPC to configured origins
Tw93211e1eb9797a
diff --git a/.gitignore b/.gitignoreindex 518540e9..1b7e620d 100644--- a/.gitignore+++ b/.gitignore@@ -41,6 +41,7 @@ src-tauri/.cargo/src-tauri/.cargo/config.tomlsrc-tauri/.pake/src-tauri/gen+src-tauri/permissions/autogenerated/yarn-debug.log*yarn-error.log*diff --git a/AGENTS.md b/AGENTS.mdindex 855b0486..b51d7946 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -100,6 +100,8 @@ Oracles per row live under `tests/unit/` (for example `event-link-guard.test.js`## Current Risk Areas+- 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.- CLI options are user-facing and must stay synchronized across `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`, generated `dist/cli.js`, `schema/pake.schema.json`, and `docs/cli-usage*.md`. Schema-to-CLI sync is enforced by `tests/unit/config-file.test.ts`; the rest is manual discipline.diff --git a/docs/advanced-usage.md b/docs/advanced-usage.mdindex 92b5cc8e..a6d56511 100644--- a/docs/advanced-usage.md+++ b/docs/advanced-usage.md@@ -80,6 +80,8 @@ The download system automatically handles:Send messages between web content and Pake container.+Native IPC is available to bundled local pages and the exact configured website origin (scheme, host, and port). Login redirects and other origins do not receive native permissions. Use the final website URL when packaging an app, including its `www` or workspace subdomain. On other origins, native notifications, zoom, Pake's fullscreen controls, and opening links in the system browser are unavailable; downloads fall back to the browser, which may display cross-origin media instead of saving it. Custom commands must be registered in both `generate_handler!` and the command manifest in `src-tauri/build.rs`, with the corresponding permission added to `src-tauri/capabilities/default.json`.+**Web Side (JavaScript):**```javascriptdiff --git a/docs/advanced-usage_CN.md b/docs/advanced-usage_CN.mdindex 35d0e51b..5c8b5828 100644--- a/docs/advanced-usage_CN.md+++ b/docs/advanced-usage_CN.md@@ -80,6 +80,8 @@ if (window.Notification && Notification.permission === "default") {在网页内容和 Pake 容器之间发送消息。+原生 IPC 只开放给打包的本地页面和配置的网站来源,协议、主机名和端口都要一致,登录跳转和其他来源不会获得原生权限,打包时使用网站最终打开的网址,包括 `www` 或工作区子域。在其他来源的页面上,原生通知、缩放、Pake 的全屏控制和通过系统浏览器打开链接不可用,下载会交给网页浏览器处理,跨域图片等资源可能直接显示而不保存。自定义命令需要同时注册到 `generate_handler!` 和 `src-tauri/build.rs` 的命令清单,并在 `src-tauri/capabilities/default.json` 中添加对应权限。+**网页端(JavaScript):**```javascriptdiff --git a/src-tauri/build.rs b/src-tauri/build.rsindex 70cec8cf..2f464a68 100644--- a/src-tauri/build.rs+++ b/src-tauri/build.rs@@ -1,5 +1,18 @@fn main() {println!("cargo:rerun-if-changed=.pake/pake.json");println!("cargo:rerun-if-changed=.pake/tauri.conf.json");- tauri_build::build()+ tauri_build::try_build(tauri_build::Attributes::new().app_manifest(+ tauri_build::AppManifest::new().commands(&[+ "download_file",+ "send_notification",+ "increment_dock_badge",+ "set_dock_badge",+ "set_dock_badge_label",+ "clear_dock_badge",+ "update_theme_mode",+ "set_zoom",+ "webview_navigate",+ ]),+ ))+ .expect("Failed to build Pake permissions")}diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex cc9913bb..ef9b2f99 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -3,10 +3,16 @@"identifier": "pake-capability","description": "Capability for the pake app.","webviews": ["pake", "pake-*"],- "remote": {- "urls": ["https://*.*"]- },"permissions": [+ "allow-download-file",+ "allow-send-notification",+ "allow-increment-dock-badge",+ "allow-set-dock-badge",+ "allow-set-dock-badge-label",+ "allow-clear-dock-badge",+ "allow-update-theme-mode",+ "allow-set-zoom",+ "allow-webview-navigate","shell:allow-open","core:window:allow-theme","core:window:allow-start-dragging",diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rsindex b82b6db0..fa69ab0e 100644--- a/src-tauri/src/app/config.rs+++ b/src-tauri/src/app/config.rs@@ -1,4 +1,8 @@use serde::{Deserialize, Serialize};+use tauri::ipc::RuntimeCapability;+use tauri::utils::acl::capability::{Capability, CapabilityFile, CapabilityRemote};+use tauri::utils::acl::RemoteUrlPattern;+use tauri::Url;#[derive(Clone, Debug, Serialize, Deserialize)]pub struct WindowConfig {@@ -100,4 +104,245 @@ impl PakeConfig {pub fn show_system_tray(&self) -> bool {self.system_tray.copied()}++ pub fn remote_capability(+ &self,+ ) -> Result<Option<RemoteCapability>, Box<dyn std::error::Error>> {+ let mut origins = Vec::new();+ for window in self+ .windows+ .iter()+ .filter(|window| window.url_type == "web")+ {+ let url = Url::parse(&window.url)?;+ let host = url.host_str().ok_or("Remote IPC requires a hostname")?;+ // URLPattern metacharacters in a host must never turn a configured+ // literal origin into a wildcard or regular expression grant.+ if !matches!(url.scheme(), "http" | "https")+ || host.contains(['*', '?', '(', ')', '{', '}', '\\'])+ {+ return Err("Remote IPC requires a literal HTTP or HTTPS origin".into());+ }+ // Colons inside an IPv6 literal are URLPattern name delimiters+ // unless escaped. Keep the actual port delimiter unescaped.+ let port = url+ .port()+ .map(|port| format!(":{port}"))+ .unwrap_or_default();+ let origin = format!("{}://{}{}/*", url.scheme(), host.replace(':', "\\:"), port);+ origin.parse::<RemoteUrlPattern>()?;+ if !origins.contains(&origin) {+ origins.push(origin);+ }+ }+ if origins.is_empty() {+ return Ok(None);+ }++ // Reuse the local permission set, including scopes, without keeping a+ // second list that can drift or widening grants after navigation.+ let mut capability: Capability =+ serde_json::from_str(include_str!("../../capabilities/default.json"))?;+ capability.identifier = "pake-configured-origins".into();+ capability.local = false;+ capability.remote = Some(CapabilityRemote { urls: origins });+ Ok(Some(RemoteCapability(capability)))+ }+}++pub struct RemoteCapability(Capability);++impl RuntimeCapability for RemoteCapability {+ fn build(self) -> CapabilityFile {+ CapabilityFile::Capability(self.0)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::BTreeMap;+ use tauri::utils::acl::{manifest::Manifest, resolved::Resolved, ExecutionContext};++ fn config_for(url: &str) -> PakeConfig {+ let mut config: PakeConfig = serde_json::from_str(include_str!("../../pake.json")).unwrap();+ config.windows[0].url = url.into();+ config.windows[0].url_type = "web".into();+ config+ }++ fn resolve(config: &PakeConfig) -> Resolved {+ let manifest: BTreeMap<String, Manifest> = serde_json::from_str(include_str!(concat!(+ env!("OUT_DIR"),+ "/acl-manifests.json"+ )))+ .unwrap();+ let local: Capability =+ serde_json::from_str(include_str!("../../capabilities/default.json")).unwrap();+ let mut capabilities = BTreeMap::from([(local.identifier.clone(), local)]);+ if let Some(remote) = config.remote_capability().unwrap() {+ capabilities.insert(remote.0.identifier.clone(), remote.0);+ }+ Resolved::resolve(+ &manifest,+ capabilities,+ tauri::utils::platform::Target::current(),+ )+ .unwrap()+ }++ fn allows(acl: &Resolved, command: &str, label: &str, url: Option<&str>) -> bool {+ acl.allowed_commands.get(command).is_some_and(|grants| {+ grants.iter().any(|grant| {+ let context_matches = match (&grant.context, url) {+ (ExecutionContext::Local, None) => true,+ (ExecutionContext::Remote { url: pattern }, Some(url)) => {+ pattern.test(&Url::parse(url).unwrap())+ }+ _ => false,+ };+ context_matches && grant.webviews.iter().any(|pattern| pattern.matches(label))+ })+ })+ }++ #[test]+ fn remote_ipc_requires_the_configured_scheme_host_and_port() {+ let acl = resolve(&config_for("https://example.com/app?next=https://evil.com"));+ assert!(acl.has_app_acl);+ for command in ["download_file", "set_zoom", "plugin:window|is_fullscreen"] {+ for label in ["pake", "pake-1"] {+ assert!(allows(+ &acl,+ command,+ label,+ Some("https://example.com/other?q=1#x")+ ));+ for url in [+ "https://evil.com/",+ "https://sub.example.com/",+ "https://example.com.evil.com/",+ "http://example.com/",+ "https://example.com:8443/",+ "https://evil.com/?next=https://example.com/",+ ] {+ assert!(+ !allows(&acl, command, label, Some(url)),+ "allowed {command} on {url}"+ );+ }+ }+ assert!(!allows(+ &acl,+ command,+ "unrelated",+ Some("https://example.com/")+ ));+ }+ }++ #[test]+ fn local_pages_keep_permissions_without_any_remote_grant() {+ let mut config = config_for("index.html");+ config.windows[0].url_type = "local".into();+ assert!(config.remote_capability().unwrap().is_none());+ let acl = resolve(&config);+ assert!(acl.has_app_acl);+ assert!(allows(&acl, "download_file", "pake", None));+ assert!(!allows(+ &acl,+ "download_file",+ "pake",+ Some("https://example.com/")+ ));+ }++ #[test]+ fn remote_ipc_handles_loopback_ipv6_and_international_domains_literally() {+ for url in [+ "http://127.0.0.1:8123/app",+ "http://[::1]:8123/app",+ "https://例子.测试/app",+ ] {+ let acl = resolve(&config_for(url));+ assert!(+ allows(&acl, "download_file", "pake", Some(url)),+ "denied {url}"+ );+ assert!(!allows(+ &acl,+ "download_file",+ "pake",+ Some("https://evil.com/")+ ));+ }+ }++ #[test]+ fn remote_ipc_deduplicates_origins_and_ignores_local_entries() {+ let mut config = config_for("https://example.com/one");+ let mut second = config.windows[0].clone();+ second.url = "https://example.com/two".into();+ config.windows.push(second);+ let mut local = config.windows[0].clone();+ local.url = "index.html".into();+ local.url_type = "local".into();+ config.windows.push(local);+ let remote = config.remote_capability().unwrap().unwrap();+ assert_eq!(remote.0.remote.unwrap().urls, vec!["https://example.com/*"]);+ assert!(!remote.0.local);+ }++ #[test]+ fn remote_ipc_rejects_pattern_hosts_and_non_web_schemes() {+ for url in [+ "https://*.example.com/",+ "https://(evil).com/",+ "file:///tmp/index.html",+ "data:text/html,hello",+ ] {+ assert!(+ config_for(url).remote_capability().is_err(),+ "accepted {url}"+ );+ }+ }++ #[test]+ fn every_registered_app_command_is_gated_and_remains_available_on_the_entry_origin() {+ let acl = resolve(&config_for("https://example.com/"));+ assert!(acl.has_app_acl);+ let source = include_str!("../lib.rs");+ let registered = source+ .split("tauri::generate_handler![")+ .nth(1)+ .unwrap()+ .split(']')+ .next()+ .unwrap();+ for command in registered+ .split(',')+ .map(str::trim)+ .filter(|name| !name.is_empty())+ {+ assert!(+ allows(&acl, command, "pake", None),+ "missing local permission for {command}"+ );+ assert!(+ allows(&acl, command, "pake", Some("https://example.com/")),+ "missing remote permission for {command}"+ );+ assert!(+ !allows(&acl, command, "pake", Some("https://evil.com/")),+ "ungated {command}"+ );+ }+ assert!(!allows(+ &acl,+ "unregistered_command",+ "pake",+ Some("https://example.com/")+ ));+ }}diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.jsindex ae7646b8..1f54c6f2 100644--- a/src-tauri/src/inject/event.js+++ b/src-tauri/src/inject/event.js@@ -689,12 +689,14 @@ document.addEventListener("DOMContentLoaded", () => {// on_download handler then writes the file to the Downloads folder. This is// used for blob:/data: URLs because routing their bytes through the Tauri// IPC fails on strict-CSP sites (e.g. Gemini), whose connect-src blocks the- // IPC origin. The native download path is independent of the page CSP.+ // IPC origin. It also handles attachments when remote IPC is denied.+ const nativeDownloadAnchors = new WeakSet();function triggerNativeDownload(url, filename) {const anchor = document.createElement("a");anchor.href = url;anchor.download = filename || "";anchor.style.display = "none";+ nativeDownloadAnchors.add(anchor);document.body.appendChild(anchor);anchor.click();document.body.removeChild(anchor);@@ -724,6 +726,21 @@ document.addEventListener("DOMContentLoaded", () => {});};+ function downloadFile(url, filename) {+ return invoke("download_file", {+ params: { url, filename, language: getUserLanguage() },+ }).catch((error) => {+ // Debug and release builds have different ACL rejection messages.+ // Let the browser handle attachments without granting remote IPC.+ if (/^(?:Command )?download_file not allowed\b/.test(String(error))) {+ triggerNativeDownload(url, filename);+ return;+ }+ console.error("Failed to download file:", filename, error);+ showDownloadError(filename);+ });+ }+const isInternalUrl = (url) => matchesInternalUrl(url, window.location.href);const detectAnchorElementClick = (e) => {@@ -733,6 +750,8 @@ document.addEventListener("DOMContentLoaded", () => {}const anchorElement = e.target.closest("a");+ if (anchorElement && nativeDownloadAnchors.has(anchorElement)) return;+if (anchorElement && anchorElement.href) {const rawHref = anchorElement.getAttribute("href") || "";if (shouldBypassPakeLinkHandling(rawHref)) {@@ -826,10 +845,7 @@ document.addEventListener("DOMContentLoaded", () => {}e.preventDefault();e.stopImmediatePropagation();- const userLanguage = getUserLanguage();- invoke("download_file", {- params: { url: absoluteUrl, filename, language: userLanguage },- });+ downloadFile(absoluteUrl, filename);return;}@@ -1139,17 +1155,7 @@ document.addEventListener("DOMContentLoaded", () => {triggerNativeDownload(imageUrl, filename);} else {// Regular HTTP(S) image- const userLanguage = getUserLanguage();- invoke("download_file", {- params: {- url: imageUrl,- filename: filename,- language: userLanguage,- },- }).catch((error) => {- console.error("Failed to download image:", filename, error);- showDownloadError(filename);- });+ downloadFile(imageUrl, filename);}}@@ -1196,7 +1202,6 @@ document.addEventListener("DOMContentLoaded", () => {// Simplified menu builderfunction buildMenuItems(type, data) {- const userLanguage = getUserLanguage();const items = [];switch (type) {@@ -1221,12 +1226,7 @@ document.addEventListener("DOMContentLoaded", () => {items.push(createMenuItem(menuTexts.downloadFile, () => {const filename = getFilenameFromUrl(data.url);- invoke("download_file", {- params: { url: data.url, filename, language: userLanguage },- }).catch((error) => {- console.error("Failed to download file:", filename, error);- showDownloadError(filename);- });+ downloadFile(data.url, filename);}),);}diff --git a/src-tauri/src/inject/fullscreen.js b/src-tauri/src/inject/fullscreen.jsindex 807eae5c..fb637599 100644--- a/src-tauri/src/inject/fullscreen.js+++ b/src-tauri/src/inject/fullscreen.js@@ -80,44 +80,46 @@}function enterFullscreen(element) {- fullscreenElement = element;- // Preserve the requested subtree. Extracting a video from a document- // fullscreen request separates it from its controls and overlays.- const targetElement = element;- actualFullscreenElement = element;-- originalStyles = {- position: targetElement.style.position,- top: targetElement.style.top,- left: targetElement.style.left,- width: targetElement.style.width,- height: targetElement.style.height,- maxWidth: targetElement.style.maxWidth,- maxHeight: targetElement.style.maxHeight,- margin: targetElement.style.margin,- padding: targetElement.style.padding,- zIndex: targetElement.style.zIndex,- background: targetElement.style.background,- objectFit: targetElement.style.objectFit,- };-- wasInBody =- targetElement === document.documentElement ||- targetElement === document.body ||- targetElement.parentNode === document.body;- if (!wasInBody) {- originalParent = targetElement.parentNode;- originalNextSibling = targetElement.nextSibling;- }+ // Commit DOM changes only after native fullscreen succeeds. An ACL+ // rejection must leave the original player and its controls untouched.+ return appWindow.setFullscreen(true).then(() => {+ fullscreenElement = element;+ // Preserve the requested subtree. Extracting a video from a document+ // fullscreen request separates it from its controls and overlays.+ const targetElement = element;+ actualFullscreenElement = element;++ originalStyles = {+ position: targetElement.style.position,+ top: targetElement.style.top,+ left: targetElement.style.left,+ width: targetElement.style.width,+ height: targetElement.style.height,+ maxWidth: targetElement.style.maxWidth,+ maxHeight: targetElement.style.maxHeight,+ margin: targetElement.style.margin,+ padding: targetElement.style.padding,+ zIndex: targetElement.style.zIndex,+ background: targetElement.style.background,+ objectFit: targetElement.style.objectFit,+ };++ wasInBody =+ targetElement === document.documentElement ||+ targetElement === document.body ||+ targetElement.parentNode === document.body;+ if (!wasInBody) {+ originalParent = targetElement.parentNode;+ originalNextSibling = targetElement.nextSibling;+ }- targetElement.classList.add("pake-fullscreen-element");- document.body.classList.add("pake-fullscreen-active");+ targetElement.classList.add("pake-fullscreen-element");+ document.body.classList.add("pake-fullscreen-active");- if (!wasInBody) {- document.body.appendChild(targetElement);- }+ if (!wasInBody) {+ document.body.appendChild(targetElement);+ }- appWindow.setFullscreen(true).then(() => {startFullscreenMonitor();const event = new Event("fullscreenchange", { bubbles: true });document.dispatchEvent(event);@@ -129,8 +131,6 @@document.dispatchEvent(webkitEvent);element.dispatchEvent(webkitEvent);});-- return Promise.resolve();}function exitFullscreen() {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e1d0b336..9da1d13a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -397,6 +397,11 @@ pub fn run_app() {webview_navigate,]).setup(move |app| {+ // Grant remote IPC only to the immutable, packaged entry origins,+ // before any webview can start loading untrusted content.+ if let Some(capability) = pake_config.remote_capability()? {+ app.add_capability(capability)?;+ }app.manage(MultiWindowState::new(pake_config.clone(),tauri_config.clone(),diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rsindex 61def01f..da78e3be 100644--- a/src-tauri/src/util.rs+++ b/src-tauri/src/util.rs@@ -193,7 +193,12 @@ pub fn sanitize_download_filename(filename: &str) -> String {return "download".to_string();};- if candidate == "." || candidate == ".." {+ // A colon can retain a Windows drive prefix or alternate data stream even+ // after separators have been removed. Colons are ordinary names on Unix.+ if candidate == "."+ || candidate == ".."+ || (cfg!(target_os = "windows") && candidate.contains(':'))+ {"download".to_string()} else {candidate.to_string()@@ -415,6 +420,32 @@ mod tests {}}+ #[cfg(target_os = "windows")]+ #[test]+ fn sanitize_download_filename_rejects_windows_drive_prefixes_and_streams() {+ for filename in [+ "C:payload.txt",+ "C:",+ "report.txt:payload",+ "..\\D:payload.txt",+ ] {+ assert_eq!(+ sanitize_download_filename(filename),+ "download",+ "{filename}"+ );+ }+ }++ #[cfg(not(target_os = "windows"))]+ #[test]+ fn sanitize_download_filename_preserves_colons_on_unix() {+ assert_eq!(+ sanitize_download_filename("report-14:30.txt"),+ "report-14:30.txt"+ );+ }+#[test]fn download_message_falls_back_to_english_for_unknown_locale() {let msg = get_download_message_with_lang(MessageType::Start, Some("fr-FR".to_string()));diff --git a/tests/browser/fullscreen.mjs b/tests/browser/fullscreen.mjsindex 878e23fb..00bee108 100644--- a/tests/browser/fullscreen.mjs+++ b/tests/browser/fullscreen.mjs@@ -178,3 +178,62 @@ for (const target of ["html", "body", "#player"]) {}});}++// A denied native request must not leave the page in a fake fullscreen layout.+test("denied polyfill fullscreen leaves the player in its original layout", async () => {+ const browser = await chromium.launch({+ headless: true,+ ...(process.env.PAKE_BROWSER_EXECUTABLE+ ? { executablePath: process.env.PAKE_BROWSER_EXECUTABLE }+ : {}),+ });+ try {+ const page = await browser.newPage();+ await page.setContent(+ '<main><section id="player"><video></video><button>Pause</button></section></main>',+ );+ await page.evaluate(() => {+ window.__TAURI__ = {+ window: {+ getCurrentWindow: () => ({+ setFullscreen: async () => {+ throw new Error(+ "Command plugin:window|set_fullscreen not allowed by ACL",+ );+ },+ isFullscreen: async () => false,+ }),+ },+ };+ });+ await page.addScriptTag({+ content: await fs.readFile(+ `${process.env.PAKE_INJECT_ROOT || "src-tauri/src/inject"}/fullscreen.js`,+ "utf8",+ ),+ });+ assert.deepEqual(+ await page.evaluate(async () => {+ const player = document.querySelector("#player");+ const parent = player.parentElement;+ let denied = false;+ try {+ await player.requestFullscreen();+ } catch {+ denied = true;+ }+ return {+ denied,+ sameParent: player.parentElement === parent,+ fullscreen: document.fullscreenElement === null,+ styled: !!document.querySelector(+ ".pake-fullscreen-element, .pake-fullscreen-active",+ ),+ };+ }),+ { denied: true, sameParent: true, fullscreen: true, styled: false },+ );+ } finally {+ await browser.close();+ }+});diff --git a/tests/integration/ipc-security.mjs b/tests/integration/ipc-security.mjsnew file mode 100644index 00000000..dab58307--- /dev/null+++ b/tests/integration/ipc-security.mjs@@ -0,0 +1,253 @@+// Native WebView coverage for origin ACLs and the disclosed download payload.+import assert from "node:assert/strict";+import fs from "node:fs/promises";+import http from "node:http";+import os from "node:os";+import path from "node:path";+import { spawn } from "node:child_process";+import { once } from "node:events";++if (process.platform !== "darwin") {+ throw new Error("This native IPC fixture currently requires macOS.");+}+const repo = process.cwd();+const root = await fs.mkdtemp(path.join(os.tmpdir(), "pake-ipc-security-"));+const fixture = path.join(root, "fixture");+const downloads = path.join(root, "downloads");+const identifier = `com.pake.ipc-probe-${process.pid}`;+const reports = new Map();+let app;+let attackerOrigin;+let entryOrigin;++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 check = async (command, args) => {+ try { await invoke(command, args); return "allowed"; }+ catch (error) { return "denied: " + String(error); }+ };+ const results = {};+ results.download = await check("download_file", {params: {+ url: ${JSON.stringify(origin + "/payload")}, filename: ${JSON.stringify(stage + ".txt")}+ }});+ results.zoom = await check("set_zoom", {percent: 100});+ results.window = await check("plugin:window|is_fullscreen", {label: "pake"});+ ${+ stage === "entry"+ ? `results.traversal = await check("download_file", {params: {+ url: ${JSON.stringify(origin + "/payload")}, filename: "../outside.txt"+ }});`+ : ""+ }+ ${+ stage === "attacker"+ ? `+ await new Promise(resolve => document.readyState === "loading"+ ? document.addEventListener("DOMContentLoaded", resolve, {once:true}) : resolve());+ await new Promise(resolve => setTimeout(resolve, 250));+ for (const [url, filename] of [["/native.txt", "native.txt"], [${JSON.stringify(entryOrigin + "/attachment")}, "native-cross.txt"]]) {+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = filename;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ await new Promise(resolve => setTimeout(resolve, 500));+ }+ const player = document.querySelector("#player");+ const parent = player.parentElement;+ try { await player.requestFullscreen(); results.fullscreen = "allowed"; }+ catch (error) { results.fullscreen = "denied: " + String(error); }+ results.layoutPreserved = player.parentElement === parent+ && document.fullscreenElement === null && !document.querySelector(".pake-fullscreen-element, .pake-fullscreen-active");+ `+ : ""+ }+ await fetch("/report", {method:"POST", body:JSON.stringify(results)});+ ${stage === "entry" ? `location.replace(${JSON.stringify(attackerOrigin)});` : ""}+})().catch(error => fetch("/report", {method:"POST", body:JSON.stringify({error:String(error)})}));+</script>`;+}++async function server(stage) {+ let origin;+ const server = http.createServer(async (request, response) => {+ if (request.url === "/native.txt" || request.url === "/attachment") {+ response.writeHead(200, {+ "content-type": "application/octet-stream",+ "content-disposition": `attachment; filename="${request.url === "/native.txt" ? "native.txt" : "native-cross.txt"}"`,+ });+ response.end("pake-native-browser-download");+ } else if (request.url === "/payload") {+ response.writeHead(200, { "content-type": "text/plain" });+ response.end("pake-native-ipc-proof");+ } else if (request.url === "/report") {+ const chunks = [];+ for await (const chunk of request) chunks.push(chunk);+ reports.set(stage, JSON.parse(Buffer.concat(chunks).toString()));+ response.end("ok");+ } else {+ response.writeHead(200, { "content-type": "text/html" });+ response.end(page(stage, origin));+ }+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ origin = `http://127.0.0.1:${server.address().port}`;+ return { server, origin };+}++const attacker = await server("attacker");+attackerOrigin = attacker.origin;+const entry = await server("entry");+entryOrigin = entry.origin;+try {+ await fs.mkdir(fixture);+ await fs.cp(path.join(repo, "src-tauri"), path.join(fixture, "src-tauri"), {+ recursive: true,+ filter: (file) => {+ const relative = path.relative(path.join(repo, "src-tauri"), file);+ return (+ !["target", ".pake", "gen", ".cargo"].includes(+ relative.split(path.sep)[0],+ ) && !relative.startsWith(path.join("permissions", "autogenerated"))+ );+ },+ });+ await fs.copyFile(+ path.join(repo, "rust-toolchain.toml"),+ path.join(fixture, "rust-toolchain.toml"),+ );+ await fs.mkdir(path.join(fixture, "dist"));+ await fs.writeFile(path.join(fixture, "dist", "index.html"), "IPC fixture");+ const pake = JSON.parse(+ await fs.readFile(path.join(fixture, "src-tauri", "pake.json")),+ );+ pake.windows[0].url = entry.origin;+ pake.windows[0].url_type = "web";+ pake.download_dir = downloads;+ pake.system_tray.macos = false;+ const tauri = JSON.parse(+ await fs.readFile(path.join(fixture, "src-tauri", "tauri.conf.json")),+ );+ tauri.identifier = identifier;+ tauri.productName = "PakeSecurityProbe";+ const configDir = path.join(fixture, "src-tauri", ".pake");+ await fs.mkdir(configDir);+ await fs.writeFile(path.join(configDir, "pake.json"), JSON.stringify(pake));+ await fs.writeFile(+ path.join(configDir, "tauri.conf.json"),+ JSON.stringify(tauri),+ );++ const log = await fs.open(path.join(root, "build.log"), "w");+ console.log("Building native IPC fixture...");+ const compiler = spawn(+ "cargo",+ ["build", "--locked", "--features", "cli-build"],+ {+ cwd: path.join(fixture, "src-tauri"),+ env: {+ ...process.env,+ TAURI_CONFIG: JSON.stringify(tauri),+ CARGO_TARGET_DIR: path.join(repo, "src-tauri", "target"),+ },+ stdio: ["ignore", log.fd, log.fd],+ },+ );+ const [exitCode] = await once(compiler, "exit");+ await log.close();+ if (exitCode !== 0) {+ console.error(await fs.readFile(path.join(root, "build.log"), "utf8"));+ throw new Error(`Native fixture build failed with exit code ${exitCode}`);+ }+ console.log("Running real macOS WebView origin probes...");+ app = spawn(path.join(repo, "src-tauri", "target", "debug", "pake"), [], {+ stdio: "ignore",+ });+ const deadline = Date.now() + 45_000;+ while (!reports.has("attacker") && Date.now() < deadline) {+ if (app.exitCode !== null)+ throw new Error(`Native app exited with ${app.exitCode}`);+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ assert.ok(reports.has("entry"), "configured entry page did not report");+ assert.ok(reports.has("attacker"), "cross-origin page did not report");+ const trusted = reports.get("entry");+ const untrusted = reports.get("attacker");+ for (const command of ["download", "zoom", "window", "traversal"]) {+ assert.equal(trusted[command], "allowed", `configured origin: ${command}`);+ }+ for (const command of ["download", "zoom", "window"]) {+ assert.match(+ untrusted[command],+ /^denied: .*not allowed/i,+ `untrusted origin: ${command}`,+ );+ }+ const downloadDeadline = Date.now() + 5000;+ while (Date.now() < downloadDeadline) {+ try {+ await fs.stat(path.join(downloads, "native-cross.txt"));+ break;+ } catch {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ }+ for (const file of ["native.txt", "native-cross.txt"]) {+ assert.equal(+ await fs.readFile(path.join(downloads, file), "utf8"),+ "pake-native-browser-download",+ );+ }+ assert.match(untrusted.fullscreen, /^denied: .*not allowed/i);+ assert.equal(+ untrusted.layoutPreserved,+ true,+ "denied fullscreen changed the player layout",+ );+ assert.equal(+ await fs.readFile(path.join(downloads, "entry.txt"), "utf8"),+ "pake-native-ipc-proof",+ );+ assert.equal(+ await fs.readFile(path.join(downloads, "outside.txt"), "utf8"),+ "pake-native-ipc-proof",+ );+ for (const file of [+ path.join(root, "outside.txt"),+ path.join(downloads, "attacker.txt"),+ ]) {+ await assert.rejects(fs.stat(file), { code: "ENOENT" });+ }+ console.log(+ "Native IPC PASS: entry commands work, cross-origin commands are denied, browser downloads survive denied IPC, fullscreen denial preserves layout, traversal remains inside Downloads.",+ );+} finally {+ if (app && app.exitCode === null) {+ const stopped = once(app, "exit");+ app.kill("SIGTERM");+ await stopped;+ }+ await Promise.all(+ [entry, attacker].map(+ ({ server }) => new Promise((resolve) => server.close(resolve)),+ ),+ );+ await fs.rm(root, { recursive: true, force: true });+ await fs.rm(+ path.join(os.homedir(), "Library", "Application Support", identifier),+ { recursive: true, force: true },+ );+ await fs.rm(path.join(os.homedir(), "Library", "Caches", identifier), {+ recursive: true,+ force: true,+ });+ await fs.rm(path.join(os.homedir(), "Library", "WebKit", identifier), {+ recursive: true,+ force: true,+ });+}diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.jsindex fc66dc6b..fa60c659 100644--- a/tests/unit/event-link-guard.test.js+++ b/tests/unit/event-link-guard.test.js@@ -7,6 +7,7 @@ function loadEventHelpers({withTauri = false,userAgent = "Mozilla/5.0",initialZoom = null,+ downloadError = null,} = {}) {const source = ["link_policy.js", "event.js"].map((file) =>@@ -18,8 +19,11 @@ function loadEventHelpers({.join("\n");const invokeCalls = [];+ const nativeDownloadClicks = [];const invoke = (command, payload) => {invokeCalls.push([command, payload]);+ if (command === "download_file" && downloadError)+ return Promise.reject(downloadError);return Promise.resolve();};const eventListeners = {};@@ -45,7 +49,17 @@ function loadEventHelpers({this.children = this.children.filter((item) => item !== child);if (child.id) elementsById.delete(child.id);},- click: () => {},+ click() {+ nativeDownloadClicks.push([this.href, this.download]);+ // A transient native-download anchor still passes through document capture.+ getClickGuard({ eventListeners })(makeClickEvent(this));+ },+ closest() {+ return this;+ },+ getAttribute(name) {+ return name === "href" ? this.href : "";+ },set id(value) {this._id = value;elementsById.set(value, this);@@ -118,7 +132,13 @@ function loadEventHelpers({}runInNewContext(source, context);- return { ...context, eventListeners, invokeCalls, localStorageValues };+ return {+ ...context,+ eventListeners,+ invokeCalls,+ localStorageValues,+ nativeDownloadClicks,+ };}function runDomReady(context) {@@ -151,6 +171,46 @@ function makeClickEvent(anchor) {}describe("event link guard", () => {+ it.each([+ 'download_file not allowed on window "pake", webview "pake", URL: https://other.example/',+ "Command download_file not allowed by ACL",+ ])(+ "falls back once to browser downloads on ACL denial: %s",+ async (downloadError) => {+ const context = loadEventHelpers({ withTauri: true, downloadError });+ runDomReady(context);+ const anchor = makeAnchor("https://example.com/report.pdf", "_self");+ anchor.download = "report.pdf";+ getClickGuard(context)(makeClickEvent(anchor));+ await vi.waitFor(() =>+ expect(context.nativeDownloadClicks).toEqual([+ [anchor.href, "report.pdf"],+ ]),+ );+ expect(+ context.invokeCalls.filter(([command]) => command === "download_file"),+ ).toHaveLength(1);+ },+ );++ it("does not retry failed HTTP downloads through the browser", async () => {+ const context = loadEventHelpers({+ withTauri: true,+ downloadError: "Download failed with HTTP status 403 Forbidden",+ });+ runDomReady(context);+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ getClickGuard(context)(+ makeClickEvent(makeAnchor("https://example.com/report.pdf", "_self")),+ );+ await vi.waitFor(() => expect(log).toHaveBeenCalled());+ expect(context.nativeDownloadClicks).toEqual([]);+ } finally {+ log.mockRestore();+ }+ });+it.each([undefined, "", " ", "about:blank", "about:blank#download"])("preserves a native blank popup proxy for %s",(url) => {diff --git a/tests/unit/ipc-permissions.test.ts b/tests/unit/ipc-permissions.test.tsnew file mode 100644index 00000000..2973237b--- /dev/null+++ b/tests/unit/ipc-permissions.test.ts@@ -0,0 +1,33 @@+import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++const read = (file: string) =>+ fs.readFileSync(path.join(process.cwd(), 'src-tauri', file), 'utf8');++describe('native IPC permission registration', () => {+ it('puts every registered app command in the Tauri ACL manifest', () => {+ const handler = read('src/lib.rs').match(+ /tauri::generate_handler!\[([^\]]+)\]/,+ )?.[1];+ const manifest = read('build.rs').match(+ /tauri_build::AppManifest::new\(\)\.commands\(&\[([^\]]+)\]\)/,+ )?.[1];+ expect(handler).toBeTruthy();+ expect(manifest).toBeTruthy();+ const commands = handler!+ .split(',')+ .map((name) => name.trim())+ .filter(Boolean);+ const declared = [...manifest!.matchAll(/"([a-z_]+)"/g)].map(+ (match) => match[1],+ );+ for (const command of commands) expect(declared).toContain(command);+ });++ it('keeps the packaged capability local until configured origins are granted', () => {+ const capability = JSON.parse(read('capabilities/default.json'));+ expect(capability.remote).toBeUndefined();+ expect(capability.permissions).toContain('allow-download-file');+ });+});