SPB Git

Repository Public

ProfileContext.swift 9.3 KB 193 lines swift

1import AppKit2import WebKit34/// Everything that belongs to one browsing identity: its WebKit data store and its local metadata.5/// A private context keeps cookies, site data, history and permissions in memory only.6@MainActor7final class ProfileContext {8    let profile: Profile9    let isPrivate: Bool10    let dataStore: WKWebsiteDataStore11    let history: HistoryStore12    let bookmarks: BookmarkStore13    let notes: NotesStore14    let permissions: SitePermissionStore15    let workspaces: JSONFileStore<[Workspace]>16    /// AURA Flow: how pages led to one another. In memory only for a private context.17    let flow: FlowStore18    /// AURA Canvas boards. A private window sees the profile's boards (adding a card is an explicit request to keep it).19    let canvas: CanvasStore2021    /// Persistent profile backed by `directory` and by a WebKit data store identified by the profile id.22    init(profile: Profile, directory: URL) throws {23        self.profile = profile24        self.isPrivate = false25        // Each profile gets its own persistent store: cookies, caches and storage are not shared between profiles.26        self.dataStore = WKWebsiteDataStore(forIdentifier: profile.id)27        let db = try ProfileSchema.open(at: directory.appendingPathComponent("profile.sqlite"))28        history = HistoryStore(db: db)29        bookmarks = BookmarkStore(db: db)30        notes = NotesStore(db: db)31        permissions = SitePermissionStore(url: directory.appendingPathComponent("site-settings.json"))32        workspaces = JSONFileStore(url: directory.appendingPathComponent("workspaces.json"), defaults: Workspace.defaults())33        if workspaces.value.isEmpty { workspaces.value = Workspace.defaults() }34        flow = FlowStore(url: directory.appendingPathComponent("flow.json"))35        canvas = CanvasStore(directory: directory.appendingPathComponent("Canvas", isDirectory: true))36    }3738    /// Private context derived from `parent`: a fresh non-persistent data store and in-memory history/permissions.39    /// Bookmarks and notes are the parent's, because saving one is an explicit request to keep it.40    init(privateFrom parent: ProfileContext) throws {41        profile = parent.profile42        isPrivate = true43        dataStore = .nonPersistent()44        history = HistoryStore(db: try ProfileSchema.open(at: nil))45        bookmarks = parent.bookmarks46        notes = parent.notes47        permissions = SitePermissionStore(url: nil)48        workspaces = JSONFileStore(url: nil, defaults: [Workspace(name: L("Private"), symbol: "eyeglasses", colorIndex: 2)])49        flow = FlowStore(url: nil)50        canvas = parent.canvas51    }5253    /// Removes cookies, caches and storage for `host` and its sub-domains. Returns the number of records removed.54    @discardableResult55    func clearSiteData(host: String) async -> Int {56        let key = URLInspector.registrableDomain(of: host)57        let records = await dataStore.dataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes())58        let matching = records.filter { record in59            let name = record.displayName.lowercased()60            return name == key || name.hasSuffix("." + key) || key.hasSuffix("." + name)61        }62        await dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: matching)63        return matching.count64    }6566    func clearAllSiteData() async {67        await dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast)68    }6970    func cookies(forHost host: String) async -> [HTTPCookie] {71        let key = URLInspector.registrableDomain(of: host)72        return await dataStore.httpCookieStore.allCookies().filter { cookie in73            let domain = cookie.domain.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "."))74            return domain == key || domain.hasSuffix("." + key) || host.lowercased().hasSuffix(domain)75        }.sorted { $0.name < $1.name }76    }77}7879/// Compiles the blocker rules into a `WKContentRuleList` and keeps every live web view in sync with it.80@MainActor81@Observable82final class ContentBlockerService {83    private(set) var ruleList: WKContentRuleList?84    private(set) var ruleCount = 085    private(set) var lastError: String?86    private(set) var isCompiling = false87    @ObservationIgnored private var compiledIdentifier: String?88    @ObservationIgnored private var controllers = NSHashTable<WKUserContentController>.weakObjects()8990    func options(settings: AppSettings, lists: BlockListState) -> BlockerRuleBuilder.Options {91        .init(trackers: settings.blockTrackers, ads: settings.blockAds, extraDomains: lists.activeDomains,92              disabledHosts: settings.blockerDisabledHosts)93    }9495    /// Recompiles when the effective rules changed, then pushes the result to all registered controllers.96    func refresh(settings: AppSettings, lists: BlockListState) async {97        guard settings.contentBlockerEnabled else {98            ruleList = nil; ruleCount = 0; compiledIdentifier = nil; lastError = nil99            applyToAll()100            return101        }102        let options = options(settings: settings, lists: lists)103        let identifier = BlockerRuleBuilder.identifier(for: options)104        guard identifier != compiledIdentifier else { return }105        let json = BlockerRuleBuilder.json(for: options)106        let count = BlockerRuleBuilder.rules(for: options).count107        guard count > 0, let store = WKContentRuleListStore.default() else {108            ruleList = nil; ruleCount = 0; compiledIdentifier = identifier109            applyToAll()110            return111        }112        isCompiling = true113        defer { isCompiling = false }114        do {115            let previous = compiledIdentifier116            ruleList = try await store.compileContentRuleList(forIdentifier: identifier, encodedContentRuleList: json)117            ruleCount = count118            compiledIdentifier = identifier119            lastError = nil120            if let previous, previous != identifier { try? await store.removeContentRuleList(forIdentifier: previous) }121        } catch {122            lastError = error.localizedDescription123            Log.event("blocker", "rule compilation failed: \(error.localizedDescription)")124        }125        applyToAll()126    }127128    func register(_ controller: WKUserContentController) {129        controllers.add(controller)130        apply(to: controller)131    }132133    private func applyToAll() { controllers.allObjects.forEach(apply(to:)) }134135    private func apply(to controller: WKUserContentController) {136        controller.removeAllContentRuleLists()137        if let ruleList { controller.add(ruleList) }138    }139140    /// Downloads one remote list on the user's request and extracts its domains. HTTPS only, no cookies.141    func fetchDomains(from source: BlockListSource) async throws -> [String] {142        guard source.isFetchable, let url = URL(string: source.url) else {143            throw AIError.invalidConfiguration(L("Lists must be downloaded over HTTPS."))144        }145        var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)146        request.httpShouldHandleCookies = false147        let (data, response) = try await URLSession(configuration: .ephemeral).data(for: request)148        guard (response as? HTTPURLResponse)?.statusCode == 200, data.count < 30_000_000,149              let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {150            throw AIError.unreachable(L("The list could not be downloaded."))151        }152        return Array(BlockListParser.domains(from: text).prefix(BlockerRuleBuilder.maxDomains))153    }154}155156/// Wraps user scripts so that each one runs only on the hosts it declares, inside an isolated content world:157/// it can read and change the page's DOM but shares no JavaScript objects with the page or with the browser.158@MainActor159enum UserScriptInjector {160    static let world = WKContentWorld.world(name: "SPBrowserUserScripts")161162    static func wrappedSource(for script: UserScript) -> String {163        let patterns = script.hosts.map { $0.lowercased() }.filter(HostPattern.isValid)164        let json = (try? String(data: JSONSerialization.data(withJSONObject: patterns), encoding: .utf8)) ?? "[]"165        return """166        (function () {167          const host = (location.hostname || '').toLowerCase();168          const allowed = \(json).some(function (p) {169            if (p.startsWith('*.')) { return host.endsWith(p.slice(1)); }170            return host === p || host.endsWith('.' + p);171          });172          if (!allowed) { return; }173          try {174        \(script.source)175          } catch (error) { console.error('SP Browser user script failed:', error); }176        })();177        """178    }179180    static func install(_ scripts: [UserScript], enabled: Bool, into controller: WKUserContentController) {181        controller.removeAllUserScripts()182        // The browser's own page bridge (hovered link, reading progress) lives in the internal world and is always present.183        controller.addUserScript(AuraPageBridge.userScript)184        guard enabled else { return }185        for script in scripts where script.enabled && !script.hosts.isEmpty {186            controller.addUserScript(WKUserScript(187                source: wrappedSource(for: script),188                injectionTime: script.runAt == .documentStart ? .atDocumentStart : .atDocumentEnd,189                forMainFrameOnly: script.mainFrameOnly, in: world))190        }191    }192}193
Files main
Menu

Theme