Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: give a sized sign-in popup its own window on macOS and Windows

Tw9341e1a6f9bccb
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.md
index e62a6b59..66b3e42c 100644
--- a/.claude/rules/tauri-runtime.md
+++ b/.claude/rules/tauri-runtime.md
@@ -17,7 +17,8 @@ paths:
- Windows `--password-autosave` is opt-in and disabled in private windows. Every window creation must apply both true and false through `ICoreWebView2Settings4::SetIsPasswordAutosaveEnabled`; do not treat the false case as a no-op. Legacy configs default to false. This controls new save/update prompts, not existing password autofill or general autofill, and does not share an Edge or Chrome profile. Keep the native bool, CLI/config surface, and both language docs consistent; cover all four requested/private combinations and the missing-field default in the `config.rs` Rust tests, and keep `tests/unit/password-autosave.test.ts` asserting that both values reach the native call.
- `--new-window` and `--multi-window` do not bypass every provider policy. Google OAuth and similar embedded-WebView restrictions may still require a normal browser or native client.
- macOS Basic Auth keeps only an enablement boolean in CLI/config. Usernames and passwords are runtime-only input for the target host and session; never put them in CLI arguments, config, generated artifacts, logs, or persistence. Native dialog changes need a real macOS smoke covering the icon, button alignment, label/input baselines, field width, and outer margins; compile and unit tests do not prove the layout.
-- macOS auth-popup behavior is fragile. Auth and sign-in URLs that trigger WebKit's native auth-popup path should stay in the current window when that path can abort the app. URL matching lives in `src-tauri/src/inject/auth.js` (`matchesAuthUrl`, injected from `src-tauri/src/app/window.rs`) and is covered by `tests/unit/auth-sso-patterns.test.js`; main-page `window.open` interception lives in `event.js`, and the lightweight subframe interception lives in `frame_links.js`. Changes need the corresponding routing tests. Apple Sign-In (`appleid.apple.com` / `AppleAuthentication` named windows) is the exception and must keep the native `window.open` popup.
+- A sized `window.open` to a sign-in URL, or to the app's own site, is a popup flow: the popup signs in, answers `window.opener` and closes itself (the Google button on TikTok and X, Notion's own redirect page, Sign in with Apple). On macOS and Windows it gets a real window under every `--new-window` setting. Navigating the opener there instead, which macOS did from 0419e982 to avoid a WebKit abort that 63863b7e's target-configuration popups later removed, left the callback page with nobody to answer: a blank window after the Google password (user reports, 2026-11-18), and a frame's popup (Google's button on X is a frame) was refused outright. `requestsPopupWindow` and `openPopupThroughBlank` in `link_policy.js` open the popup blank and send it to its address, from `event.js` and from `frame_links.js`, because the native handler builds a blank popup under every setting while one that starts at its address exists only with `--new-window`. "Sized" follows the window features as a browser reads them: commas or spaces separate, an explicit `popup` decides, `noopener` and `noreferrer` rule a popup out, since it could not be sent to its address. Every other sign-in `window.open` keeps its route through `openAuthNavigation` (no size, `noopener`, a `_self` target, a popup the engine refused): the current window on macOS and Linux, a native popup first on Windows. A sized popup of another site goes to the system browser unless its URL or its window name (`login`, `oauth` and the rest of `isAuthPopup`) marks a sign-in. WebView2 runs `event.js` in subframes too, where the app's own site is `pakeConfig.url`, not the frame's address. Linux is left out by `opensSignInPopups` until a self-closing popup has been run on a real WebKitGTK desktop: Wry destroys the web view at once there, which nobody has measured against an IPC call in flight. URL matching lives in `src-tauri/src/inject/auth.js` (`matchesAuthUrl`), covered by `tests/unit/auth-sso-patterns.test.js`; routing changes need `tests/unit/event-link-guard.test.js`, `tests/unit/frame-links.test.js` and `tests/browser/popup-routing.mjs`, whose frame cases pass on any code because Chromium never refuses a popup.
+- A popup's page closes it with `window.close()`. WKWebView closes nothing for that call unless its UI delegate implements `webViewDidClose:`, which Wry's does not; `src-tauri/src/app/popup_close.rs` closes the window, and only for windows a page opened (`page_popup`), since WebKit sends the same message for a main window whose page calls `window.close()`. WebView2 closes the window itself; on Linux the window stays with its web view destroyed, as before. On macOS the timing is load-bearing twice. WebKit cancels a closing page's requests, a callback page closes in its first script, and Tauri's notification plugin has an IPC call out in every document (`is_permission_granted`); the answer to a cancelled `ipc://` request makes WebKit raise, and under the release profile's `panic = "abort"` Wry's `objc2::exception::catch` cannot hold, so the whole app quit on every sign-in (measured on macOS 26.7; with `panic = "unwind"` the same run passed, at 2.0 MB more per architecture, 11.8 to 13.8 MB). So `event.js` delays every top-level page's own `window.close()` by `WINDOW_CLOSE_DELAY_MS` (WebKit runs the same cancel for any window a script may close, a first page in the main window included), and the native side hides the window at once and destroys it after `CLOSE_GRACE`, because destroying the web view cancels requests too. Not covered: an opener that closes a cross-origin popup calls the engine's own `close`, a page that navigates within the delay after `close()` loses the close, and the same abort is possible wherever a page with an IPC call in flight is torn down. Page-opened popups take `pake-popup-N` labels (`POPUP_WINDOW_LABEL_PREFIX`) and the window-state plugin filters them out, so a popup opens at the size its page asked for and a Cmd+N window never inherits one. Verify on a real bundle with `tests/integration/signin-popup-server.mjs`: each of its three buttons must end with the app's page in place, the answer received, the popup gone and the app still running, several times in a row, and its `/selfclose` page must leave the main window open.
- Auth routing matches provider hostnames and endpoint-shaped paths separately, never query strings or fragments. Tracking links carrying a login URL must still open externally. Cover main-page and subframe clicks in `tests/browser/popup-routing.mjs`; classifier-only tests do not prove routing.
- Blank/two-stage popups need a real WindowProxy, not the main window. Normalize omitted/empty URLs to `about:blank` in both JS entry points: Tauri rejects WebKit's empty URL before calling `on_new_window`. The default native handler must create a managed blank popup with Pake's download delegate even without `--new-window`; `NewWindowResponse::Allow` does not provide that delegate. Verify actual macOS attachment bytes and preservation of the main URL, not only Chromium popup creation.
- `--download-dir` / `downloadDir` is embedded as trusted `pake.download_dir`, shared by native and IPC downloads through `get_download_dir`. Empty means system Downloads; quoted `~/path` expands against the runtime user home. Reject relative paths and absolute tilde suffixes, create missing directories on download, and surface directory creation plus file open/write failures without redirecting to another folder. Do not accept a directory from remote-page IPC arguments.
diff --git a/AGENTS.md b/AGENTS.md
index 445cb2b6..5b8ae974 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -61,7 +61,7 @@ For proactive latent-bug sweeps, pick one row and go deep; do not invent a whole
| Download success semantics | `invoke.rs`, `window.rs` `on_download` | Non-2xx toasted as success; toast/IPC hardcoded to `"pake"`; request drops session cookies |
| Menu / focused window | `menu.rs` | Commands hit the main window, not the focused one; eval dead on error pages |
| Startup visibility | `lib.rs`, `setup.rs` | Blank shell, `about:blank` false ready, user hide racing fallback reveal |
-| Auth / popup | `auth.js`, `event.js` | macOS auth crash, SSO in system browser, Apple popup exception |
+| Auth / popup | `auth.js`, `event.js` | Sign-in popup loses its opener or stays open, abort on its close, SSO in system browser |
| Clipboard | `event.js` | keydown steals native paste; double-paste fallback |
| Multi-window / icon | `window.rs`, `setup.rs` | Missing `reapply_window_icon` on show; secondary window toast/target; Cmd+N blank flash |
| Platform capability | `auth.rs`, proxy, WebKit flags | Flag name present, platform no-op |
diff --git a/docs/faq.md b/docs/faq.md
index a1b9d4e3..d24c835f 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -456,7 +456,7 @@ This is usually due to web compatibility issues. Try:
Some authentication providers, especially Google, may block sign-in inside embedded webviews. Because Pake packages sites into a desktop webview, Google properties or sites that rely on Google OAuth may still fail to sign in even when `--new-window` or `--multi-window` is enabled. This is provider policy, not a packaging bug, so use the normal browser, a browser-installed app, or a native desktop client for those sites.
- Pake keeps **Sign in with Apple** popup flows (e.g. Yelp, Upwork) on the native popup path so Apple's callback can return to the opener page. On macOS and Linux, other sign-in popups open in the current window instead, because the WebKit webview there can crash on them or drop them silently; on Windows they stay popups.
+ When a site signs in through a popup with a size of its own (the Google button on TikTok, Notion and X, or Sign in with Apple on Yelp and Upwork), Pake on macOS and Windows opens that popup as a separate window, so it can hand the result back to the page that opened it and close itself, with or without `--new-window`. A sign-in the site opens as a link, or as a `window.open` with no size, continues in the current window on macOS and Linux, and so does every sign-in popup on Linux for now.
Passkeys and Touch ID sign-in are not available in Pake apps on macOS, because the system only offers them to browsers and to apps tied to the site's domain. Sign in with a password and a two-factor code instead.
diff --git a/docs/faq_CN.md b/docs/faq_CN.md
index 138ec3c3..cedab1ce 100644
--- a/docs/faq_CN.md
+++ b/docs/faq_CN.md
@@ -454,7 +454,7 @@ Pake 可以自动转换普通图片,但提供正确的格式更可靠。Icon C
某些认证提供方,尤其是 Google,可能会阻止在嵌入式 WebView 中完成登录。由于 Pake 是把网站包装进桌面 WebView,Google 自家站点或依赖 Google OAuth 的网站,即使启用了 `--new-window` 或 `--multi-window`,也仍然可能无法在应用内完成登录。这属于提供方策略限制,不是打包逻辑错误,这类站点改用普通浏览器、浏览器安装版站点应用或官方原生桌面客户端。
- Pake 会让 **Sign in with Apple**(弹窗模式,例如 Yelp、Upwork)继续走原生弹窗路径,确保 Apple 的回调可以返回原页面。在 macOS 和 Linux 上,其他登录弹窗会改在当前窗口内跳转,因为这两个平台的 WebKit 内核可能因弹窗崩溃或悄悄丢掉弹窗,Windows 上仍保持弹窗。
+ 网站用自带尺寸的弹窗登录时(TikTok、Notion、X 上的 Google 登录,Yelp、Upwork 上的 Sign in with Apple),macOS 和 Windows 上的 Pake 会把这个弹窗开成独立窗口,登录完由它把结果交回原页面并自己关闭,开没开 `--new-window` 都一样。网站用普通链接或不带尺寸的 `window.open` 发起的登录,在 macOS 和 Linux 上仍在当前窗口内跳转,Linux 上的登录弹窗目前也都还是这样。
macOS 上的 Pake 应用用不了通行密钥和指纹登录,系统只把这项能力开放给浏览器和与网站域名绑定的应用,登录时改用密码加两步验证码。
diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs
index 9dba1a3b..36eca584 100644
--- a/src-tauri/src/app/mod.rs
+++ b/src-tauri/src/app/mod.rs
@@ -17,6 +17,8 @@ pub mod menu;
pub mod nav_buttons;
pub mod navigation;
pub mod notification;
+#[cfg(target_os = "macos")]
+pub mod popup_close;
#[cfg(any(target_os = "linux", target_os = "windows", test))]
pub mod recovery;
#[cfg(target_os = "macos")]
diff --git a/src-tauri/src/app/popup_close.rs b/src-tauri/src/app/popup_close.rs
new file mode 100644
index 00000000..ede093b2
--- /dev/null
+++ b/src-tauri/src/app/popup_close.rs
@@ -0,0 +1,144 @@
+//! `window.close()` for a popup on macOS.
+//!
+//! A sign-in popup hands its result to its opener and closes itself. WebKit
+//! does not close anything for that call: it tells the UI delegate
+//! (`webViewDidClose:`), and Wry's delegate has no such method, so the popup
+//! stayed on screen, blank, after the sign-in it was opened for had finished.
+//!
+//! The method goes on the delegate's own class, as `script_dialogs.rs` adds
+//! its panels, and it closes only windows marked here: the popups a page
+//! opened. WebKit also sends the message for a main window whose page calls
+//! `window.close()`, and that window must stay.
+//!
+//! The window is hidden at once and closed a moment later. A callback page
+//! closes itself while it is still loading, when Pake's own scripts have IPC
+//! calls in flight; destroying the web view stops those requests, WebKit
+//! raises on an answer to a stopped request, and the release profile's
+//! `panic = "abort"` turns that exception into the whole app quitting (Wry's
+//! `objc2::exception::catch` around the answer cannot hold under it). Measured
+//! on macOS 26.7: closing at once aborted the app on every sign-in.
+
+use objc2::ffi::class_addMethod;
+use objc2::msg_send;
+use objc2::rc::Retained;
+use objc2::runtime::{AnyClass, AnyObject, Imp, Sel};
+use objc2_foundation::NSString;
+use std::ffi::CStr;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tauri::{AppHandle, Manager};
+
+/// How long a hidden popup outlives its `window.close()`: the IPC calls of a
+/// page load answer in milliseconds.
+const CLOSE_GRACE: Duration = Duration::from_millis(1_000);
+
+/// `void webViewDidClose:(WKWebView *)webView`: return, self, `_cmd`, webview.
+const DID_CLOSE: (&CStr, &CStr) = (c"webViewDidClose:", c"v@:@");
+
+/// The delegate method carries no Rust context; a process hosts one app.
+static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
+
+/// Its address keys the popup's window label on the webview.
+static POPUP_LABEL_KEY: u8 = 0;
+
+extern "C" fn did_close(_this: &AnyObject, _cmd: Sel, webview: *mut AnyObject) {
+ if webview.is_null() {
+ return;
+ }
+ // SAFETY: WebKit calls this on the main thread with the live webview, and
+ // the associated object is the NSString `install` retained on it.
+ let label = unsafe {
+ let label = objc2::ffi::objc_getAssociatedObject(
+ webview as *const AnyObject,
+ &POPUP_LABEL_KEY as *const u8 as *const std::ffi::c_void,
+ ) as *const NSString;
+ match label.as_ref() {
+ Some(label) => label.to_string(),
+ // Not a popup: the page's window.close() leaves the window alone.
+ None => return,
+ }
+ };
+ let Some(window) = APP_HANDLE
+ .get()
+ .and_then(|app| app.get_webview_window(&label))
+ else {
+ return;
+ };
+ // Gone from the screen now; see the module comment for the wait.
+ if let Err(error) = window.hide() {
+ eprintln!("[Pake] Failed to hide the popup its page closed: {error}");
+ }
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(CLOSE_GRACE).await;
+ // Tauri's own close, so the window leaves its window list as it
+ // would from the close button.
+ if let Err(error) = window.close() {
+ eprintln!("[Pake] Failed to close the popup its page closed: {error}");
+ }
+ });
+}
+
+/// Let the page in this popup close its window. `label` is the popup's Tauri
+/// window label. Idempotent for the class; every popup is marked.
+pub fn install(app: &AppHandle, label: &str, webview: &tauri::webview::PlatformWebview) {
+ let _ = APP_HANDLE.set(app.clone());
+ let view = webview.inner() as *mut AnyObject;
+ if view.is_null() {
+ eprintln!("[Pake] Failed to access WKWebView for its popup close");
+ return;
+ }
+ // SAFETY: Tauri runs this on the main thread with the live WKWebView.
+ unsafe {
+ let delegate: *mut AnyObject = msg_send![view, UIDelegate];
+ if delegate.is_null() {
+ eprintln!("[Pake] The WKWebView has no UI delegate for its popup close");
+ return;
+ }
+ let marker = NSString::from_str(label);
+ objc2::ffi::objc_setAssociatedObject(
+ view,
+ &POPUP_LABEL_KEY as *const u8 as *const std::ffi::c_void,
+ Retained::as_ptr(&marker) as *mut AnyObject,
+ objc2::ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,
+ );
+
+ let class: *const AnyClass = msg_send![delegate, class];
+ let class = &*class;
+ let selector = Sel::register(DID_CLOSE.0);
+ if class.instance_method(selector).is_none() {
+ let imp: Imp = std::mem::transmute::<extern "C" fn(&AnyObject, Sel, *mut AnyObject), Imp>(
+ did_close,
+ );
+ let added = class_addMethod(
+ class as *const AnyClass as *mut AnyClass,
+ selector,
+ imp,
+ DID_CLOSE.1.as_ptr(),
+ );
+ if !added.as_bool() {
+ eprintln!("[Pake] Failed to install the popup close on the UI delegate.");
+ return;
+ }
+ }
+ // WebKit notes which methods a delegate answers when it is set, so
+ // the same delegate is set again, as for the script dialogs.
+ let Some(delegate) = Retained::retain(delegate) else {
+ return;
+ };
+ let none: *mut AnyObject = std::ptr::null_mut();
+ let _: () = msg_send![view, setUIDelegate: none];
+ let _: () = msg_send![view, setUIDelegate: &*delegate];
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_close_encoding_matches_its_selector() {
+ let selector = DID_CLOSE.0.to_str().unwrap();
+ let arguments = DID_CLOSE.1.to_str().unwrap().strip_prefix("v@:").unwrap();
+ assert_eq!(arguments.chars().count(), selector.matches(':').count());
+ }
+}
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index b680588a..6a65f185 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -98,10 +98,22 @@ impl MultiWindowState {
let index = self.next_window_index.fetch_add(1, Ordering::Relaxed) + 1;
format!("{SECONDARY_WINDOW_LABEL_PREFIX}{index}")
}
+
+ fn next_popup_label(&self) -> String {
+ let index = self.next_window_index.fetch_add(1, Ordering::Relaxed) + 1;
+ format!("{POPUP_WINDOW_LABEL_PREFIX}{index}")
+ }
}
-/// Secondary windows (Cmd+N clones, `--new-window` popups, blank two-stage
-/// popups) take `pake-N` labels. `capabilities/default.json` must cover them
+/// Windows a page opened take `pake-popup-N` labels: still under the
+/// `pake-*` capability glob, and apart from the Cmd+N clones' `pake-N`, so
+/// the window-state plugin can leave them out. A sign-in popup's size is the
+/// page's to choose every time, and a clone that later takes the same label
+/// must not open at the size of a sign-in popup.
+pub const POPUP_WINDOW_LABEL_PREFIX: &str = "pake-popup-";
+
+/// Secondary windows take labels under `pake-`: Cmd+N clones `pake-N`, and
+/// windows a page opened `pake-popup-N`. `capabilities/default.json` must cover them
/// with a matching glob: an uncovered label has every IPC call denied, so
/// external links, downloads and toasts silently stop working there.
const SECONDARY_WINDOW_LABEL_PREFIX: &str = "pake-";
@@ -124,6 +136,8 @@ mod capability_tests {
assert!(webviews.contains(&"pake"));
assert!(webviews.contains(&format!("{SECONDARY_WINDOW_LABEL_PREFIX}*").as_str()));
+ // The one glob covers page-opened popups as well.
+ assert!(super::POPUP_WINDOW_LABEL_PREFIX.starts_with(SECONDARY_WINDOW_LABEL_PREFIX));
}
}
@@ -259,7 +273,7 @@ fn open_requested_window(
features: NewWindowFeatures,
) -> tauri::Result<WebviewWindow> {
let state = app.state::<MultiWindowState>();
- let label = state.next_window_label();
+ let label = state.next_popup_label();
let window = build_window(
app,
config,
@@ -272,8 +286,10 @@ fn open_requested_window(
},
)?;
- let title = target_url.host_str().unwrap_or(target_url.as_str());
- let _ = window.set_title(title);
+ // A blank popup keeps the app's title until its page has one.
+ if let Some(host) = target_url.host_str() {
+ let _ = window.set_title(host);
+ }
reapply_window_icon(&window);
let _ = window.set_focus();
@@ -465,6 +481,9 @@ fn build_window(
visible,
new_window_features,
} = opts;
+ // A window a page opened: a sign-in popup, a blank two-stage one.
+ #[cfg(target_os = "macos")]
+ let page_popup = new_window_features.is_some();
#[cfg(target_os = "macos")]
let use_native_window_tabbing = config.multi_window && new_window_features.is_none();
#[cfg(target_os = "macos")]
@@ -879,6 +898,15 @@ fn build_window(
prepare_macos_new_window_configuration(&features)?;
window_builder = window_builder.window_features(features).focused(true);
+ // A popup that starts blank and is then sent to its address has no
+ // title of its own; it takes its page's, as a browser's popup does.
+ window_builder = window_builder.on_document_title_changed(|window, title| {
+ if !title.trim().is_empty() {
+ if let Err(error) = window.set_title(&title) {
+ eprintln!("[Pake] Failed to update the popup title: {error}");
+ }
+ }
+ });
}
// Capture webview-initiated downloads (blob:, data:, Content-Disposition,
@@ -1052,6 +1080,19 @@ fn build_window(
eprintln!("[Pake] Failed to access WKWebView for history swipe gestures: {error}");
}
+ // A popup's page closes it with window.close() once it has answered its
+ // opener, and WKWebView closes nothing unless its UI delegate does.
+ #[cfg(target_os = "macos")]
+ if page_popup {
+ let popup_app = app.clone();
+ let popup_label = label.to_string();
+ if let Err(error) = window.with_webview(move |webview| {
+ crate::app::popup_close::install(&popup_app, &popup_label, &webview);
+ }) {
+ eprintln!("[Pake] Failed to access WKWebView for its popup close: {error}");
+ }
+ }
+
// A page's alert(), confirm() and prompt() show nothing in a WKWebView
// unless its UI delegate answers, and Wry's does not: every window's does.
#[cfg(target_os = "macos")]
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 1ac56ef1..645771fa 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -673,6 +673,33 @@ function openAuthNavigation(originalWindowOpen, url, name, specs) {
return authWindow;
}
+// A popup's page closes itself the moment it has answered its opener, often
+// in its first script, while an IPC call of that page load is still out:
+// Tauri's notification plugin asks for its permission in every document.
+// WebKit cancels a closing page's requests, and on macOS the answer to a
+// cancelled IPC request ends the whole app, because the release profile
+// cannot catch the exception WebKit raises for it (measured: every sign-in
+// popup that closed itself took the app with it). The answer takes a couple
+// of milliseconds, so the close waits them out. WebKit runs the same cancel
+// for any window a script may close, a first page in the main window
+// included, so every top-level page gets the wait, not only popups.
+const WINDOW_CLOSE_DELAY_MS = 150;
+function deferWindowClose() {
+ if (window !== window.top) return;
+ if (!/mac/i.test(getDesktopPlatform())) return;
+ const nativeClose = window.close.bind(window);
+ let pending = false;
+ window.close = function () {
+ if (pending) return;
+ pending = true;
+ setTimeout(() => {
+ pending = false;
+ nativeClose();
+ }, WINDOW_CLOSE_DELAY_MS);
+ };
+}
+deferWindowClose();
+
// Install the receiver at document start: a subframe can open a link before
// the main page's DOMContentLoaded routing setup has run.
let openFrameLink = null;
@@ -993,7 +1020,43 @@ document.addEventListener("DOMContentLoaded", () => {
return originalWindowOpen.call(window, url, name, specs);
}
- // Avoid macOS WebKit auth-popup crashes by navigating auth URLs in-place.
+ // A sized sign-in popup, or a sized popup of the app's own site, answers
+ // its opener and closes; it gets a real window on macOS and Windows.
+ if (opensSignInPopups() && requestsPopupWindow(name, specs)) {
+ let popupUrl = "";
+ try {
+ popupUrl = new URL(url, window.location.href).href;
+ } catch (error) {
+ popupUrl = "";
+ }
+ // WebView2 runs this script in subframes too, where the app's own site
+ // is the configured one, not the frame's address.
+ const ownSite =
+ window === window.top
+ ? isInternalUrl(popupUrl)
+ : matchesInternalUrl(
+ popupUrl,
+ window.pakeConfig?.url || window.location.href,
+ );
+ if (
+ /^https?:/i.test(popupUrl) &&
+ (window.isAuthPopup(popupUrl, name) ||
+ (!window.pakeConfig?.new_window && ownSite))
+ ) {
+ const popup = openPopupThroughBlank(
+ originalWindowOpen,
+ window,
+ popupUrl,
+ name,
+ specs,
+ );
+ if (popup) return popup;
+ }
+ }
+
+ // Every other sign-in window.open: no size, noopener, a _self target, a
+ // popup the engine refused, and all of them on Linux. macOS and Linux
+ // continue in the current window, Windows asks for a native popup first.
if (window.isAuthPopup(url, name)) {
try {
const baseUrl = window.location.origin + window.location.pathname;
diff --git a/src-tauri/src/inject/frame_links.js b/src-tauri/src/inject/frame_links.js
index eedf808b..abc7d391 100644
--- a/src-tauri/src/inject/frame_links.js
+++ b/src-tauri/src/inject/frame_links.js
@@ -32,8 +32,37 @@
window.top.postMessage({ type: "pake:frame-external-link", url }, "*");
}
+ // A frame's own sized sign-in popup (Google's button is such a frame) needs
+ // the same real window as the main page's, with this frame as its opener.
+ function popupDestination(rawUrl, name, specs) {
+ if (!opensSignInPopups() || !requestsPopupWindow(name, specs)) return null;
+ const raw = String(rawUrl ?? "").trim();
+ if (!raw || raw.startsWith("#")) return null;
+ try {
+ const url = new URL(raw, document.baseURI);
+ if (!["http:", "https:"].includes(url.protocol)) return null;
+ if (window.isAuthPopup(url.href, name)) return url.href;
+ if (config.new_window !== true && isInternalUrl(url.href, config.url))
+ return url.href;
+ } catch (error) {
+ return null;
+ }
+ return null;
+ }
+
window.open = function (url, name, specs) {
url = normalizePopupUrl(url);
+ const popupUrl = popupDestination(url, name, specs);
+ if (popupUrl) {
+ const popup = openPopupThroughBlank(
+ originalOpen,
+ window,
+ popupUrl,
+ name,
+ specs,
+ );
+ if (popup) return popup;
+ }
// 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.js
index fb096f35..0bfe08c2 100644
--- a/src-tauri/src/inject/link_policy.js
+++ b/src-tauri/src/inject/link_policy.js
@@ -6,6 +6,70 @@ function normalizePopupUrl(url) {
: url;
}
+// A window.open call that asks for a sized window is a flow the page means to
+// finish through window.opener: the popup signs in, hands the result back and
+// closes itself. Navigating the opener there instead leaves the callback page
+// with nobody to answer, which is the blank window after a Google sign-in.
+function requestsPopupWindow(name, specs) {
+ if (typeof specs !== "string") return false;
+ if (["_self", "_top", "_parent"].includes(String(name || "").toLowerCase()))
+ return false;
+ // Features are separated by commas or spaces, and "width = 500" is one.
+ const features = new Map(
+ specs
+ .replace(/\s*=\s*/g, "=")
+ .split(/[\s,]+/)
+ .filter(Boolean)
+ .map((feature) => {
+ const [key, value = ""] = feature.split("=");
+ return [key.toLowerCase(), value.toLowerCase()];
+ }),
+ );
+ const enabled = (key) =>
+ features.has(key) && !["0", "no", "false"].includes(features.get(key));
+ // Without an opener the popup cannot be handed its address afterwards.
+ if (enabled("noopener") || enabled("noreferrer")) return false;
+ // An explicit popup feature decides; a size asks for a popup otherwise.
+ if (features.has("popup")) return enabled("popup");
+ return ["width", "height", "innerwidth", "innerheight"].some(
+ (key) => parseFloat(features.get(key)) > 0,
+ );
+}
+
+// WebKitGTK keeps its previous routes: a popup there that closes itself has
+// not been run on a real desktop yet, and Wry tears its web view down at once.
+function opensSignInPopups() {
+ const platform =
+ typeof navigator === "undefined"
+ ? ""
+ : navigator.userAgentData?.platform ||
+ navigator.platform ||
+ navigator.userAgent ||
+ "";
+ return !/linux/i.test(platform);
+}
+
+// The native handler builds a blank popup under every setting and on every
+// platform, with its opener and Pake's download delegate; a popup that starts
+// at its address exists only with --new-window. So a sign-in popup starts
+// blank and is sent to its address, the two-stage form sites use themselves.
+function openPopupThroughBlank(nativeOpen, opener, url, name, specs) {
+ const popup = nativeOpen.call(opener, "about:blank", name, specs);
+ if (!popup) return null;
+ try {
+ popup.location.href = url;
+ } catch (error) {
+ console.error("[Pake] Failed to send a popup to its address:", error);
+ try {
+ popup.close();
+ } catch (closeError) {
+ // The caller falls back to its previous route either way.
+ }
+ return null;
+ }
+ return popup;
+}
+
// This list intentionally preserves Pake's existing domain routing policy.
const MULTI_PART_PUBLIC_SUFFIXES = [
"co.uk",
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 242e2f77..47aecc27 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -341,6 +341,8 @@ pub fn run_app() {
// doesn't force fullscreen on a rebuild without --fullscreen.
StateFlags::all() & !StateFlags::VISIBLE & !StateFlags::FULLSCREEN
})
+ // A popup a page opened is sized by that page, every time.
+ .with_filter(|label| !label.starts_with(app::window::POPUP_WINDOW_LABEL_PREFIX))
.build();
#[allow(deprecated)]
diff --git a/tests/browser/popup-routing.mjs b/tests/browser/popup-routing.mjs
index 5fbbedd5..008fd2af 100644
--- a/tests/browser/popup-routing.mjs
+++ b/tests/browser/popup-routing.mjs
@@ -120,6 +120,46 @@ for (const frame of [false, true]) {
}
}
+for (const frame of [false, true]) {
+ for (const [label, destination] of [
+ ["provider", "https://accounts.google.com/o/oauth2/v2/auth?client_id=1"],
+ ["own-site", "https://mail.example.com/googlepopupredirect?flow=popup"],
+ ]) {
+ // TikTok, Notion and X sign in with Google through a sized popup that
+ // answers window.opener; navigating the app there left a blank window.
+ test(`${frame ? "frame" : "main"} sized ${label} sign-in popup keeps its opener and the app's page`, async () => {
+ await fixture(frame, async (page, target, context) => {
+ await target.evaluate((destination) => {
+ window.answers = [];
+ addEventListener("message", (event) =>
+ window.answers.push(event.data),
+ );
+ document.querySelector("#go").onclick = () => {
+ const popup = window.open(
+ destination,
+ "g_auth_token_window",
+ "toolbar=no,location=no,width=590,height=830,top=143.5,left=569",
+ );
+ window.popupIsSelf = popup === window || popup === window.top;
+ };
+ }, destination);
+ const popupReady = context.waitForEvent("page", { timeout: 3000 });
+ await target.locator("#go").click();
+ const popup = await popupReady;
+ await popup.waitForURL(destination);
+ assert.equal(page.url(), "https://mail.example.com/");
+ assert.equal(await target.evaluate(() => window.popupIsSelf), false);
+ await popup.evaluate(() => window.opener.postMessage("signed-in", "*"));
+ await target.waitForFunction(() =>
+ window.answers.includes("signed-in"),
+ );
+ assert.deepEqual(await page.evaluate(() => window.opened), []);
+ await popup.close();
+ });
+ });
+ }
+}
+
for (const destination of [
"https://slack.com/openid/connect/authorize?client_id=123",
"https://identity.example/connect/authorize",
diff --git a/tests/integration/signin-popup-server.mjs b/tests/integration/signin-popup-server.mjs
new file mode 100644
index 00000000..8b1f8f14
--- /dev/null
+++ b/tests/integration/signin-popup-server.mjs
@@ -0,0 +1,109 @@
+// A site and an identity provider that sign in through a popup, for checking
+// a real bundle by hand or with a click driver:
+//
+// node tests/integration/signin-popup-server.mjs [delay-ms]
+//
+// Package http://localhost:8731/ and click each button, on macOS or Windows
+// (Linux keeps its previous routes). The app's page must stay where it is and
+// its title must end as shown:
+//
+// G the page opens the provider sized (TikTok's Google button)
+// "H G open=proxy | MSG http://localhost:8731 {"code":"ok","via":"g"} | G closed"
+// N the page opens a sized page of its own that redirects to the provider
+// and back (Notion's)
+// "... N open=proxy | MSG http://localhost:8731 {"code":"ok","via":"n"} | N closed"
+// F a frame of the provider opens the provider's popup, which answers the
+// frame (X's Google button)
+// "... {"frameOpen":"proxy"} ... {"frame":{"code":"frame-ok"},...} ... {"frameClosed":true}"
+//
+// Before the popups were real windows, G and N left the app on a blank
+// callback page and F did nothing. A popup that stays on screen after
+// "closed", or an app that quits, is the other half of the regression.
+//
+// Package http://localhost:8731/selfclose as well: its page calls
+// window.close() in its first script, as a callback page does. The window
+// must stay open with the title "S still here" and the app must keep running.
+import http from "node:http";
+
+const APP = 8731;
+const PROVIDER = 8732;
+const delay = Number(process.argv[2] || 3000);
+
+const appPage = `<!doctype html><meta charset=utf-8><title>H start</title>
+<style>button{display:block;width:300px;height:60px;margin:20px;font-size:18px}
+iframe{border:1px solid #999;width:340px;height:110px;margin:0 20px}</style>
+<button id=g>G provider popup</button>
+<button id=n>N own-site popup</button>
+<iframe src="http://127.0.0.1:${PROVIDER}/button"></iframe>
+<pre id=log></pre>
+<script>
+const log=[];function show(){document.title='H '+log.join(' | ');document.getElementById('log').textContent=log.join('\\n')}
+addEventListener('message',e=>{log.push('MSG '+e.origin+' '+JSON.stringify(e.data));show()});
+function watch(p,tag){log.push(tag+' open='+(p?(p===window?'self':'proxy'):'null'));show();
+ if(!p||p===window)return;const t=setInterval(()=>{if(p.closed){log.push(tag+' closed');show();clearInterval(t)}},300)}
+g.onclick=()=>watch(window.open('http://127.0.0.1:${PROVIDER}/o/oauth2/v2/auth?redirect_uri='+encodeURIComponent('http://localhost:${APP}/callback?via=g'),'g_auth_token_window','toolbar=no,width=590,height=630,top=143,left=569'),'G');
+n.onclick=()=>watch(window.open('/popup-start?via=n',' Login','toolbar=0,menubar=0,location=0,width=610,height=600,scrollbars=1'),'N');
+show();
+</script>`;
+
+const callbackPage = `<!doctype html><meta charset=utf-8><title>callback</title><script>
+const q=new URLSearchParams(location.search);
+if(window.opener){window.opener.postMessage({code:q.get('code'),via:q.get('via')},'*');window.close()}
+</script>`;
+
+const providerPage = `<!doctype html><meta charset=utf-8><title>Provider sign-in</title>
+<h1>Provider sign-in</h1><p id=s></p><script>
+const q=new URLSearchParams(location.search);
+document.getElementById('s').textContent='opener='+(window.opener?'yes':'no');
+setTimeout(()=>{if(q.get('mode')==='frame'){if(window.opener){window.opener.postMessage({code:'frame-ok'},'*')}window.close()}
+else{const u=new URL(q.get('redirect_uri'));u.searchParams.set('code','ok');location.href=u.href}},${delay});
+</script>`;
+
+const buttonPage = `<!doctype html><meta charset=utf-8><button id=f style="width:300px;height:60px;margin:20px;font-size:18px">F frame popup</button><script>
+addEventListener('message',e=>{parent.postMessage({frame:e.data,from:e.origin},'*')});
+f.onclick=()=>{const p=window.open('/o/oauth2/v2/auth?mode=frame','g_frame_window','width=500,height=600,top=100,left=100');
+ parent.postMessage({frameOpen:p?'proxy':'null'},'*');
+ if(p){const t=setInterval(()=>{if(p.closed){parent.postMessage({frameClosed:true},'*');clearInterval(t)}},300)}};
+</script>`;
+
+function send(response, body, status = 200, headers = {}) {
+ response.writeHead(status, {
+ "Content-Type": "text/html; charset=utf-8",
+ "Cache-Control": "no-store",
+ ...headers,
+ });
+ response.end(body);
+}
+
+const selfClosePage = `<!doctype html><meta charset=utf-8><title>S closing</title><script>
+window.close();
+setTimeout(()=>{document.title='S still here'},1500);
+</script><h1>This window closes itself while loading</h1>`;
+
+const routes = {
+ [APP]: {
+ "/": (response) => send(response, appPage),
+ "/popup-start": (response) =>
+ send(response, "", 302, {
+ Location: `http://127.0.0.1:${PROVIDER}/o/oauth2/v2/auth?redirect_uri=${encodeURIComponent(`http://localhost:${APP}/callback?via=n`)}`,
+ }),
+ "/callback": (response) => send(response, callbackPage),
+ "/selfclose": (response) => send(response, selfClosePage),
+ },
+ [PROVIDER]: {
+ "/o/oauth2/v2/auth": (response) => send(response, providerPage),
+ "/button": (response) => send(response, buttonPage),
+ },
+};
+
+for (const port of [APP, PROVIDER]) {
+ http
+ .createServer((request, response) => {
+ const route =
+ routes[port][new URL(request.url, "http://localhost").pathname];
+ if (route) route(response);
+ else send(response, "not found", 404);
+ })
+ .listen(port, "127.0.0.1");
+}
+console.log(`ready: package http://localhost:${APP}/`);
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
index 3f9878fe..ed503401 100644
--- a/tests/unit/event-link-guard.test.js
+++ b/tests/unit/event-link-guard.test.js
@@ -10,6 +10,8 @@ function loadEventHelpers({
downloadError = null,
nativeDownloads = false,
topWindow = null,
+ opener = null,
+ nativeClose = () => {},
} = {}) {
const source = ["link_policy.js", "event.js"]
.map((file) =>
@@ -107,6 +109,8 @@ function loadEventHelpers({
addEventListener: registerListener,
dispatchEvent: () => {},
open: () => ({}),
+ opener,
+ close: nativeClose,
isAuthLink: () => false,
isAuthPopup: () => false,
pakeConfig: {},
@@ -284,6 +288,226 @@ describe("event link guard", () => {
},
);
+ const GOOGLE_POPUP =
+ "https://accounts.google.com/o/oauth2/v2/auth?gsiwebsdk=gis_attributes&client_id=1";
+ const GOOGLE_SPECS =
+ "toolbar=no,location=no,menubar=no,resizable=no,width=590,height=830,top=143.5,left=569";
+ const loadPopupPage = (userAgent, config = {}) => {
+ const context = loadEventHelpers({ withTauri: true, userAgent });
+ context.window.pakeConfig = config;
+ context.window.isAuthPopup = (url) => url.includes("accounts.google.com");
+ const popup = { location: { href: "about:blank" }, close: vi.fn() };
+ const nativeOpen = vi.fn(() => popup);
+ context.window.open = nativeOpen;
+ runDomReady(context);
+ return { context, popup, nativeOpen };
+ };
+ const MAC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_5)";
+
+ const WINDOWS = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)";
+ const LINUX = "Mozilla/5.0 (X11; Linux x86_64)";
+
+ it.each([
+ ["macOS", MAC],
+ ["Windows", WINDOWS],
+ ])(
+ "gives a sized sign-in popup its own window and opener on %s",
+ (_platform, userAgent) => {
+ // TikTok's Google button: the page waits for this popup to answer it.
+ const { context, popup, nativeOpen } = loadPopupPage(userAgent);
+ const result = context.window.open(
+ GOOGLE_POPUP,
+ "g_auth_token_window",
+ GOOGLE_SPECS,
+ );
+ expect(result).toBe(popup);
+ expect(nativeOpen.mock.calls).toEqual([
+ ["about:blank", "g_auth_token_window", GOOGLE_SPECS],
+ ]);
+ expect(popup.location.href).toBe(GOOGLE_POPUP);
+ expect(context.window.location.href).toBe("https://example.com/app");
+ },
+ );
+
+ it("keeps Linux on its previous sign-in route until popups are checked there", () => {
+ const { context, nativeOpen } = loadPopupPage(LINUX);
+ expect(
+ context.window.open(GOOGLE_POPUP, "g_auth_token_window", GOOGLE_SPECS),
+ ).toBe(context.window);
+ expect(nativeOpen).not.toHaveBeenCalled();
+ expect(context.window.location.href).toBe(GOOGLE_POPUP);
+ });
+
+ it("judges the app's own site by its configured address in a Windows subframe", () => {
+ // WebView2 runs event.js in frames; a widget's own address is not the app.
+ const load = () => {
+ const context = loadEventHelpers({
+ withTauri: true,
+ userAgent: WINDOWS,
+ topWindow: { postMessage: () => {} },
+ });
+ context.window.pakeConfig = { url: "https://app.example.net/" };
+ const popup = { location: { href: "about:blank" }, close: vi.fn() };
+ const nativeOpen = vi.fn(() => popup);
+ context.window.open = nativeOpen;
+ runDomReady(context);
+ return { context, popup, nativeOpen };
+ };
+
+ const widget = load();
+ widget.context.window.open(
+ "https://example.com/share",
+ "share",
+ "width=600,height=400",
+ );
+ expect(widget.nativeOpen).not.toHaveBeenCalledWith(
+ "about:blank",
+ "share",
+ "width=600,height=400",
+ );
+
+ const app = load();
+ expect(
+ app.context.window.open(
+ "https://app.example.net/popup",
+ "flow",
+ "width=600,height=400",
+ ),
+ ).toBe(app.popup);
+ expect(app.nativeOpen.mock.calls).toEqual([
+ ["about:blank", "flow", "width=600,height=400"],
+ ]);
+ expect(app.popup.location.href).toBe("https://app.example.net/popup");
+ });
+
+ it("gives a sized popup of the app's own site its own window", () => {
+ // Notion's Google button opens a page of its own that redirects to Google.
+ const { context, popup, nativeOpen } = loadPopupPage(MAC);
+ const specs = "toolbar=0,menubar=0,location=0,width=610,height=700";
+ const result = context.window.open(
+ "/verifyNoPopupBlockerHtmlAndRedirect?redirectUri=x",
+ " Google",
+ specs,
+ );
+ expect(result).toBe(popup);
+ expect(nativeOpen.mock.calls).toEqual([["about:blank", " Google", specs]]);
+ expect(popup.location.href).toBe(
+ "https://example.com/verifyNoPopupBlockerHtmlAndRedirect?redirectUri=x",
+ );
+ expect(context.window.location.href).toBe("https://example.com/app");
+ });
+
+ it("leaves a sized own-site popup on the native route with new_window", () => {
+ const { context, popup, nativeOpen } = loadPopupPage(MAC, {
+ new_window: true,
+ });
+ expect(context.window.open("/compose", "compose", "width=600")).toBe(popup);
+ expect(nativeOpen.mock.calls).toEqual([
+ ["https://example.com/compose", "compose", "width=600"],
+ ]);
+ });
+
+ it.each([
+ ["no features", "oauth", undefined],
+ ["noopener", "oauth", "noopener,width=590,height=830"],
+ ["noopener after a space", "oauth", "width=590 height=830 noopener"],
+ ["a _self target", "_self", "width=590,height=830"],
+ ["a zero size", "oauth", "width=0,height=0"],
+ ["popup=no beside a size", "oauth", "popup=no,width=590,height=830"],
+ ])(
+ "keeps a macOS sign-in with %s in the current window",
+ (_case, name, specs) => {
+ const { context, nativeOpen } = loadPopupPage(MAC);
+ expect(context.window.open(GOOGLE_POPUP, name, specs)).toBe(
+ context.window,
+ );
+ expect(nativeOpen).not.toHaveBeenCalled();
+ expect(context.window.location.href).toBe(GOOGLE_POPUP);
+ },
+ );
+
+ it("falls back to the current window when the blank popup is refused", () => {
+ const { context, nativeOpen } = loadPopupPage(MAC);
+ nativeOpen.mockReturnValue(null);
+ expect(context.window.open(GOOGLE_POPUP, "oauth", GOOGLE_SPECS)).toBe(
+ context.window,
+ );
+ expect(nativeOpen.mock.calls).toEqual([
+ ["about:blank", "oauth", GOOGLE_SPECS],
+ ]);
+ expect(context.window.location.href).toBe(GOOGLE_POPUP);
+ });
+
+ it.each([
+ ["a popup", {}],
+ ["the main window", null],
+ ])(
+ "waits out the page load's IPC before %s closes itself on macOS",
+ (_case, opener) => {
+ vi.useFakeTimers();
+ try {
+ const nativeClose = vi.fn();
+ const { window } = loadEventHelpers({
+ userAgent: MAC,
+ opener,
+ nativeClose,
+ });
+ // A callback page answers its opener and closes in its first script.
+ window.close();
+ window.close();
+ expect(nativeClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(149);
+ expect(nativeClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(nativeClose).toHaveBeenCalledOnce();
+ // A close the engine refused does not swallow the next one.
+ window.close();
+ vi.advanceTimersByTime(150);
+ expect(nativeClose).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it.each([
+ ["Windows", WINDOWS],
+ ["Linux", LINUX],
+ ])("leaves window.close alone on %s", (_platform, userAgent) => {
+ const nativeClose = vi.fn();
+ const { window } = loadEventHelpers({ userAgent, opener: {}, nativeClose });
+ window.close();
+ expect(nativeClose).toHaveBeenCalledOnce();
+ });
+
+ it("leaves a frame's window.close alone on macOS", () => {
+ const nativeClose = vi.fn();
+ const { window } = loadEventHelpers({
+ userAgent: MAC,
+ nativeClose,
+ topWindow: { postMessage: () => {} },
+ });
+ window.close();
+ expect(nativeClose).toHaveBeenCalledOnce();
+ });
+
+ it("still sends a sized popup of another site to the system browser", () => {
+ const { context, nativeOpen } = loadPopupPage(MAC);
+ expect(
+ context.window.open(
+ "https://outside.example/share",
+ "share",
+ "width=600,height=400",
+ ),
+ ).toBeNull();
+ expect(nativeOpen).not.toHaveBeenCalled();
+ expect(context.invokeCalls).toContainEqual([
+ "plugin:shell|open",
+ { path: "https://outside.example/share" },
+ ]);
+ expect(context.window.location.href).toBe("https://example.com/app");
+ });
+
it.each(["https://outside.example/report", "https://example.com/report"])(
"retains the default route for a new named context: %s",
(url) => {
diff --git a/tests/unit/frame-links.test.js b/tests/unit/frame-links.test.js
index 57247d6b..2bfa1657 100644
--- a/tests/unit/frame-links.test.js
+++ b/tests/unit/frame-links.test.js
@@ -3,14 +3,15 @@ import path from "node:path";
import { runInNewContext } from "node:vm";
import { describe, expect, it, vi } from "vitest";
-function loadFrame(config = {}) {
+function loadFrame(config = {}, navigator = undefined) {
const messages = [];
- const nativeWindow = {};
+ const nativeWindow = { location: { href: "about:blank" }, close: vi.fn() };
const nativeOpen = vi.fn(() => nativeWindow);
const listeners = {};
const context = {
URL,
console,
+ ...(navigator ? { navigator } : {}),
window: {
location: { href: "https://mail.example.com/app" },
pakeConfig: { url: "https://mail.example.com/app", ...config },
@@ -93,13 +94,11 @@ describe("subframe external links", () => {
["https://outside.example/article", "_self", {}],
["https://outside.example/article", "_parent", {}],
["https://outside.example/article", "_top", {}],
- ["/message/42", "_blank", {}],
+ ["/message/42", "_blank", { new_window: true }],
["about:blank", "_blank", {}],
["", "_blank", {}],
[" #message", "_blank", {}],
- ["https://appleid.apple.com/auth/authorize", "AppleAuthentication", {}],
["about:blank", "AppleAuthentication", {}],
- ["https://accounts.google.com/o/oauth2/auth", "oauth", {}],
[
"https://outside.example/article",
"_blank",
@@ -108,7 +107,7 @@ describe("subframe external links", () => {
[
"https://outside.example/article",
"_blank",
- { internal_url_regex: "outside\\.example" },
+ { internal_url_regex: "outside\\.example", new_window: true },
],
["file:///tmp/article", "_blank", {}],
["javascript:void(0)", "_blank", {}],
@@ -123,6 +122,102 @@ describe("subframe external links", () => {
expect(frame.messages).toEqual([]);
});
+ it.each([
+ [
+ "https://accounts.google.com/o/oauth2/v2/auth?client_id=1",
+ "g_auth_token_window",
+ "toolbar=no,width=590,height=830,top=143.5,left=569",
+ {},
+ ],
+ [
+ "https://appleid.apple.com/auth/authorize",
+ "AppleAuthentication",
+ "width=400",
+ {},
+ ],
+ ["https://accounts.google.com/o/oauth2/auth", "oauth", "popup", {}],
+ ["/message/42", "_blank", "width=400", {}],
+ [
+ "https://accounts.google.com/o/oauth2/auth",
+ "oauth",
+ "width=400",
+ { new_window: true },
+ ],
+ ])(
+ "opens the sized popup %s (%s) blank and sends it to its address",
+ (url, name, specs, config) => {
+ const frame = loadFrame(config);
+ expect(frame.window.open(url, name, specs)).toBe(frame.nativeWindow);
+ expect(frame.nativeOpen).toHaveBeenCalledOnce();
+ expect(frame.nativeOpen).toHaveBeenCalledWith("about:blank", name, specs);
+ expect(frame.nativeWindow.location.href).toBe(
+ new URL(url, "https://mail.example.com/app").href,
+ );
+ expect(frame.messages).toEqual([]);
+ },
+ );
+
+ it.each([
+ ["https://accounts.google.com/o/oauth2/auth", "oauth", undefined],
+ [
+ "https://accounts.google.com/o/oauth2/auth",
+ "oauth",
+ "noopener,width=400",
+ ],
+ [
+ "https://accounts.google.com/o/oauth2/auth",
+ "oauth",
+ "width=400 noopener",
+ ],
+ ["https://accounts.google.com/o/oauth2/auth", "_top", "width=400"],
+ ["https://accounts.google.com/o/oauth2/auth", "oauth", "width=0"],
+ [
+ "https://accounts.google.com/o/oauth2/auth",
+ "oauth",
+ "popup=no,width=400",
+ ],
+ ])(
+ "leaves %s (%s, %s) on the native route when it asks for no popup window",
+ (url, name, specs) => {
+ const frame = loadFrame();
+ frame.window.open(url, name, specs);
+ expect(frame.nativeOpen).toHaveBeenCalledOnce();
+ expect(frame.nativeOpen).toHaveBeenCalledWith(url, name, specs);
+ },
+ );
+
+ it("opens a sized sign-in popup given as a URL object", () => {
+ const frame = loadFrame();
+ const url = new URL("https://accounts.google.com/o/oauth2/auth?x=1");
+ expect(frame.window.open(url, "oauth", "width = 400")).toBe(
+ frame.nativeWindow,
+ );
+ expect(frame.nativeOpen.mock.calls).toEqual([
+ ["about:blank", "oauth", "width = 400"],
+ ]);
+ expect(frame.nativeWindow.location.href).toBe(url.href);
+ });
+
+ it("keeps a Linux frame on the native route", () => {
+ const frame = loadFrame({}, { platform: "Linux x86_64" });
+ const url = "https://accounts.google.com/o/oauth2/auth";
+ frame.window.open(url, "oauth", "width=400");
+ expect(frame.nativeOpen.mock.calls).toEqual([[url, "oauth", "width=400"]]);
+ });
+
+ it("falls back to the native route when the blank popup is refused", () => {
+ const frame = loadFrame();
+ frame.nativeOpen.mockReturnValueOnce(null);
+ const url = "https://accounts.google.com/o/oauth2/auth";
+ expect(frame.window.open(url, "oauth", "width=400")).toBe(
+ frame.nativeWindow,
+ );
+ expect(frame.nativeOpen.mock.calls).toEqual([
+ ["about:blank", "oauth", "width=400"],
+ [url, "oauth", "width=400"],
+ ]);
+ });
+
it("forwards external anchors while preserving downloads and named frames", () => {
const frame = loadFrame();
const anchor = {
diff --git a/tests/unit/popup-close.test.ts b/tests/unit/popup-close.test.ts
new file mode 100644
index 00000000..07b53f48
--- /dev/null
+++ b/tests/unit/popup-close.test.ts
@@ -0,0 +1,92 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const rustRoot = path.join(process.cwd(), 'src-tauri', 'src');
+const read = (relative: string) =>
+ // A Windows checkout has CRLF line endings; the patterns below are written for LF.
+ fs.readFileSync(path.join(rustRoot, relative), 'utf8').replace(/\r\n/g, '\n');
+
+const buildWindow = () => {
+ const window = read('app/window.rs');
+ const start = window.indexOf('fn build_window(');
+ return window.slice(start, window.indexOf('\n}\n', start));
+};
+
+describe('a popup its page closes', () => {
+ it('closes on macOS, where WKWebView only tells its UI delegate', () => {
+ expect(read('app/mod.rs')).toMatch(
+ /#\[cfg\(target_os = "macos"\)\]\npub mod popup_close;/,
+ );
+ expect(buildWindow()).toMatch(
+ /#\[cfg\(target_os = "macos"\)\]\s+if page_popup \{[\s\S]+?crate::app::popup_close::install\(&popup_app, &popup_label, &webview\);/,
+ );
+
+ const close = read('app/popup_close.rs');
+ expect(close).toContain('c"webViewDidClose:"');
+ expect(close).toContain('if class.instance_method(selector).is_none() {');
+ // WebKit caches which methods a delegate answers when it is set.
+ const added = close.indexOf('class_addMethod(');
+ const reset = close.indexOf('msg_send![view, setUIDelegate: none]');
+ const restored = close.indexOf(
+ 'msg_send![view, setUIDelegate: &*delegate]',
+ );
+ expect(added).toBeGreaterThan(-1);
+ expect(reset).toBeGreaterThan(added);
+ expect(restored).toBeGreaterThan(reset);
+ });
+
+ it('leaves the main window and Cmd+N windows open on macOS', () => {
+ const close = read('app/popup_close.rs');
+ // WebKit sends webViewDidClose: for any page that calls window.close();
+ // only a webview marked as a popup has a label to close.
+ const marked = close.indexOf('objc2::ffi::objc_getAssociatedObject(');
+ const unmarked = close.indexOf('None => return,');
+ const closed = close.indexOf('if let Err(error) = window.close() {');
+ expect(marked).toBeGreaterThan(-1);
+ expect(unmarked).toBeGreaterThan(marked);
+ expect(closed).toBeGreaterThan(unmarked);
+ });
+
+ it('hides the popup at once and closes it after its page load has settled', () => {
+ const close = read('app/popup_close.rs');
+ // Destroying the web view under an IPC answer aborts the app: WebKit
+ // raises on a stopped request and the release profile cannot catch it.
+ const hidden = close.indexOf('if let Err(error) = window.hide() {');
+ const waited = close.indexOf('tokio::time::sleep(CLOSE_GRACE).await;');
+ const closed = close.indexOf('if let Err(error) = window.close() {');
+ expect(hidden).toBeGreaterThan(-1);
+ expect(waited).toBeGreaterThan(hidden);
+ expect(closed).toBeGreaterThan(waited);
+ expect(buildWindow()).toMatch(
+ /#\[cfg\(target_os = "macos"\)\]\s+let page_popup = new_window_features\.is_some\(\);/,
+ );
+ });
+
+ it('keeps page-opened popups out of the saved window sizes', () => {
+ const window = read('app/window.rs');
+ expect(window).toContain(
+ 'pub const POPUP_WINDOW_LABEL_PREFIX: &str = "pake-popup-";',
+ );
+ const start = window.indexOf('fn open_requested_window(');
+ expect(window.slice(start, window.indexOf('\n}\n', start))).toContain(
+ 'let label = state.next_popup_label();',
+ );
+ // A Cmd+N window that later takes a popup's label would open at the
+ // popup's size, and a sign-in popup would ignore the size its page asked for.
+ expect(read('lib.rs')).toContain(
+ '.with_filter(|label| !label.starts_with(app::window::POPUP_WINDOW_LABEL_PREFIX))',
+ );
+ });
+
+ it('takes its page title, since a popup that starts blank has none', () => {
+ expect(buildWindow()).toMatch(
+ /window_features\(features\)\.focused\(true\);[\s\S]{0,260}window_builder\.on_document_title_changed\(/,
+ );
+ const window = read('app/window.rs');
+ const start = window.indexOf('fn open_requested_window(');
+ const body = window.slice(start, window.indexOf('\n}\n', start));
+ expect(body).toContain('if let Some(host) = target_url.host_str() {');
+ expect(body).not.toContain('target_url.as_str()');
+ });
+});