Repository Public License
1import Foundation23/// Everything the policy needs to know about one navigation, free of WebKit types so it can be unit-tested.4public struct NavigationContext: Sendable, Hashable {5 public enum Kind: String, Sendable { case linkActivated, formSubmitted, backForward, reload, formResubmitted, other }67 public var url: URL8 public var isMainFrame: Bool9 public var kind: Kind10 /// True when the browser itself asked for this exact URL (omnibox, bookmark, session restore, internal page).11 /// Never true for anything web content started, including server redirects.12 public var isAppInitiated: Bool13 /// Scheme of the frame that started the navigation (`nil` when unknown).14 public var sourceScheme: String?15 /// Scheme of the document currently committed in the main frame.16 public var mainDocumentScheme: String?17 /// WebKit says the action is a download (`<a download>`).18 public var shouldPerformDownload: Bool1920 public init(url: URL, isMainFrame: Bool = true, kind: Kind = .other, isAppInitiated: Bool = false,21 sourceScheme: String? = nil, mainDocumentScheme: String? = nil, shouldPerformDownload: Bool = false) {22 self.url = url; self.isMainFrame = isMainFrame; self.kind = kind; self.isAppInitiated = isAppInitiated23 self.sourceScheme = sourceScheme; self.mainDocumentScheme = mainDocumentScheme24 self.shouldPerformDownload = shouldPerformDownload25 }26}2728public struct NavigationPolicySettings: Sendable, Hashable {29 /// `file:` may be opened by the user. Always false on iOS, where the browser has no file access of its own.30 public var allowsFileURLs: Bool31 /// Upgrade top-level `http:` navigations to `https:` and stop on failure (the UI shows an interstitial).32 public var httpsOnly: Bool33 /// Loopback hosts are not upgraded (local development servers rarely speak TLS).34 public var httpsOnlyExemptsLoopback: Bool35 /// Hosts the user chose to open over http after a failed upgrade. Session only.36 public var httpAllowedHosts: Set<String>3738 public init(allowsFileURLs: Bool = NavigationPolicySettings.platformAllowsFileURLs, httpsOnly: Bool = false,39 httpsOnlyExemptsLoopback: Bool = true, httpAllowedHosts: Set<String> = []) {40 self.allowsFileURLs = allowsFileURLs; self.httpsOnly = httpsOnly41 self.httpsOnlyExemptsLoopback = httpsOnlyExemptsLoopback; self.httpAllowedHosts = httpAllowedHosts42 }4344 public static var platformAllowsFileURLs: Bool {45 #if os(macOS)46 true47 #else48 false49 #endif50 }51}5253public enum NavigationBlockReason: String, Sendable, Hashable, Codable {54 /// `javascript:`, `vbscript:` — never navigated to.55 case scriptScheme56 /// Top-level `data:` or `blob:` that is not a download.57 case opaqueTopLevelDocument58 /// `file:` requested by web content, or file access disabled.59 case localFileFromWeb60 /// `orix:` requested by web content.61 case internalPageFromWeb62 /// An application scheme requested from a sub-frame.63 case externalSchemeInSubframe64 /// An application link arrived while another confirmation was pending, or nothing can present one.65 case externalAppUnavailable66 /// The URL has no scheme or cannot be understood.67 case malformed68}6970public enum NavigationVerdict: Sendable, Hashable {71 case allow72 /// Turn the navigation into a download.73 case download74 case block(NavigationBlockReason)75 /// Leave the browser for another application — only after asking the user.76 case external(URL)77 /// Cancel and load this https URL instead (HTTPS-only mode).78 case upgradeToHTTPS(URL)79}8081/// The scheme allow-list of the browser. Pure and deterministic.82public enum NavigationPolicy {83 /// Schemes that hand off to another application after a user confirmation. Any other unknown scheme is84 /// treated the same way: the user decides, the browser never opens an app silently.85 public static let wellKnownExternalSchemes: Set<String> = [86 "mailto", "tel", "sms", "facetime", "facetime-audio", "itms", "itms-apps", "itms-appss", "itms-books",87 "maps", "music", "news", "shortcuts", "x-apple-reminder", "webcal", "feed", "ms-outlook", "zoommtg",88 "slack", "tg", "whatsapp", "spotify", "magnet", "ssh", "vnc", "sip", "xmpp", "geo",89 ]9091 static let scriptSchemes: Set<String> = ["javascript", "vbscript", "livescript", "jscript"]9293 public static func decide(_ context: NavigationContext, settings: NavigationPolicySettings) -> NavigationVerdict {94 guard let scheme = context.url.scheme?.lowercased(), !scheme.isEmpty else { return .block(.malformed) }95 let privilegedHistoryMove = context.kind == .backForward || context.kind == .reload9697 if scriptSchemes.contains(scheme) { return .block(.scriptScheme) }9899 switch scheme {100 case "http", "https":101 if context.shouldPerformDownload { return .download }102 if context.isMainFrame, scheme == "http", settings.httpsOnly, let upgraded = httpsUpgrade(of: context.url, settings: settings) {103 return .upgradeToHTTPS(upgraded)104 }105 return .allow106107 case "about":108 // about:blank and about:srcdoc are inert documents.109 let path = context.url.absoluteString.lowercased()110 if path == "about:blank" || path.hasPrefix("about:blank#") || path.hasPrefix("about:blank?") || path == "about:srcdoc" {111 return .allow112 }113 return .block(.malformed)114115 case "blob", "data":116 if context.shouldPerformDownload { return .download }117 // Sub-frames may show generated documents; the address bar never shows an opaque origin.118 return context.isMainFrame ? .block(.opaqueTopLevelDocument) : .allow119120 case "file":121 guard settings.allowsFileURLs else { return .block(.localFileFromWeb) }122 if context.isMainFrame {123 if context.isAppInitiated || privilegedHistoryMove { return .allow }124 // Links between local documents keep working; the web cannot reach the disk.125 return context.sourceScheme == "file" && context.mainDocumentScheme == "file" ? .allow : .block(.localFileFromWeb)126 }127 return context.mainDocumentScheme == "file" ? .allow : .block(.localFileFromWeb)128129 case WebRuntimeConstants.internalScheme:130 if context.isMainFrame {131 if context.isAppInitiated || privilegedHistoryMove { return .allow }132 let fromInternal = context.sourceScheme == WebRuntimeConstants.internalScheme133 && context.mainDocumentScheme == WebRuntimeConstants.internalScheme134 return fromInternal ? .allow : .block(.internalPageFromWeb)135 }136 return context.mainDocumentScheme == WebRuntimeConstants.internalScheme ? .allow : .block(.internalPageFromWeb)137138 default:139 // mailto:, tel:, itms-apps:, custom app schemes…140 return context.isMainFrame ? .external(context.url) : .block(.externalSchemeInSubframe)141 }142 }143144 /// Decision for a URL the browser itself is about to load (omnibox, bookmarks, restore).145 public static func decideAppLoad(_ url: URL, settings: NavigationPolicySettings) -> NavigationVerdict {146 decide(NavigationContext(url: url, isMainFrame: true, kind: .other, isAppInitiated: true), settings: settings)147 }148149 static func httpsUpgrade(of url: URL, settings: NavigationPolicySettings) -> URL? {150 guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false),151 let host = components.host?.lowercased(), !host.isEmpty else { return nil }152 if settings.httpAllowedHosts.contains(host) { return nil }153 if settings.httpsOnlyExemptsLoopback && isLoopback(host) { return nil }154 components.scheme = "https"155 // An explicit :80 would be wrong for https; any other explicit port is kept as typed.156 if components.port == 80 { components.port = nil }157 return components.url158 }159160 public static func isLoopback(_ host: String) -> Bool {161 let host = host.lowercased()162 return host == "localhost" || host.hasSuffix(".localhost") || host == "::1" || host == "[::1]"163 || host.hasPrefix("127.")164 }165166 /// True when the response should be saved rather than shown.167 public static func responseIsDownload(canShowMIMEType: Bool, contentDisposition: String?) -> Bool {168 if let disposition = contentDisposition?.trimmingCharacters(in: .whitespaces).lowercased(),169 disposition.hasPrefix("attachment") {170 return true171 }172 return !canShowMIMEType173 }174175 /// Two URLs denote the same navigation target (WebKit adds the trailing slash of an empty path and drops176 /// default ports; fragments do not matter for matching a pending request).177 public static func sameDocumentTarget(_ lhs: URL, _ rhs: URL) -> Bool { canonical(lhs) == canonical(rhs) }178179 static func canonical(_ url: URL) -> String {180 if url.isFileURL { return "file://" + url.standardizedFileURL.path }181 guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return url.absoluteString }182 components.fragment = nil183 components.scheme = components.scheme?.lowercased()184 components.host = components.host?.lowercased()185 if components.path.isEmpty { components.path = "/" }186 if (components.scheme == "http" && components.port == 80) || (components.scheme == "https" && components.port == 443) {187 components.port = nil188 }189 return components.string ?? url.absoluteString190 }191}192