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(macos): tighten when a page may use the runtime's passkeys
Tw931382507e007b
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.mdindex 051b315e..0b40fb09 100644--- a/.claude/rules/tauri-runtime.md+++ b/.claude/rules/tauri-runtime.md@@ -10,7 +10,7 @@ paths:- The `runtime-template` Cargo feature builds a prebuilt runtime that a separate builder customizes without a compiler: at launch it reads `pake-runtime/{pake.json, app.json, custom.js?, tray.png?}` from `Contents/Resources` on macOS or next to the executable elsewhere, and applies app.json's `identifier` and `productName` to the Tauri context before build. The CLI never enables the feature, so CLI-built apps keep their compiled configuration even if such a folder appears. A present but invalid override exits with a `[Pake]` message instead of falling back to the template's identity. A runtime app keys its WebView profile folder under the config dir (`%APPDATA%\<identifier>\EBWebView` on Windows) by identifier instead of product name (`data_dir_name`), so a rename keeps logins and a generated name cannot share another program's folder; CLI apps keep the product-name folder. On Windows a runtime app also sets the process AppUserModelID to its identifier before any window exists, so shortcuts carrying that ID group with the running window and toasts are attributed to it. Logic and tests live in `src-tauri/src/util.rs` (`apply_runtime_override`, `data_dir_name`, `set_app_user_model_id`); `PakeConfig::runtime_app` is the single runtime-app flag, and `run_app` copies the overridden identity from the returned Tauri config into the context; keep `cargo clippy` and `cargo test --lib` green both with and without `--features runtime-template`.- The app is built with `withGlobalTauri: false`: a page can read `window.__TAURI__`, and DeepSeek's front end shows "Abnormal usage environment" when `"__TAURI__" in window` holds (measured on a real bundle, 2026-11-18; its other tests are a user agent naming Tauri or Electron). Injected scripts reach the native side only through `window.__PAKE_NATIVE__` from `src-tauri/src/inject/bridge.js`, which keeps the shape they used (`core.invoke`, `shell.open` and `window.getCurrentWindow()` with the nine window commands the capability grants) over `__TAURI_INTERNALS__`; a new window call is added there with the command and argument names Tauri's own API sends, and needs its permission in the capability. Tauri decides the global API at compile time, so a prebuilt runtime cannot switch it per app: the user's own code, a bundled local page or an injected script that names `__TAURI__`, gets the name pointed at the bridge instead (`global_api_name_script` in `window.rs`): a local app only on its own `tauri:` pages, so a site it links out to stays clean, while an app with such a script shows the name to its site again. The rest of Tauri's global API (events, paths, DPI types) is gone for such code; the capability never granted a page most of it. `isTauri`, `__TAURI_INTERNALS__` and the plugins' `__TAURI_PLUGIN_*` names remain and are not configurable from a script; hiding them means patching the tauri crate, to do only when a site is shown to read them. `tests/unit/native-bridge.test.js` holds the scripts and the config to this.- A page's `alert()`, `confirm()` and `prompt()` show nothing in a WKWebView unless its UI delegate implements the three `runJavaScript…Panel` methods, and Wry's does not (through 0.57.2): `alert` returned at once, `confirm` returned false and `prompt` null in a millisecond, so a site that confirms before logging out did nothing (a user's report, 2026-11-17; WebView2 and WebKitGTK show their own). `src-tauri/src/app/script_dialogs.rs` adds the three methods to the delegate's class where it lacks them, for every webview from `build_window`, and then sets the same delegate on the webview again: WebKit records which methods a delegate answers when it is set, and without the reset the added methods are never called. Each panel is an NSAlert sheet on the page's window whose completion calls WebKit's handler exactly once (WebKit raises on zero or two calls), which keeps the script waiting as a browser does. The sheet goes on the window even when it is hidden, as a closed window is with hide-on-close: AppKit then shows the window with its sheet (measured: a window hidden with Cmd+W came back on screen when its page called `confirm()`), where an app-modal panel would float over whatever else the user is doing; only a webview with no window falls back to `runModal`. Cancel carries an explicit Escape key equivalent, because AppKit gives Escape only to a button titled Cancel and the Chinese title is 取消. Verify on a real bundle with a page that calls all three and writes what it got back: OK gives `true`, Cancel `false`, a prompt its field's text or `null`, and each wait is seconds, not a millisecond. Send the keys with a CGEvent tool of your own: Escape must give `false` and `null`, Return `true`. Cover it with `tests/unit/macos-script-dialogs.test.ts` and the `script_panel_encodings_match_their_selectors` Rust test, which keeps each selector's colons and its type encoding in step.-- Passkeys on macOS (2026-11-19): WKWebView refuses WebAuthn in an app that neither lists the site under `webcredentials` nor holds Apple's browser entitlement, which an ad hoc signed app never can, so `create` and `get` failed in 30 ms with `NotAllowedError`. `src-tauri/src/inject/passkey.js` (main frame, not incognito) hands a `publicKey` request to the `pakePasskey` `WKScriptMessageHandlerWithReply` in `src-tauri/src/app/passkey/macos.rs`, which takes the origin from WebKit's `WKFrameInfo` (main frames only, never from the page), checks the rpId against the public suffix list (`resolve_rp_id`), makes a non-permanent Secure Enclave P-256 key gated by `userPresence` (Touch ID, or the login password), keeps its token (`toid`) in `<app data>/passkeys.json`, and writes `none` attestation itself; no keychain entitlement is needed. The passkeys stay in that app on that Mac, outside iCloud Keychain; a sign-in with none shows a sheet saying so. Any process of the same user can read the store and sign after a prompt that names that process, as with Chrome's profile authenticator. One ceremony runs at a time under a token (`OWNER`); the page's abort or timeout (5 minutes when the site gives none) sends `cancel`, which counts only from the webview that started it, frees it at once, invalidates the LAContext and ends the sheet; a key made after that is not saved; a sheet left on a closed or close-hidden window (not a minimized one, nor while the app is hidden) gives way to the next request, since the sheet keeps its `Reply` alive. The credential object must read as a browser's: its fields are enumerable getters with no setter and its methods writable, one prototype step up (`shaped`), so `Object.keys` is empty, `for...in` lists the fields (FIDO's webauthn-demo serialises that way) and a page may replace a method, because GitHub's webauthn-json assigns `credential.toJSON = ...` in strict mode and a read-only property made every registration fail after the key was saved (found on github.com with a probe that reported `unhandledrejection`; GitHub's error said only "Passkey registration failed"). Verify on a real bundle: a localhost page backed by py_webauthn for register, sign-in with and without `allowCredentials`, the account picker, cancel then retry; then add and use a passkey on github.com. Cover it with the `app::passkey` Rust tests and `tests/unit/passkey-bridge.test.js`.+- Passkeys on macOS (2026-11-19): WKWebView refuses WebAuthn in an app that neither lists the site under `webcredentials` nor holds Apple's browser entitlement, which an ad hoc signed app never can, so `create` and `get` failed in 30 ms with `NotAllowedError`. `src-tauri/src/inject/passkey.js` (main frame; not incognito, nor with `ignore_certificate_errors`, where a stand-in on the network would get a signature for the real origin; `passkey::enabled`) hands a `publicKey` request to the `pakePasskey` `WKScriptMessageHandlerWithReply` in `src-tauri/src/app/passkey/macos.rs`, which takes the origin from WebKit's `WKFrameInfo` (main frames only, never from the page), checks the rpId against the public suffix list (`resolve_rp_id`), makes a non-permanent Secure Enclave P-256 key gated by `userPresence` (Touch ID, or the login password), keeps its token (`toid`) in `<app data>/passkeys.json`, and writes `none` attestation itself; no keychain entitlement is needed. The passkeys stay in that app on that Mac, outside iCloud Keychain; a sign-in with none shows a sheet saying so. Any process of the same user can read the store and sign after a prompt that names that process, as with Chrome's profile authenticator. Only the key window of the active app may start a ceremony, and a Mac without an enclave refuses without a sheet. One ceremony runs at a time under a token (`OWNER`); leaving the page (`pagehide`) cancels it like an abort; the page's abort or timeout (5 minutes when the site gives none) sends `cancel`, which counts only from the webview that started it, frees it at once, invalidates the LAContext and ends the sheet; a key made after that is not saved; a sheet left on a closed or close-hidden window (not a minimized one, nor while the app is hidden) gives way to the next request, since the sheet keeps its `Reply` alive. The credential object must read as a browser's: its fields are enumerable getters with no setter and its methods writable, one prototype step up (`shaped`), so `Object.keys` is empty, `for...in` lists the fields (FIDO's webauthn-demo serialises that way) and a page may replace a method, because GitHub's webauthn-json assigns `credential.toJSON = ...` in strict mode and a read-only property made every registration fail after the key was saved (found on github.com with a probe that reported `unhandledrejection`; GitHub's error said only "Passkey registration failed"). Verify on a real bundle: a localhost page backed by py_webauthn for register, sign-in with and without `allowCredentials`, the account picker, cancel then retry; then add and use a passkey on github.com. Cover it with the `app::passkey` Rust tests and `tests/unit/passkey-bridge.test.js`.- `navigation_buttons` is a runtime-only macOS window field (no CLI flag; the paid apps set it, off by default): `src-tauri/src/app/nav_buttons.rs` adds Back and Forward to the title bar in a leading accessory beside the traffic lights, for people with a plain mouse who have neither the swipe nor Cmd-[. The buttons call `history_step`, the native step the Navigation menu uses, so they work on a blank error page; their action lives on the window's class as `tab_bar.rs`'s does. Enabled state follows the WKWebView's `canGoBack` and `canGoForward` by key-value observing; do not poll. The webview owns the observer through an associated object, which means the observer drops only while the webview is deallocating, when a weak reference to it already reads nil: removal in `Drop` never runs, so the observer unregisters on `NSWindowWillCloseNotification`, behind one flag because removing an unregistered observer raises (`auth.rs`'s delegate still has only the `Drop` removal). Alignment is to ink, checked on a 2x capture: each chevron's middle goes on the close button's centre line, read from `standardWindowButton:` (the lights sit 16 points down a 32 point bar on macOS 26) and from the cell's `imageRectForBounds:` (NSButton sets a 16 point image half a point above a 22 point button's middle), and redone on resize and around full screen. The chevrons are drawn, not `chevron.left`, because that symbol sits on a text baseline 1.5 points high. Labels are the system's own, 返回 and 前进, 上一頁 and 下一頁, through `UiLanguage`. A real-bundle check measures the rows of the red light and of each chevron in a `screencapture -l` PNG, whose centres must be equal, and opens then closes a Cmd+N window with the app still running. Under `hide_title_bar` the buttons sit over the page beside the lights, and the per-site `immersive` paddings in `style.js` clear only the lights' width. Cover it with `tests/unit/macos-navigation-buttons.test.ts` and the `navigation_buttons_are_opt_in` Rust test.- `transparent_title_bar` is a runtime-only macOS window field (no CLI flag; the paid apps set it): Tauri's `Transparent` title bar keeps the page below the bar, and `src-tauri/src/inject/title_bar.js` paints the window background with the page's top-edge color through `set_title_bar_color`. `hide_title_bar` keeps precedence and its overlay behavior. The color is the majority of three top-edge samples, resolved through a canvas so `oklch()`/`color()` values work; do not skip sampling for `document.hidden`, or windows revealed after load stay uncolored. Cover it with `tests/unit/title-bar-color.test.js`; when checking a real bundle, window captures carry the display profile, so convert the sRGB page color before comparing pixels.- `site_styles` is a runtime-only window field (no CLI flag; default true): the paid apps write false when the app carries a browser extension that restyles its site (Minimal Theme for Twitter on X), and `style.js` then leaves out that site's `content` rules, keeping the global and `immersive` ones. On X the runtime's 700 px column, `!important` under `#react-root`, overrode the extension's own width setting. `page_config` in `window.rs` forces it back to true wherever the app's extensions do not run (no `pake-runtime/extensions`, macOS before 15.4, Linux), so a site never loses both. Covered by `site_styles_stay_on_unless_the_builder_turns_them_off`, `site_styles_turn_off_only_where_extensions_run` and `tests/unit/site-styles.test.js`.diff --git a/docs/faq.md b/docs/faq.mdindex 69e546f7..ceee3b8a 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -458,7 +458,7 @@ This is usually due to web compatibility issues. Try: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.- On macOS a Pake app keeps its own passkeys in the Mac's Secure Enclave and signs in with Touch ID, or with the login password on a Mac without it. They stay in that app on that Mac, so a passkey saved in iCloud Keychain or on an iPhone is not offered: sign in another way once, then add a passkey in the site's settings. An `--incognito` app keeps none, and signing in by scanning a QR code with a phone is not supported yet.+ On macOS a Pake app keeps its own passkeys in the Mac's Secure Enclave and signs in with Touch ID, or with the login password on a Mac without it. They stay in that app on that Mac, so a passkey saved in iCloud Keychain or on an iPhone is not offered: sign in another way once, then add a passkey in the site's settings. This needs Apple silicon or an Intel Mac with a T2 chip. An app made with `--incognito` or `--ignore-certificate-errors` keeps none, and signing in by scanning a QR code with a phone is not supported yet.5. **WeChat Web login environment error**diff --git a/docs/faq_CN.md b/docs/faq_CN.mdindex b8a774f1..20ef5dfc 100644--- a/docs/faq_CN.md+++ b/docs/faq_CN.md@@ -456,7 +456,7 @@ Pake 可以自动转换普通图片,但提供正确的格式更可靠。Icon C网站用自带尺寸的弹窗登录时(TikTok、Notion、X 上的 Google 登录,Yelp、Upwork 上的 Sign in with Apple),macOS 和 Windows 上的 Pake 会把这个弹窗开成独立窗口,登录完由它把结果交回原页面并自己关闭,开没开 `--new-window` 都一样。网站用普通链接或不带尺寸的 `window.open` 发起的登录,在 macOS 和 Linux 上仍在当前窗口内跳转,Linux 上的登录弹窗目前也都还是这样。- macOS 上的 Pake 应用会把自己的通行密钥存在这台 Mac 的安全芯片里,登录时按一下指纹就行,没有 Touch ID 的 Mac 输入登录密码。这些通行密钥只在这个应用里用,iCloud 钥匙串和 iPhone 上已有的用不了,第一次先用其他方式登录,再到网站设置里添加一个通行密钥。`--incognito` 打包的应用不保存通行密钥,用手机扫码登录暂时还不支持。+ macOS 上的 Pake 应用会把自己的通行密钥存在这台 Mac 的安全隔区里,登录时按一下指纹就行,没有 Touch ID 的 Mac 输入登录密码,需要 Apple 芯片或带 T2 芯片的 Intel Mac。这些通行密钥只在这个应用里用,iCloud 钥匙串和 iPhone 上已有的用不了,第一次先用其他方式登录,再到网站设置里添加一个通行密钥。用 `--incognito` 或 `--ignore-certificate-errors` 打包的应用不保存通行密钥,用手机扫码登录暂时还不支持。5. **微信 Web 版登录环境异常**diff --git a/src-tauri/src/app/passkey/macos.rs b/src-tauri/src/app/passkey/macos.rsindex 0302bd2e..01e4a9ff 100644--- a/src-tauri/src/app/passkey/macos.rs+++ b/src-tauri/src/app/passkey/macos.rs@@ -307,7 +307,14 @@ fn save(path: &Path, store: &Store) -> std::io::Result<()> {.open(&temporary)?;file.write_all(store.to_json().as_bytes())?;file.sync_all()?;- std::fs::rename(&temporary, path)+ std::fs::rename(&temporary, path)?;+ // The rename itself is in the folder, so a power loss right after a site+ // learned the key does not bring the old file back. Best effort: not every+ // volume flushes a folder.+ if let Some(directory) = path.parent() {+ let _ = std::fs::File::open(directory).and_then(|folder| folder.sync_all());+ }+ Ok(())}fn now() -> u64 {@@ -775,10 +782,36 @@ fn receive(}Request::Create { .. } | Request::Get { .. } => {}}+ // A Mac without an enclave makes no passkeys, so it offers none and+ // tells nobody to add one: the page goes on to its other sign-in.+ if !available() {+ return reply.fail(Failure::NotAllowed);+ }+ let window: Option<Retained<AnyObject>> = unsafe {+ let webview = webview as *mut AnyObject;+ if webview.is_null() {+ None+ } else {+ let window: *mut AnyObject = msg_send![webview, window];+ Retained::retain(window)+ }+ };+ // Only the page in front may ask, as in a browser: a hidden window or one+ // behind another app would raise Touch ID, or pull itself on screen with a+ // sheet, for a sign-in the user never started.+ let app = NSApplication::sharedApplication(mtm);+ let active: Bool = unsafe { msg_send![&*app, isActive] };+ let in_front = window.as_ref().is_some_and(|window| {+ let key: Bool = unsafe { msg_send![&**window, isKeyWindow] };+ key.as_bool()+ });+ if !active.as_bool() || !in_front {+ return reply.fail(Failure::NotAllowed);+ }// A sheet on a window that was closed (with its popup, or hidden by the// close button) would hold every later request as busy, so it gives way.// A minimized window, or any while the app is hidden, still has its sheet.- let app_hidden: Bool = unsafe { msg_send![&*NSApplication::sharedApplication(mtm), isHidden] };+ let app_hidden: Bool = unsafe { msg_send![&*app, isHidden] };if !app_hidden.as_bool() {cancel(|ceremony| {ceremony.sheet.as_ref().is_some_and(|(_, window)| {@@ -805,15 +838,6 @@ fn receive(sheet: None,})});- let window: Option<Retained<AnyObject>> = unsafe {- let webview = webview as *mut AnyObject;- if webview.is_null() {- None- } else {- let window: *mut AnyObject = msg_send![webview, window];- Retained::retain(window)- }- };match request {Request::Create { options } => create(mtm, window, store_path, origin, options, reply),Request::Get { options } => get(mtm, window, store_path, origin, options, reply),diff --git a/src-tauri/src/app/passkey/mod.rs b/src-tauri/src/app/passkey/mod.rsindex bf45bb66..16b23844 100644--- a/src-tauri/src/app/passkey/mod.rs+++ b/src-tauri/src/app/passkey/mod.rs@@ -301,6 +301,14 @@ struct RelyingParty {id: Option<String>,}+/// Whether a window gets passkeys. A private window keeps nothing between+/// runs, and one that accepts any certificate cannot tell the site from a+/// stand-in on the network, which would then get a Touch ID signature for+/// the real origin; a browser refuses WebAuthn on a certificate error too.+pub fn enabled(incognito: bool, ignores_certificate_errors: bool) -> bool {+ !incognito && !ignores_certificate_errors+}+impl CreateOptions {/// The rpId the site asked for, before it is checked.pub fn rp_id(&self) -> Option<&str> {@@ -995,4 +1003,11 @@ mod tests {assert!(title.contains("x.com") && !button.is_empty());}}++ #[test]+ fn leaves_out_private_windows_and_ones_that_accept_any_certificate() {+ assert!(enabled(false, false));+ assert!(!enabled(true, false));+ assert!(!enabled(false, true));+ }}diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 89ccbeae..a1ec1987 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -966,9 +966,11 @@ fn build_window(window_builder.initialization_script(include_str!("../inject/title_bar.js"));}- // A private window keeps nothing between runs, so it makes no passkeys either.#[cfg(target_os = "macos")]- if !window_config.incognito {+ if crate::app::passkey::enabled(+ window_config.incognito,+ window_config.ignore_certificate_errors,+ ) {window_builder = window_builder.initialization_script(include_str!("../inject/passkey.js"));}@@ -1430,7 +1432,10 @@ fn build_window(// WKWebView refuses WebAuthn in this app, so the runtime answers passkey.js itself.#[cfg(target_os = "macos")]- if !window_config.incognito {+ if crate::app::passkey::enabled(+ window_config.incognito,+ window_config.ignore_certificate_errors,+ ) {if let Ok(directory) = app.path().app_data_dir() {let store = directory.join(crate::app::passkey::STORE_FILE);if let Err(error) = window.with_webview(move |webview| {diff --git a/src-tauri/src/inject/passkey.js b/src-tauri/src/inject/passkey.jsindex 6bfca3a9..70ebcff3 100644--- a/src-tauri/src/inject/passkey.js+++ b/src-tauri/src/inject/passkey.js@@ -246,6 +246,7 @@let timer = 0;const settle = () => {if (signal) signal.removeEventListener("abort", onAbort);+ window.removeEventListener("pagehide", onHide);clearTimeout(timer);};const stop = (error) => {@@ -258,7 +259,10 @@reject(error);};const onAbort = () => stop(abortReason(signal));+ // A page that goes away mid-prompt never learns a key made after it.+ const onHide = () => stop(notAllowed());if (signal) signal.addEventListener("abort", onAbort, { once: true });+ window.addEventListener("pagehide", onHide, { once: true });timer = setTimeout(() => stop(notAllowed()), timeoutOf(timeout));call(request).then((reply) => {diff --git a/tests/unit/passkey-bridge.test.js b/tests/unit/passkey-bridge.test.jsindex 9ff353a1..37a8db1e 100644--- a/tests/unit/passkey-bridge.test.js+++ b/tests/unit/passkey-bridge.test.js@@ -43,7 +43,11 @@ function load({ reply, handler = true, top = true } = {}) {}}const posted = [];+ const page = new EventTarget();const window = {+ addEventListener: page.addEventListener.bind(page),+ removeEventListener: page.removeEventListener.bind(page),+ dispatchEvent: page.dispatchEvent.bind(page),PublicKeyCredential,CredentialsContainer,AuthenticatorAttestationResponse,@@ -283,6 +287,18 @@ describe("passkey bridge", () => {expect(posted[1].id).toBe(posted[0].id);});+ it("tells the native side to close its prompt when the page goes away", async () => {+ const { window, credentials, posted } = load({+ reply: (request) =>+ request.kind === "cancel" ? {} : new Promise(() => {}),+ });+ const pending = credentials.create(createOptions);+ window.dispatchEvent(new Event("pagehide"));+ await expect(pending).rejects.toMatchObject({ name: "NotAllowedError" });+ expect(posted.map((request) => request.kind)).toEqual(["create", "cancel"]);+ expect(posted[1].id).toBe(posted[0].id);+ });+it("gives up after the site's timeout, never below the browser's floor", async () => {vi.useFakeTimers();try {