Skip to content

armgit / Pake

Public Imported from GitHub
0

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

feat: support HTTP Basic auth on macOS WKWebView (#1356)

xiaojueshi891bab1d451c
diff --git a/AGENTS.md b/AGENTS.md
index 7e6708b4..13d805c0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -85,7 +85,7 @@ Proactive latent-bug sweeps use `.agents/skills/bugs/SKILL.md`. Pick one row and
| Auth / popup | `auth.js`, `event.js` | macOS auth crash, SSO in system browser, Apple popup exception |
| Clipboard | `event.js` | keydown steals native paste; double-paste fallback |
| Multi-window / icon | `window.rs`, `setup.rs` | Missing `reapply_window_icon` on show; secondary window toast/target; Cmd+N blank flash |
-| Platform capability | `cert.rs`, proxy, WebKit flags | Flag name present, platform no-op |
+| Platform capability | `auth.rs`, proxy, WebKit flags | Flag name present, platform no-op |
| CLI / config contract | `bin/`, `schema/` | Config smuggles out-of-range values CLI rejects |
## Current Risk Areas
diff --git a/bin/defaults.ts b/bin/defaults.ts
index 3b0a24c4..2d864b12 100644
--- a/bin/defaults.ts
+++ b/bin/defaults.ts
@@ -33,6 +33,7 @@ export const DEFAULT_PAKE_OPTIONS: PakeCliOptions = {
useLocalFile: false,
systemTrayIcon: '',
proxyUrl: '',
+ basicAuth: false,
debug: false,
json: false,
inject: [],
diff --git a/bin/helpers/cli-program.ts b/bin/helpers/cli-program.ts
index 5e2602d1..ea367f7f 100644
--- a/bin/helpers/cli-program.ts
+++ b/bin/helpers/cli-program.ts
@@ -79,6 +79,14 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
'--config <path>',
'Load options from a JSON config file (fields mirror CLI options, see schema/pake.schema.json)',
)
+ .addOption(
+ new Option(
+ '--basic-auth',
+ 'Prompt for HTTP Basic credentials at runtime (macOS only)',
+ )
+ .default(DEFAULT.basicAuth)
+ .hideHelp(),
+ )
.addOption(
new Option(
'--proxy-url <url>',
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index e8f5cfb9..b135fea5 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -447,7 +447,8 @@ async function injectCustomCode(
options: PakeAppOptions,
tauriConf: PakeTauriConfig,
): Promise<void> {
- const { inject, proxyUrl, multiInstance, multiWindow, wasm } = options;
+ const { inject, proxyUrl, basicAuth, multiInstance, multiWindow, wasm } =
+ options;
const injectFilePath = path.join(
npmDirectory,
'src-tauri/src/inject/custom.js',
@@ -474,6 +475,7 @@ async function injectCustomCode(
}
tauriConf.pake.proxy_url = proxyUrl || '';
+ tauriConf.pake.basic_auth = basicAuth;
tauriConf.pake.multi_instance = multiInstance;
tauriConf.pake.multi_window = multiWindow;
diff --git a/bin/types.ts b/bin/types.ts
index 068c11bf..a8c29dcd 100644
--- a/bin/types.ts
+++ b/bin/types.ts
@@ -84,6 +84,9 @@ export interface PakeCliOptions {
// Set Api Proxy
proxyUrl: string;
+ // Prompt for HTTP Basic credentials at runtime on macOS, default false.
+ basicAuth: boolean;
+
// Installer language, valid for Windows users, default is en-US
installerLanguage: string;
@@ -201,6 +204,7 @@ export interface PakeConfig {
system_tray: PlatformSpecific<boolean>;
system_tray_path: string;
proxy_url: string;
+ basic_auth: boolean;
multi_instance: boolean;
multi_window: boolean;
inject?: string[];
diff --git a/dist/cli.js b/dist/cli.js
index 12ff44f1..c0bafddc 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -919,7 +919,7 @@ async function mergeIcons(options, name, tauriConf, platform, safeAppName) {
delete tauriConf.app.trayIcon;
}
async function injectCustomCode(options, tauriConf) {
- const { inject, proxyUrl, multiInstance, multiWindow, wasm } = options;
+ const { inject, proxyUrl, basicAuth, multiInstance, multiWindow, wasm } = options;
const injectFilePath = path.join(npmDirectory, 'src-tauri/src/inject/custom.js');
if (inject?.length > 0) {
const injectArray = Array.isArray(inject) ? inject : [inject];
@@ -936,6 +936,7 @@ async function injectCustomCode(options, tauriConf) {
await fsExtra.writeFile(injectFilePath, '');
}
tauriConf.pake.proxy_url = proxyUrl || '';
+ tauriConf.pake.basic_auth = basicAuth;
tauriConf.pake.multi_instance = multiInstance;
tauriConf.pake.multi_window = multiWindow;
if (wasm) {
@@ -3031,6 +3032,7 @@ const DEFAULT_PAKE_OPTIONS = {
useLocalFile: false,
systemTrayIcon: '',
proxyUrl: '',
+ basicAuth: false,
debug: false,
json: false,
inject: [],
@@ -3133,6 +3135,9 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
.option('--debug', 'Debug build and more output', DEFAULT_PAKE_OPTIONS.debug)
.option('--json', 'Machine-readable output: logs to stderr, one JSON result on stdout', DEFAULT_PAKE_OPTIONS.json)
.option('--config <path>', 'Load options from a JSON config file (fields mirror CLI options, see schema/pake.schema.json)')
+ .addOption(new Option('--basic-auth', 'Prompt for HTTP Basic credentials at runtime (macOS only)')
+ .default(DEFAULT_PAKE_OPTIONS.basicAuth)
+ .hideHelp())
.addOption(new Option('--proxy-url <url>', 'Proxy URL for all network requests (http://, https://, socks5://)')
.default(DEFAULT_PAKE_OPTIONS.proxyUrl)
.hideHelp())
diff --git a/docs/cli-usage.md b/docs/cli-usage.md
index 096eb30c..0ac7dfb5 100644
--- a/docs/cli-usage.md
+++ b/docs/cli-usage.md
@@ -595,6 +595,14 @@ Set proxy server for all network requests. Supports HTTP, HTTPS, and SOCKS5. Ava
--proxy-url socks5://127.0.0.1:7891
```
+#### [basic-auth]
+
+Prompt for HTTP Basic credentials when the target site requests them. This is only needed on macOS, where WKWebView does not provide its own 401 login dialog. Credentials are entered in the packaged app at runtime and are kept only for the current session.
+
+```shell
+--basic-auth
+```
+
#### [debug]
Enable developer tools and detailed logging for debugging.
diff --git a/docs/cli-usage_CN.md b/docs/cli-usage_CN.md
index c7cfbc8f..2eaef456 100644
--- a/docs/cli-usage_CN.md
+++ b/docs/cli-usage_CN.md
@@ -593,6 +593,14 @@ pake ./my-app/index.html --name "my-app" --use-local-file
--proxy-url socks5://127.0.0.1:7891
```
+#### [basic-auth]
+
+当目标站点请求 HTTP Basic 认证时显示登录提示。此选项仅用于 macOS,因为 WKWebView 不会自行显示 401 登录框。凭据在打包后的应用中运行时输入,并且只在当前会话中保留。
+
+```shell
+--basic-auth
+```
+
#### [debug]
启用开发者工具和详细日志输出,用于调试。
diff --git a/schema/pake.schema.json b/schema/pake.schema.json
index d2a8ffd7..8da9def9 100644
--- a/schema/pake.schema.json
+++ b/schema/pake.schema.json
@@ -86,6 +86,11 @@
"description": "Proxy URL for all network requests (http://, https://, socks5://).",
"default": ""
},
+ "basicAuth": {
+ "type": "boolean",
+ "description": "Prompt for HTTP Basic credentials at runtime on macOS (works around the missing WKWebView 401 dialog).",
+ "default": false
+ },
"userAgent": {
"type": "string",
"description": "Custom user agent.",
diff --git a/src-tauri/src/app/auth.rs b/src-tauri/src/app/auth.rs
new file mode 100644
index 00000000..a1ab16e7
--- /dev/null
+++ b/src-tauri/src/app/auth.rs
@@ -0,0 +1,473 @@
+// macOS authentication handling for HTTP Basic auth and invalid certificates.
+//
+// WKWebView does not show its own HTTP Basic login dialog, and it ignores the
+// Chromium certificate-error flag. Wry's navigation delegate also does not
+// implement the authentication-challenge callback. This host-scoped proxy
+// handles the two opt-in cases and forwards every other selector to wry.
+
+use objc2::rc::{Retained, Weak};
+use objc2::runtime::{AnyObject, Bool, NSObject, NSObjectProtocol, Sel};
+use objc2::{class, define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
+use objc2_app_kit::{
+ NSAlert, NSAlertFirstButtonReturn, NSControlSize, NSSecureTextField, NSTextField, NSView,
+};
+use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
+use std::ffi::c_void;
+
+// NSURLSessionAuthChallengeDisposition values.
+const USE_CREDENTIAL: isize = 0;
+const PERFORM_DEFAULT_HANDLING: isize = 1;
+const CANCEL_AUTHENTICATION_CHALLENGE: isize = 2;
+
+// NSURLCredentialPersistenceForSession.
+const CREDENTIAL_PERSISTENCE_FOR_SESSION: usize = 1;
+
+// NSKeyValueObservingOptionNew.
+const KVO_OPTION_NEW: usize = 1;
+
+const HTTP_BASIC_METHOD: &str = "NSURLAuthenticationMethodHTTPBasic";
+const SERVER_TRUST_METHOD: &str = "NSURLAuthenticationMethodServerTrust";
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ChallengeAction {
+ Default,
+ PromptForBasicCredentials,
+ TrustServerCertificate,
+}
+
+pub struct PakeAuthDelegateIvars {
+ // Wry's real navigation delegate; all non-challenge selectors forward here.
+ inner: Weak<AnyObject>,
+ // The proxy observes this webview so it can recover if WebKit replaces the
+ // navigation delegate after construction but before the first challenge.
+ webview: Weak<AnyObject>,
+ allowed_host: String,
+ prompt_for_basic_auth: bool,
+ allow_invalid_certificates: bool,
+}
+
+static AUTH_DELEGATE_ASSOCIATION_KEY: u8 = 0;
+
+fn hosts_match(allowed_host: &str, challenge_host: &str) -> bool {
+ allowed_host
+ .trim_end_matches('.')
+ .eq_ignore_ascii_case(challenge_host.trim_end_matches('.'))
+}
+
+fn challenge_action(
+ allowed_host: &str,
+ challenge_host: &str,
+ authentication_method: &str,
+ has_server_trust: bool,
+ prompt_for_basic_auth: bool,
+ allow_invalid_certificates: bool,
+) -> ChallengeAction {
+ if !hosts_match(allowed_host, challenge_host) {
+ return ChallengeAction::Default;
+ }
+ if allow_invalid_certificates
+ && has_server_trust
+ && authentication_method == SERVER_TRUST_METHOD
+ {
+ return ChallengeAction::TrustServerCertificate;
+ }
+ if prompt_for_basic_auth && authentication_method == HTTP_BASIC_METHOD {
+ return ChallengeAction::PromptForBasicCredentials;
+ }
+ ChallengeAction::Default
+}
+
+fn prompt_for_credentials(
+ mtm: MainThreadMarker,
+ host: &str,
+ realm: Option<&str>,
+ previous_failures: usize,
+) -> Option<(String, String)> {
+ let alert = NSAlert::new(mtm);
+ let title = if previous_failures == 0 {
+ format!("Sign In to {host}")
+ } else {
+ format!("Couldn't Sign In to {host}")
+ };
+ alert.setMessageText(&NSString::from_str(&title));
+
+ let detail = match (previous_failures, realm.filter(|value| !value.is_empty())) {
+ (0, Some(realm)) => format!("Enter the username and password for {realm}."),
+ (0, None) => "Enter the username and password for this server.".to_string(),
+ _ => "The username or password was incorrect. Try again.".to_string(),
+ };
+ alert.setInformativeText(&NSString::from_str(&detail));
+
+ let accessory = NSView::initWithFrame(
+ mtm.alloc(),
+ NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(320.0, 70.0)),
+ );
+ let username_label = NSTextField::labelWithString(&NSString::from_str("Username:"), mtm);
+ username_label.setFrame(NSRect::new(
+ NSPoint::new(0.0, 45.0),
+ NSSize::new(76.0, 18.0),
+ ));
+ let username = NSTextField::initWithFrame(
+ mtm.alloc(),
+ NSRect::new(NSPoint::new(84.0, 38.0), NSSize::new(236.0, 28.0)),
+ );
+ username.setControlSize(NSControlSize::Large);
+ let password_label = NSTextField::labelWithString(&NSString::from_str("Password:"), mtm);
+ password_label.setFrame(NSRect::new(
+ NSPoint::new(0.0, 11.0),
+ NSSize::new(76.0, 18.0),
+ ));
+ let password = NSSecureTextField::initWithFrame(
+ mtm.alloc(),
+ NSRect::new(NSPoint::new(84.0, 4.0), NSSize::new(236.0, 28.0)),
+ );
+ password.setControlSize(NSControlSize::Large);
+ accessory.addSubview(&username_label);
+ accessory.addSubview(&username);
+ accessory.addSubview(&password_label);
+ accessory.addSubview(&password);
+ alert.setAccessoryView(Some(&accessory));
+ let sign_in_button = alert.addButtonWithTitle(&NSString::from_str("Sign In"));
+ sign_in_button.setControlSize(NSControlSize::Large);
+ let cancel_button = alert.addButtonWithTitle(&NSString::from_str("Cancel"));
+ cancel_button.setControlSize(NSControlSize::Large);
+ alert.layout();
+ for button in [&sign_in_button, &cancel_button] {
+ let size = button.frame().size;
+ button.setFrameSize(NSSize::new(size.width, 34.0));
+ }
+ alert.window().makeFirstResponder(Some(&username));
+
+ if alert.runModal() != NSAlertFirstButtonReturn {
+ return None;
+ }
+ Some((
+ username.stringValue().to_string(),
+ password.stringValue().to_string(),
+ ))
+}
+
+define_class!(
+ #[unsafe(super(NSObject))]
+ #[name = "PakeAuthenticationDelegate"]
+ #[thread_kind = MainThreadOnly]
+ #[ivars = PakeAuthDelegateIvars]
+ struct PakeAuthDelegate;
+
+ unsafe impl NSObjectProtocol for PakeAuthDelegate {}
+
+ impl PakeAuthDelegate {
+ #[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
+ fn did_receive_challenge(
+ &self,
+ _webview: &AnyObject,
+ challenge: &AnyObject,
+ handler: &block2::Block<dyn Fn(isize, *mut AnyObject)>,
+ ) {
+ unsafe {
+ let space: *mut AnyObject = msg_send![challenge, protectionSpace];
+ if space.is_null() {
+ handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
+ return;
+ }
+
+ let host: *mut NSString = msg_send![space, host];
+ let method: *mut NSString = msg_send![space, authenticationMethod];
+ if host.is_null() || method.is_null() {
+ handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
+ return;
+ }
+ let challenge_host = (&*host).to_string();
+ let authentication_method = (&*method).to_string();
+ let server_trust: *mut AnyObject = msg_send![space, serverTrust];
+
+ match challenge_action(
+ &self.ivars().allowed_host,
+ &challenge_host,
+ &authentication_method,
+ !server_trust.is_null(),
+ self.ivars().prompt_for_basic_auth,
+ self.ivars().allow_invalid_certificates,
+ ) {
+ ChallengeAction::Default => {
+ handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
+ }
+ ChallengeAction::TrustServerCertificate => {
+ let credential: *mut AnyObject = msg_send![
+ class!(NSURLCredential),
+ credentialForTrust: server_trust
+ ];
+ if credential.is_null() {
+ handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
+ } else {
+ handler.call((USE_CREDENTIAL, credential));
+ }
+ }
+ ChallengeAction::PromptForBasicCredentials => {
+ let realm: *mut NSString = msg_send![space, realm];
+ let realm = (!realm.is_null()).then(|| (&*realm).to_string());
+ let previous_failures: usize =
+ msg_send![challenge, previousFailureCount];
+ let Some((user, password)) = prompt_for_credentials(
+ self.mtm(),
+ &challenge_host,
+ realm.as_deref(),
+ previous_failures,
+ ) else {
+ handler.call((
+ CANCEL_AUTHENTICATION_CHALLENGE,
+ core::ptr::null_mut(),
+ ));
+ return;
+ };
+ let credential: *mut AnyObject = msg_send![
+ class!(NSURLCredential),
+ credentialWithUser: &*NSString::from_str(&user),
+ password: &*NSString::from_str(&password),
+ persistence: CREDENTIAL_PERSISTENCE_FOR_SESSION
+ ];
+ if credential.is_null() {
+ handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
+ } else {
+ handler.call((USE_CREDENTIAL, credential));
+ }
+ }
+ }
+ }
+ }
+
+ #[unsafe(method(respondsToSelector:))]
+ fn responds_to_selector(&self, selector: Sel) -> Bool {
+ let responds: Bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
+ if responds.as_bool() {
+ return Bool::YES;
+ }
+ self.ivars()
+ .inner
+ .load()
+ .map(|inner| unsafe { msg_send![&*inner, respondsToSelector: selector] })
+ .unwrap_or(Bool::NO)
+ }
+
+ #[unsafe(method(forwardingTargetForSelector:))]
+ fn forwarding_target(&self, _selector: Sel) -> *mut AnyObject {
+ self.ivars()
+ .inner
+ .load()
+ .map(|inner| Retained::as_ptr(&inner) as *mut AnyObject)
+ .unwrap_or(core::ptr::null_mut())
+ }
+
+ #[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
+ fn observe_value(
+ &self,
+ key_path: &NSString,
+ object: &AnyObject,
+ change: *mut AnyObject,
+ context: *mut c_void,
+ ) {
+ unsafe {
+ if key_path.to_string() != "navigationDelegate" {
+ let _: () = msg_send![
+ super(self),
+ observeValueForKeyPath: key_path,
+ ofObject: object,
+ change: change,
+ context: context
+ ];
+ return;
+ }
+ let current: *mut AnyObject = msg_send![object, navigationDelegate];
+ let self_ptr = self as *const Self as *mut AnyObject;
+ if current != self_ptr {
+ let _: () = msg_send![object, setNavigationDelegate: self];
+ }
+ }
+ }
+ }
+);
+
+impl Drop for PakeAuthDelegate {
+ fn drop(&mut self) {
+ if let Some(webview) = self.ivars().webview.load() {
+ unsafe {
+ let key_path = NSString::from_str("navigationDelegate");
+ let self_ptr = self as *const Self as *mut AnyObject;
+ let _: () = msg_send![
+ &*webview,
+ removeObserver: self_ptr,
+ forKeyPath: &*key_path
+ ];
+ }
+ }
+ }
+}
+
+impl PakeAuthDelegate {
+ fn new(
+ webview: &Retained<AnyObject>,
+ inner: &Retained<AnyObject>,
+ allowed_host: String,
+ prompt_for_basic_auth: bool,
+ allow_invalid_certificates: bool,
+ mtm: MainThreadMarker,
+ ) -> Retained<Self> {
+ let this = mtm
+ .alloc::<PakeAuthDelegate>()
+ .set_ivars(PakeAuthDelegateIvars {
+ inner: Weak::from_retained(inner),
+ webview: Weak::from_retained(webview),
+ allowed_host,
+ prompt_for_basic_auth,
+ allow_invalid_certificates,
+ });
+ unsafe { msg_send![super(this), init] }
+ }
+}
+
+/// Install the authentication proxy before navigating to the target URL.
+/// Credentials are requested inside the packaged app and retained only by the
+/// current URL session. Returns false when setup cannot be completed.
+pub fn install_auth_delegate_and_navigate(
+ webview_ptr: *mut c_void,
+ allowed_host: String,
+ target_url: String,
+ prompt_for_basic_auth: bool,
+ allow_invalid_certificates: bool,
+) -> bool {
+ if webview_ptr.is_null()
+ || allowed_host.is_empty()
+ || target_url.is_empty()
+ || (!prompt_for_basic_auth && !allow_invalid_certificates)
+ {
+ return false;
+ }
+ let Some(mtm) = MainThreadMarker::new() else {
+ return false;
+ };
+ unsafe {
+ let Some(webview) = Retained::retain(webview_ptr as *mut AnyObject) else {
+ return false;
+ };
+ let existing: *mut AnyObject = msg_send![&*webview, navigationDelegate];
+ if existing.is_null() {
+ return false;
+ }
+ let Some(inner) = Retained::retain(existing) else {
+ return false;
+ };
+ let proxy = PakeAuthDelegate::new(
+ &webview,
+ &inner,
+ allowed_host,
+ prompt_for_basic_auth,
+ allow_invalid_certificates,
+ mtm,
+ );
+ objc2::ffi::objc_setAssociatedObject(
+ &*webview as *const AnyObject as *mut AnyObject,
+ std::ptr::addr_of!(AUTH_DELEGATE_ASSOCIATION_KEY).cast(),
+ Retained::as_ptr(&proxy) as *mut AnyObject,
+ objc2::ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,
+ );
+ let key_path = NSString::from_str("navigationDelegate");
+ let observer_ptr = &*proxy as *const PakeAuthDelegate as *mut AnyObject;
+ let _: () = msg_send![
+ &*webview,
+ addObserver: observer_ptr,
+ forKeyPath: &*key_path,
+ options: KVO_OPTION_NEW,
+ context: core::ptr::null_mut::<c_void>()
+ ];
+ let _: () = msg_send![&*webview, setNavigationDelegate: &*proxy];
+
+ let target_url = NSString::from_str(&target_url);
+ let ns_url: *mut AnyObject = msg_send![class!(NSURL), URLWithString: &*target_url];
+ if ns_url.is_null() {
+ return false;
+ }
+ let request: *mut AnyObject = msg_send![class!(NSURLRequest), requestWithURL: ns_url];
+ if request.is_null() {
+ return false;
+ }
+ let _: () = msg_send![&*webview, loadRequest: request];
+ true
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ challenge_action, hosts_match, ChallengeAction, HTTP_BASIC_METHOD, SERVER_TRUST_METHOD,
+ };
+
+ #[test]
+ fn matches_only_the_configured_host() {
+ assert!(hosts_match("INTERNAL.EXAMPLE.COM", "internal.example.com"));
+ assert!(hosts_match("internal.example.com.", "internal.example.com"));
+ assert!(!hosts_match("internal.example.com", "login.example.com"));
+ }
+
+ #[test]
+ fn prompts_for_basic_auth_only_when_enabled_on_the_target_host() {
+ assert_eq!(
+ challenge_action(
+ "internal.example.com",
+ "internal.example.com",
+ HTTP_BASIC_METHOD,
+ true,
+ true,
+ true,
+ ),
+ ChallengeAction::PromptForBasicCredentials
+ );
+ assert_eq!(
+ challenge_action(
+ "internal.example.com",
+ "login.example.com",
+ HTTP_BASIC_METHOD,
+ false,
+ true,
+ false,
+ ),
+ ChallengeAction::Default
+ );
+ assert_eq!(
+ challenge_action(
+ "internal.example.com",
+ "internal.example.com",
+ HTTP_BASIC_METHOD,
+ false,
+ false,
+ false,
+ ),
+ ChallengeAction::Default
+ );
+ }
+
+ #[test]
+ fn accepts_server_trust_only_when_enabled_on_the_target_host() {
+ assert_eq!(
+ challenge_action(
+ "internal.example.com",
+ "internal.example.com",
+ SERVER_TRUST_METHOD,
+ true,
+ false,
+ true,
+ ),
+ ChallengeAction::TrustServerCertificate
+ );
+ assert_eq!(
+ challenge_action(
+ "internal.example.com",
+ "login.example.com",
+ SERVER_TRUST_METHOD,
+ true,
+ true,
+ true,
+ ),
+ ChallengeAction::Default
+ );
+ }
+}
diff --git a/src-tauri/src/app/cert.rs b/src-tauri/src/app/cert.rs
deleted file mode 100644
index ebba28e7..00000000
--- a/src-tauri/src/app/cert.rs
+++ /dev/null
@@ -1,187 +0,0 @@
-// macOS TLS certificate bypass for `--ignore-certificate-errors`.
-//
-// On macOS the webview is a WKWebView, which ignores the Chromium
-// `--ignore-certificate-errors` flag entirely, so Pake's flag was a no-op here
-// (see the Windows/Linux vs macOS split in window.rs). wry's own
-// `WryNavigationDelegate` does not implement
-// `webView:didReceiveAuthenticationChallenge:completionHandler:`, so WKWebView
-// falls back to default validation and rejects self-signed certs.
-//
-// This installs a thin navigation-delegate proxy that accepts server trust only
-// for the configured target host and forwards every other selector to wry's
-// original delegate, so navigation policy, downloads, and page-load callbacks
-// keep working untouched. It is installed only when the user opts in via
-// `--ignore-certificate-errors`.
-
-use objc2::rc::{Retained, Weak};
-use objc2::runtime::{AnyObject, Bool, NSObject, NSObjectProtocol, Sel};
-use objc2::{class, define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
-use objc2_foundation::NSString;
-use std::ffi::c_void;
-
-// NSURLSessionAuthChallengeDisposition values.
-const USE_CREDENTIAL: isize = 0;
-const PERFORM_DEFAULT_HANDLING: isize = 1;
-
-pub struct PakeCertDelegateIvars {
- // wry's real navigation delegate; every non-challenge selector forwards here.
- inner: Weak<AnyObject>,
- allowed_host: String,
-}
-
-static CERT_BYPASS_ASSOCIATION_KEY: u8 = 0;
-
-fn hosts_match(allowed_host: &str, challenge_host: &str) -> bool {
- allowed_host
- .trim_end_matches('.')
- .eq_ignore_ascii_case(challenge_host.trim_end_matches('.'))
-}
-
-define_class!(
- #[unsafe(super(NSObject))]
- #[name = "PakeCertBypassDelegate"]
- #[thread_kind = MainThreadOnly]
- #[ivars = PakeCertDelegateIvars]
- struct PakeCertBypassDelegate;
-
- unsafe impl NSObjectProtocol for PakeCertBypassDelegate {}
-
- impl PakeCertBypassDelegate {
- #[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
- fn did_receive_challenge(
- &self,
- _webview: &AnyObject,
- challenge: &AnyObject,
- handler: &block2::Block<dyn Fn(isize, *mut AnyObject)>,
- ) {
- unsafe {
- let space: *mut AnyObject = msg_send![challenge, protectionSpace];
- if space.is_null() {
- handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
- return;
- }
- let host: *mut NSString = msg_send![space, host];
- if host.is_null()
- || !hosts_match(&self.ivars().allowed_host, &(&*host).to_string())
- {
- handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
- return;
- }
- // Only server-trust challenges carry a non-null serverTrust; for
- // anything else (e.g. HTTP basic auth) defer to default handling.
- let server_trust: *mut AnyObject = msg_send![space, serverTrust];
- if server_trust.is_null() {
- handler.call((PERFORM_DEFAULT_HANDLING, core::ptr::null_mut()));
- return;
- }
- let credential: *mut AnyObject =
- msg_send![class!(NSURLCredential), credentialForTrust: server_trust];
- handler.call((USE_CREDENTIAL, credential));
- }
- }
-
- // WKWebView probes respondsToSelector: before calling optional delegate
- // methods, so report our own methods plus everything wry implements.
- #[unsafe(method(respondsToSelector:))]
- fn responds_to_selector(&self, selector: Sel) -> Bool {
- let responds: Bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
- if responds.as_bool() {
- return Bool::YES;
- }
- self.ivars()
- .inner
- .load()
- .map(|inner| unsafe { msg_send![&*inner, respondsToSelector: selector] })
- .unwrap_or(Bool::NO)
- }
-
- // Fast-forward any selector we do not implement to wry's delegate.
- #[unsafe(method(forwardingTargetForSelector:))]
- fn forwarding_target(&self, _selector: Sel) -> *mut AnyObject {
- self.ivars()
- .inner
- .load()
- .map(|inner| Retained::as_ptr(&inner) as *mut AnyObject)
- .unwrap_or(core::ptr::null_mut())
- }
- }
-);
-
-impl PakeCertBypassDelegate {
- fn new(
- inner: &Retained<AnyObject>,
- allowed_host: String,
- mtm: MainThreadMarker,
- ) -> Retained<Self> {
- let this = mtm
- .alloc::<PakeCertBypassDelegate>()
- .set_ivars(PakeCertDelegateIvars {
- inner: Weak::from_retained(inner),
- allowed_host,
- });
- unsafe { msg_send![super(this), init] }
- }
-}
-
-/// Replace the WKWebView's navigation delegate with a proxy that accepts
-/// invalid TLS certificates for the configured target host, then navigate to
-/// that target. `webview_ptr` is the raw `WKWebView` from
-/// `PlatformWebview::inner()`. Returns false if setup cannot be completed.
-pub fn install_cert_bypass_and_navigate(
- webview_ptr: *mut c_void,
- allowed_host: String,
- target_url: String,
-) -> bool {
- if webview_ptr.is_null() || allowed_host.is_empty() || target_url.is_empty() {
- return false;
- }
- let Some(mtm) = MainThreadMarker::new() else {
- return false;
- };
- unsafe {
- let webview: &AnyObject = &*(webview_ptr as *const AnyObject);
- let existing: *mut AnyObject = msg_send![webview, navigationDelegate];
- if existing.is_null() {
- return false;
- }
- let Some(inner) = Retained::retain(existing) else {
- return false;
- };
- let proxy = PakeCertBypassDelegate::new(&inner, allowed_host, mtm);
- objc2::ffi::objc_setAssociatedObject(
- webview as *const AnyObject as *mut AnyObject,
- std::ptr::addr_of!(CERT_BYPASS_ASSOCIATION_KEY).cast(),
- Retained::as_ptr(&proxy) as *mut AnyObject,
- objc2::ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,
- );
- let _: () = msg_send![webview, setNavigationDelegate: &*proxy];
-
- let target_url = NSString::from_str(&target_url);
- let ns_url: *mut AnyObject = msg_send![class!(NSURL), URLWithString: &*target_url];
- if ns_url.is_null() {
- return false;
- }
- let request: *mut AnyObject = msg_send![class!(NSURLRequest), requestWithURL: ns_url];
- if request.is_null() {
- return false;
- }
- let _: () = msg_send![webview, loadRequest: request];
- true
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::hosts_match;
-
- #[test]
- fn accepts_the_configured_host_case_insensitively() {
- assert!(hosts_match("INTERNAL.EXAMPLE.COM", "internal.example.com"));
- assert!(hosts_match("internal.example.com.", "internal.example.com"));
- }
-
- #[test]
- fn rejects_other_hosts() {
- assert!(!hosts_match("internal.example.com", "login.example.com"));
- }
-}
diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rs
index 5724f5e6..d99e11c9 100644
--- a/src-tauri/src/app/config.rs
+++ b/src-tauri/src/app/config.rs
@@ -83,6 +83,11 @@ pub struct PakeConfig {
pub system_tray: FunctionON,
pub system_tray_path: String,
pub proxy_url: String,
+ /// Prompt for HTTP Basic credentials at runtime on macOS. WKWebView does
+ /// not provide its own 401 login dialog, while Windows and Linux WebViews
+ /// handle this flow natively.
+ #[serde(default)]
+ pub basic_auth: bool,
#[serde(default)]
pub multi_instance: bool,
#[serde(default)]
diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs
index 0b28fc68..db014488 100644
--- a/src-tauri/src/app/mod.rs
+++ b/src-tauri/src/app/mod.rs
@@ -1,5 +1,5 @@
#[cfg(target_os = "macos")]
-pub mod cert;
+pub mod auth;
pub mod config;
pub mod invoke;
#[cfg(target_os = "macos")]
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index d705c757..01a21b17 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -375,10 +375,13 @@ fn build_window(
))
})?;
+ // On macOS both HTTP Basic auth and certificate bypass use the same
+ // navigation-delegate proxy. Start on a neutral page so the proxy is in
+ // place before the target can issue its first authentication challenge.
#[cfg(target_os = "macos")]
- let cert_bypass_target = if label == "pake"
- && window_config.ignore_certificate_errors
+ let auth_target = if label == "pake"
&& window_config.url_type == "web"
+ && (config.basic_auth || window_config.ignore_certificate_errors)
{
Url::parse(&window_config.url).ok()
} else {
@@ -388,7 +391,7 @@ fn build_window(
// The delegate must be installed before the first TLS challenge. Start on
// a neutral page, then navigate from the with_webview callback below.
#[cfg(target_os = "macos")]
- let url = if cert_bypass_target.is_some() {
+ let url = if auth_target.is_some() {
WebviewUrl::CustomProtocol(
Url::parse("about:blank").expect("about:blank must be a valid URL"),
)
@@ -686,25 +689,28 @@ fn build_window(
let window = window_builder.build()?;
- // macOS WKWebView ignores the Chromium --ignore-certificate-errors flag, so
- // install a host-scoped delegate on the process-lifetime main window only.
- // Queue setup after construction so wry cannot replace the proxy while it
- // finishes initializing its own navigation delegate.
+ // WKWebView does not show an HTTP Basic login dialog and ignores Chromium's
+ // certificate-error flag. Install one host-scoped delegate for both flows
+ // on the process-lifetime main window, then navigate to the real target.
#[cfg(target_os = "macos")]
- if let Some(target_url) = cert_bypass_target {
+ if let Some(target_url) = auth_target {
let allowed_host = target_url
.host_str()
.expect("web URLs must have a host")
.to_owned();
- let cert_window = window.clone();
+ let prompt_for_basic_auth = config.basic_auth;
+ let allow_invalid_certificates = window_config.ignore_certificate_errors;
+ let auth_window = window.clone();
Queue::main().exec_async(move || {
- if let Err(error) = cert_window.with_webview(move |webview| {
- if !crate::app::cert::install_cert_bypass_and_navigate(
+ if let Err(error) = auth_window.with_webview(move |webview| {
+ if !crate::app::auth::install_auth_delegate_and_navigate(
webview.inner(),
allowed_host,
target_url.to_string(),
+ prompt_for_basic_auth,
+ allow_invalid_certificates,
) {
- eprintln!("[Pake] Failed to configure macOS certificate bypass.");
+ eprintln!("[Pake] Failed to configure macOS authentication handling.");
}
}) {
eprintln!("[Pake] Failed to access the macOS webview: {error}");
diff --git a/tests/unit/cli-options.test.ts b/tests/unit/cli-options.test.ts
index 1f0568f9..313097bd 100644
--- a/tests/unit/cli-options.test.ts
+++ b/tests/unit/cli-options.test.ts
@@ -29,6 +29,16 @@ describe('CLI options', () => {
expect(option?.defaultValue).toBe(false);
});
+ it('registers hidden --basic-auth as a runtime opt-in', () => {
+ const option = program.options.find((item) => item.long === '--basic-auth');
+
+ expect(option).toBeDefined();
+ expect(option?.defaultValue).toBe(false);
+ expect(option?.hidden).toBe(true);
+ expect(option?.required).toBe(false);
+ expect(option?.optional).toBe(false);
+ });
+
it('exposes --internal-url-regex option', () => {
const option = program.options.find(
(item) => item.long === '--internal-url-regex',
diff --git a/tests/unit/config-file.test.ts b/tests/unit/config-file.test.ts
index ddcc8222..81b34caa 100644
--- a/tests/unit/config-file.test.ts
+++ b/tests/unit/config-file.test.ts
@@ -151,5 +151,12 @@ describe('loadConfigFile', () => {
await expect(loadConfigFile(configPath2, validKeys)).rejects.toThrow(
/"inject" must be of type string\[\]/,
);
+ const configPath3 = await writeConfig(
+ { basicAuth: 'alice:secret' },
+ 'bad-basic-auth.json',
+ );
+ await expect(loadConfigFile(configPath3, validKeys)).rejects.toThrow(
+ /"basicAuth" must be of type boolean/,
+ );
});
});