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
feat(macos): passkeys in generated apps, behind Touch ID
Tw93c65878c377d4
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.mdindex 2691ecd6..051b315e 100644--- a/.claude/rules/tauri-runtime.md+++ b/.claude/rules/tauri-runtime.md@@ -10,6 +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`.- `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 d24c835f..69e546f7 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.- 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.+ 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.5. **WeChat Web login environment error**diff --git a/docs/faq_CN.md b/docs/faq_CN.mdindex cedab1ce..b8a774f1 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 应用用不了通行密钥和指纹登录,系统只把这项能力开放给浏览器和与网站域名绑定的应用,登录时改用密码加两步验证码。+ macOS 上的 Pake 应用会把自己的通行密钥存在这台 Mac 的安全芯片里,登录时按一下指纹就行,没有 Touch ID 的 Mac 输入登录密码。这些通行密钥只在这个应用里用,iCloud 钥匙串和 iPhone 上已有的用不了,第一次先用其他方式登录,再到网站设置里添加一个通行密钥。`--incognito` 打包的应用不保存通行密钥,用手机扫码登录暂时还不支持。5. **微信 Web 版登录环境异常**diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 5bbb3830..ff6cf189 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2816,6 +2816,7 @@ name = "pake"version = "3.19.5"dependencies = ["adblock",+ "base64 0.22.1","block2","dispatch","flate2",@@ -2824,8 +2825,10 @@ dependencies = ["objc2-app-kit","objc2-foundation","objc2-web-kit",+ "psl","serde","serde_json",+ "sha2 0.10.9","tauri","tauri-build","tauri-plugin-global-shortcut",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex c2a78a0d..1a189f55 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -20,6 +20,10 @@ tauri-build = { version = "2.7.5", features = [] }[dependencies]serde_json = "1.0.154"serde = { version = "1.0.229", features = ["derive"] }+# Passkeys (src/app/passkey): base64url, the client data hash, registrable domains.+base64 = "0.22.1"+sha2 = "0.10.9"+psl = "2.1.257"tokio = { version = "1.54.1", features = ["time", "fs"] }# Content blocking (feature `content-blocking`): Brave's filter engine, MPL-2.0.# Without single-thread its Engine is Send + Sync for the WebView2 handler.@@ -55,6 +59,7 @@ objc2-foundation = { version = "0.3", features = ["NSLocale","NSDate","NSSet",+ "NSData","NSString","NSURL","NSUUID",@@ -65,6 +70,11 @@ objc2-web-kit = { version = "0.3", default-features = false, features = ["block2","WKContentRuleList","WKContentRuleListStore",+ "WKContentWorld",+ "WKFrameInfo",+ "WKScriptMessage",+ "WKScriptMessageHandlerWithReply",+ "WKSecurityOrigin","WKUserContentController","WKWebExtension","WKWebExtensionContext",diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rsindex 32910506..2e343efa 100644--- a/src-tauri/src/app/mod.rs+++ b/src-tauri/src/app/mod.rs@@ -19,6 +19,7 @@ pub mod menu;pub mod nav_buttons;pub mod navigation;pub mod notification;+pub mod passkey;#[cfg(target_os = "macos")]pub mod popup_close;pub mod recovery;diff --git a/src-tauri/src/app/passkey/macos.rs b/src-tauri/src/app/passkey/macos.rsnew file mode 100644index 00000000..0302bd2e--- /dev/null+++ b/src-tauri/src/app/passkey/macos.rs@@ -0,0 +1,907 @@+//! The enclave, the prompts and the script message handler for passkeys on macOS.+//!+//! The handler is a `WKScriptMessageHandlerWithReply` in the page's world, so+//! the page's request arrives with WebKit's own record of the calling frame:+//! only a main frame may ask, and its security origin, not anything the page+//! says, goes into the client data the site verifies.+//!+//! The key is made with the plain Security API (`SecKeyCreateRandomKey` with+//! `kSecAttrTokenIDSecureEnclave`), which an ad hoc signed app may call+//! without any keychain entitlement as long as the key is not permanent; its+//! token (`toid`, the same blob CryptoKit's `dataRepresentation` holds) is+//! what the store keeps, and `SecKeyCreateWithData` rebuilds the key from it.+//! The key's access control asks for user presence, which is Touch ID, or the+//! login password on a Mac without it, every time it signs. Signing waits for+//! the user, so it runs off the main thread, and the page's answer goes back+//! on the main thread.++use super::{+ assertion_message, existing_text, failure_reply, finish_create, finish_get, missing_text,+ picker_labels, picker_text, plan_create, plan_get, prompt_reason, resolve_rp_id, Envelope,+ Failure, Origin, Request, Store, HANDLER_NAME,+};+use crate::util::UiLanguage;+use block2::{DynBlock, RcBlock};+use objc2::rc::{autoreleasepool, Allocated, Retained};+use objc2::runtime::{AnyClass, AnyObject, Bool, NSObject, NSObjectProtocol, Sel};+use objc2::{class, define_class, msg_send, sel, DefinedClass, MainThreadMarker, MainThreadOnly};+use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn, NSAlertSecondButtonReturn, NSApplication};+use objc2_foundation::{NSData, NSPoint, NSRect, NSSize, NSString};+use objc2_web_kit::{WKScriptMessage, WKScriptMessageHandlerWithReply, WKUserContentController};+use std::cell::{Cell, RefCell};+use std::ffi::c_void;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::OnceLock;++const ACCESS_PRIVATE_KEY_USAGE: usize = 1 << 30;+const ACCESS_USER_PRESENCE: usize = 1 << 0;+const PICKER_WIDTH: f64 = 260.0;+const PICKER_HEIGHT: f64 = 26.0;++#[link(name = "Security", kind = "framework")]+extern "C" {+ static kSecAttrKeyType: *const AnyObject;+ static kSecAttrKeyTypeECSECPrimeRandom: *const AnyObject;+ static kSecAttrKeySizeInBits: *const AnyObject;+ static kSecAttrKeyClass: *const AnyObject;+ static kSecAttrKeyClassPrivate: *const AnyObject;+ static kSecAttrTokenID: *const AnyObject;+ static kSecAttrTokenIDSecureEnclave: *const AnyObject;+ static kSecAttrIsPermanent: *const AnyObject;+ static kSecAttrAccessControl: *const AnyObject;+ static kSecAttrAccessibleWhenUnlockedThisDeviceOnly: *const AnyObject;+ static kSecPrivateKeyAttrs: *const AnyObject;+ static kSecUseAuthenticationContext: *const AnyObject;+ static kSecKeyAlgorithmECDSASignatureMessageX962SHA256: *const AnyObject;+ static kSecRandomDefault: *const c_void;++ fn SecAccessControlCreateWithFlags(+ allocator: *const c_void,+ protection: *const AnyObject,+ flags: usize,+ error: *mut *mut AnyObject,+ ) -> *mut AnyObject;+ fn SecKeyCreateRandomKey(+ parameters: *const AnyObject,+ error: *mut *mut AnyObject,+ ) -> *mut AnyObject;+ fn SecKeyCopyAttributes(key: *const AnyObject) -> *mut AnyObject;+ fn SecKeyCreateWithData(+ data: *const AnyObject,+ attributes: *const AnyObject,+ error: *mut *mut AnyObject,+ ) -> *mut AnyObject;+ fn SecKeyCopyPublicKey(key: *const AnyObject) -> *mut AnyObject;+ fn SecKeyCopyExternalRepresentation(+ key: *const AnyObject,+ error: *mut *mut AnyObject,+ ) -> *mut AnyObject;+ fn SecKeyCreateSignature(+ key: *const AnyObject,+ algorithm: *const AnyObject,+ data: *const AnyObject,+ error: *mut *mut AnyObject,+ ) -> *mut AnyObject;+ fn SecRandomCopyBytes(rnd: *const c_void, count: usize, bytes: *mut u8) -> i32;+}++#[link(name = "LocalAuthentication", kind = "framework")]+extern "C" {}++/// One ceremony at a time: the token of the one running, or 0. A second+/// request while it runs is refused; a cancel frees it at once, so the page's+/// next request is not refused while the old prompt is still closing.+static OWNER: AtomicU64 = AtomicU64::new(0);+static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);++/// A Security call's result, owned under the Create rule, or its error logged.+unsafe fn created(+ object: *mut AnyObject,+ error: *mut AnyObject,+ what: &str,+) -> Option<Retained<AnyObject>> {+ if let Some(error) = Retained::from_raw(error) {+ let code: isize = msg_send![&*error, code];+ eprintln!("[Pake] Passkey {what} failed: {code}");+ }+ Retained::from_raw(object)+}++fn dictionary(entries: &[(*const AnyObject, &AnyObject)]) -> Retained<AnyObject> {+ unsafe {+ let dictionary: Retained<AnyObject> = msg_send![class!(NSMutableDictionary), new];+ for (key, value) in entries {+ let _: () = msg_send![&*dictionary, setObject: *value, forKey: *key];+ }+ dictionary+ }+}++fn data_bytes(data: &AnyObject) -> Vec<u8> {+ unsafe {+ let length: usize = msg_send![data, length];+ let bytes: *const u8 = msg_send![data, bytes];+ if bytes.is_null() || length == 0 {+ return Vec::new();+ }+ std::slice::from_raw_parts(bytes, length).to_vec()+ }+}++fn number(value: i32) -> Retained<AnyObject> {+ unsafe { msg_send![class!(NSNumber), numberWithInt: value] }+}++fn boolean(value: bool) -> Retained<AnyObject> {+ unsafe { msg_send![class!(NSNumber), numberWithBool: Bool::new(value)] }+}++/// A new enclave key that signs only after user presence, when `present` holds.+fn new_key(present: bool) -> Option<Retained<AnyObject>> {+ unsafe {+ let flags = ACCESS_PRIVATE_KEY_USAGE | if present { ACCESS_USER_PRESENCE } else { 0 };+ let mut error: *mut AnyObject = std::ptr::null_mut();+ let access = SecAccessControlCreateWithFlags(+ std::ptr::null(),+ kSecAttrAccessibleWhenUnlockedThisDeviceOnly,+ flags,+ &mut error,+ );+ let access = created(access, error, "access control")?;+ let private = dictionary(&[+ (kSecAttrIsPermanent, &boolean(false)),+ (kSecAttrAccessControl, &access),+ ]);+ let parameters = dictionary(&[+ (kSecAttrKeyType, &*kSecAttrKeyTypeECSECPrimeRandom),+ (kSecAttrKeySizeInBits, &number(256)),+ (kSecAttrTokenID, &*kSecAttrTokenIDSecureEnclave),+ (kSecPrivateKeyAttrs, &private),+ ]);+ let mut error: *mut AnyObject = std::ptr::null_mut();+ let key = SecKeyCreateRandomKey(Retained::as_ptr(¶meters), &mut error);+ created(key, error, "key creation")+ }+}++/// Whether this Mac has an enclave that will make a key, asked once.+fn available() -> bool {+ static AVAILABLE: OnceLock<bool> = OnceLock::new();+ *AVAILABLE.get_or_init(|| autoreleasepool(|_| new_key(false).is_some()))+}++/// The enclave's token for `key`, which is what the store keeps.+fn key_token(key: &AnyObject) -> Option<Vec<u8>> {+ unsafe {+ let attributes = Retained::from_raw(SecKeyCopyAttributes(key))?;+ let name = NSString::from_str("toid");+ let token: *mut AnyObject = msg_send![&*attributes, objectForKey: &*name];+ token+ .as_ref()+ .map(data_bytes)+ .filter(|token| !token.is_empty())+ }+}++/// `04 || x || y` for the public half of `key`.+fn public_point(key: &AnyObject) -> Option<Vec<u8>> {+ unsafe {+ let public = Retained::from_raw(SecKeyCopyPublicKey(key))?;+ let mut error: *mut AnyObject = std::ptr::null_mut();+ let data = SecKeyCopyExternalRepresentation(Retained::as_ptr(&public), &mut error);+ let data = created(data, error, "public key export")?;+ Some(data_bytes(&data))+ }+}++/// A Touch ID context whose prompt reads "<App> is trying to <reason>.". Made+/// on the main thread so a cancel there can `invalidate` it, which ends the+/// prompt and fails the signature waiting on it.+fn new_context(reason: &str) -> Option<Retained<AnyObject>> {+ let class = AnyClass::get(c"LAContext")?;+ unsafe {+ let context: Option<Retained<AnyObject>> = msg_send![class, new];+ let context = context?;+ let reason = NSString::from_str(reason);+ let _: () = msg_send![&*context, setLocalizedReason: &*reason];+ Some(context)+ }+}++/// An Objective-C object handed to the signing thread.+struct Shared(Retained<AnyObject>);++// SAFETY: LAContext may be evaluated and invalidated from any thread.+unsafe impl Send for Shared {}++/// Sign `message` with the key behind `token`, after Touch ID or the login+/// password through `context`.+fn sign(token: &[u8], context: &AnyObject, message: &[u8]) -> Result<Vec<u8>, Failure> {+ autoreleasepool(|_| unsafe {+ let token = NSData::with_bytes(token);+ let toid = NSString::from_str("toid");+ let attributes = dictionary(&[+ (kSecAttrKeyType, &*kSecAttrKeyTypeECSECPrimeRandom),+ (kSecAttrKeyClass, &*kSecAttrKeyClassPrivate),+ (kSecAttrTokenID, &*kSecAttrTokenIDSecureEnclave),+ (Retained::as_ptr(&toid) as *const AnyObject, &token),+ (kSecUseAuthenticationContext, context),+ ]);+ let empty = NSData::new();+ let mut error: *mut AnyObject = std::ptr::null_mut();+ let key = SecKeyCreateWithData(+ Retained::as_ptr(&empty) as *const AnyObject,+ Retained::as_ptr(&attributes),+ &mut error,+ );+ let key = created(key, error, "key rebuild").ok_or(Failure::NotAllowed)?;+ let message = NSData::with_bytes(message);+ let mut error: *mut AnyObject = std::ptr::null_mut();+ let signature = SecKeyCreateSignature(+ Retained::as_ptr(&key),+ kSecKeyAlgorithmECDSASignatureMessageX962SHA256,+ Retained::as_ptr(&message) as *const AnyObject,+ &mut error,+ );+ // A cancelled prompt lands here too: the page gets NotAllowedError, as in a browser.+ let signature = created(signature, error, "signature").ok_or(Failure::NotAllowed)?;+ Ok(data_bytes(&signature))+ })+}++fn random_id() -> Option<Vec<u8>> {+ let mut id = vec![0u8; 16];+ let status = unsafe { SecRandomCopyBytes(kSecRandomDefault, id.len(), id.as_mut_ptr()) };+ (status == 0).then_some(id)+}++/// A new passkey: its credential id, its public key as `04 || x || y` and its enclave token.+struct Made {+ id: Vec<u8>,+ point: Vec<u8>,+ token: Vec<u8>,+}++/// A new passkey, once the user approved it through `context`.+fn make_passkey(context: &AnyObject, client_data: &[u8]) -> Result<Made, Failure> {+ let (point, token) = autoreleasepool(|_| {+ let key = new_key(true)?;+ Some((public_point(&key)?, key_token(&key)?))+ })+ .ok_or(Failure::NotAllowed)?;+ // Making the key asks nothing; signing once with it asks for Touch ID, so+ // the passkey exists only if the user agreed, and the site's UV flag is true.+ sign(&token, context, client_data)?;+ let id = random_id().ok_or(Failure::NotAllowed)?;+ Ok(Made { id, point, token })+}++/// The store, or `Err` when a file is there but cannot be read: the file is+/// the only copy of every passkey's token, so nothing may be saved over it then.+fn load(path: &Path) -> Result<Store, ()> {+ match std::fs::read_to_string(path) {+ Ok(text) => Store::parse(&text).ok_or_else(|| {+ eprintln!("[Pake] The passkey store could not be parsed");+ }),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Store::default()),+ Err(error) => {+ eprintln!("[Pake] The passkey store could not be read: {error}");+ Err(())+ }+ }+}++fn save(path: &Path, store: &Store) -> std::io::Result<()> {+ use std::io::Write;+ use std::os::unix::fs::OpenOptionsExt;+ if let Some(directory) = path.parent() {+ std::fs::create_dir_all(directory)?;+ }+ let temporary = path.with_extension("json.tmp");+ let mut file = std::fs::OpenOptions::new()+ .write(true)+ .create(true)+ .truncate(true)+ .mode(0o600)+ .open(&temporary)?;+ file.write_all(store.to_json().as_bytes())?;+ file.sync_all()?;+ std::fs::rename(&temporary, path)+}++fn now() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|elapsed| elapsed.as_secs())+ .unwrap_or_default()+}++/// The ceremony in progress, so a cancel from the page can end it: the id the+/// page sent it under and its webview (ids restart in every page, so a cancel+/// counts only from the same webview), the Touch ID context while one is up,+/// and the sheet while one is shown.+struct Ceremony {+ id: u64,+ webview: usize,+ token: u64,+ context: Option<Retained<AnyObject>>,+ sheet: Option<(Retained<NSAlert>, Retained<AnyObject>)>,+}++thread_local! {+ static CURRENT: RefCell<Option<Ceremony>> = const { RefCell::new(None) };+}++/// Update the running ceremony, only if it is still the one holding `token`.+fn with_current(token: u64, update: impl FnOnce(&mut Ceremony)) {+ CURRENT.with(|current| {+ if let Some(ceremony) = current.borrow_mut().as_mut().filter(|c| c.token == token) {+ update(ceremony);+ }+ });+}++/// Whether `token` still names the running ceremony, which a cancel ends.+fn is_current(token: u64) -> bool {+ CURRENT.with(|current| {+ current+ .borrow()+ .as_ref()+ .is_some_and(|ceremony| ceremony.token == token)+ })+}++/// End the running ceremony if `matches` says so, and free it at once. The+/// handles are taken out first: ending a sheet runs its completion, which+/// replies and clears `CURRENT`.+fn cancel(matches: impl FnOnce(&Ceremony) -> bool) {+ let Some(ceremony) = CURRENT.with(|current| {+ let mut current = current.borrow_mut();+ if current.as_ref().is_some_and(matches) {+ current.take()+ } else {+ None+ }+ }) else {+ return;+ };+ let _ = OWNER.compare_exchange(ceremony.token, 0, Ordering::SeqCst, Ordering::SeqCst);+ let (context, sheet) = (ceremony.context, ceremony.sheet);+ if let Some(context) = context {+ let _: () = unsafe { msg_send![&*context, invalidate] };+ }+ if let Some((alert, window)) = sheet {+ let sheet_window = alert.window();+ let _: () = unsafe {+ msg_send![&*window, endSheet: &*sheet_window, returnCode: NSAlertSecondButtonReturn]+ };+ }+}++/// WebKit's reply handler, answered at most once on the main thread. `token`+/// is the ceremony this request runs, 0 for one that runs none, and only that+/// ceremony is freed when it answers. A reply dropped unanswered (a panic in+/// the worker) still frees it; WebKit then rejects the page's promise itself.+/// A sheet keeps its reply alive, so one left on a window that is gone is+/// reclaimed by the next request instead (`receive`).+struct Reply {+ block: Option<RcBlock<dyn Fn(*mut AnyObject, *mut NSString)>>,+ token: u64,+}++// SAFETY: the block is only called on the main thread: `off_main` hands it back there.+unsafe impl Send for Reply {}++impl Reply {+ fn release(&mut self) {+ let token = std::mem::take(&mut self.token);+ if token == 0 {+ return;+ }+ let _ = OWNER.compare_exchange(token, 0, Ordering::SeqCst, Ordering::SeqCst);+ if MainThreadMarker::new().is_some() {+ CURRENT.with(|current| {+ let mut current = current.borrow_mut();+ if current+ .as_ref()+ .is_some_and(|ceremony| ceremony.token == token)+ {+ *current = None;+ }+ });+ }+ }++ fn send(mut self, text: String) {+ self.release();+ if let Some(block) = self.block.take() {+ let text = NSString::from_str(&text);+ block.call((+ Retained::as_ptr(&text) as *mut AnyObject,+ std::ptr::null_mut(),+ ));+ }+ }++ fn fail(self, failure: Failure) {+ self.send(failure_reply(failure, ""));+ }+}++impl Drop for Reply {+ fn drop(&mut self) {+ self.release();+ }+}++/// Run `work` off the main thread and give its result to `then` back on it; a+/// panic in `work` arrives as a refusal, so the page is still answered.+fn off_main<T: Send + 'static>(+ work: impl FnOnce() -> Result<T, Failure> + Send + 'static,+ then: impl FnOnce(Result<T, Failure>) + Send + 'static,+) {+ std::thread::spawn(move || {+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work))+ .unwrap_or(Err(Failure::NotAllowed));+ dispatch::Queue::main().exec_async(move || then(result));+ });+}++/// A sheet on `window`, or an app-modal panel when there is none; `done` gets+/// whether the first button was pressed. A sheet is recorded so a cancel can end it.+fn present(+ token: u64,+ alert: Retained<NSAlert>,+ window: Option<Retained<AnyObject>>,+ done: Box<dyn FnOnce(bool)>,+) {+ let done = Cell::new(Some(done));+ let shown = alert.clone();+ let answer = RcBlock::new(move |response: isize| {+ let _ = &shown;+ with_current(token, |ceremony| ceremony.sheet = None);+ if let Some(done) = done.take() {+ done(response == NSAlertFirstButtonReturn);+ }+ });+ match window {+ Some(window) => unsafe {+ with_current(token, |ceremony| {+ ceremony.sheet = Some((alert.clone(), window.clone()))+ });+ let _: () =+ msg_send![&*alert, beginSheetModalForWindow: &*window, completionHandler: &*answer];+ },+ None => {+ let response = alert.runModal();+ answer.call((response,));+ }+ }+}++/// A notice with one button; the page gets `failure` once it is dismissed.+fn notice(+ mtm: MainThreadMarker,+ window: Option<Retained<AnyObject>>,+ title: &str,+ line: Option<&str>,+ button: &str,+ reply: Reply,+ failure: Failure,+) {+ let alert = NSAlert::new(mtm);+ alert.setMessageText(&NSString::from_str(title));+ if let Some(line) = line {+ alert.setInformativeText(&NSString::from_str(line));+ }+ alert.addButtonWithTitle(&NSString::from_str(button));+ present(+ reply.token,+ alert,+ window,+ Box::new(move |_| reply.fail(failure)),+ );+}++/// A saved day and time in the user's own format, for telling two accounts apart.+fn saved_at(created: u64) -> String {+ unsafe {+ let formatter: Retained<AnyObject> = msg_send![class!(NSDateFormatter), new];+ let _: () = msg_send![&*formatter, setDateStyle: 2usize];+ let _: () = msg_send![&*formatter, setTimeStyle: 1usize];+ let date: Retained<AnyObject> =+ msg_send![class!(NSDate), dateWithTimeIntervalSince1970: created as f64];+ let text: Retained<NSString> = msg_send![&*formatter, stringFromDate: &*date];+ text.to_string()+ }+}++fn pick(+ token: u64,+ mtm: MainThreadMarker,+ window: Option<Retained<AnyObject>>,+ rp_id: &str,+ candidates: &[super::Passkey],+ done: Box<dyn FnOnce(Option<usize>)>,+) {+ let (title, accept, cancel) = picker_text(rp_id, UiLanguage::system());+ let alert = NSAlert::new(mtm);+ alert.setMessageText(&NSString::from_str(&title));+ let popup: Retained<AnyObject> = unsafe {+ let allocated: Allocated<AnyObject> = msg_send![class!(NSPopUpButton), alloc];+ let frame = NSRect::new(+ NSPoint::new(0.0, 0.0),+ NSSize::new(PICKER_WIDTH, PICKER_HEIGHT),+ );+ msg_send![allocated, initWithFrame: frame, pullsDown: Bool::NO]+ };+ // Through the menu, which keeps items that read the same (the button's own+ // `addItemWithTitle:` drops them), each tagged with its candidate's index.+ let menu: Retained<AnyObject> = unsafe { msg_send![&*popup, menu] };+ let empty = NSString::new();+ for (index, label) in picker_labels(candidates, saved_at).iter().enumerate() {+ let label = NSString::from_str(label);+ unsafe {+ let item: Retained<AnyObject> = msg_send![+ &*menu,+ addItemWithTitle: &*label,+ action: None::<Sel>,+ keyEquivalent: &*empty+ ];+ let _: () = msg_send![&*item, setTag: index as isize];+ }+ }+ let _: () = unsafe { msg_send![&*popup, selectItemAtIndex: 0isize] };+ let _: () = unsafe { msg_send![&*alert, setAccessoryView: &*popup] };+ alert.addButtonWithTitle(&NSString::from_str(accept));+ let cancel = alert.addButtonWithTitle(&NSString::from_str(cancel));+ // AppKit gives Escape only to a button titled Cancel, which a translated title is not.+ cancel.setKeyEquivalent(&NSString::from_str("\u{1b}"));+ let chosen = popup.clone();+ let count = candidates.len();+ present(+ token,+ alert,+ window,+ Box::new(move |accepted| {+ let item: Option<Retained<AnyObject>> = unsafe { msg_send![&*chosen, selectedItem] };+ let index = item.map(|item| {+ let tag: isize = unsafe { msg_send![&*item, tag] };+ tag+ });+ let index = index+ .filter(|_| accepted)+ .and_then(|tag| usize::try_from(tag).ok())+ .filter(|&index| index < count);+ done(index);+ }),+ );+}++fn create(+ mtm: MainThreadMarker,+ window: Option<Retained<AnyObject>>,+ store_path: PathBuf,+ origin: Origin,+ options: super::CreateOptions,+ reply: Reply,+) {+ let Ok(store) = load(&store_path) else {+ return reply.fail(Failure::NotAllowed);+ };+ let asked = options.rp_id().map(str::to_owned);+ let plan = match plan_create(&origin, options, &store) {+ Ok(plan) => plan,+ Err(Failure::InvalidState) => {+ // The spec has the user agree before the site learns this, so a+ // page cannot probe which passkeys the app holds without a click.+ let rp_id = resolve_rp_id(&origin, asked.as_deref()).unwrap_or_default();+ let (title, button) = existing_text(&rp_id, UiLanguage::system());+ return notice(+ mtm,+ window,+ &title,+ None,+ button,+ reply,+ Failure::InvalidState,+ );+ }+ Err(failure) => return reply.fail(failure),+ };+ let reason = prompt_reason(true, &plan.rp_id, UiLanguage::system());+ let Some(context) = new_context(&reason) else {+ return reply.fail(Failure::NotAllowed);+ };+ with_current(reply.token, |ceremony| {+ ceremony.context = Some(context.clone())+ });+ let context = Shared(context);+ let client_data = plan.client_data.clone();+ off_main(+ move || {+ let context = context;+ make_passkey(&context.0, &client_data)+ },+ move |made| {+ let made = match made {+ Ok(made) => made,+ Err(failure) => return reply.fail(failure),+ };+ // Touch ID can pass just as the page gives up; the site then never+ // learns this key, so it is not kept to be offered later.+ if !is_current(reply.token) {+ return reply.fail(Failure::NotAllowed);+ }+ let Some((passkey, answer)) =+ finish_create(&plan, &made.id, &made.point, &made.token, now())+ else {+ return reply.fail(Failure::NotAllowed);+ };+ let Ok(mut store) = load(&store_path) else {+ return reply.fail(Failure::NotAllowed);+ };+ store.upsert(passkey);+ match save(&store_path, &store) {+ Ok(()) => reply.send(answer),+ Err(error) => {+ eprintln!("[Pake] Failed to save a passkey: {error}");+ reply.fail(Failure::NotAllowed);+ }+ }+ },+ );+}++fn sign_in(plan: super::GetPlan, index: usize, reply: Reply) {+ let passkey = plan.candidates[index].clone();+ let Some(token) = passkey.key_token() else {+ return reply.fail(Failure::NotAllowed);+ };+ let reason = prompt_reason(false, &plan.rp_id, UiLanguage::system());+ let Some(context) = new_context(&reason) else {+ return reply.fail(Failure::NotAllowed);+ };+ with_current(reply.token, |ceremony| {+ ceremony.context = Some(context.clone())+ });+ let context = Shared(context);+ let message = assertion_message(&plan);+ off_main(+ move || {+ let context = context;+ sign(&token, &context.0, &message)+ },+ move |signed| match signed {+ Ok(signature) => reply.send(finish_get(&plan, &passkey, &signature)),+ Err(failure) => reply.fail(failure),+ },+ );+}++fn get(+ mtm: MainThreadMarker,+ window: Option<Retained<AnyObject>>,+ store_path: PathBuf,+ origin: Origin,+ options: super::GetOptions,+ reply: Reply,+) {+ // An unreadable store is left as it is (load logged it): saying there is+ // no passkey would send the user to add one, which create then refuses.+ let Ok(store) = load(&store_path) else {+ return reply.fail(Failure::NotAllowed);+ };+ let plan = match plan_get(&origin, options, &store) {+ Ok(plan) => plan,+ Err(failure) => return reply.fail(failure),+ };+ match plan.candidates.len() {+ 0 => {+ let (title, line, button) = missing_text(&plan.rp_id, UiLanguage::system());+ notice(+ mtm,+ window,+ &title,+ Some(line),+ button,+ reply,+ Failure::NotAllowed,+ );+ }+ 1 => sign_in(plan, 0, reply),+ _ => {+ let rp_id = plan.rp_id.clone();+ let candidates = plan.candidates.clone();+ pick(+ reply.token,+ mtm,+ window,+ &rp_id,+ &candidates,+ Box::new(move |choice| match choice {+ Some(index) => sign_in(plan, index, reply),+ None => reply.fail(Failure::NotAllowed),+ }),+ );+ }+ }+}++/// The calling frame's origin, only for a main frame.+fn main_frame_origin(message: &WKScriptMessage) -> Option<Origin> {+ unsafe {+ let frame = message.frameInfo();+ if !frame.isMainFrame() {+ return None;+ }+ let origin = frame.securityOrigin();+ let port = origin.port();+ Some(Origin {+ scheme: origin.protocol().to_string().to_ascii_lowercase(),+ host: origin.host().to_string(),+ port: u16::try_from(port).unwrap_or(0),+ })+ }+}++fn receive(+ mtm: MainThreadMarker,+ store_path: PathBuf,+ message: &WKScriptMessage,+ mut reply: Reply,+) {+ let body = unsafe { message.body() };+ let Some(Envelope { id, request }) = body+ .downcast_ref::<NSString>()+ .and_then(|text| serde_json::from_str::<Envelope>(&text.to_string()).ok())+ else {+ return reply.fail(Failure::Type);+ };+ let Some(origin) = main_frame_origin(message) else {+ return reply.fail(Failure::NotAllowed);+ };+ let webview: *mut AnyObject = unsafe { msg_send![message, webView] };+ let webview = webview as usize;+ match request {+ Request::Available => {+ let available = available();+ return reply.send(serde_json::json!({ "available": available }).to_string());+ }+ Request::Cancel => {+ cancel(|ceremony| ceremony.id == id && ceremony.webview == webview);+ return reply.send("{}".to_owned());+ }+ Request::Create { .. } | Request::Get { .. } => {}+ }+ // 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] };+ if !app_hidden.as_bool() {+ cancel(|ceremony| {+ ceremony.sheet.as_ref().is_some_and(|(_, window)| {+ let visible: Bool = unsafe { msg_send![&**window, isVisible] };+ let minimized: Bool = unsafe { msg_send![&**window, isMiniaturized] };+ !visible.as_bool() && !minimized.as_bool()+ })+ });+ }+ let token = NEXT_TOKEN.fetch_add(1, Ordering::SeqCst);+ if OWNER+ .compare_exchange(0, token, Ordering::SeqCst, Ordering::SeqCst)+ .is_err()+ {+ return reply.fail(Failure::NotAllowed);+ }+ reply.token = token;+ CURRENT.with(|current| {+ *current.borrow_mut() = Some(Ceremony {+ id,+ webview,+ token,+ context: None,+ 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),+ Request::Available | Request::Cancel => {}+ }+}++struct HandlerIvars {+ store: PathBuf,+}++define_class!(+ // SAFETY: NSObject has no subclassing requirements and the handler has no Drop.+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "PakePasskeyHandler"]+ #[ivars = HandlerIvars]+ struct PasskeyHandler;++ unsafe impl NSObjectProtocol for PasskeyHandler {}++ unsafe impl WKScriptMessageHandlerWithReply for PasskeyHandler {+ #[unsafe(method(userContentController:didReceiveScriptMessage:replyHandler:))]+ fn did_receive(+ &self,+ _controller: &WKUserContentController,+ message: &WKScriptMessage,+ reply: &DynBlock<dyn Fn(*mut AnyObject, *mut NSString)>,+ ) {+ let Some(reply) =+ (unsafe { RcBlock::copy(reply as *const DynBlock<_> as *mut DynBlock<_>) })+ else {+ return;+ };+ let reply = Reply {+ block: Some(reply),+ token: 0,+ };+ receive(self.mtm(), self.ivars().store.clone(), message, reply);+ }+ }+);++impl PasskeyHandler {+ fn new(mtm: MainThreadMarker, store: PathBuf) -> Retained<Self> {+ let this = mtm+ .alloc::<PasskeyHandler>()+ .set_ivars(HandlerIvars { store });+ unsafe { msg_send![super(this), init] }+ }+}++/// Answer `passkey.js` in this webview, keeping the passkeys at `store`.+/// A popup may share its opener's content controller, so a handler already+/// there is replaced rather than added twice, which WebKit refuses with an exception.+pub fn install(webview: &tauri::webview::PlatformWebview, store: PathBuf) {+ let Some(mtm) = MainThreadMarker::new() else {+ return;+ };+ let view = webview.inner() as *mut AnyObject;+ if view.is_null() {+ return;+ }+ // SAFETY: Tauri runs this on the main thread with the live WKWebView.+ unsafe {+ let configuration: *mut AnyObject = msg_send![view, configuration];+ let controller: *mut AnyObject = msg_send![configuration, userContentController];+ if controller.is_null() {+ return;+ }+ let add: Sel = sel!(addScriptMessageHandlerWithReply:contentWorld:name:);+ let responds: bool = msg_send![controller, respondsToSelector: add];+ let Some(world_class) = AnyClass::get(c"WKContentWorld") else {+ return;+ };+ if !responds {+ return;+ }+ let world: *mut AnyObject = msg_send![world_class, pageWorld];+ let name = NSString::from_str(HANDLER_NAME);+ let _: () =+ msg_send![controller, removeScriptMessageHandlerForName: &*name, contentWorld: world];+ let handler = PasskeyHandler::new(mtm, store);+ let _: () = msg_send![+ controller,+ addScriptMessageHandlerWithReply: &*handler,+ contentWorld: world,+ name: &*name+ ];+ }+}diff --git a/src-tauri/src/app/passkey/mod.rs b/src-tauri/src/app/passkey/mod.rsnew file mode 100644index 00000000..bf45bb66--- /dev/null+++ b/src-tauri/src/app/passkey/mod.rs@@ -0,0 +1,998 @@+//! Passkeys for pages in a macOS app, kept in the Mac's Secure Enclave behind Touch ID.+//!+//! WKWebView runs WebAuthn only for a site the app lists under `webcredentials`+//! or in an app Apple grants its browser entitlement, and a Pake app has+//! neither: `navigator.credentials.create` and `get` fail at once with+//! `NotAllowedError`. So the runtime answers them itself, as Chrome's own+//! Touch ID authenticator does beside iCloud Keychain: `passkey.js` hands the+//! page's request to a script message handler, which takes the page's origin+//! from WebKit, never from the page, makes or uses a P-256 key in the Secure+//! Enclave that only Touch ID or the login password unlocks, and writes the+//! authenticator data and `none` attestation itself.+//!+//! The passkeys stay on this Mac and in this app, outside iCloud Keychain, so a+//! passkey kept on an iPhone is not offered. Each is a record in the app's data+//! folder whose key only this Mac's enclave can use.+//!+//! This file holds what does not touch the system, so it is tested everywhere;+//! `macos.rs` holds the enclave, the prompts and the handler.++#![cfg_attr(not(target_os = "macos"), allow(dead_code))]++#[cfg(target_os = "macos")]+mod macos;+#[cfg(target_os = "macos")]+pub use macos::install;++use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};+use base64::Engine;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};++use crate::util::UiLanguage;++/// The name the page script posts to.+pub const HANDLER_NAME: &str = "pakePasskey";+/// The store inside the app's data folder.+pub const STORE_FILE: &str = "passkeys.json";+/// ES256, the one algorithm the Secure Enclave signs with.+const ES256: i64 = -7;+/// User presence and user verification: Touch ID or the login password ran.+const FLAGS_UP_UV: u8 = 0x05;+/// Attested credential data follows the counter.+const FLAG_AT: u8 = 0x40;+/// A user handle is at most 64 bytes.+const MAX_USER_HANDLE: usize = 64;+/// The DER prefix of a P-256 SubjectPublicKeyInfo, before the 65-byte point.+const P256_SPKI_PREFIX: [u8; 26] = [+ 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,+ 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,+];++/// The DOMException a request ends with, as the page script raises it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Failure {+ NotAllowed,+ Security,+ InvalidState,+ NotSupported,+ Type,+}++impl Failure {+ pub fn name(self) -> &'static str {+ match self {+ Failure::NotAllowed => "NotAllowedError",+ Failure::Security => "SecurityError",+ Failure::InvalidState => "InvalidStateError",+ Failure::NotSupported => "NotSupportedError",+ Failure::Type => "TypeError",+ }+ }+}++pub fn failure_reply(failure: Failure, message: &str) -> String {+ serde_json::json!({ "error": failure.name(), "message": message }).to_string()+}++pub fn b64url(bytes: &[u8]) -> String {+ URL_SAFE_NO_PAD.encode(bytes)+}++pub fn from_b64url(text: &str) -> Option<Vec<u8>> {+ URL_SAFE_NO_PAD.decode(text.trim_end_matches('=')).ok()+}++fn sha256(bytes: &[u8]) -> [u8; 32] {+ Sha256::digest(bytes).into()+}++/// The page's origin as WebKit reports it for the calling frame.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Origin {+ pub scheme: String,+ pub host: String,+ /// 0 for the scheme's default port.+ pub port: u16,+}++impl Origin {+ pub fn serialized(&self) -> String {+ if self.port == 0 {+ format!("{}://{}", self.scheme, self.host)+ } else {+ format!("{}://{}:{}", self.scheme, self.host, self.port)+ }+ }++ /// A secure context, as WebAuthn requires: https, or http on this machine.+ fn is_secure(&self) -> bool {+ match self.scheme.as_str() {+ "https" => !self.host.is_empty(),+ "http" => {+ matches!(self.host.as_str(), "localhost" | "127.0.0.1" | "[::1]")+ || self.host.ends_with(".localhost")+ }+ _ => false,+ }+ }+}++/// The relying party a request may use: the origin's host, or a parent of it+/// that is still a registrable domain, so `accounts.google.com` may ask for+/// `google.com` and nobody may ask for `co.uk` or `github.io`.+pub fn resolve_rp_id(origin: &Origin, requested: Option<&str>) -> Result<String, Failure> {+ if !origin.is_secure() {+ return Err(Failure::Security);+ }+ let host = origin.host.to_ascii_lowercase();+ let Some(requested) = requested else {+ return Ok(host);+ };+ // An empty id is not a domain, as a browser reads it, not a missing one.+ if requested.is_empty() {+ return Err(Failure::Security);+ }+ let requested = requested.to_ascii_lowercase();+ if requested == host {+ return Ok(requested);+ }+ let is_parent = host+ .strip_suffix(&requested)+ .is_some_and(|rest| rest.ends_with('.'));+ if is_parent && psl::domain_str(&requested).is_some() {+ Ok(requested)+ } else {+ Err(Failure::Security)+ }+}++/// The CBOR shapes WebAuthn's authenticator data and attestation use.+enum Cbor {+ Uint(u64),+ /// A negative integer, by its value.+ Nint(i64),+ Bytes(Vec<u8>),+ Text(&'static str),+ Map(Vec<(Cbor, Cbor)>),+}++fn cbor_head(out: &mut Vec<u8>, major: u8, value: u64) {+ let major = major << 5;+ match value {+ 0..=23 => out.push(major | value as u8),+ 24..=0xff => out.extend([major | 24, value as u8]),+ 0x100..=0xffff => {+ out.push(major | 25);+ out.extend((value as u16).to_be_bytes());+ }+ 0x1_0000..=0xffff_ffff => {+ out.push(major | 26);+ out.extend((value as u32).to_be_bytes());+ }+ _ => {+ out.push(major | 27);+ out.extend(value.to_be_bytes());+ }+ }+}++fn cbor(value: &Cbor, out: &mut Vec<u8>) {+ match value {+ Cbor::Uint(value) => cbor_head(out, 0, *value),+ Cbor::Nint(value) => cbor_head(out, 1, (-1 - value) as u64),+ Cbor::Bytes(bytes) => {+ cbor_head(out, 2, bytes.len() as u64);+ out.extend(bytes);+ }+ Cbor::Text(text) => {+ cbor_head(out, 3, text.len() as u64);+ out.extend(text.as_bytes());+ }+ Cbor::Map(entries) => {+ cbor_head(out, 5, entries.len() as u64);+ for (key, value) in entries {+ cbor(key, out);+ cbor(value, out);+ }+ }+ }+}++fn encode(value: Cbor) -> Vec<u8> {+ let mut out = Vec::new();+ cbor(&value, &mut out);+ out+}++/// The COSE form of a P-256 public key given as `04 || x || y`, keys in CTAP2's canonical order.+fn cose_key(point: &[u8]) -> Option<Vec<u8>> {+ if point.len() != 65 || point[0] != 0x04 {+ return None;+ }+ Some(encode(Cbor::Map(vec![+ (Cbor::Uint(1), Cbor::Uint(2)),+ (Cbor::Uint(3), Cbor::Nint(ES256)),+ (Cbor::Nint(-1), Cbor::Uint(1)),+ (Cbor::Nint(-2), Cbor::Bytes(point[1..33].to_vec())),+ (Cbor::Nint(-3), Cbor::Bytes(point[33..].to_vec())),+ ])))+}++/// Authenticator data for a sign-in: the relying party's hash, the flags and a+/// zero counter, which tells the site this authenticator keeps none.+pub fn assertion_auth_data(rp_id: &str) -> Vec<u8> {+ let mut data = sha256(rp_id.as_bytes()).to_vec();+ data.push(FLAGS_UP_UV);+ data.extend([0, 0, 0, 0]);+ data+}++/// Authenticator data for a new passkey: as a sign-in's, then a zero AAGUID,+/// the credential id and its public key.+fn attested_auth_data(rp_id: &str, credential_id: &[u8], point: &[u8]) -> Option<Vec<u8>> {+ let key = cose_key(point)?;+ let mut data = sha256(rp_id.as_bytes()).to_vec();+ data.push(FLAGS_UP_UV | FLAG_AT);+ data.extend([0, 0, 0, 0]);+ data.extend([0; 16]);+ data.extend((credential_id.len() as u16).to_be_bytes());+ data.extend(credential_id);+ data.extend(key);+ Some(data)+}++#[derive(Serialize)]+struct ClientData<'a> {+ #[serde(rename = "type")]+ kind: &'a str,+ challenge: &'a str,+ origin: &'a str,+ #[serde(rename = "crossOrigin")]+ cross_origin: bool,+}++/// One message from `passkey.js`: the page's request and the id it was sent under,+/// which a later `cancel` names when the page aborts it or its timeout passes.+#[derive(Debug, Deserialize)]+pub struct Envelope {+ #[serde(default)]+ pub id: u64,+ #[serde(flatten)]+ pub request: Request,+}++/// What the page asked, as `passkey.js` posts it: WebAuthn's options with every buffer in base64url.+#[derive(Debug, Deserialize)]+#[serde(tag = "kind", rename_all = "lowercase")]+pub enum Request {+ Available,+ Cancel,+ Create {+ #[serde(rename = "publicKey")]+ options: CreateOptions,+ },+ Get {+ #[serde(rename = "publicKey")]+ options: GetOptions,+ },+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CreateOptions {+ challenge: String,+ #[serde(default)]+ rp: RelyingParty,+ user: User,+ #[serde(default)]+ pub_key_cred_params: Vec<Parameter>,+ #[serde(default)]+ exclude_credentials: Vec<Descriptor>,+ #[serde(default)]+ authenticator_selection: Option<Selection>,+ #[serde(default)]+ extensions: Option<serde_json::Value>,+}++#[derive(Debug, Default, Deserialize)]+struct RelyingParty {+ #[serde(default)]+ id: Option<String>,+}++impl CreateOptions {+ /// The rpId the site asked for, before it is checked.+ pub fn rp_id(&self) -> Option<&str> {+ self.rp.id.as_deref()+ }+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+struct User {+ id: String,+ #[serde(default)]+ name: String,+ #[serde(default)]+ display_name: String,+}++#[derive(Debug, Deserialize)]+struct Parameter {+ #[serde(rename = "type", default)]+ kind: String,+ alg: i64,+}++#[derive(Debug, Deserialize)]+struct Descriptor {+ id: String,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+struct Selection {+ #[serde(default)]+ authenticator_attachment: Option<String>,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct GetOptions {+ challenge: String,+ #[serde(default)]+ rp_id: Option<String>,+ #[serde(default)]+ allow_credentials: Vec<Descriptor>,+}++/// One passkey in the app's store. `key` is the enclave's token for the+/// private key, useless on any other Mac.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct Passkey {+ pub id: String,+ pub rp_id: String,+ pub user_handle: String,+ pub user_name: String,+ pub display_name: String,+ pub key: String,+ pub created: u64,+}++impl Passkey {+ /// What the account picker shows for it.+ pub fn label(&self) -> String {+ match (self.user_name.is_empty(), self.display_name.is_empty()) {+ (false, _) => self.user_name.clone(),+ (true, false) => self.display_name.clone(),+ (true, true) => self.rp_id.clone(),+ }+ }++ pub fn key_token(&self) -> Option<Vec<u8>> {+ STANDARD.decode(&self.key).ok()+ }+}++#[derive(Debug, Default, Serialize, Deserialize)]+pub struct Store {+ #[serde(default)]+ pub passkeys: Vec<Passkey>,+}++impl Store {+ pub fn parse(text: &str) -> Option<Self> {+ serde_json::from_str(text).ok()+ }++ pub fn to_json(&self) -> String {+ serde_json::to_string_pretty(self).unwrap_or_default()+ }++ /// A site makes one passkey per account here: a new one for the same+ /// account replaces the old, as in a browser.+ pub fn upsert(&mut self, passkey: Passkey) {+ self.passkeys+ .retain(|old| !(old.rp_id == passkey.rp_id && old.user_handle == passkey.user_handle));+ self.passkeys.push(passkey);+ }+}++/// A checked request to make a passkey, waiting for the enclave.+#[derive(Debug)]+pub struct CreatePlan {+ pub rp_id: String,+ pub client_data: Vec<u8>,+ user_handle: String,+ user_name: String,+ display_name: String,+ cred_props: bool,+}++/// A checked request to sign in, with the passkeys it may use, newest first.+#[derive(Debug)]+pub struct GetPlan {+ pub rp_id: String,+ pub client_data: Vec<u8>,+ pub candidates: Vec<Passkey>,+}++fn client_data(kind: &str, challenge: &str, origin: &Origin) -> Result<Vec<u8>, Failure> {+ // Re-encoded, so the JSON carries exactly the challenge's canonical form.+ let challenge = from_b64url(challenge)+ .filter(|bytes| !bytes.is_empty())+ .ok_or(Failure::Type)?;+ let origin = origin.serialized();+ serde_json::to_vec(&ClientData {+ kind,+ challenge: &b64url(&challenge),+ origin: &origin,+ cross_origin: false,+ })+ .map_err(|_| Failure::NotAllowed)+}++pub fn plan_create(+ origin: &Origin,+ options: CreateOptions,+ store: &Store,+) -> Result<CreatePlan, Failure> {+ let rp_id = resolve_rp_id(origin, options.rp.id.as_deref())?;+ let handle = from_b64url(&options.user.id).ok_or(Failure::Type)?;+ if handle.is_empty() || handle.len() > MAX_USER_HANDLE {+ return Err(Failure::Type);+ }+ // An empty list means the browser's defaults, which start with ES256.+ let es256 = options.pub_key_cred_params.is_empty()+ || options+ .pub_key_cred_params+ .iter()+ .any(|param| param.alg == ES256 && param.kind == "public-key");+ if !es256 {+ return Err(Failure::NotSupported);+ }+ // A security key or a phone was asked for, which this authenticator is not.+ if options+ .authenticator_selection+ .as_ref()+ .and_then(|selection| selection.authenticator_attachment.as_deref())+ == Some("cross-platform")+ {+ return Err(Failure::NotAllowed);+ }+ let excluded = options.exclude_credentials.iter().any(|excluded| {+ store+ .passkeys+ .iter()+ .any(|passkey| passkey.rp_id == rp_id && passkey.id == excluded.id)+ });+ if excluded {+ return Err(Failure::InvalidState);+ }+ let cred_props = options+ .extensions+ .as_ref()+ .and_then(|extensions| extensions.get("credProps"))+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false);+ Ok(CreatePlan {+ client_data: client_data("webauthn.create", &options.challenge, origin)?,+ rp_id,+ user_handle: b64url(&handle),+ user_name: options.user.name,+ display_name: options.user.display_name,+ cred_props,+ })+}++/// The passkey to store and the page's answer, once the enclave made the key+/// (`point` is its public key as `04 || x || y`) and the user approved.+pub fn finish_create(+ plan: &CreatePlan,+ credential_id: &[u8],+ point: &[u8],+ key_token: &[u8],+ created: u64,+) -> Option<(Passkey, String)> {+ let auth_data = attested_auth_data(&plan.rp_id, credential_id, point)?;+ let attestation = encode(Cbor::Map(vec![+ (Cbor::Text("fmt"), Cbor::Text("none")),+ (Cbor::Text("attStmt"), Cbor::Map(Vec::new())),+ (Cbor::Text("authData"), Cbor::Bytes(auth_data.clone())),+ ]));+ let mut spki = P256_SPKI_PREFIX.to_vec();+ spki.extend(point);+ let id = b64url(credential_id);+ let extensions = if plan.cred_props {+ serde_json::json!({ "credProps": { "rk": true } })+ } else {+ serde_json::json!({})+ };+ let reply = serde_json::json!({+ "id": id,+ "authenticatorAttachment": "platform",+ "clientExtensionResults": extensions,+ "response": {+ "clientDataJSON": b64url(&plan.client_data),+ "attestationObject": b64url(&attestation),+ "authenticatorData": b64url(&auth_data),+ "publicKey": b64url(&spki),+ "publicKeyAlgorithm": ES256,+ "transports": ["internal"],+ },+ });+ let passkey = Passkey {+ id,+ rp_id: plan.rp_id.clone(),+ user_handle: plan.user_handle.clone(),+ user_name: plan.user_name.clone(),+ display_name: plan.display_name.clone(),+ key: STANDARD.encode(key_token),+ created,+ };+ Some((passkey, reply.to_string()))+}++pub fn plan_get(origin: &Origin, options: GetOptions, store: &Store) -> Result<GetPlan, Failure> {+ let rp_id = resolve_rp_id(origin, options.rp_id.as_deref())?;+ let mut candidates: Vec<Passkey> = store+ .passkeys+ .iter()+ .filter(|passkey| passkey.rp_id == rp_id)+ .filter(|passkey| {+ options.allow_credentials.is_empty()+ || options+ .allow_credentials+ .iter()+ .any(|allowed| allowed.id == passkey.id)+ })+ .cloned()+ .collect();+ candidates.sort_by_key(|passkey| std::cmp::Reverse(passkey.created));+ Ok(GetPlan {+ client_data: client_data("webauthn.get", &options.challenge, origin)?,+ rp_id,+ candidates,+ })+}++/// What the enclave signs for a sign-in.+pub fn assertion_message(plan: &GetPlan) -> Vec<u8> {+ let mut message = assertion_auth_data(&plan.rp_id);+ message.extend(sha256(&plan.client_data));+ message+}++/// The page's answer for a sign-in with `passkey`, given the enclave's DER signature.+pub fn finish_get(plan: &GetPlan, passkey: &Passkey, signature: &[u8]) -> String {+ serde_json::json!({+ "id": passkey.id,+ "authenticatorAttachment": "platform",+ "clientExtensionResults": {},+ "response": {+ "clientDataJSON": b64url(&plan.client_data),+ "authenticatorData": b64url(&assertion_auth_data(&plan.rp_id)),+ "signature": b64url(signature),+ "userHandle": passkey.user_handle,+ },+ })+ .to_string()+}++/// The picker's line for each candidate. Two accounts that read the same get+/// the day they were saved after the name, through `date`, so they can be told apart.+pub fn picker_labels(candidates: &[Passkey], date: impl Fn(u64) -> String) -> Vec<String> {+ let labels: Vec<String> = candidates.iter().map(Passkey::label).collect();+ labels+ .iter()+ .zip(candidates)+ .map(|(label, passkey)| {+ if labels.iter().filter(|other| *other == label).count() > 1 {+ format!("{label} · {}", date(passkey.created))+ } else {+ label.clone()+ }+ })+ .collect()+}++/// The words after the app's name in the Touch ID prompt, which macOS writes+/// as "<App> is trying to <reason>."+pub fn prompt_reason(creating: bool, rp_id: &str, language: UiLanguage) -> String {+ match (language, creating) {+ (UiLanguage::English, true) => format!("save a passkey for {rp_id}"),+ (UiLanguage::English, false) => format!("sign in to {rp_id}"),+ (UiLanguage::SimplifiedChinese, true) => format!("为 {rp_id} 存储通行密钥"),+ (UiLanguage::SimplifiedChinese, false) => format!("登录 {rp_id}"),+ (UiLanguage::TraditionalChinese, true) => format!("為 {rp_id} 儲存通行密鑰"),+ (UiLanguage::TraditionalChinese, false) => format!("登入 {rp_id}"),+ }+}++/// The account picker's title and its two buttons.+pub fn picker_text(rp_id: &str, language: UiLanguage) -> (String, &'static str, &'static str) {+ match language {+ UiLanguage::English => (format!("Sign In to {rp_id}"), "Continue", "Cancel"),+ UiLanguage::SimplifiedChinese => (format!("登录 {rp_id}"), "继续", "取消"),+ UiLanguage::TraditionalChinese => (format!("登入 {rp_id}"), "繼續", "取消"),+ }+}++/// The notice for a site asking for a second passkey for an account this app+/// already keeps one for: its title and its button.+pub fn existing_text(rp_id: &str, language: UiLanguage) -> (String, &'static str) {+ match language {+ UiLanguage::English => (format!("This App Already Has a Passkey for {rp_id}"), "OK"),+ UiLanguage::SimplifiedChinese => (format!("这个应用里已经有 {rp_id} 的通行密钥"), "好"),+ UiLanguage::TraditionalChinese => {+ (format!("這個應用程式裡已經有 {rp_id} 的通行密鑰"), "好")+ }+ }+}++/// The notice for a sign-in this app has no passkey for: its title, its line and its button.+pub fn missing_text(rp_id: &str, language: UiLanguage) -> (String, &'static str, &'static str) {+ match language {+ UiLanguage::English => (+ format!("No Passkey for {rp_id}"),+ "Passkeys in iCloud Keychain can't be used in this app. Sign in another way, then add a passkey in the site's settings.",+ "OK",+ ),+ UiLanguage::SimplifiedChinese => (+ format!("这个应用里没有 {rp_id} 的通行密钥"),+ "iCloud 钥匙串里的通行密钥在这里用不了,可以先用其他方式登录,再到网站设置里添加通行密钥。",+ "好",+ ),+ UiLanguage::TraditionalChinese => (+ format!("這個應用程式裡沒有 {rp_id} 的通行密鑰"),+ "iCloud 鑰匙圈裡的通行密鑰在這裡無法使用,可以先用其他方式登入,再到網站設定裡加入通行密鑰。",+ "好",+ ),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn https(host: &str) -> Origin {+ Origin {+ scheme: "https".into(),+ host: host.into(),+ port: 0,+ }+ }++ fn point() -> Vec<u8> {+ let mut point = vec![0x04];+ point.extend(1..=64u8);+ point+ }++ #[test]+ fn rp_id_is_the_host_or_a_registrable_parent() {+ let origin = https("accounts.google.com");+ assert_eq!(resolve_rp_id(&origin, None).unwrap(), "accounts.google.com");+ assert_eq!(resolve_rp_id(&origin, Some("")), Err(Failure::Security));+ assert_eq!(+ resolve_rp_id(&origin, Some("Google.com")).unwrap(),+ "google.com"+ );+ assert_eq!(resolve_rp_id(&origin, Some("com")), Err(Failure::Security));+ assert_eq!(+ resolve_rp_id(&origin, Some("ogle.com")),+ Err(Failure::Security)+ );+ assert_eq!(+ resolve_rp_id(&origin, Some("example.com")),+ Err(Failure::Security)+ );+ assert_eq!(+ resolve_rp_id(&https("a.github.io"), Some("github.io")),+ Err(Failure::Security)+ );+ assert_eq!(+ resolve_rp_id(&https("shop.example.co.uk"), Some("example.co.uk")).unwrap(),+ "example.co.uk"+ );+ assert_eq!(+ resolve_rp_id(&https("example.co.uk"), Some("co.uk")),+ Err(Failure::Security)+ );+ }++ #[test]+ fn only_a_secure_context_may_ask() {+ let http = |host: &str| Origin {+ scheme: "http".into(),+ host: host.into(),+ port: 8080,+ };+ assert_eq!(+ resolve_rp_id(&http("example.com"), None),+ Err(Failure::Security)+ );+ assert_eq!(+ resolve_rp_id(&http("localhost"), None).unwrap(),+ "localhost"+ );+ assert_eq!(+ resolve_rp_id(&http("app.localhost"), None).unwrap(),+ "app.localhost"+ );+ let file = Origin {+ scheme: "file".into(),+ host: String::new(),+ port: 0,+ };+ assert_eq!(resolve_rp_id(&file, None), Err(Failure::Security));+ assert_eq!(http("localhost").serialized(), "http://localhost:8080");+ assert_eq!(https("x.com").serialized(), "https://x.com");+ }++ #[test]+ fn cbor_writes_the_lengths_its_heads_announce() {+ let mut out = Vec::new();+ cbor_head(&mut out, 2, 23);+ cbor_head(&mut out, 2, 24);+ cbor_head(&mut out, 2, 300);+ cbor_head(&mut out, 1, 6);+ assert_eq!(out, [0x57, 0x58, 24, 0x59, 0x01, 0x2c, 0x26]);+ // -7 is major type 1 with value 6.+ assert_eq!(encode(Cbor::Nint(-7)), [0x26]);+ }++ #[test]+ fn cose_key_is_canonical_es256() {+ let key = cose_key(&point()).unwrap();+ assert_eq!(+ &key[..9],+ &[0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58]+ );+ assert_eq!(key.len(), 1 + 2 + 2 + 2 + (2 + 1 + 32) * 2);+ assert!(cose_key(&point()[1..]).is_none());+ }++ fn create_request(json: serde_json::Value) -> CreateOptions {+ match serde_json::from_value::<Request>(json).unwrap() {+ Request::Create { options } => options,+ other => panic!("{other:?}"),+ }+ }++ fn sample_create() -> serde_json::Value {+ serde_json::json!({+ "kind": "create",+ "publicKey": {+ "challenge": b64url(b"challenge-bytes"),+ "rp": { "name": "Example" },+ "user": { "id": b64url(b"user-1"), "name": "[email protected]", "displayName": "Me" },+ "pubKeyCredParams": [{ "type": "public-key", "alg": -8 }, { "type": "public-key", "alg": -7 }],+ "extensions": { "credProps": true },+ }+ })+ }++ #[test]+ fn a_new_passkey_answers_with_none_attestation() {+ let plan = plan_create(+ &https("example.com"),+ create_request(sample_create()),+ &Store::default(),+ )+ .unwrap();+ assert_eq!(plan.rp_id, "example.com");+ let client: serde_json::Value = serde_json::from_slice(&plan.client_data).unwrap();+ assert_eq!(client["type"], "webauthn.create");+ assert_eq!(client["origin"], "https://example.com");+ assert_eq!(client["challenge"], b64url(b"challenge-bytes"));+ assert_eq!(client["crossOrigin"], false);++ let (passkey, reply) = finish_create(&plan, &[9; 16], &point(), b"token", 7).unwrap();+ assert_eq!(passkey.user_handle, b64url(b"user-1"));+ assert_eq!(passkey.key_token().unwrap(), b"token");+ let reply: serde_json::Value = serde_json::from_str(&reply).unwrap();+ assert_eq!(reply["id"], b64url(&[9; 16]));+ assert_eq!(reply["clientExtensionResults"]["credProps"]["rk"], true);+ let auth = from_b64url(reply["response"]["authenticatorData"].as_str().unwrap()).unwrap();+ assert_eq!(&auth[..32], &sha256(b"example.com"));+ assert_eq!(auth[32], 0x45);+ assert_eq!(&auth[53..55], &[0, 16]);+ let attestation =+ from_b64url(reply["response"]["attestationObject"].as_str().unwrap()).unwrap();+ // {"fmt": "none", "attStmt": {}, "authData": ...}+ assert_eq!(&attestation[..19], b"\xa3\x63fmt\x64none\x67attStmt\xa0");+ let spki = from_b64url(reply["response"]["publicKey"].as_str().unwrap()).unwrap();+ assert_eq!(spki.len(), 91);+ }++ #[test]+ fn a_create_the_enclave_cannot_answer_is_refused() {+ let mut request = sample_create();+ request["publicKey"]["pubKeyCredParams"] =+ serde_json::json!([{ "type": "public-key", "alg": -257 }]);+ assert_eq!(+ plan_create(+ &https("example.com"),+ create_request(request),+ &Store::default()+ )+ .unwrap_err(),+ Failure::NotSupported+ );+ let mut request = sample_create();+ request["publicKey"]["authenticatorSelection"] =+ serde_json::json!({ "authenticatorAttachment": "cross-platform" });+ assert_eq!(+ plan_create(+ &https("example.com"),+ create_request(request),+ &Store::default()+ )+ .unwrap_err(),+ Failure::NotAllowed+ );+ let mut request = sample_create();+ request["publicKey"]["user"]["id"] = serde_json::json!(b64url(&[1; 65]));+ assert_eq!(+ plan_create(+ &https("example.com"),+ create_request(request),+ &Store::default()+ )+ .unwrap_err(),+ Failure::Type+ );+ }++ fn stored(id: &str, rp_id: &str, user: &str, created: u64) -> Passkey {+ Passkey {+ id: id.into(),+ rp_id: rp_id.into(),+ user_handle: b64url(user.as_bytes()),+ user_name: user.into(),+ display_name: String::new(),+ key: STANDARD.encode(b"token"),+ created,+ }+ }++ #[test]+ fn an_excluded_passkey_already_here_stops_a_create() {+ let store = Store {+ passkeys: vec![stored("abc", "example.com", "me", 1)],+ };+ let mut request = sample_create();+ request["publicKey"]["excludeCredentials"] =+ serde_json::json!([{ "type": "public-key", "id": "abc" }]);+ assert_eq!(+ plan_create(&https("example.com"), create_request(request), &store).unwrap_err(),+ Failure::InvalidState+ );+ }++ #[test]+ fn a_new_passkey_replaces_the_same_accounts_old_one() {+ let mut store = Store::default();+ store.upsert(stored("a", "example.com", "me", 1));+ store.upsert(stored("b", "example.com", "you", 2));+ store.upsert(stored("c", "example.com", "me", 3));+ store.upsert(stored("d", "other.com", "me", 4));+ let ids: Vec<_> = store+ .passkeys+ .iter()+ .map(|passkey| passkey.id.as_str())+ .collect();+ assert_eq!(ids, ["b", "c", "d"]);+ let again = Store::parse(&store.to_json()).unwrap();+ assert_eq!(again.passkeys, store.passkeys);+ }++ fn get_request(json: serde_json::Value) -> GetOptions {+ match serde_json::from_value::<Request>(json).unwrap() {+ Request::Get { options } => options,+ other => panic!("{other:?}"),+ }+ }++ #[test]+ fn a_sign_in_offers_the_sites_passkeys_newest_first() {+ let store = Store {+ passkeys: vec![+ stored("old", "google.com", "a", 1),+ stored("new", "google.com", "b", 5),+ stored("x", "x.com", "c", 9),+ ],+ };+ let request = serde_json::json!({+ "kind": "get",+ "publicKey": { "challenge": b64url(b"c"), "rpId": "google.com" }+ });+ let plan = plan_get(&https("accounts.google.com"), get_request(request), &store).unwrap();+ let ids: Vec<_> = plan+ .candidates+ .iter()+ .map(|passkey| passkey.id.as_str())+ .collect();+ assert_eq!(ids, ["new", "old"]);++ let request = serde_json::json!({+ "kind": "get",+ "publicKey": {+ "challenge": b64url(b"c"),+ "rpId": "google.com",+ "allowCredentials": [{ "type": "public-key", "id": "old" }],+ }+ });+ let plan = plan_get(&https("accounts.google.com"), get_request(request), &store).unwrap();+ assert_eq!(plan.candidates.len(), 1);+ let message = assertion_message(&plan);+ assert_eq!(message.len(), 37 + 32);+ assert_eq!(message[32], FLAGS_UP_UV);+ let reply: serde_json::Value =+ serde_json::from_str(&finish_get(&plan, &plan.candidates[0], b"sig")).unwrap();+ assert_eq!(reply["response"]["userHandle"], b64url(b"a"));+ assert_eq!(reply["response"]["signature"], b64url(b"sig"));+ let client: serde_json::Value = serde_json::from_slice(+ &from_b64url(reply["response"]["clientDataJSON"].as_str().unwrap()).unwrap(),+ )+ .unwrap();+ assert_eq!(client["type"], "webauthn.get");+ assert_eq!(client["origin"], "https://accounts.google.com");+ }++ #[test]+ fn only_accounts_that_read_the_same_carry_a_date() {+ let candidates = [+ stored("a", "x.com", "me", 1),+ stored("b", "x.com", "you", 2),+ stored("c", "x.com", "me", 3),+ ];+ let labels = picker_labels(&candidates, |created| format!("day {created}"));+ assert_eq!(labels, ["me · day 1", "you", "me · day 3"]);+ }++ #[test]+ fn a_message_carries_its_id_beside_the_request() {+ let envelope: Envelope =+ serde_json::from_value(serde_json::json!({ "kind": "cancel", "id": 7 })).unwrap();+ assert_eq!(envelope.id, 7);+ assert!(matches!(envelope.request, Request::Cancel));+ let envelope: Envelope = serde_json::from_value(serde_json::json!({+ "kind": "get", "id": 8, "publicKey": { "challenge": "AQ" }+ }))+ .unwrap();+ assert!(matches!(envelope.request, Request::Get { .. }));+ }++ #[test]+ fn a_challenge_must_be_base64url() {+ let request = serde_json::json!({+ "kind": "get",+ "publicKey": { "challenge": "not base64!" }+ });+ assert_eq!(+ plan_get(&https("x.com"), get_request(request), &Store::default()).unwrap_err(),+ Failure::Type+ );+ }++ #[test]+ fn prompts_are_written_in_every_language() {+ for language in [+ UiLanguage::English,+ UiLanguage::SimplifiedChinese,+ UiLanguage::TraditionalChinese,+ ] {+ assert!(prompt_reason(true, "x.com", language).contains("x.com"));+ assert!(prompt_reason(false, "x.com", language).contains("x.com"));+ let (title, accept, cancel) = picker_text("x.com", language);+ assert!(title.contains("x.com") && accept != cancel);+ let (title, line, button) = missing_text("x.com", language);+ assert!(title.contains("x.com") && !line.is_empty() && !button.is_empty());+ let (title, button) = existing_text("x.com", language);+ assert!(title.contains("x.com") && !button.is_empty());+ }+ }+}diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 6d40caf4..ac86c861 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -965,6 +965,12 @@ 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 {+ window_builder = window_builder.initialization_script(include_str!("../inject/passkey.js"));+ }+let custom_js = config.runtime_custom_js.as_deref()@@ -1411,6 +1417,19 @@ fn build_window(eprintln!("[Pake] Failed to access WKWebView for its script dialogs: {error}");}+ // WKWebView refuses WebAuthn in this app, so the runtime answers passkey.js itself.+ #[cfg(target_os = "macos")]+ if !window_config.incognito {+ 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| {+ crate::app::passkey::install(&webview, store);+ }) {+ eprintln!("[Pake] Failed to access WKWebView for passkeys: {error}");+ }+ }+ }+// The tab bar's + button exists only while some window class answers// `newWindowForTab:`. Install it for every tabbing window, the main one// included: its tab bar is the one the user sees first.diff --git a/src-tauri/src/inject/passkey.js b/src-tauri/src/inject/passkey.jsnew file mode 100644index 00000000..6bfca3a9--- /dev/null+++ b/src-tauri/src/inject/passkey.js@@ -0,0 +1,360 @@+// Passkeys for the page in a macOS app (src/app/passkey). WKWebView refuses+// WebAuthn in an app without Apple's browser entitlement, so a publicKey+// request goes to the runtime's own authenticator instead: a Secure Enclave+// key behind Touch ID, kept in this app. The native side takes the page's+// origin from WebKit and builds the client data; this script only carries the+// options over as JSON and turns the answer back into a PublicKeyCredential.+// Every other credential request keeps the engine's own path.+(function () {+ "use strict";+ if (window.top !== window || window.__PAKE_PASSKEYS__) return;+ if (+ typeof window.PublicKeyCredential !== "function" ||+ typeof window.CredentialsContainer !== "function"+ ) {+ return;+ }+ Object.defineProperty(window, "__PAKE_PASSKEYS__", { value: true });++ const HANDLER = "pakePasskey";+ const container = window.CredentialsContainer.prototype;+ const nativeCreate = container.create;+ const nativeGet = container.get;++ // Added by the native side right after the webview is built, so looked up at call time.+ const handler = () => {+ const handlers = window.webkit && window.webkit.messageHandlers;+ return handlers && handlers[HANDLER];+ };++ const bytesOf = (source) => {+ // By tag, so a buffer made in another frame is taken too.+ if (Object.prototype.toString.call(source) === "[object ArrayBuffer]") {+ return new Uint8Array(source);+ }+ if (ArrayBuffer.isView(source)) {+ return new Uint8Array(+ source.buffer,+ source.byteOffset,+ source.byteLength,+ );+ }+ throw new TypeError("Expected an ArrayBuffer or a view of one");+ };++ const toBase64Url = (source) => {+ const bytes = bytesOf(source);+ let binary = "";+ for (let index = 0; index < bytes.length; index += 1) {+ binary += String.fromCharCode(bytes[index]);+ }+ return btoa(binary)+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+ };++ const fromBase64Url = (text) => {+ const base = text.replace(/-/g, "+").replace(/_/g, "/");+ const binary = atob(base + "===".slice((base.length + 3) % 4));+ const bytes = new Uint8Array(binary.length);+ for (let index = 0; index < binary.length; index += 1) {+ bytes[index] = binary.charCodeAt(index);+ }+ return bytes.buffer;+ };++ const descriptors = (list) =>+ Array.from(list || [], (descriptor) => ({+ type: descriptor.type,+ id: toBase64Url(descriptor.id),+ }));++ const createRequest = (options) => {+ const selection = options.authenticatorSelection;+ const extensions = options.extensions;+ return {+ kind: "create",+ publicKey: {+ challenge: toBase64Url(options.challenge),+ rp: { id: options.rp && options.rp.id },+ user: {+ id: toBase64Url(options.user.id),+ name: String(options.user.name || ""),+ displayName: String(options.user.displayName || ""),+ },+ pubKeyCredParams: Array.from(+ options.pubKeyCredParams || [],+ (param) => ({+ type: param.type,+ alg: param.alg,+ }),+ ),+ excludeCredentials: descriptors(options.excludeCredentials),+ authenticatorSelection: selection+ ? { authenticatorAttachment: selection.authenticatorAttachment }+ : undefined,+ extensions: extensions+ ? { credProps: Boolean(extensions.credProps) }+ : undefined,+ },+ };+ };++ const getRequest = (options) => ({+ kind: "get",+ publicKey: {+ challenge: toBase64Url(options.challenge),+ rpId: options.rpId,+ allowCredentials: descriptors(options.allowCredentials),+ },+ });++ const call = (request) => {+ const target = handler();+ if (!target) return Promise.reject(notAllowed());+ return target.postMessage(JSON.stringify(request)).then((text) => {+ const reply = JSON.parse(text);+ if (reply.error === "TypeError")+ throw new TypeError(reply.message || "Invalid options");+ if (reply.error) {+ throw new DOMException(+ reply.message || "The operation either timed out or was not allowed.",+ reply.error,+ );+ }+ return reply;+ });+ };++ // An object that reads as the engine's own: the values sit one step up as+ // enumerable getters and methods on the engine's prototype, so `instanceof`+ // holds, `Object.keys` is empty and `for...in` lists the fields, as on a+ // browser's credential (FIDO's webauthn-demo serialises it that way). A field+ // has no setter, and a method may be replaced, as GitHub's webauthn-json does+ // with `credential.toJSON = ...` in strict mode.+ const shaped = (Engine, values) => {+ const shape = Object.create(Engine ? Engine.prototype : Object.prototype);+ for (const key of Object.keys(values)) {+ const value = values[key];+ Object.defineProperty(+ shape,+ key,+ typeof value === "function"+ ? { value, writable: true, enumerable: true, configurable: true }+ : { get: () => value, enumerable: true, configurable: true },+ );+ }+ return Object.create(shape);+ };++ const credentialFrom = (reply) => {+ const answer = reply.response;+ const created = typeof answer.attestationObject === "string";+ const Response = created+ ? window.AuthenticatorAttestationResponse+ : window.AuthenticatorAssertionResponse;+ const values = { clientDataJSON: fromBase64Url(answer.clientDataJSON) };+ if (created) {+ const authenticatorData = fromBase64Url(answer.authenticatorData);+ const publicKey = fromBase64Url(answer.publicKey);+ values.attestationObject = fromBase64Url(answer.attestationObject);+ values.getTransports = () => answer.transports.slice();+ values.getAuthenticatorData = () => authenticatorData.slice(0);+ values.getPublicKey = () => publicKey.slice(0);+ values.getPublicKeyAlgorithm = () => answer.publicKeyAlgorithm;+ } else {+ values.authenticatorData = fromBase64Url(answer.authenticatorData);+ values.signature = fromBase64Url(answer.signature);+ values.userHandle = answer.userHandle+ ? fromBase64Url(answer.userHandle)+ : null;+ }+ const response = shaped(Response, values);++ const json = created+ ? {+ clientDataJSON: answer.clientDataJSON,+ attestationObject: answer.attestationObject,+ authenticatorData: answer.authenticatorData,+ publicKey: answer.publicKey,+ publicKeyAlgorithm: answer.publicKeyAlgorithm,+ transports: answer.transports.slice(),+ }+ : {+ clientDataJSON: answer.clientDataJSON,+ authenticatorData: answer.authenticatorData,+ signature: answer.signature,+ userHandle: answer.userHandle || null,+ };+ return shaped(window.PublicKeyCredential, {+ id: reply.id,+ rawId: fromBase64Url(reply.id),+ type: "public-key",+ authenticatorAttachment: "platform",+ response,+ getClientExtensionResults: () =>+ Object.assign({}, reply.clientExtensionResults),+ toJSON: () => ({+ id: reply.id,+ rawId: reply.id,+ type: "public-key",+ authenticatorAttachment: "platform",+ clientExtensionResults: Object.assign({}, reply.clientExtensionResults),+ response: json,+ }),+ });+ };++ const abortReason = (signal) =>+ signal.reason !== undefined+ ? signal.reason+ : new DOMException("The operation was aborted.", "AbortError");++ const notAllowed = () =>+ new DOMException(+ "The operation either timed out or was not allowed.",+ "NotAllowedError",+ );++ // A browser keeps a ceremony between these bounds whatever the site asks,+ // and gives one that asks nothing five minutes.+ const MIN_TIMEOUT = 30000;+ const MAX_TIMEOUT = 600000;+ const DEFAULT_TIMEOUT = 300000;+ const timeoutOf = (value) =>+ typeof value === "number" && value > 0+ ? Math.min(Math.max(value, MIN_TIMEOUT), MAX_TIMEOUT)+ : DEFAULT_TIMEOUT;++ let nextId = 0;++ // One ceremony with the native side. When the page aborts it or its timeout+ // passes, the page's promise settles at once and the native side is told to+ // close its prompt, so a request that follows is not refused as busy.+ const ceremony = (signal, timeout, build) => {+ if (signal && signal.aborted) return Promise.reject(abortReason(signal));+ let request;+ try {+ request = build();+ } catch (error) {+ return Promise.reject(error);+ }+ const id = (nextId += 1);+ request.id = id;+ return new Promise((resolve, reject) => {+ let timer = 0;+ const settle = () => {+ if (signal) signal.removeEventListener("abort", onAbort);+ clearTimeout(timer);+ };+ const stop = (error) => {+ settle();+ const target = handler();+ if (target)+ target+ .postMessage(JSON.stringify({ kind: "cancel", id }))+ .catch(() => {});+ reject(error);+ };+ const onAbort = () => stop(abortReason(signal));+ if (signal) signal.addEventListener("abort", onAbort, { once: true });+ timer = setTimeout(() => stop(notAllowed()), timeoutOf(timeout));+ call(request).then(+ (reply) => {+ settle();+ resolve(credentialFrom(reply));+ },+ (error) => {+ settle();+ reject(error);+ },+ );+ });+ };++ // A request that asks nothing of the user waits until the page aborts it.+ const waiting = (signal) => {+ if (signal && signal.aborted) return Promise.reject(abortReason(signal));+ return new Promise((_, reject) => {+ if (signal) {+ signal.addEventListener("abort", () => reject(abortReason(signal)), {+ once: true,+ });+ }+ });+ };++ const override = (target, name, value) => {+ try {+ Object.defineProperty(target, name, {+ value,+ writable: true,+ configurable: true,+ });+ } catch (_) {+ // A page that froze the API keeps the engine's.+ }+ };++ override(container, "create", function create(options) {+ if (!options || !options.publicKey)+ return nativeCreate.apply(this, arguments);+ // A conditional create is the site's quiet upgrade after a password+ // sign-in; a browser declines it unless its own conditions hold, and here+ // it would raise an unasked-for Touch ID prompt.+ if (options.mediation === "conditional")+ return Promise.reject(notAllowed());+ const publicKey = options.publicKey;+ return ceremony(options.signal, publicKey.timeout, () =>+ createRequest(publicKey),+ );+ });++ override(container, "get", function get(options) {+ if (!options || !options.publicKey) return nativeGet.apply(this, arguments);+ // No autofill list to fill: a conditional request waits, as a browser+ // with nothing to suggest does, until the page aborts it.+ if (options.mediation === "conditional") return waiting(options.signal);+ const publicKey = options.publicKey;+ return ceremony(options.signal, publicKey.timeout, () =>+ getRequest(publicKey),+ );+ });++ // Only an answer is kept: a call before the native side is ready asks again next time.+ let available;+ const isAvailable = () => {+ if (available !== undefined) return Promise.resolve(available);+ return call({ kind: "available" }).then(+ (reply) => (available = Boolean(reply.available)),+ () => false,+ );+ };++ const PublicKeyCredential = window.PublicKeyCredential;+ override(+ PublicKeyCredential,+ "isUserVerifyingPlatformAuthenticatorAvailable",+ isAvailable,+ );+ override(PublicKeyCredential, "isConditionalMediationAvailable", () =>+ Promise.resolve(false),+ );+ if (typeof PublicKeyCredential.getClientCapabilities === "function") {+ override(PublicKeyCredential, "getClientCapabilities", () =>+ isAvailable().then((platform) => ({+ conditionalCreate: false,+ conditionalGet: false,+ hybridTransport: false,+ passkeyPlatformAuthenticator: platform,+ userVerifyingPlatformAuthenticator: platform,+ relatedOrigins: false,+ signalAllAcceptedCredentials: false,+ signalCurrentUserDetails: false,+ signalUnknownCredential: false,+ "extension:credProps": true,+ })),+ );+ }+})();diff --git a/tests/unit/passkey-bridge.test.js b/tests/unit/passkey-bridge.test.jsnew file mode 100644index 00000000..9ff353a1--- /dev/null+++ b/tests/unit/passkey-bridge.test.js@@ -0,0 +1,322 @@+import fs from "fs";+import path from "path";+import { runInNewContext } from "node:vm";+import { describe, expect, it, vi } from "vitest";++// passkey.js hands a page's WebAuthn request to the native authenticator in a+// macOS app and turns the answer back into a PublicKeyCredential.+const source = fs.readFileSync(+ path.join(process.cwd(), "src-tauri/src/inject/passkey.js"),+ "utf-8",+);++const b64url = (bytes) =>+ Buffer.from(bytes)+ .toString("base64")+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");++function load({ reply, handler = true, top = true } = {}) {+ class PublicKeyCredential {+ static isUserVerifyingPlatformAuthenticatorAvailable() {+ return Promise.resolve(false);+ }+ static isConditionalMediationAvailable() {+ return Promise.resolve(true);+ }+ get id() {+ throw new TypeError("Illegal invocation");+ }+ }+ class AuthenticatorAttestationResponse {}+ class AuthenticatorAssertionResponse {}+ const nativeCalls = [];+ class CredentialsContainer {+ create(options) {+ nativeCalls.push(["create", options]);+ return Promise.resolve("native");+ }+ get(options) {+ nativeCalls.push(["get", options]);+ return Promise.resolve("native");+ }+ }+ const posted = [];+ const window = {+ PublicKeyCredential,+ CredentialsContainer,+ AuthenticatorAttestationResponse,+ AuthenticatorAssertionResponse,+ webkit: handler+ ? {+ messageHandlers: {+ pakePasskey: {+ postMessage(text) {+ const request = JSON.parse(text);+ posted.push(request);+ const answer = reply(request);+ return Promise.resolve(answer).then((value) =>+ JSON.stringify(value),+ );+ },+ },+ },+ }+ : undefined,+ };+ window.top = top ? window : {};+ runInNewContext(source, {+ window,+ btoa,+ atob,+ DOMException,+ Promise,+ Uint8Array,+ ArrayBuffer,+ setTimeout,+ clearTimeout,+ });+ return {+ window,+ credentials: new CredentialsContainer(),+ posted,+ nativeCalls,+ };+}++const created = {+ id: b64url([1, 2, 3]),+ authenticatorAttachment: "platform",+ clientExtensionResults: { credProps: { rk: true } },+ response: {+ clientDataJSON: b64url(Buffer.from('{"type":"webauthn.create"}')),+ attestationObject: b64url([0xa3]),+ authenticatorData: b64url([9, 9]),+ publicKey: b64url([4, 5]),+ publicKeyAlgorithm: -7,+ transports: ["internal"],+ },+};++const signedIn = {+ id: b64url([1, 2, 3]),+ authenticatorAttachment: "platform",+ clientExtensionResults: {},+ response: {+ clientDataJSON: b64url(Buffer.from('{"type":"webauthn.get"}')),+ authenticatorData: b64url([7]),+ signature: b64url([0x30, 0x44]),+ userHandle: b64url([42]),+ },+};++const createOptions = {+ publicKey: {+ challenge: new Uint8Array([250, 251, 252]),+ rp: { id: "example.com", name: "Example" },+ user: { id: new Uint8Array([1]).buffer, name: "me", displayName: "Me" },+ pubKeyCredParams: [{ type: "public-key", alg: -7 }],+ excludeCredentials: [{ type: "public-key", id: new Uint8Array([5]) }],+ extensions: { credProps: true },+ },+};++describe("passkey bridge", () => {+ it("sends a create's buffers as base64url and answers with a real-looking credential", async () => {+ const { window, credentials, posted } = load({ reply: () => created });+ const credential = await credentials.create(createOptions);+ expect(posted[0].kind).toBe("create");+ expect(posted[0].publicKey.challenge).toBe("-vv8");+ expect(posted[0].publicKey.user.id).toBe("AQ");+ expect(posted[0].publicKey.excludeCredentials).toEqual([+ { type: "public-key", id: "BQ" },+ ]);+ expect(credential instanceof window.PublicKeyCredential).toBe(true);+ expect(+ credential.response instanceof window.AuthenticatorAttestationResponse,+ ).toBe(true);+ expect(credential.id).toBe(created.id);+ expect([...new Uint8Array(credential.rawId)]).toEqual([1, 2, 3]);+ expect(credential.response.getTransports()).toEqual(["internal"]);+ expect(credential.response.getPublicKeyAlgorithm()).toBe(-7);+ expect([+ ...new Uint8Array(credential.response.getAuthenticatorData()),+ ]).toEqual([9, 9]);+ expect(credential.getClientExtensionResults()).toEqual({+ credProps: { rk: true },+ });+ expect(credential.toJSON().response.attestationObject).toBe(+ created.response.attestationObject,+ );+ });++ it("lets a page replace a credential's methods, as GitHub's webauthn-json does", async () => {+ const { credentials } = load({ reply: () => created });+ const credential = await credentials.create(createOptions);+ // GitHub: `let t = await navigator.credentials.create(e); return t.toJSON = () => ..., t`+ const assign = new Function(+ "credential",+ '"use strict"; credential.toJSON = () => "page"; return credential.toJSON();',+ );+ expect(assign(credential)).toBe("page");+ expect(() =>+ new Function("credential", '"use strict"; credential.id = "x";')(+ credential,+ ),+ ).toThrow(TypeError);+ expect(credential.id).toBe(created.id);+ // Assigning made `toJSON` an own key, as on a browser; a fresh one has none.+ const fresh = await credentials.create(createOptions);+ expect(Object.keys(fresh)).toEqual([]);+ // FIDO's webauthn-demo serialises a credential with `for (key in credential)`.+ const listed = [];+ for (const key in fresh) listed.push(key);+ expect(listed).toEqual(+ expect.arrayContaining(["id", "rawId", "type", "response"]),+ );+ const fields = [];+ for (const key in fresh.response) fields.push(key);+ expect(fields).toEqual(+ expect.arrayContaining(["clientDataJSON", "attestationObject"]),+ );+ });++ it("answers a sign-in with an assertion carrying the user handle", async () => {+ const { window, credentials, posted } = load({ reply: () => signedIn });+ const credential = await credentials.get({+ publicKey: { challenge: new Uint8Array([1]), rpId: "example.com" },+ });+ expect(posted[0]).toEqual({+ id: 1,+ kind: "get",+ publicKey: { challenge: "AQ", rpId: "example.com", allowCredentials: [] },+ });+ expect(+ credential.response instanceof window.AuthenticatorAssertionResponse,+ ).toBe(true);+ expect([...new Uint8Array(credential.response.userHandle)]).toEqual([42]);+ expect(credential.toJSON().response.signature).toBe(+ signedIn.response.signature,+ );+ });++ it("raises the native side's failure as the DOMException a browser would", async () => {+ const { credentials } = load({+ reply: () => ({ error: "NotAllowedError", message: "" }),+ });+ await expect(+ credentials.get({ publicKey: { challenge: new Uint8Array([1]) } }),+ ).rejects.toMatchObject({+ name: "NotAllowedError",+ });+ const typed = load({+ reply: () => ({ error: "TypeError", message: "bad" }),+ });+ await expect(typed.credentials.create(createOptions)).rejects.toMatchObject(+ { name: "TypeError" },+ );+ });++ it("leaves requests without publicKey to the engine", async () => {+ const { credentials, nativeCalls, posted } = load({ reply: () => created });+ expect(await credentials.get({ password: true })).toBe("native");+ expect(nativeCalls).toHaveLength(1);+ expect(posted).toHaveLength(0);+ });++ it("holds a conditional request until the page aborts it, and asks nothing", async () => {+ const { window, credentials, posted } = load({ reply: () => signedIn });+ const controller = new AbortController();+ const pending = credentials.get({+ mediation: "conditional",+ signal: controller.signal,+ publicKey: { challenge: new Uint8Array([1]) },+ });+ controller.abort();+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });+ expect(posted).toHaveLength(0);+ expect(+ await window.PublicKeyCredential.isConditionalMediationAvailable(),+ ).toBe(false);+ });++ it("reports the platform authenticator from the native side", async () => {+ let ready = false;+ const { window, posted } = load({+ reply: () => (ready ? { available: true } : { error: "NotAllowedError" }),+ });+ // A call before the native side answers is not remembered as "no".+ expect(+ await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(),+ ).toBe(false);+ ready = true;+ expect(+ await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(),+ ).toBe(true);+ await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();+ expect(posted).toHaveLength(2);+ });++ it("refuses when the native handler is missing, and stays out of frames", async () => {+ const { credentials } = load({ handler: false, reply: () => created });+ await expect(credentials.create(createOptions)).rejects.toMatchObject({+ name: "NotAllowedError",+ });+ const framed = load({ top: false, reply: () => created });+ expect(await framed.credentials.create(createOptions)).toBe("native");+ });++ it("tells the native side to close its prompt when the page aborts", async () => {+ const { credentials, posted } = load({+ reply: (request) =>+ request.kind === "cancel" ? {} : new Promise(() => {}),+ });+ const controller = new AbortController();+ const pending = credentials.get({+ signal: controller.signal,+ publicKey: { challenge: new Uint8Array([1]) },+ });+ controller.abort();+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });+ expect(posted.map((request) => request.kind)).toEqual(["get", "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 {+ const { credentials, posted } = load({+ reply: (request) =>+ request.kind === "cancel" ? {} : new Promise(() => {}),+ });+ let settled = null;+ credentials+ .get({ publicKey: { challenge: new Uint8Array([1]), timeout: 1000 } })+ .catch((error) => (settled = error.name));+ await vi.advanceTimersByTimeAsync(1000);+ expect(settled).toBe(null);+ await vi.advanceTimersByTimeAsync(29000);+ expect(settled).toBe("NotAllowedError");+ expect(posted.map((request) => request.kind)).toEqual(["get", "cancel"]);+ let unbounded = null;+ credentials+ .get({ publicKey: { challenge: new Uint8Array([1]) } })+ .catch((error) => (unbounded = error.name));+ await vi.advanceTimersByTimeAsync(299000);+ expect(unbounded).toBe(null);+ await vi.advanceTimersByTimeAsync(1000);+ expect(unbounded).toBe("NotAllowedError");+ } finally {+ vi.useRealTimers();+ }+ });++ it("declines a conditional create without asking the user", async () => {+ const { credentials, posted } = load({ reply: () => created });+ await expect(+ credentials.create({ ...createOptions, mediation: "conditional" }),+ ).rejects.toMatchObject({ name: "NotAllowedError" });+ expect(posted).toHaveLength(0);+ });+});