SPB Git

Repository Public License

MemoryPolicy.swift 13.4 KB 228 lines swift

1// MemoryEngine — what may be indexed: opt-in, ghost rejection, host exclusions, sensitive-page heuristics.2import Foundation3import NavigatorCore4import Persistence56public enum MemoryItemKind: String, Sendable, Codable, CaseIterable, Hashable {7    case page, note, archive, snapshot8}910/// Facts about a page that only the caller (the web runtime) can observe.11public struct MemoryPageFacts: Sendable, Hashable {12    /// The response carried `Cache-Control: no-store`.13    public var cacheControlNoStore: Bool14    /// The document contains an `<input type="password">`.15    public var hasPasswordField: Bool16    /// The content comes from a ghost (private) window, whatever its profile id says.17    public var isPrivate: Bool1819    public init(cacheControlNoStore: Bool = false, hasPasswordField: Bool = false, isPrivate: Bool = false) {20        self.cacheControlNoStore = cacheControlNoStore; self.hasPasswordField = hasPasswordField; self.isPrivate = isPrivate21    }22}2324/// One thing to index: the caller has already extracted the text.25public struct MemoryInput: Sendable, Hashable {26    public var kind: MemoryItemKind27    /// Stable identifier of the item within its kind (a note id, an archive id, a snapshot id; for a page, its URL).28    public var itemID: String29    public var profileID: ProfileID?30    public var spaceID: SpaceID?31    public var url: URL?32    public var title: String33    public var text: String34    /// When the content was seen or written (visit time, note update, capture time).35    public var date: Date36    public var facts: MemoryPageFacts3738    public init(kind: MemoryItemKind, itemID: String, profileID: ProfileID? = nil, spaceID: SpaceID? = nil, url: URL? = nil,39                title: String, text: String, date: Date = .now, facts: MemoryPageFacts = MemoryPageFacts()) {40        self.kind = kind; self.itemID = itemID; self.profileID = profileID; self.spaceID = spaceID; self.url = url41        self.title = title; self.text = text; self.date = date; self.facts = facts42    }4344    /// A visited page, keyed by its URL within the profile.45    public static func page(url: URL, title: String, text: String, profileID: ProfileID, spaceID: SpaceID? = nil,46                            date: Date = .now, facts: MemoryPageFacts) -> MemoryInput {47        MemoryInput(kind: .page, itemID: "\(profileID.string)|\(url.absoluteString)", profileID: profileID, spaceID: spaceID, url: url,48                    title: title, text: text, date: date, facts: facts)49    }5051    public static func note(_ note: Note) -> MemoryInput {52        MemoryInput(kind: .note, itemID: note.id.string, spaceID: note.spaceID, url: note.url, title: note.title,53                    text: [note.quote, note.body].compactMap { $0 }.joined(separator: "\n\n"), date: note.updatedAt)54    }5556    public static func snapshot(_ snapshot: PageSnapshot) -> MemoryInput {57        MemoryInput(kind: .snapshot, itemID: snapshot.id.string, profileID: snapshot.profileID, url: snapshot.url, title: snapshot.title,58                    text: snapshot.text, date: snapshot.takenAt)59    }6061    /// An archive; the caller supplies the text extracted from the archived file.62    public static func archive(_ archive: Archive, text: String) -> MemoryInput {63        MemoryInput(kind: .archive, itemID: archive.id.string, profileID: archive.profileID, url: archive.url, title: archive.title,64                    text: text, date: archive.capturedAt)65    }66}6768public enum MemorySensitiveCategory: String, Sendable, Hashable, CaseIterable, Codable {69    case authentication, account, banking, payment, health, webmail, credentialsInURL, localNetwork70}7172public enum MemorySkipReason: Sendable, Hashable {73    /// The user has not turned the memory on.74    case disabled75    /// Ghost (private) content is never indexed.76    case ghost77    /// The profile is not stored (unknown, deleted, or ghost and therefore never stored).78    case profileNotPersisted79    case excludedHost(pattern: String)80    case sensitiveURL(MemorySensitiveCategory)81    case noStore82    case passwordField83    case unsupportedScheme84    case emptyText85    case tooLarge86}8788/// A host exclusion written by the user. `example.org` covers the host and its subdomains; `*.example.org`89/// covers only subdomains; a leading `=` (`=example.org`) covers exactly that host.90public struct MemoryHostPattern: Hashable, Sendable {91    public let text: String9293    /// `nil` when the text cannot be a host pattern.94    public init?(_ raw: String) {95        var value = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()96        if let url = URL(string: value), let host = url.host, url.scheme != nil { value = host }97        let body = value.hasPrefix("*.") ? String(value.dropFirst(2)) : (value.hasPrefix("=") ? String(value.dropFirst()) : value)98        guard !body.isEmpty, body.utf8.count <= 253, !body.hasPrefix("."), !body.hasSuffix("."), !body.contains(".."),99              body.unicodeScalars.allSatisfy({ $0 == "." || $0 == "-" || $0.properties.isAlphabetic || ($0.value >= 48 && $0.value <= 57) }) else {100            return nil101        }102        text = value103    }104105    public func matches(host: String) -> Bool {106        var host = host.lowercased()107        if host.hasSuffix(".") { host.removeLast() }108        if text.hasPrefix("*.") { return host.hasSuffix(text.dropFirst(1)) }109        if text.hasPrefix("=") { return host == text.dropFirst() }110        return host == text || host.hasSuffix("." + text)111    }112}113114/// The rules that decide whether something may enter the index. Pure: no database, no clock.115public struct MemoryPolicy: Sendable, Hashable {116    public var isEnabled: Bool117    public var excludedHosts: [MemoryHostPattern]118    /// Hosts the user explicitly exempted from the sensitive-page heuristics (false positives). They never119    /// override `no-store`, password fields, ghost content or an explicit exclusion.120    public var allowedHosts: [MemoryHostPattern]121    public var usesDefaultExclusions: Bool122123    public init(isEnabled: Bool = false, excludedHosts: [MemoryHostPattern] = [], allowedHosts: [MemoryHostPattern] = [],124                usesDefaultExclusions: Bool = true) {125        self.isEnabled = isEnabled; self.excludedHosts = excludedHosts; self.allowedHosts = allowedHosts126        self.usesDefaultExclusions = usesDefaultExclusions127    }128129    static let authenticationWords: Set<String> = ["login", "logon", "signin", "signup", "logout", "signout", "auth", "authenticate", "authentication",130                                                    "authorize", "oauth", "oauth2", "sso", "saml", "openid", "password", "passwd", "passcode",131                                                    "2fa", "mfa", "otp", "verify", "verification", "recover", "recovery", "challenge", "captcha"]132    static let accountWords: Set<String> = ["account", "accounts", "myaccount", "billing", "subscription", "subscriptions"]133    static let paymentWords: Set<String> = ["checkout", "payment", "payments", "pay", "wallet", "invoice", "invoices", "card", "cards"]134    // "bank" alone is an ordinary word in a path (an encyclopedia article); only the service words count.135    static let bankingWords: Set<String> = ["banking", "ebanking", "onlinebanking", "netbanking"]136    static let credentialKeys: Set<String> = ["token", "accesstoken", "idtoken", "refreshtoken", "code", "session", "sessionid", "sid", "key", "apikey",137                                               "password", "passwd", "pwd", "secret", "auth", "signature", "sig", "otp", "state", "ticket", "jwt"]138    static let authenticationLabels: Set<String> = ["login", "signin", "auth", "sso", "id", "idp", "identity", "account", "accounts", "secure", "oauth", "passport"]139    static let webmailLabels: Set<String> = ["mail", "webmail", "email", "outlook", "inbox", "owa"]140    static let webmailHosts: [String] = ["mail.google.com", "outlook.live.com", "outlook.office.com", "outlook.office365.com", "mail.yahoo.com",141                                         "mail.proton.me", "app.fastmail.com", "mail.zoho.com", "app.hey.com", "mail.aol.com", "tutanota.com"]142    static let bankingFragments = ["bank", "banque", "banco", "sparkasse", "creditunion", "caisse", "desjardins", "paypal", "wise.com"]143    static let healthFragments = ["health", "sante", "santé", "clinic", "clinique", "hospital", "hopital", "medical", "medic", "patient", "pharma", "doctor",144                                  "mychart", "therapy", "dossier-sante"]145146    /// Words of a path or of a key: lowercased runs of letters and digits, plus the two-word forms joined147    /// (`sign-in` → `signin`, `access_token` → `accesstoken`).148    static func words(_ text: String) -> Set<String> {149        let parts = text.lowercased().split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map(String.init)150        var result = Set(parts)151        for index in parts.indices.dropFirst() { result.insert(parts[index - 1] + parts[index]) }152        return result153    }154155    static func isLocal(host: String) -> Bool {156        if host == "localhost" || host.hasSuffix(".local") || host.hasSuffix(".localhost") || host.hasSuffix(".internal")157            || host.hasSuffix(".lan") || host.hasSuffix(".home.arpa") || host.contains(":") || !host.contains(".") { return true }158        let octets = host.split(separator: ".").map { Int($0) }159        if octets.count == 4, octets.allSatisfy({ $0 != nil }) { return true }   // any IPv4 literal: no public site is browsed by address160        return false161    }162163    /// The sensitive category a URL falls in by the default heuristics, if any.164    public static func sensitiveCategory(of url: URL) -> MemorySensitiveCategory? {165        guard var host = url.host?.lowercased() else { return nil }166        if host.hasSuffix(".") { host.removeLast() }167        if isLocal(host: host) { return .localNetwork }168        if webmailHosts.contains(where: { host == $0 || host.hasSuffix("." + $0) }) { return .webmail }169        let labels = host.split(separator: ".").map(String.init)170        // The registrable part is not a signal ("mail.com" is a site, "mail.example.com" is somebody's webmail).171        let subdomains = labels.dropLast(2)172        if subdomains.contains(where: webmailLabels.contains) { return .webmail }173        if subdomains.contains(where: authenticationLabels.contains) { return .authentication }174        if bankingFragments.contains(where: host.contains) { return .banking }175        if healthFragments.contains(where: host.contains) { return .health }176        if host == "www.icloud.com" || host == "icloud.com", url.path.hasPrefix("/mail") { return .webmail }177        let pathWords = words(url.path)178        if !pathWords.isDisjoint(with: authenticationWords) { return .authentication }179        if !pathWords.isDisjoint(with: bankingWords) { return .banking }180        if !pathWords.isDisjoint(with: paymentWords) { return .payment }181        if !pathWords.isDisjoint(with: accountWords) { return .account }182        if let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems {183            for item in items {184                let key = item.name.lowercased().filter { $0.isLetter || $0.isNumber }185                if credentialKeys.contains(key) { return .credentialsInURL }186            }187        }188        if let fragment = url.fragment?.lowercased(), fragment.contains("token=") || fragment.contains("code=") { return .credentialsInURL }189        return nil190    }191192    /// Why an input must not be indexed, or `nil` when it may. `profileIsStored` and `isGhost` are resolved by193    /// the caller against the database (`nil` profile → both checks are skipped, see docs/MEMORY.md).194    public func skipReason(for input: MemoryInput, profileIsStored: Bool?, isGhost: Bool) -> MemorySkipReason? {195        guard isEnabled else { return .disabled }196        if isGhost || input.facts.isPrivate { return .ghost }197        if profileIsStored == false { return .profileNotPersisted }198        if input.facts.cacheControlNoStore { return .noStore }199        if input.facts.hasPasswordField { return .passwordField }200        if let url = input.url {201            guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", let host = url.host, !host.isEmpty else {202                return .unsupportedScheme203            }204            if url.user != nil || url.password != nil { return .sensitiveURL(.credentialsInURL) }205            if let pattern = excludedHosts.first(where: { $0.matches(host: host) }) { return .excludedHost(pattern: pattern.text) }206            if usesDefaultExclusions, !allowedHosts.contains(where: { $0.matches(host: host) }),207               let category = Self.sensitiveCategory(of: url) {208                return .sensitiveURL(category)209            }210        } else if input.kind == .page {211            return .unsupportedScheme212        }213        if input.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return .emptyText }214        return nil215    }216}217218/// Setting keys of the module (all under `memory.`; none is exported in capsules or synchronised).219public enum MemorySettings {220    public static let enabled = SettingKey<Bool>("memory.enabled", default: false)221    public static let excludedHosts = SettingKey<[String]>("memory.excluded_hosts", default: [])222    public static let allowedHosts = SettingKey<[String]>("memory.allowed_hosts", default: [])223    public static let usesDefaultExclusions = SettingKey<Bool>("memory.default_exclusions", default: true)224    public static let storageCapBytes = SettingKey<Int64>("memory.storage_cap_bytes", default: 256 * 1024 * 1024)225    /// Version of the module's own tables.226    public static let schemaVersion = SettingKey<Int>("memory.schema_version", default: 0)227}228
Files main
Menu

Theme