Repository Public License
1import Diagnostics2import Foundation3import NavigatorCore4import WebKit56#if canImport(AppKit)7import AppKit8#elseif canImport(UIKit)9import UIKit10#endif1112/// The Objective-C face of a `WebEngine`: WebKit's delegates and the script message handler.13/// It holds the engine weakly — `WKUserContentController` retains its handlers, so a strong reference here14/// would keep every closed tab alive.15@MainActor16final class WebEngineAdapter: NSObject, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {17 private weak var engine: WebEngine?1819 init(engine: WebEngine) { self.engine = engine }2021 // MARK: WKScriptMessageHandler2223 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {24 engine?.receive(message)25 }2627 // MARK: WKNavigationDelegate — policy2829 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,30 preferences: WKWebpagePreferences,31 decisionHandler: @escaping @MainActor (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {32 guard let engine, engine.webView === webView else { decisionHandler(.cancel, preferences); return }33 decisionHandler(engine.decidePolicy(for: navigationAction, preferences: preferences), preferences)34 }3536 func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,37 decisionHandler: @escaping @MainActor (WKNavigationResponsePolicy) -> Void) {38 let disposition = (navigationResponse.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition")39 let isDownload = NavigationPolicy.responseIsDownload(canShowMIMEType: navigationResponse.canShowMIMEType,40 contentDisposition: disposition)41 decisionHandler(isDownload ? .download : .allow)42 }4344 func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {45 engine?.adopt(download)46 }4748 func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {49 engine?.adopt(download)50 }5152 // MARK: WKNavigationDelegate — progress5354 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {55 engine?.didStartProvisionalNavigation()56 }5758 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {59 engine?.didCommitNavigation()60 }6162 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {63 engine?.didFinishNavigation()64 }6566 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: any Error) {67 engine?.didFailNavigation(error, provisional: true)68 }6970 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: any Error) {71 engine?.didFailNavigation(error, provisional: false)72 }7374 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {75 engine?.webContentProcessDidTerminate()76 }7778 // MARK: WKNavigationDelegate — security7980 func webView(_ webView: WKWebView, respondTo challenge: URLAuthenticationChallenge)81 async -> (URLSession.AuthChallengeDisposition, URLCredential?) {82 guard let engine else { return (.cancelAuthenticationChallenge, nil) }83 return await engine.respond(to: challenge)84 }8586 func webView(_ webView: WKWebView, shouldAllowDeprecatedTLSFor challenge: URLAuthenticationChallenge) async -> Bool {87 // TLS 1.0/1.1 are never negotiated silently; the load fails and the UI shows a connection error.88 false89 }9091 // MARK: WKUIDelegate — windows9293 func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration,94 for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {95 engine?.createChild(configuration: configuration, action: navigationAction, features: windowFeatures)96 }9798 func webViewDidClose(_ webView: WKWebView) {99 guard let engine else { return }100 engine.navigationDelegate?.webEngineDidRequestClose(engine)101 }102103 // MARK: WKUIDelegate — dialogs104105 func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async {106 _ = await engine?.presentDialog(.alert, message: message, frame: frame)107 }108109 func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String,110 initiatedByFrame frame: WKFrameInfo) async -> Bool {111 await engine?.presentDialog(.confirm, message: message, frame: frame).accepted ?? false112 }113114 func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?,115 initiatedByFrame frame: WKFrameInfo) async -> String? {116 guard let response = await engine?.presentDialog(.prompt(defaultText: defaultText), message: prompt, frame: frame),117 response.accepted else { return nil }118 return response.text ?? ""119 }120121 // MARK: WKUIDelegate — permissions122123 func webView(_ webView: WKWebView, decideMediaCapturePermissionsFor origin: WKSecurityOrigin,124 initiatedBy frame: WKFrameInfo, type: WKMediaCaptureType) async -> WKPermissionDecision {125 guard let engine else { return .deny }126 let kinds: [PermissionKind] = switch type {127 case .camera: [.camera]128 case .microphone: [.microphone]129 case .cameraAndMicrophone: [.camera, .microphone]130 @unknown default: [.camera, .microphone]131 }132 return await engine.resolvePermission(kinds, requestingOrigin: WebOrigin(origin), isMainFrame: frame.isMainFrame)133 ? .grant : .deny134 }135136 #if os(iOS)137 func webView(_ webView: WKWebView, requestDeviceOrientationAndMotionPermissionFor origin: WKSecurityOrigin,138 initiatedByFrame frame: WKFrameInfo, decisionHandler: @escaping @MainActor (WKPermissionDecision) -> Void) {139 guard let engine else { decisionHandler(.deny); return }140 let requesting = WebOrigin(origin), isMainFrame = frame.isMainFrame141 Task { @MainActor in142 let granted = await engine.resolvePermission([.deviceMotion], requestingOrigin: requesting, isMainFrame: isMainFrame)143 decisionHandler(granted ? .grant : .deny)144 }145 }146 #endif147148 /// OS 27 lets the app decide geolocation per origin. On earlier systems this method does not exist for149 /// WebKit and its built-in behaviour applies (see WEBKIT_LIMITATIONS.md).150 @available(macOS 27.0, iOS 27.0, *)151 func webView(_ webView: WKWebView, requestGeolocationPermissionFor origin: WKSecurityOrigin,152 initiatedBy frame: WKFrameInfo) async -> WKPermissionDecision {153 guard let engine else { return .deny }154 return await engine.resolvePermission([.location], requestingOrigin: WebOrigin(origin), isMainFrame: frame.isMainFrame)155 ? .grant : .deny156 }157158 // MARK: WKUIDelegate — files and context menus159160 #if os(macOS)161 func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters,162 initiatedByFrame frame: WKFrameInfo) async -> [URL]? {163 guard let engine, let delegate = engine.uiDelegate else { return nil }164 let request = FileChooserRequest(allowsMultipleSelection: parameters.allowsMultipleSelection,165 allowsDirectories: parameters.allowsDirectories,166 origin: WebOrigin(frame.securityOrigin))167 return await delegate.webEngine(engine, chooseFilesFor: request)168 }169 #endif170171 #if os(iOS)172 func webView(_ webView: WKWebView, contextMenuConfigurationFor elementInfo: WKContextMenuElementInfo) async -> UIContextMenuConfiguration? {173 guard let engine else { return nil }174 let element = ContextMenuElement(pageURL: engine.url, linkURL: elementInfo.linkURL)175 engine.contextElement = element176 if let delegate = engine.contextMenuDelegate {177 return delegate.webEngine(engine, contextMenuConfigurationFor: element)178 }179 return WebContextMenu.configuration(for: element, engine: engine)180 }181182 func webView(_ webView: WKWebView, contextMenuForElement elementInfo: WKContextMenuElementInfo,183 willCommitWithAnimator animator: any UIContextMenuInteractionCommitAnimating) {184 guard let engine else { return }185 let element = ContextMenuElement(pageURL: engine.url, linkURL: elementInfo.linkURL)186 if let delegate = engine.contextMenuDelegate {187 delegate.webEngine(engine, commitPreviewFor: element)188 } else if let url = element.linkURL {189 engine.load(url, transition: .link)190 }191 }192 #endif193}194195// MARK: - Engine side of the delegates196197extension WebEngine {198 // MARK: Navigation policy199200 func decidePolicy(for action: WKNavigationAction, preferences: WKWebpagePreferences) -> WKNavigationActionPolicy {201 guard let url = action.request.url else { return .cancel }202 let opensNewWindow = action.targetFrame == nil203 let isMainFrame = action.targetFrame?.isMainFrame ?? true204205 let kind: NavigationContext.Kind = switch action.navigationType {206 case .linkActivated: .linkActivated207 case .formSubmitted: .formSubmitted208 case .backForward: .backForward209 case .reload: .reload210 case .formResubmitted: .formResubmitted211 default: .other212 }213214 var isAppInitiated = false215 if isMainFrame, !opensNewWindow {216 if isRestoringSession {217 isAppInitiated = true218 } else if let pending = pendingAppURL, NavigationPolicy.sameDocumentTarget(pending, url),219 kind == .other || kind == .reload || kind == .backForward {220 isAppInitiated = true221 }222 }223224 // `sourceFrame` is declared non-null but is nil for loads the app started; KVC returns a real optional.225 let sourceFrame = action.value(forKey: "sourceFrame") as? WKFrameInfo226 var navigationSettings = settings.navigation227 navigationSettings.httpAllowedHosts.formUnion(profile.httpAllowedHosts)228 let context = NavigationContext(url: url, isMainFrame: isMainFrame, kind: kind, isAppInitiated: isAppInitiated,229 sourceScheme: sourceFrame?.securityOrigin.protocol.lowercased(),230 mainDocumentScheme: committedURL?.scheme?.lowercased(),231 shouldPerformDownload: action.shouldPerformDownload)232233 switch NavigationPolicy.decide(context, settings: navigationSettings) {234 case .allow:235 #if os(macOS)236 // ⌘-click opens a tab instead of navigating; ⇧ brings it to the front.237 if kind == .linkActivated, isMainFrame, !opensNewWindow, action.modifierFlags.contains(.command) {238 let disposition: NewTabRequest.Disposition = action.modifierFlags.contains(.shift) ? .foreground : .background239 navigationDelegate?.webEngine(self, requestsNewTab: NewTabRequest(url: url, disposition: disposition,240 openerTabID: id, isUserGesture: true))241 if navigationDelegate != nil { return .cancel }242 }243 #endif244 if isMainFrame, !opensNewWindow {245 provisionalMainURL = url246 if !isAppInitiated { pendingTransition = Self.transition(for: kind) }247 preferences.preferredContentMode = switch contentMode {248 case .automatic: .recommended249 case .desktop: .desktop250 case .mobile: .mobile251 }252 }253 return .allow254255 case .download:256 return .download257258 case .block(let reason):259 noteBlocked(url, reason: reason, isMainFrame: isMainFrame)260 return .cancel261262 case .external(let target):263 requestExternalApp(target)264 return .cancel265266 case .upgradeToHTTPS(let upgraded):267 httpsUpgradeAttempt = (original: url, upgraded: upgraded)268 let transition = isAppInitiated ? pendingTransition : Self.transition(for: kind)269 // The cancelled http navigation must finish unwinding before the https one starts.270 Task { @MainActor [weak self] in self?.startLoad(upgraded, transition: transition) }271 return .cancel272 }273 }274275 static func transition(for kind: NavigationContext.Kind) -> NavigationEntry.Transition {276 switch kind {277 case .linkActivated: .link278 case .formSubmitted, .formResubmitted: .formSubmit279 case .backForward: .backForward280 case .reload: .reload281 case .other: .other282 }283 }284285 private func requestExternalApp(_ target: URL) {286 // One prompt at a time: a page cannot stack confirmation dialogs by firing app links in a loop.287 guard !isExternalRequestPending, let delegate = navigationDelegate else {288 noteBlocked(target, reason: .externalAppUnavailable, isMainFrame: true)289 return290 }291 isExternalRequestPending = true292 let request = ExternalAppRequest(url: target, scheme: target.scheme?.lowercased() ?? "", sourceURL: committedURL,293 isUserGesture: hasRecentUserActivation)294 Task { @MainActor [weak self] in295 guard let self else { return }296 _ = await delegate.webEngine(self, requestsExternalApp: request)297 self.isExternalRequestPending = false298 }299 }300301 func adopt(_ download: WKDownload) {302 profile.downloads.adopt(download, originURL: committedURL ?? url)303 }304305 // MARK: Navigation progress306307 func didStartProvisionalNavigation() {308 assign(\.loadError, nil)309 pendingCertificateError = nil310 if let attempt = httpsUpgradeAttempt, let current = webView?.url,311 !NavigationPolicy.sameDocumentTarget(current, attempt.upgraded) {312 httpsUpgradeAttempt = nil313 }314 if httpsUpgradeAttempt == nil { assign(\.httpsUpgradeFailure, nil) }315 assign(\.certificateError, nil)316 }317318 func didCommitNavigation() {319 let current = webView?.url320 committedURL = current321 commitCount += 1322 if let current { assign(\.url, current) }323 resetPageState(for: current)324 assign(\.processState, .running)325 assign(\.loadError, nil)326 assign(\.certificateError, nil)327 assign(\.httpsUpgradeFailure, nil)328 httpsUpgradeAttempt = nil329 pendingCertificateError = nil330 let transition = pendingTransition331 provisionalMainURL = nil332 pendingAppURL = nil333 pendingTransition = .link334 isRestoringSession = false335 refreshServerTrust()336 refreshPopupVerdict(for: current)337 if let current { recordVisit(current, transition: transition) }338 lastActiveAt = .now339 }340341 func didFinishNavigation() {342 if let view = webView {343 assign(\.title, view.title ?? "")344 assign(\.canGoBack, view.canGoBack)345 assign(\.canGoForward, view.canGoForward)346 }347 refreshServerTrust()348 }349350 func didFailNavigation(_ error: any Error, provisional: Bool) {351 let nsError = error as NSError352 pendingAppURL = nil353 provisionalMainURL = nil354 isRestoringSession = false355 let certificateFailure = pendingCertificateError356 pendingCertificateError = nil357358 // WebKit reverts `url` to the page still displayed; the address that failed stays in the address bar so359 // the error page names it and a reload retries it.360 if let certificateFailure {361 if let attempt = httpsUpgradeAttempt {362 httpsUpgradeAttempt = nil363 assign(\.url, attempt.original)364 assign(\.httpsUpgradeFailure, HTTPSUpgradeFailure(originalURL: attempt.original, attemptedURL: attempt.upgraded,365 error: nil, certificateError: certificateFailure))366 } else {367 if let failed = certificateFailure.failingURL { assign(\.url, failed) }368 assign(\.certificateError, certificateFailure)369 }370 return371 }372 // Cancelled by the user or superseded by another navigation.373 if nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled { return }374 // "Frame load interrupted": the response became a download, or a policy decision cancelled it.375 if nsError.domain == "WebKitErrorDomain" && nsError.code == 102 { return }376377 let failure = PageLoadError(error: error, fallbackURL: webView?.url ?? url)378 if provisional, let attempt = httpsUpgradeAttempt {379 httpsUpgradeAttempt = nil380 assign(\.url, attempt.original)381 assign(\.httpsUpgradeFailure, HTTPSUpgradeFailure(originalURL: attempt.original, attemptedURL: attempt.upgraded,382 error: failure, certificateError: nil))383 return384 }385 if let failed = failure.url, provisional { assign(\.url, failed) }386 assign(\.loadError, failure)387 }388389 func webContentProcessDidTerminate() {390 terminationCount += 1391 mediaFrames.removeAll()392 mediaFrameInfos.removeAll()393 assign(\.isPlayingAudio, false)394 assign(\.mediaActivity, MediaActivity())395 assign(\.isLoading, false)396 processState = .terminated(count: terminationCount, at: .now)397 Log.web.error("Web content process terminated (\(self.terminationCount, privacy: .public) so far for this tab)")398 }399400 // MARK: Authentication challenges401402 func respond(to challenge: URLAuthenticationChallenge) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {403 let space = challenge.protectionSpace404 switch space.authenticationMethod {405 case NSURLAuthenticationMethodServerTrust:406 guard let trust = space.serverTrust else { return (.performDefaultHandling, nil) }407 let host = space.host, port = space.port408 switch await profile.evaluate(trust: trust, host: host, port: port) {409 case .performDefaultHandling:410 return (.performDefaultHandling, nil)411 case .acceptWithUserException:412 return (.useCredential, URLCredential(trust: trust))413 case .reject(var failure):414 // Never proceed: cancel, and tell the UI what was wrong.415 if let target = provisionalMainURL, target.host()?.lowercased() == host.lowercased() {416 failure.failingURL = target417 pendingCertificateError = failure418 } else {419 insecureSubresourceBlockCount += 1420 }421 return (.cancelAuthenticationChallenge, nil)422 }423424 case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM:425 guard let delegate = uiDelegate, challenge.previousFailureCount < 5 else { return (.performDefaultHandling, nil) }426 let method: AuthenticationRequest.Method = switch space.authenticationMethod {427 case NSURLAuthenticationMethodHTTPBasic: .basic428 case NSURLAuthenticationMethodHTTPDigest: .digest429 default: .ntlm430 }431 let request = AuthenticationRequest(host: space.host, port: space.port, realm: space.realm, method: method,432 isProxy: space.isProxy(), isSecureTransport: space.receivesCredentialSecurely,433 previousFailureCount: challenge.previousFailureCount,434 proposedUser: challenge.proposedCredential?.user)435 switch await delegate.webEngine(self, credentialsFor: request) {436 case .credential(let user, let password, let remember):437 return (.useCredential, URLCredential(user: user, password: password, persistence: remember ? .forSession : .none))438 case .cancel:439 // Continue without credentials: WebKit shows the server's 401 page.440 return (.performDefaultHandling, nil)441 }442443 default:444 // Client certificates, Negotiate/Kerberos: the system's default behaviour.445 return (.performDefaultHandling, nil)446 }447 }448449 // MARK: Popups450451 func createChild(configuration: WKWebViewConfiguration, action: WKNavigationAction, features: WKWindowFeatures) -> WKWebView? {452 let target = action.request.url.flatMap { $0.absoluteString.isEmpty ? nil : $0 }453 let origin = committedURL.flatMap(WebOrigin.init(url:))454 let isLinkActivation = action.navigationType == .linkActivated455 let isUserGesture = isLinkActivation || hasRecentUserActivation456 let verdict = origin.flatMap { popupVerdicts[$0] } ?? .ask457458 // allow: every window opens. ask: only on a user gesture. deny: only an activated link (target=_blank).459 let permitted = verdict == .allow || (verdict == .ask && isUserGesture) || isLinkActivation460 guard permitted else {461 blockedPopups.append(BlockedPopup(url: target, sourceOrigin: origin))462 if blockedPopups.count > 50 { blockedPopups.removeFirst(blockedPopups.count - 50) }463 return nil464 }465 if let target, let scheme = target.scheme?.lowercased(), scheme != "about" {466 let context = NavigationContext(url: target, isMainFrame: true, kind: isLinkActivation ? .linkActivated : .other,467 sourceScheme: committedURL?.scheme?.lowercased(),468 mainDocumentScheme: committedURL?.scheme?.lowercased())469 if case .block(let reason) = NavigationPolicy.decide(context, settings: settings.navigation) {470 noteBlocked(target, reason: reason, isMainFrame: true)471 return nil472 }473 }474 guard let delegate = navigationDelegate else {475 // Nobody can show a second tab: a clicked link still has to go somewhere.476 if isLinkActivation, let target { startLoad(target, transition: .link) }477 return nil478 }479 var childSettings = settings480 childSettings.contentMode = contentMode481 let child = WebEngine(profile: profile, settings: childSettings, opener: id, adopting: configuration)482 let width = features.width?.doubleValue, height = features.height?.doubleValue483 let disposition: NewTabRequest.Disposition = (width != nil || height != nil) ? .popup(width: width, height: height) : .foreground484 let request = NewTabRequest(url: target, disposition: disposition, openerTabID: id, isUserGesture: isUserGesture)485 guard delegate.webEngine(self, didCreateChild: child, for: request) else {486 child.close()487 return nil488 }489 return child.webView490 }491492 /// Opens a popup the engine blocked, at the user's request, as an unrelated tab.493 public func openBlockedPopup(_ popup: BlockedPopup) {494 blockedPopups.removeAll { $0.id == popup.id }495 guard let url = popup.url else { return }496 navigationDelegate?.webEngine(self, requestsNewTab: NewTabRequest(url: url, disposition: .foreground,497 openerTabID: id, isUserGesture: true))498 }499500 /// Re-reads stored permissions that the engine caches (the popup verdict of the current site). Call it after501 /// the user changed a site permission.502 public func refreshCachedPermissions() { refreshPopupVerdict(for: committedURL) }503504 // MARK: Dialogs505506 func presentDialog(_ kind: JavaScriptDialog.Kind, message: String, frame: WKFrameInfo) async -> JavaScriptDialogResponse {507 guard !areDialogsSuppressed, let delegate = uiDelegate else {508 if areDialogsSuppressed { suppressedDialogCount += 1 }509 return .dismissed510 }511 dialogSequence += 1512 let dialog = JavaScriptDialog(kind: kind, message: String(message.prefix(10_000)),513 origin: WebOrigin(frame.securityOrigin), isMainFrame: frame.isMainFrame,514 sequenceOnPage: dialogSequence)515 let response = await delegate.webEngine(self, present: dialog)516 if response.suppressFurtherDialogs { areDialogsSuppressed = true }517 return response518 }519520 // MARK: Permissions521522 /// Stored verdicts first; the user is asked only for what is still undecided. The decision is keyed by the523 /// top-level origin: an embedded frame borrows the permission of the page the user is looking at.524 func resolvePermission(_ kinds: [PermissionKind], requestingOrigin: WebOrigin?, isMainFrame: Bool) async -> Bool {525 guard let origin = committedURL.flatMap(WebOrigin.init(url:)) ?? requestingOrigin else { return false }526 let profileID = profile.profile.id527 var undecided: [PermissionKind] = []528 for kind in kinds {529 let verdict = await profile.services.permissions?.verdict(for: kind, origin: origin, profileID: profileID) ?? .ask530 switch verdict {531 case .deny: return false532 case .allow: continue533 case .ask: undecided.append(kind)534 }535 }536 if undecided.isEmpty { return true }537 guard let delegate = uiDelegate else { return false }538 let request = PermissionRequest(kinds: undecided, origin: origin,539 requestingOrigin: requestingOrigin == origin ? nil : requestingOrigin,540 isMainFrame: isMainFrame)541 let response = await delegate.webEngine(self, decide: request)542 if response.remember, !profile.isGhost, let permissions = profile.services.permissions {543 for kind in undecided {544 await permissions.record(response.allow ? .allow : .deny, for: kind, origin: origin, profileID: profileID)545 }546 }547 return response.allow548 }549550 // MARK: Context menu (macOS)551552 #if os(macOS)553 func willOpenContextMenu(_ menu: NSMenu) {554 // The page reports the element just before WebKit builds the menu; anything older belongs to another click.555 let isFresh = contextElementDate.map { Date().timeIntervalSince($0) < 2 } ?? false556 let element = (isFresh ? contextElement : nil) ?? ContextMenuElement(pageURL: url)557 contextMenuDelegate?.webEngine(self, willOpen: menu, for: element)558 }559 #endif560}561