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: preserve two-stage popups and external link routing
youxi79863863b7e8685
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 31579ffb..8a07ddc4 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -179,6 +179,31 @@ struct WindowBuildOptions<'a> {new_window_features: Option<NewWindowFeatures>,}+fn is_blank_popup_url(url: &Url) -> bool {+ url.scheme() == "about" && url.path() == "blank"+}++#[cfg(test)]+mod popup_tests {+ use super::is_blank_popup_url;+ use tauri::Url;++ #[test]+ fn only_blank_documents_get_the_default_popup_exception() {+ for input in ["about:blank", "about:blank#download", "about:blank?pending"] {+ assert!(is_blank_popup_url(&Url::parse(input).unwrap()));+ }+ for input in [+ "https://example.com/",+ "about:srcdoc",+ "about:blankness",+ "file:///tmp/file",+ ] {+ assert!(!is_blank_popup_url(&Url::parse(input).unwrap()));+ }+ }+}+fn open_requested_window(app: &AppHandle,config: &PakeConfig,@@ -472,11 +497,17 @@ fn build_window(window_builder = window_builder.disable_drag_drop_handler();}- if window_config.new_window {+ {+ let allow_new_window = window_config.new_window;let app_handle = app.clone();let popup_config = config.clone();let popup_tauri_config = tauri_config.clone();window_builder = window_builder.on_new_window(move |target_url, features| {+ // Even without --new-window, two-stage popups need a real webview+ // with our download delegate, never a proxy for the main window.+ if !allow_new_window && !is_blank_popup_url(&target_url) {+ return NewWindowResponse::Deny;+ }match open_requested_window(&app_handle,&popup_config,diff --git a/src-tauri/src/inject/auth.js b/src-tauri/src/inject/auth.jsindex 4df84d7f..2973508f 100644--- a/src-tauri/src/inject/auth.js+++ b/src-tauri/src/inject/auth.js@@ -6,26 +6,20 @@ function matchesAuthUrl(url, baseUrl = window.location.href) {const urlObj = new URL(url, baseUrl);const hostname = urlObj.hostname.toLowerCase();const pathname = urlObj.pathname.toLowerCase();- const fullUrl = urlObj.href.toLowerCase();-- // Common OAuth providers and paths- const oauthPatterns = [- /accounts\.google\.com/,- /accounts\.google\.[a-z]+/,- /login\.microsoftonline\.com/,- /github\.com\/login/,- /facebook\.com\/.*\/dialog/,- /twitter\.com\/oauth/,- /appleid\.apple\.com/,- /\/oauth\//,- /\/auth\//,- /\/authorize/,- /\/login\/oauth/,- /\/signin/,- /\/login/,- /servicelogin/,- /\/o\/oauth2/,+ // Host patterns never inspect user-controlled query strings or fragments.+ const oauthHostPatterns = [+ /^accounts\.google\.(?:com|[a-z]{2}|com\.[a-z]{2}|co\.[a-z]{2})$/,+ /^login\.microsoftonline\.com$/,+ /^appleid\.apple\.com$/,+ ];+ // Match complete path segments, including nested identity-provider routes.+ // /login-tips is content; /tenant/login remains an authentication endpoint.+ const oauthPathPatterns = [+ /\/(?:oauth2?|auth|authorize|signin|login|servicelogin)(?:\/|$)/,];+ const providerEndpoint =+ /^(?:www\.)?facebook\.com$/.test(hostname) &&+ /^\/(?:[^/]+\/)?dialog(?:\/|$)/.test(pathname);// Enterprise SSO. Match identity providers on the host, and SAML/SSO/ADFS on// the pathname with endpoint-shaped patterns only, so ordinary pages such as@@ -39,12 +33,9 @@ function matchesAuthUrl(url, baseUrl = window.location.href) {];const isMatch =- oauthPatterns.some(- (pattern) =>- pattern.test(hostname) ||- pattern.test(pathname) ||- pattern.test(fullUrl),- ) ||+ oauthHostPatterns.some((pattern) => pattern.test(hostname)) ||+ oauthPathPatterns.some((pattern) => pattern.test(pathname)) ||+ providerEndpoint ||enterpriseHostPatterns.some((pattern) => pattern.test(hostname)) ||enterprisePathPatterns.some((pattern) => pattern.test(pathname));diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.jsindex dabe8247..71d571dd 100644--- a/src-tauri/src/inject/event.js+++ b/src-tauri/src/inject/event.js@@ -859,7 +859,13 @@ document.addEventListener("DOMContentLoaded", () => {// Rewrite the window.open function.const originalWindowOpen = window.open;window.open = function (url, name, specs) {+ url = normalizePopupUrl(url);const normalizedUrl = normalizeAnchorHref(url);+ // A two-stage popup needs its own WindowProxy. Returning the main window+ // makes a later popup.location assignment navigate away from the app.+ if (/^about:blank(?:[?#]|$)/i.test(normalizedUrl)) {+ return originalWindowOpen.call(window, url, name, specs);+ }if (normalizedUrl.startsWith("#")) {window.location.href = new URL(normalizedUrl, window.location.href).href;return window;diff --git a/src-tauri/src/inject/frame_links.js b/src-tauri/src/inject/frame_links.jsindex fd4696e4..eedf808b 100644--- a/src-tauri/src/inject/frame_links.js+++ b/src-tauri/src/inject/frame_links.js@@ -4,11 +4,11 @@(function () {if (window === window.top) return;const config = window.pakeConfig || {};- if (config.force_internal_navigation === true) return;const isInternalUrl = createInternalUrlMatcher(config.internal_url_regex);const originalOpen = window.open;function externalDestination(rawUrl, name) {+ if (config.force_internal_navigation === true) return null;if (typeof rawUrl !== "string" ||!rawUrl.trim() ||@@ -33,6 +33,7 @@}window.open = function (url, name, specs) {+ url = normalizePopupUrl(url);// Named targets can navigate an existing frame and must retain its proxy.if (name && String(name).toLowerCase() !== "_blank") {return originalOpen.call(window, url, name, specs);diff --git a/src-tauri/src/inject/link_policy.js b/src-tauri/src/inject/link_policy.jsindex 6f669b9a..fb096f35 100644--- a/src-tauri/src/inject/link_policy.js+++ b/src-tauri/src/inject/link_policy.js@@ -1,4 +1,11 @@// Shared by the main page and the lightweight subframe bridge.+// Tauri rejects WebKit's empty popup URL before calling our native handler.+function normalizePopupUrl(url) {+ return url === undefined || (typeof url === "string" && !url.trim())+ ? "about:blank"+ : url;+}+// This list intentionally preserves Pake's existing domain routing policy.const MULTI_PART_PUBLIC_SUFFIXES = ["co.uk",diff --git a/tests/browser/popup-routing.mjs b/tests/browser/popup-routing.mjsnew file mode 100644index 00000000..5fbbedd5--- /dev/null+++ b/tests/browser/popup-routing.mjs@@ -0,0 +1,139 @@+// Real WindowProxy and DOM propagation coverage for two-stage popups and links.+import assert from "node:assert/strict";+import fs from "node:fs/promises";+import { pathToFileURL } from "node:url";+import { test } from "node:test";+const { chromium } = await import(+ process.env.PAKE_PLAYWRIGHT_MODULE+ ? pathToFileURL(process.env.PAKE_PLAYWRIGHT_MODULE).href+ : "playwright"+);+const source = await Promise.all(+ ["link_policy.js", "auth.js", "frame_links.js", "event.js"].map((name) =>+ fs.readFile(+ `${process.env.PAKE_INJECT_ROOT || "src-tauri/src/inject"}/${name}`,+ "utf8",+ ),+ ),+);+async function fixture(frame, run) {+ const browser = await chromium.launch({+ headless: true,+ ...(process.env.PAKE_BROWSER_EXECUTABLE+ ? { executablePath: process.env.PAKE_BROWSER_EXECUTABLE }+ : {}),+ });+ try {+ const context = await browser.newContext();+ await context.route("**/*", (route) =>+ route.fulfill({+ contentType: "text/html",+ body: '<html><body><button id="go">Open</button></body></html>',+ }),+ );+ await context.addInitScript(+ ({ source }) => {+ window.opened = [];+ window.pakeConfig = { url: "https://mail.example.com/" };+ window.__TAURI__ = {+ core: {+ invoke: (cmd, args) => {+ if (cmd === "plugin:shell|open") window.opened.push(args.path);+ return Promise.resolve();+ },+ },+ window: { getCurrentWindow: () => ({}) },+ };+ for (const script of window === window.top+ ? source+ : source.slice(0, 3))+ (0, eval)(script);+ },+ { source },+ );+ const page = await context.newPage();+ await page.goto("https://mail.example.com/");+ if (frame) {+ await page.evaluate(() => {+ const el = document.createElement("iframe");+ el.src = "/message";+ document.body.append(el);+ });+ await page.waitForFunction(() =>+ document.querySelector("iframe")?.contentDocument?.querySelector("#go"),+ );+ }+ await run(page, frame ? page.frames()[1] : page, context);+ } finally {+ await browser.close();+ }+}+for (const frame of [false, true]) {+ for (const raw of [undefined, "", "about:blank", "about:blank#download"]) {+ test(`${frame ? "frame" : "main"} blank ${String(raw)} preserves delayed popup navigation`, async () => {+ await fixture(frame, async (page, target, context) => {+ await target.evaluate((raw) => {+ document.querySelector("#go").onclick = () => {+ const popup =+ raw === undefined ? window.open() : window.open(raw, "_blank");+ window.popupIsMain = popup === window.top;+ if (popup)+ setTimeout(() => {+ popup.location.href = "https://files.example.net/preview";+ }, 20);+ };+ }, raw);+ const popupReady = context.waitForEvent("page", { timeout: 3000 });+ await target.locator("#go").click();+ const popup = await popupReady;+ await popup.waitForURL("https://files.example.net/preview");+ assert.equal(page.url(), "https://mail.example.com/");+ assert.equal(await target.evaluate(() => window.popupIsMain), false);+ assert.deepEqual(await page.evaluate(() => window.opened), []);+ await popup.close();+ });+ });+ }+ for (const destination of [+ "https://outside.example.net/article",+ "https://outside.example.net/track?next=https://service.example.net/login",+ "https://outside.example.net/login-tips",+ "https://outside.example.net/article#/signin",+ ]) {+ test(`${frame ? "frame" : "main"} external click reaches the browser once: ${destination}`, async () => {+ await fixture(frame, async (page, target) => {+ await target.evaluate((href) => {+ document.body.innerHTML =+ '<a id="link" target="_blank"><span>Link</span></a>';+ document.querySelector("#link").href = href;+ }, destination);+ await target.locator("#link span").click();+ await page.waitForFunction(() => window.opened.length > 0, null, {+ timeout: 1500,+ });+ assert.equal(page.url(), "https://mail.example.com/");+ assert.deepEqual(await page.evaluate(() => window.opened), [+ destination,+ ]);+ });+ });+ }+}++for (const destination of [+ "https://slack.com/openid/connect/authorize?client_id=123",+ "https://identity.example/connect/authorize",+ "https://tenant.auth0.com/u/login/identifier",+]) {+ test(`nested authentication remains in the app: ${destination}`, async () => {+ await fixture(false, async (page) => {+ await page.evaluate((href) => {+ document.body.innerHTML = '<a id="link" target="_blank">Sign in</a>';+ document.querySelector("#link").href = href;+ }, destination);+ await page.locator("#link").click();+ await page.waitForURL(destination);+ assert.deepEqual(await page.evaluate(() => window.opened), []);+ });+ });+}diff --git a/tests/unit/auth-sso-patterns.test.js b/tests/unit/auth-sso-patterns.test.jsindex 35bf65fb..9bd6ab0e 100644--- a/tests/unit/auth-sso-patterns.test.js+++ b/tests/unit/auth-sso-patterns.test.js@@ -68,4 +68,37 @@ describe("auth SSO patterns", () => {it("treats known auth window names as popups", () => {expect(isAuthPopup("https://example.com/dashboard", "oauth2")).toBe(true);});++ it.each([+ "https://outside.example/track?next=https://service.example/login",+ "https://outside.example/track?next=https://accounts.google.com/o/oauth2/auth",+ "https://outside.example/article#/signin",+ "https://outside.example/login-tips",+ "https://outside.example/authorize-your-team",+ "https://accounts.google.com.evil.test/article",+ "https://notaccounts.google.com/article",+ ])(+ "does not infer authentication from ordinary external content: %s",+ (url) => {+ expect(isAuthLink(url)).toBe(false);+ expect(isAuthPopup(url, "_blank")).toBe(false);+ },+ );++ it.each([+ "https://slack.com/openid/connect/authorize?client_id=123",+ "https://identity.example/connect/authorize",+ "https://tenant.auth0.com/u/login/identifier",+ "https://www.amazon.com/ap/signin",+ "https://example.com/tenant/oauth/authorize",+ "https://example.com/login?next=/dashboard",+ "https://example.com/signin/",+ "https://example.com/oauth/authorize",+ "https://example.com/api/auth/signin/google",+ "https://accounts.google.co.uk/ServiceLogin",+ "https://github.com/login/oauth/authorize",+ "https://appleid.apple.com/auth/authorize",+ ])("preserves authentication endpoints: %s", (url) => {+ expect(isAuthLink(url)).toBe(true);+ });});diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.jsindex f11f1921..fc66dc6b 100644--- a/tests/unit/event-link-guard.test.js+++ b/tests/unit/event-link-guard.test.js@@ -151,6 +151,47 @@ function makeClickEvent(anchor) {}describe("event link guard", () => {+ it.each([undefined, "", " ", "about:blank", "about:blank#download"])(+ "preserves a native blank popup proxy for %s",+ (url) => {+ const context = loadEventHelpers({ withTauri: true });+ const popup = { location: { href: "about:blank" } };+ const nativeOpen = vi.fn(() => popup);+ context.window.open = nativeOpen;+ runDomReady(context);+ const result = context.window.open(url, "_blank");+ expect(result).toBe(popup);+ expect(nativeOpen).toHaveBeenCalledWith(+ url === undefined || !url.trim() ? "about:blank" : url,+ "_blank",+ undefined,+ );+ 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"),+ ).toEqual([]);+ },+ );++ it.each(["https://outside.example/report", "https://example.com/report"])(+ "retains the default route for a new named context: %s",+ (url) => {+ const context = loadEventHelpers({ withTauri: true });+ context.window.open = vi.fn(() => null);+ runDomReady(context);+ context.window.open(url, "reportWindow");+ if (url.startsWith("https://outside.example/")) {+ expect(context.invokeCalls).toContainEqual([+ "plugin:shell|open",+ { path: url },+ ]);+ } else {+ expect(context.window.location.href).toBe(url);+ }+ },+ );+it.each([["internal", "https://example.com/forced", {}],["auth", "https://accounts.google.com/o/oauth2/auth", {}],diff --git a/tests/unit/frame-links.test.js b/tests/unit/frame-links.test.jsindex a136a8c9..57247d6b 100644--- a/tests/unit/frame-links.test.js+++ b/tests/unit/frame-links.test.js@@ -38,6 +38,22 @@ function loadFrame(config = {}) {}describe("subframe external links", () => {+ it.each([false, true])(+ "normalizes omitted and empty popups with force_internal_navigation=%s",+ (force_internal_navigation) => {+ const frame = loadFrame({ force_internal_navigation });+ for (const url of [undefined, "", " "]) {+ expect(frame.window.open(url, "_blank")).toBe(frame.nativeWindow);+ expect(frame.nativeOpen).toHaveBeenLastCalledWith(+ "about:blank",+ "_blank",+ undefined,+ );+ }+ expect(frame.messages).toEqual([]);+ },+ );+it("injects only the shared policy and frame bridge into subframes", () => {const source = fs.readFileSync(path.join(process.cwd(), "src-tauri/src/app/window.rs"),@@ -99,7 +115,11 @@ describe("subframe external links", () => {])("preserves native semantics for %s (%s)", (url, name, config) => {const frame = loadFrame(config);expect(frame.window.open(url, name, "width=400")).toBe(frame.nativeWindow);- expect(frame.nativeOpen).toHaveBeenCalledWith(url, name, "width=400");+ expect(frame.nativeOpen).toHaveBeenCalledWith(+ url === "" ? "about:blank" : url,+ name,+ "width=400",+ );expect(frame.messages).toEqual([]);});diff --git a/tests/unit/new-window-macos.test.js b/tests/unit/new-window-macos.test.jsindex 99cebea0..fde16258 100644--- a/tests/unit/new-window-macos.test.js+++ b/tests/unit/new-window-macos.test.js@@ -8,7 +8,9 @@ describe("macOS new-window handling (regression: #1194)", () => {it("creates popups via open_requested_window on every platform", () => {const source = fs.readFileSync(sourcePath, "utf-8");- const blockStart = source.indexOf("if window_config.new_window");+ const blockStart = source.indexOf(+ "let allow_new_window = window_config.new_window;",+ );const blockEnd = source.indexOf("// Add initialization scripts",blockStart,@@ -22,6 +24,9 @@ describe("macOS new-window handling (regression: #1194)", () => {// and custom protocol state. NewWindowResponse::Allow creates a plain// WKWebView that does not have Pake's runtime state.expect(newWindowBlock).toContain("open_requested_window");+ expect(newWindowBlock).toContain(+ "!allow_new_window && !is_blank_popup_url(&target_url)",+ );expect(newWindowBlock).toContain("NewWindowResponse::Create");expect(newWindowBlock).not.toMatch(/NewWindowResponse::Allow\b/);expect(newWindowBlock).not.toMatch(/#\[cfg\(target_os = "macos"\)\]/);