SPB Git

Repository Public License

ProfileContext.swift 16.8 KB 337 lines swift

1import Diagnostics2import Foundation3import NavigatorCore4import Security5import WebKit67/// Storage-side services of one profile, injected by the app. Any of them may be absent (tests, early boot):8/// permissions then default to "ask", history is not recorded and downloads are cancelled.9public struct WebServices: Sendable {10    public var permissions: (any PermissionProvider)?11    public var history: (any HistoryRecorder)?12    public var downloads: (any DownloadSink)?1314    public init(permissions: (any PermissionProvider)? = nil, history: (any HistoryRecorder)? = nil,15                downloads: (any DownloadSink)? = nil) {16        self.permissions = permissions; self.history = history; self.downloads = downloads17    }1819    public static let none = WebServices()20}2122/// Kinds of website data, mapped to `WKWebsiteDataType…` constants.23public enum WebsiteDataKind: String, Sendable, CaseIterable, Codable {24    case cookies, diskCache, memoryCache, fetchCache, localStorage, sessionStorage, indexedDB, webSQL25    case serviceWorkers, fileSystem, searchFieldHistory, mediaKeys, hashSalt2627    public var webKitType: String {28        switch self {29        case .cookies: WKWebsiteDataTypeCookies30        case .diskCache: WKWebsiteDataTypeDiskCache31        case .memoryCache: WKWebsiteDataTypeMemoryCache32        case .fetchCache: WKWebsiteDataTypeFetchCache33        case .localStorage: WKWebsiteDataTypeLocalStorage34        case .sessionStorage: WKWebsiteDataTypeSessionStorage35        case .indexedDB: WKWebsiteDataTypeIndexedDBDatabases36        case .webSQL: WKWebsiteDataTypeWebSQLDatabases37        case .serviceWorkers: WKWebsiteDataTypeServiceWorkerRegistrations38        case .fileSystem: WKWebsiteDataTypeFileSystem39        case .searchFieldHistory: WKWebsiteDataTypeSearchFieldRecentSearches40        case .mediaKeys: WKWebsiteDataTypeMediaKeys41        case .hashSalt: WKWebsiteDataTypeHashSalt42        }43    }4445    public static let caches: Set<WebsiteDataKind> = [.diskCache, .memoryCache, .fetchCache]46    public static let siteStorage: Set<WebsiteDataKind> = [47        .cookies, .localStorage, .sessionStorage, .indexedDB, .webSQL, .serviceWorkers, .fileSystem,48    ]49    public static let all = Set(WebsiteDataKind.allCases)5051    static func webKitTypes(_ kinds: Set<WebsiteDataKind>) -> Set<String> { Set(kinds.map(\.webKitType)) }52}5354/// One row of "site data": WebKit groups data by registrable domain, not by full host.55public struct WebsiteDataSummary: Sendable, Hashable, Identifiable {56    /// The registrable domain WebKit reports ("example.com", "localhost", an IP address).57    public var domain: String58    public var kinds: Set<WebsiteDataKind>59    public var id: String { domain }60}6162public enum ProfileStoreError: Error, Sendable, Hashable, CustomStringConvertible {63    /// Web views of the profile are still alive; WebKit refuses to delete a store in use.64    case storeInUse(liveEngines: Int)65    case ghostHasNoPersistentStore66    case removalFailed(String)6768    public var description: String {69        switch self {70        case .storeInUse(let count): "The profile still has \(count) live web view(s)"71        case .ghostHasNoPersistentStore: "Ghost profiles have no store on disk"72        case .removalFailed(let message): "WebKit could not remove the data store: \(message)"73        }74    }75}7677/// The WebKit side of one browsing identity: its data store, its configuration factory, its attached content78/// rule lists, and the certificate exceptions of the session.79///80/// A standard profile maps to `WKWebsiteDataStore(forIdentifier: profile.dataStoreIdentifier)`. A ghost profile81/// gets a new `.nonPersistent()` store per `ProfileContext`: every tab created from the same context shares it,82/// and it vanishes with the context.83@MainActor84public final class ProfileContext: Identifiable {85    public let profile: Profile86    public let dataStore: WKWebsiteDataStore87    public let services: WebServices88    /// Unique per context. Two ghost sessions of the same profile have different session ids.89    public let sessionID = UUID()9091    /// Supplies `orix://` content for web views of this profile.92    public weak var internalContentProvider: (any InternalContentProvider)? {93        didSet { internalSchemeHandler.provider = internalContentProvider }94    }9596    let internalSchemeHandler: InternalSchemeHandler97    private(set) lazy var downloads = DownloadCoordinator(context: self)98    private let engines = NSHashTable<WebEngine>.weakObjects()99    private var ruleLists: [(identifier: String, list: WKContentRuleList)] = []100101    /// Invalid certificates the user explicitly accepted during this session. In memory only.102    public private(set) var certificateExceptions: [CertificateException] = []103104    /// Hosts the user chose to open over plain http after HTTPS-only mode failed. Session only.105    public internal(set) var httpAllowedHosts: Set<String> = []106107    public nonisolated var id: ProfileID { profile.id }108    public var isGhost: Bool { profile.isGhost }109110    public init(profile: Profile, services: WebServices = .none) {111        self.profile = profile112        self.services = services113        self.dataStore = profile.isGhost ? .nonPersistent() : WKWebsiteDataStore(forIdentifier: profile.dataStoreIdentifier)114        self.internalSchemeHandler = InternalSchemeHandler(profile: profile)115    }116117    // MARK: Configuration factory118119    /// A configuration for a new web view of this profile. Each web view gets its own user content controller120    /// (scripts and message handlers are per tab); the data store is shared by the profile.121    ///122    /// `WKProcessPool` is not set: since macOS 12 / iOS 15 WebKit ignores distinct pools, and process sharing is123    /// decided by WebKit from the data store and site isolation.124    public func makeConfiguration(settings: WebEngineSettings = WebEngineSettings()) -> WKWebViewConfiguration {125        let configuration = WKWebViewConfiguration()126        configuration.websiteDataStore = dataStore127        configuration.setURLSchemeHandler(internalSchemeHandler, forURLScheme: InternalPage.scheme)128        apply(settings, to: configuration)129        configuration.userContentController = makeUserContentController()130        return configuration131    }132133    /// Settings that are also re-applied to a configuration handed over by WebKit for `window.open`.134    func apply(_ settings: WebEngineSettings, to configuration: WKWebViewConfiguration) {135        configuration.applicationNameForUserAgent = settings.applicationNameForUserAgent136        // The engine applies its own popup policy (user activation + per-site permission) in the UI delegate;137        // WebKit's switch would silently drop blocked popups without letting the browser count them.138        configuration.preferences.javaScriptCanOpenWindowsAutomatically = true139        configuration.preferences.isElementFullscreenEnabled = settings.elementFullscreenEnabled140        configuration.preferences.isFraudulentWebsiteWarningEnabled = settings.fraudulentWebsiteWarningEnabled141        configuration.mediaTypesRequiringUserActionForPlayback = settings.autoplayRequiresUserGesture ? .all : []142        configuration.upgradeKnownHostsToHTTPS = true143        configuration.allowsAirPlayForMediaPlayback = true144        #if os(iOS)145        configuration.allowsInlineMediaPlayback = true146        configuration.allowsPictureInPictureMediaPlayback = settings.allowsPictureInPicture147        #endif148    }149150    func makeUserContentController() -> WKUserContentController {151        let controller = WKUserContentController()152        for entry in ruleLists { controller.add(entry.list) }153        return controller154    }155156    // MARK: Live engines157158    func register(_ engine: WebEngine) { engines.add(engine) }159    func unregister(_ engine: WebEngine) { engines.remove(engine) }160161    /// Engines of this profile that currently exist (live or suspended).162    public var liveEngines: [WebEngine] { engines.allObjects }163164    // MARK: Content rule lists165166    public var attachedRuleListIdentifiers: [String] { ruleLists.map(\.identifier) }167168    /// Attaches a compiled list to every future web view of the profile and to the live ones (it applies to169    /// their next loads). A list with the same identifier is replaced.170    public func attach(_ list: WKContentRuleList) {171        detach(identifier: list.identifier)172        ruleLists.append((list.identifier, list))173        for engine in engines.allObjects where engine.isContentBlockingEnabled {174            engine.webView?.configuration.userContentController.add(list)175        }176    }177178    public func detach(identifier: String) {179        guard let index = ruleLists.firstIndex(where: { $0.identifier == identifier }) else { return }180        let list = ruleLists.remove(at: index).list181        for engine in engines.allObjects { engine.webView?.configuration.userContentController.remove(list) }182    }183184    public func detachAllRuleLists() {185        for identifier in attachedRuleListIdentifiers { detach(identifier: identifier) }186    }187188    var attachedRuleLists: [WKContentRuleList] { ruleLists.map(\.list) }189190    // MARK: Certificate exceptions (session only)191192    /// Accepts the certificate described by `error` for its host until the end of this session. The caller is193    /// the UI, after an explicit, informed user action. Returns `nil` when the error carries no certificate.194    @discardableResult195    public func grantCertificateException(for error: CertificateError) -> CertificateException? {196        guard let fingerprint = error.certificate?.sha256Fingerprint else { return nil }197        let exception = CertificateException(host: error.host, port: error.port, sha256Fingerprint: fingerprint,198                                             reason: error.reason)199        if !certificateExceptions.contains(where: { $0.id == exception.id }) { certificateExceptions.append(exception) }200        Log.web.notice("Certificate exception granted for session (host redacted), reason \(error.reason.rawValue, privacy: .public)")201        return exception202    }203204    public func revokeCertificateException(_ exception: CertificateException) {205        certificateExceptions.removeAll { $0.id == exception.id }206    }207208    public func revokeAllCertificateExceptions() { certificateExceptions.removeAll() }209210    func hasCertificateException(host: String, port: Int) -> Bool {211        certificateExceptions.contains { $0.host == host.lowercased() && $0.port == port }212    }213214    /// Runs the (blocking) trust evaluation off the main actor.215    func evaluate(trust: SecTrust, host: String, port: Int) async -> ServerTrustDecision {216        let exceptions = certificateExceptions217        // SecTrust is safe to evaluate from any single thread; it is not touched again until the task returns.218        nonisolated(unsafe) let trust = trust219        return await Task.detached(priority: .userInitiated) {220            CertificateTrustEvaluator.decide(trust: trust, host: host, port: port, exceptions: exceptions)221        }.value222    }223224    // MARK: Website data225226    /// Site data grouped by registrable domain.227    public func websiteData(kinds: Set<WebsiteDataKind> = WebsiteDataKind.all) async -> [WebsiteDataSummary] {228        let records = await dataStore.dataRecords(ofTypes: WebsiteDataKind.webKitTypes(kinds))229        return records.map { record in230            WebsiteDataSummary(domain: record.displayName,231                               kinds: Set(WebsiteDataKind.allCases.filter { record.dataTypes.contains($0.webKitType) }))232        }.sorted { $0.domain < $1.domain }233    }234235    /// Removes data of `kinds` for the given hosts. WebKit stores data per registrable domain, so removing236    /// `news.example.com` removes the record of `example.com`. Returns the number of records removed.237    @discardableResult238    public func removeWebsiteData(kinds: Set<WebsiteDataKind> = WebsiteDataKind.all, hosts: [String]) async -> Int {239        let wanted = hosts.map { $0.lowercased() }240        let types = WebsiteDataKind.webKitTypes(kinds)241        let records = await dataStore.dataRecords(ofTypes: types).filter { record in242            let domain = record.displayName.lowercased()243            return wanted.contains { $0 == domain || $0.hasSuffix("." + domain) || domain.hasSuffix("." + $0) }244        }245        guard !records.isEmpty else { return 0 }246        await dataStore.removeData(ofTypes: types, for: records)247        return records.count248    }249250    /// Removes data of `kinds` modified since `date` ("clear the last hour").251    public func removeWebsiteData(kinds: Set<WebsiteDataKind> = WebsiteDataKind.all, modifiedSince date: Date) async {252        await dataStore.removeData(ofTypes: WebsiteDataKind.webKitTypes(kinds), modifiedSince: date)253    }254255    /// Removes everything of `kinds`, whatever its age.256    public func removeAllWebsiteData(kinds: Set<WebsiteDataKind> = WebsiteDataKind.all) async {257        await dataStore.removeData(ofTypes: WebsiteDataKind.webKitTypes(kinds), modifiedSince: .distantPast)258    }259260    public func cookies() async -> [HTTPCookie] { await dataStore.httpCookieStore.allCookies() }261262    public func deleteCookie(_ cookie: HTTPCookie) async { await dataStore.httpCookieStore.deleteCookie(cookie) }263}264265/// Creates and caches `ProfileContext`s, and deletes profile stores.266@MainActor267public final class WebProfileRegistry {268    private let servicesFactory: @MainActor (Profile) -> WebServices269    private var standard: [ProfileID: ProfileContext] = [:]270    private var ghosts: [ProfileID: ProfileContext] = [:]271272    /// `services` is asked once per context for the storage services of that profile.273    public init(services: @escaping @MainActor (Profile) -> WebServices = { _ in .none }) {274        servicesFactory = services275    }276277    /// The context of `profile`. Standard profiles: one context for the life of the registry. Ghost profiles:278    /// the open ghost session, created on first use and replaced after `endGhostSession`.279    public func context(for profile: Profile) -> ProfileContext {280        if profile.isGhost {281            if let open = ghosts[profile.id] { return open }282            let context = ProfileContext(profile: profile, services: servicesFactory(profile))283            ghosts[profile.id] = context284            return context285        }286        if let existing = standard[profile.id] { return existing }287        let context = ProfileContext(profile: profile, services: servicesFactory(profile))288        standard[profile.id] = context289        return context290    }291292    public func hasOpenGhostSession(for profileID: ProfileID) -> Bool { ghosts[profileID] != nil }293294    /// Ends the ghost session: in-flight downloads are cancelled and the registry forgets the context. The295    /// non-persistent store is destroyed by WebKit when its last web view goes away, so the caller must also296    /// close the tabs of the session. The next `context(for:)` starts from an empty store.297    public func endGhostSession(for profileID: ProfileID) {298        guard let context = ghosts.removeValue(forKey: profileID) else { return }299        context.downloads.cancelAll()300        context.revokeAllCertificateExceptions()301    }302303    /// Deletes the persistent store of a standard profile from disk. Every web view of the profile must have304    /// been closed first, and the caller must hold no other reference to its `ProfileContext`: WebKit's network305    /// process keeps a store open for as long as the `WKWebsiteDataStore` object lives, and for a short moment306    /// after. The profile's `dataStoreIdentifier` must never be reused afterwards.307    public func deleteStore(of profile: Profile) async throws(ProfileStoreError) {308        guard !profile.isGhost else { throw .ghostHasNoPersistentStore }309        if let context = standard[profile.id] {310            let live = context.liveEngines.filter { $0.webView != nil }.count311            guard live == 0 else { throw .storeInUse(liveEngines: live) }312            context.downloads.cancelAll()313            standard[profile.id] = nil314        }315        try await Self.deleteStore(identifier: profile.dataStoreIdentifier)316    }317318    /// Deletes a store by identifier (also for orphans found with `allStoreIdentifiers`). WebKit refuses while319    /// its network process still has the store open, which lasts a little after the last reference is dropped:320    /// the removal is retried for up to `patience` seconds before the error is reported.321    public static func deleteStore(identifier: UUID, patience: TimeInterval = 5) async throws(ProfileStoreError) {322        let deadline = Date().addingTimeInterval(patience)323        while true {324            do {325                try await WKWebsiteDataStore.remove(forIdentifier: identifier)326                return327            } catch {328                if Date() >= deadline { throw .removalFailed((error as NSError).localizedDescription) }329                try? await Task.sleep(for: .milliseconds(100))330            }331        }332    }333334    /// Identifiers of every persistent store WebKit holds for this app.335    public static func allStoreIdentifiers() async -> [UUID] { await WKWebsiteDataStore.allDataStoreIdentifiers }336}337
Files main
Menu

Theme