SPB Git

Repository Public License

PermissionService.swift 13.4 KB 273 lines swift

1import Diagnostics2import Foundation3import NavigatorCore4import Persistence56/// How long the user wants an answer to a permission prompt to last.7public enum PermissionDuration: String, Sendable, Codable, CaseIterable {8    /// This request only: nothing is remembered.9    case once10    /// Until the app quits (kept in memory, never written).11    case session12    /// 24 hours from now (stored with an expiry date).13    case day14    /// Until revoked.15    case always16}1718/// One row of the per-site settings panel.19public struct SitePermission: Sendable, Hashable, Identifiable {20    public enum Source: String, Sendable, Codable {21        /// No decision: the default for the kind applies.22        case defaultValue23        /// Stored decision (`always` or 24 h).24        case stored25        /// In memory until the app quits or the private session ends.26        case session27        /// Forced by the browser, not changeable (camera on an insecure page, …).28        case policy29    }3031    public var origin: WebOrigin32    public var kind: PermissionKind33    public var verdict: PermissionDecision.Verdict34    public var source: Source35    public var decidedAt: Date?36    public var expiresAt: Date?3738    public var id: String { "\(origin)#\(kind.rawValue)" }39}4041public enum PermissionSettings {42    /// Per-kind default verdicts chosen by the user; kinds not present use `PermissionService.builtInDefaults`.43    public static let defaults = SettingKey<[String: String]>("permissions.defaults", default: [:])44}4546/// Per profile + origin + kind permission decisions. Implements the `PermissionProvider` contract the web layer47/// calls, and adds what the settings UI needs (durations, revocation, queries).48///49/// - Decisions for `once` are not kept. `session` decisions live in memory. `day` and `always` go to50///   `database.permissions`, with an expiry for `day`.51/// - A private (ghost) profile never reaches the database: every decision made there is kept in memory and52///   dropped by `endGhostSession(profile:)`. A ghost profile is recognised through `database.ghosts`.53/// - Camera, microphone, location and device motion are denied on insecure origins whatever is stored54///   (WebKit itself only exposes them to secure contexts; the panel then shows why).55/// - If storage fails, the answer is the safe one: `ask`, never `allow`.56public actor PermissionService: PermissionProvider {57    /// Defaults when the user never chose one for the kind.58    ///59    /// | Kind | Default | Why |60    /// |---|---|---|61    /// | camera, microphone, location, notifications, device motion, clipboard | ask | sensitive, needs consent |62    /// | pop-ups | deny | pop-ups not opened by a user gesture are blocked and counted |63    /// | autoplay | deny | media with sound does not start by itself; muted autoplay is the web layer's policy |64    /// | downloads | ask | downloads the user did not start (no gesture) need confirmation |65    public static let builtInDefaults: [PermissionKind: PermissionDecision.Verdict] = [66        .camera: .ask, .microphone: .ask, .location: .ask, .notifications: .ask, .deviceMotion: .ask, .clipboard: .ask,67        .popups: .deny, .autoplay: .deny, .downloads: .ask,68    ]6970    /// Kinds that only make sense in a secure context.71    public static let secureContextKinds: Set<PermissionKind> = [.camera, .microphone, .location, .deviceMotion]7273    private struct Key: Hashable {74        var profile: ProfileID75        var origin: WebOrigin76        var kind: PermissionKind77    }7879    private let database: NavigatorDatabase80    private let now: @Sendable () -> Date81    private var memory: [Key: PermissionDecision] = [:]8283    public init(database: NavigatorDatabase, now: @escaping @Sendable () -> Date = { .now }) {84        self.database = database85        self.now = now86    }8788    private func isGhost(_ profile: ProfileID) -> Bool { database.ghosts.contains(profile.raw) }8990    /// Whether an origin is a secure context for permission purposes: HTTPS, or a loopback host.91    public static func isSecureContext(_ origin: WebOrigin) -> Bool {92        if origin.scheme == "https" || origin.scheme == "orix" { return true }93        return origin.scheme == "http" && (origin.host == "localhost" || origin.host == "127.0.0.1" || origin.host == "[::1]"94                                           || origin.host == "::1" || origin.host.hasSuffix(".localhost"))95    }9697    // MARK: Defaults9899    public func defaultVerdict(for kind: PermissionKind) async -> PermissionDecision.Verdict {100        let chosen = (try? await database.settings.value(PermissionSettings.defaults)) ?? [:]101        return chosen[kind.rawValue].flatMap(PermissionDecision.Verdict.init(rawValue:)) ?? Self.builtInDefaults[kind] ?? .ask102    }103104    /// Sets the default for a kind; `nil` returns to the built-in default. `allow` is refused as a default for105    /// camera, microphone and location: those are granted per site only.106    public func setDefaultVerdict(_ verdict: PermissionDecision.Verdict?, for kind: PermissionKind) async throws {107        if verdict == .allow, [.camera, .microphone, .location].contains(kind) { throw PermissionError.defaultNotAllowed }108        var chosen = try await database.settings.value(PermissionSettings.defaults)109        chosen[kind.rawValue] = verdict?.rawValue110        try await database.settings.set(PermissionSettings.defaults, to: chosen, at: now())111    }112113    // MARK: PermissionProvider114115    public func verdict(for kind: PermissionKind, origin: WebOrigin, profileID: ProfileID) async -> PermissionDecision.Verdict {116        await resolve(kind: kind, origin: origin, profile: profileID).verdict117    }118119    /// The web layer calls this when the user ticked "remember": the decision is kept until revoked120    /// (in memory for a private profile).121    public func record(_ verdict: PermissionDecision.Verdict, for kind: PermissionKind, origin: WebOrigin,122                       profileID: ProfileID) async {123        do { try await decide(verdict, for: kind, origin: origin, profile: profileID, duration: .always) } catch {124            Log.privacy.error("Could not store a permission decision: \(String(describing: error), privacy: .public)")125        }126    }127128    // MARK: Decisions129130    /// Records the user's answer for the chosen duration. `.ask` as a verdict removes the decision.131    public func decide(_ verdict: PermissionDecision.Verdict, for kind: PermissionKind, origin: WebOrigin,132                       profile: ProfileID, duration: PermissionDuration) async throws {133        let key = Key(profile: profile, origin: origin, kind: kind)134        guard verdict != .ask else { try await revoke(kind, origin: origin, profile: profile); return }135        if verdict == .allow, Self.secureContextKinds.contains(kind), !Self.isSecureContext(origin) {136            throw PermissionError.insecureOrigin137        }138        let date = now()139        switch duration {140        case .once:141            return142        case .session:143            memory[key] = PermissionDecision(profileID: profile, origin: origin, kind: kind, verdict: verdict, decidedAt: date)144            // A session answer replaces what was stored: otherwise an older "always allow" would win again145            // after the user just said "deny for this session".146            if !isGhost(profile) { try await removeStored(key) }147        case .day, .always:148            let expiry = duration == .day ? date.addingTimeInterval(86_400) : nil149            let decision = PermissionDecision(profileID: profile, origin: origin, kind: kind, verdict: verdict,150                                              decidedAt: date, expiresAt: expiry)151            if isGhost(profile) {152                memory[key] = decision153            } else {154                try await database.permissions.set(decision)155                memory[key] = nil156            }157        }158    }159160    private func removeStored(_ key: Key) async throws {161        if let stored = try await database.permissions.decisions(profile: key.profile, origin: key.origin).first(where: { $0.kind == key.kind }) {162            try await database.permissions.remove(stored.id)163        }164    }165166    private func resolve(kind: PermissionKind, origin: WebOrigin, profile: ProfileID) async -> SitePermission {167        let date = now()168        if Self.secureContextKinds.contains(kind), !Self.isSecureContext(origin) {169            return SitePermission(origin: origin, kind: kind, verdict: .deny, source: .policy)170        }171        let key = Key(profile: profile, origin: origin, kind: kind)172        if let decision = memory[key] {173            if decision.isActive(at: date) {174                return SitePermission(origin: origin, kind: kind, verdict: decision.verdict, source: .session,175                                      decidedAt: decision.decidedAt, expiresAt: decision.expiresAt)176            }177            memory[key] = nil178        }179        if !isGhost(profile) {180            do {181                if let stored = try await database.permissions.decision(profile: profile, origin: origin, kind: kind, at: date) {182                    return SitePermission(origin: origin, kind: kind, verdict: stored.verdict, source: .stored,183                                          decidedAt: stored.decidedAt, expiresAt: stored.expiresAt)184                }185            } catch {186                Log.privacy.error("Permission lookup failed: \(String(describing: error), privacy: .public)")187                return SitePermission(origin: origin, kind: kind, verdict: .ask, source: .defaultValue)188            }189        }190        return SitePermission(origin: origin, kind: kind, verdict: await defaultVerdict(for: kind), source: .defaultValue)191    }192193    // MARK: Revoking194195    /// Forgets the decision for one kind on one site: the default applies again.196    public func revoke(_ kind: PermissionKind, origin: WebOrigin, profile: ProfileID) async throws {197        let key = Key(profile: profile, origin: origin, kind: kind)198        memory[key] = nil199        if !isGhost(profile) { try await removeStored(key) }200    }201202    /// Forgets every decision of a site, or of the whole profile when `origin` is `nil`. Returns how many203    /// decisions were removed.204    @discardableResult205    public func revokeAll(origin: WebOrigin? = nil, profile: ProfileID) async throws -> Int {206        let keys = memory.keys.filter { $0.profile == profile && (origin == nil || $0.origin == origin) }207        for key in keys { memory[key] = nil }208        guard !isGhost(profile) else { return keys.count }209        return keys.count + (try await database.permissions.removeAll(profile: profile, origin: origin))210    }211212    /// Drops the in-memory (`session`) decisions of one profile. Returns how many were dropped.213    @discardableResult214    public func revokeAllSessionDecisions(profile: ProfileID) async throws -> Int {215        let keys = memory.keys.filter { $0.profile == profile }216        for key in keys { memory[key] = nil }217        return keys.count218    }219220    /// Drops the in-memory decisions of a private profile when its session ends.221    public func endGhostSession(profile: ProfileID) {222        for key in memory.keys where key.profile == profile { memory[key] = nil }223    }224225    /// Drops every `session` decision (the app is about to quit, or the user asked to "forget this session").226    public func endSession() { memory.removeAll() }227228    /// Deletes stored decisions whose 24 h expiry has passed. Call at launch.229    @discardableResult230    public func purgeExpired() async throws -> Int {231        let date = now()232        for (key, decision) in memory where !decision.isActive(at: date) { memory[key] = nil }233        return try await database.permissions.purgeExpired(at: date)234    }235236    // MARK: Queries237238    /// Every permission kind for a site, with the verdict in force and where it comes from.239    public func sitePermissions(origin: WebOrigin, profile: ProfileID) async -> [SitePermission] {240        var result: [SitePermission] = []241        for kind in PermissionKind.allCases { result.append(await resolve(kind: kind, origin: origin, profile: profile)) }242        return result243    }244245    /// Explicit decisions of a profile (stored and session), grouped by site, sites and kinds in a stable order.246    public func decidedSites(profile: ProfileID) async throws -> [(origin: WebOrigin, permissions: [SitePermission])] {247        let date = now()248        var byOrigin: [WebOrigin: [PermissionKind: SitePermission]] = [:]249        if !isGhost(profile) {250            for stored in try await database.permissions.decisions(profile: profile, activeAt: date) {251                byOrigin[stored.origin, default: [:]][stored.kind] = SitePermission(252                    origin: stored.origin, kind: stored.kind, verdict: stored.verdict, source: .stored,253                    decidedAt: stored.decidedAt, expiresAt: stored.expiresAt)254            }255        }256        for (key, decision) in memory where key.profile == profile && decision.isActive(at: date) {257            byOrigin[key.origin, default: [:]][key.kind] = SitePermission(258                origin: key.origin, kind: key.kind, verdict: decision.verdict, source: .session,259                decidedAt: decision.decidedAt, expiresAt: decision.expiresAt)260        }261        return byOrigin.sorted { $0.key.description < $1.key.description }.map { origin, kinds in262            (origin, PermissionKind.allCases.compactMap { kinds[$0] })263        }264    }265}266267public enum PermissionError: Error, Sendable, Equatable {268    /// Camera, microphone, location and motion cannot be allowed on an insecure origin.269    case insecureOrigin270    /// Camera, microphone and location cannot be allowed by default for every site.271    case defaultNotAllowed272}273
Files main
Menu

Theme