Repository Public License
1import Foundation2import NavigatorCore34/// The categories of user data that can be deleted independently.5public enum UserDataType: String, Sendable, Codable, CaseIterable {6 case history, bookmarks, downloads, permissions, archives, snapshots, notes, canvases, agentRuns7 /// Tabs and windows the user closed, kept for "reopen closed tab/window".8 case recentlyClosed9 /// All windows, tabs and tab groups, open or closed.10 case session11 /// Not tied to a profile: only touched by requests without a profile.12 case workflows, settings, syncRecords1314 /// Types that have no profile: a profile-scoped deletion leaves them alone.15 public var isGlobal: Bool { self == .workflows || self == .settings || self == .syncRecords }16}1718/// What to delete: which types, for which profile (`nil` = all profiles and global data), in which time range19/// (`nil` = any time; the range is half-open, `[start, end)`).20public struct DeletionRequest: Sendable {21 public var types: Set<UserDataType>22 public var profileID: ProfileID?23 public var range: DateInterval?2425 public init(types: Set<UserDataType>, profileID: ProfileID? = nil, range: DateInterval? = nil) {26 self.types = types; self.profileID = profileID; self.range = range27 }28}2930/// An archive file whose database row was deleted. The archive module removes the file.31public struct ArchiveFileReference: Sendable, Hashable {32 public var profileID: ProfileID33 public var relativePath: String34}3536public struct DeletionReport: Sendable {37 /// Rows deleted per type (visits for history).38 public var deleted: [UserDataType: Int] = [:]39 /// Files on disk that are now orphaned.40 public var archiveFiles: [ArchiveFileReference] = []4142 public var total: Int { deleted.values.reduce(0, +) }43}4445/// A portable copy of the user's data. Contains no cookies or website storage (WebKit owns those and they are46/// never read by this module), no secrets (they live in the Keychain), no WebKit session blobs and no download47/// resume data.48public struct UserDataBundle: Codable, Sendable {49 public static let currentFormatVersion = 15051 public var formatVersion: Int52 public var schemaVersion: Int53 public var exportedAt: Date54 public var profiles: [Profile]55 public var spaces: [OrbitSpace]56 public var tabGroups: [TabGroup]57 public var windows: [BrowserWindow]58 public var tabs: [Tab]59 public var history: [NavigationEntry]60 public var bookmarks: [Bookmark]61 public var downloads: [Download]62 public var permissions: [PermissionDecision]63 public var archives: [Archive]64 public var snapshots: [PageSnapshot]65 public var notes: [Note]66 public var canvases: [CanvasDocument]67 public var agentRuns: [AgentRun]68 public var workflows: [Workflow]69 /// Raw JSON text of each setting, by key.70 public var settings: [String: String]71}7273public enum PersistenceSettings {74 /// Days of history to keep; `0` keeps history forever.75 public static let historyRetentionDays = SettingKey<Int>("history.retention_days", default: 0)76}7778/// Deletion, retention and export of user data.79public struct DataLifecycle: Sendable {80 let context: StoreContext8182 // MARK: Deletion8384 /// Deletes the requested types, in one transaction. Global types (`isGlobal`) are skipped when the request85 /// names a profile. For `.session` the range applies to the tab's last activity; for `.recentlyClosed` to86 /// the closing time.87 @discardableResult88 public func delete(_ request: DeletionRequest) async throws -> DeletionReport {89 try await context.transaction { try Self.delete(request, $0) }90 }9192 /// Deletes a profile and everything that belongs to it, including the notes, canvases and agent runs of93 /// its spaces. The caller removes the WebKit data store and the reported archive files.94 @discardableResult95 public func deleteProfile(_ id: ProfileID) async throws -> DeletionReport {96 try await context.transaction { connection in97 let report = try Self.delete(DeletionRequest(types: Set(UserDataType.allCases.filter { !$0.isGlobal }),98 profileID: id), connection)99 try connection.execute("DELETE FROM profiles WHERE id = ?", [id])100 return report101 }102 }103104 /// Deletes all user data of every profile, the profiles themselves, settings and sync state, then compacts105 /// the file so the deleted content does not linger in free pages. The schema and the sync version counter106 /// stay (the counter must never go backwards for devices that already saw higher versions).107 @discardableResult108 public func deleteEverything() async throws -> DeletionReport {109 let report = try await context.transaction { connection in110 let report = try Self.delete(DeletionRequest(types: Set(UserDataType.allCases)), connection)111 try connection.executeScript("""112 DELETE FROM profiles;113 DELETE FROM app_state WHERE key <> '\(SyncStore.versionKey)';114 INSERT INTO history_fts(history_fts) VALUES ('rebuild');115 """)116 return report117 }118 try await compact()119 return report120 }121122 /// Rebuilds the database file (`VACUUM`) and truncates the WAL. Run after large deletions.123 public func compact() async throws {124 try await context.database.write { connection in125 try connection.executeScript("VACUUM")126 _ = try? connection.query("PRAGMA wal_checkpoint(TRUNCATE)")127 }128 }129130 private static func delete(_ request: DeletionRequest, _ connection: SQLiteConnection) throws -> DeletionReport {131 var report = DeletionReport()132 let profile = request.profileID133 let start = request.range?.start, end = request.range?.end134135 /// Rows of `table` in the date range, limited to the profile through `scope` (SQL over the table that136 /// uses `?1` for the profile id).137 func remove(_ type: UserDataType, from table: String, date column: String, scope: String,138 extra: String = "1 = 1") throws {139 let count = try connection.execute("""140 DELETE FROM \(table) WHERE (?1 IS NULL OR \(scope))141 AND (?2 IS NULL OR \(column) >= ?2) AND (?3 IS NULL OR \(column) < ?3) AND \(extra)142 """, [profile, start, end])143 report.deleted[type, default: 0] += count144 }145 let viaSpace = "space_id IN (SELECT id FROM spaces WHERE profile_id = ?1)"146147 // A fixed order keeps the result independent of Set iteration order.148 for type in UserDataType.allCases where request.types.contains(type) {149 if type.isGlobal && profile != nil { continue }150 switch type {151 case .history:152 report.deleted[.history] = try HistorySQL.deleteVisits(connection, profile: profile, from: start, to: end)153 case .bookmarks:154 try remove(.bookmarks, from: "bookmarks", date: "created_at", scope: "profile_id = ?1")155 case .downloads:156 try remove(.downloads, from: "downloads", date: "started_at", scope: "profile_id = ?1")157 case .permissions:158 try remove(.permissions, from: "permissions", date: "decided_at", scope: "profile_id = ?1")159 case .archives:160 let rows = try connection.query("""161 SELECT profile_id, relative_path FROM archives WHERE (?1 IS NULL OR profile_id = ?1)162 AND (?2 IS NULL OR captured_at >= ?2) AND (?3 IS NULL OR captured_at < ?3)163 """, [profile, start, end])164 report.archiveFiles += try rows.map {165 ArchiveFileReference(profileID: try $0.get("profile_id"), relativePath: try $0.get("relative_path"))166 }167 try remove(.archives, from: "archives", date: "captured_at", scope: "profile_id = ?1")168 case .snapshots:169 try remove(.snapshots, from: "page_snapshots", date: "taken_at", scope: "profile_id = ?1")170 case .notes:171 try remove(.notes, from: "notes", date: "created_at", scope: viaSpace)172 case .canvases:173 try remove(.canvases, from: "canvas_documents", date: "created_at", scope: viaSpace)174 case .agentRuns:175 try remove(.agentRuns, from: "agent_runs", date: "started_at", scope: viaSpace)176 case .recentlyClosed:177 try remove(.recentlyClosed, from: "tabs", date: "closed_at", scope: viaSpace, extra: "closed_at IS NOT NULL")178 try remove(.recentlyClosed, from: "windows", date: "closed_at", scope: viaSpace, extra: "closed_at IS NOT NULL")179 case .session:180 try remove(.session, from: "tabs", date: "last_active_at", scope: viaSpace)181 if request.range == nil {182 try remove(.session, from: "windows", date: "sort_order", scope: viaSpace)183 try remove(.session, from: "tab_groups", date: "sort_order", scope: viaSpace)184 } else {185 // With a time range only tabs carry a date; drop windows the range left empty.186 report.deleted[.session, default: 0] += try connection.execute("""187 DELETE FROM windows WHERE (?1 IS NULL OR \(viaSpace))188 AND NOT EXISTS (SELECT 1 FROM tabs WHERE tabs.window_id = windows.id)189 """, [profile])190 }191 case .workflows:192 try remove(.workflows, from: "workflows", date: "created_at", scope: "1 = 1")193 case .settings:194 try remove(.settings, from: "settings", date: "updated_at", scope: "1 = 1")195 case .syncRecords:196 try remove(.syncRecords, from: "sync_records", date: "modified_at", scope: "1 = 1")197 }198 }199 return report200 }201202 // MARK: Retention203204 /// Deletes history visits older than `days` days before `now`. `days <= 0` keeps everything. Returns the205 /// number of visits deleted.206 @discardableResult207 public func applyHistoryRetention(days: Int, now: Date = .now) async throws -> Int {208 guard days > 0 else { return 0 }209 let cutoff = now.addingTimeInterval(-Double(days) * 86_400)210 return try await context.transaction {211 try HistorySQL.deleteVisits($0, profile: nil, from: nil, to: cutoff)212 }213 }214215 /// Applies the retention stored in `PersistenceSettings.historyRetentionDays` (call at launch and daily).216 @discardableResult217 public func applyStoredRetentionPolicy(now: Date = .now) async throws -> Int {218 let days = try await SettingsStore(context: context).value(PersistenceSettings.historyRetentionDays)219 return try await applyHistoryRetention(days: days, now: now)220 }221222 // MARK: Export223224 /// Reads the user's data (of one profile, or everything) in one consistent snapshot.225 public func exportBundle(profile: ProfileID? = nil, now: Date = .now) async throws -> UserDataBundle {226 try await context.read { connection in227 let viaSpace = "(?1 IS NULL OR space_id IN (SELECT id FROM spaces WHERE profile_id = ?1))"228 let byProfile = "(?1 IS NULL OR profile_id = ?1)"229 func rows(_ sql: String) throws -> [SQLiteRow] { try connection.query(sql, [profile]) }230 // Notes, canvases and runs without a space belong to no profile: only a full export has them.231 let optionalSpace = "(?1 IS NULL OR space_id IN (SELECT id FROM spaces WHERE profile_id = ?1))"232233 var tabs = try rows("SELECT * FROM tabs WHERE \(viaSpace) ORDER BY window_id, sort_order, id").map(Tab.init(row:))234 for index in tabs.indices { tabs[index].sessionState = nil }235 var downloads = try rows("SELECT * FROM downloads WHERE \(byProfile) ORDER BY started_at, id").map(Download.init(row:))236 for index in downloads.indices { downloads[index].resumeData = nil }237238 return UserDataBundle(239 formatVersion: UserDataBundle.currentFormatVersion,240 schemaVersion: try Migrator.currentVersion(connection),241 exportedAt: now,242 profiles: try connection.query("SELECT * FROM profiles WHERE (?1 IS NULL OR id = ?1) ORDER BY created_at, id",243 [profile]).map(Profile.init(row:)),244 spaces: try rows("SELECT * FROM spaces WHERE \(byProfile) ORDER BY sort_order, id").map(OrbitSpace.init(row:)),245 tabGroups: try rows("SELECT * FROM tab_groups WHERE \(viaSpace) ORDER BY sort_order, id").map(TabGroup.init(row:)),246 windows: try rows("SELECT * FROM windows WHERE \(viaSpace) ORDER BY sort_order, id").map(BrowserWindow.init(row:)),247 tabs: tabs,248 history: try rows("""249 SELECT v.id, v.profile_id, v.space_id, u.url, v.title, v.visited_at, v.transition250 FROM history_visits v JOIN history_urls u ON u.id = v.url_id251 WHERE (?1 IS NULL OR v.profile_id = ?1) ORDER BY v.visited_at, v.id252 """).map(HistorySQL.entry),253 bookmarks: try connection.query("\(BookmarkSQL.select) WHERE (?1 IS NULL OR b.profile_id = ?1) ORDER BY b.parent_id, b.sort_order, b.id",254 [profile]).map(Bookmark.init(row:)),255 downloads: downloads,256 permissions: try rows("SELECT * FROM permissions WHERE \(byProfile) ORDER BY origin_host, kind").map(PermissionDecision.init(row:)),257 archives: try rows("SELECT * FROM archives WHERE \(byProfile) ORDER BY captured_at, id").map(Archive.init(row:)),258 snapshots: try rows("SELECT * FROM page_snapshots WHERE \(byProfile) ORDER BY taken_at, id").map(PageSnapshot.init(row:)),259 notes: try rows("SELECT * FROM notes WHERE \(optionalSpace) ORDER BY created_at, id").map(Note.init(row:)),260 canvases: try rows("SELECT * FROM canvas_documents WHERE \(optionalSpace) ORDER BY created_at, id").map(CanvasDocument.init(row:)),261 agentRuns: try rows("SELECT * FROM agent_runs WHERE \(optionalSpace) ORDER BY started_at, id").map(AgentRun.init(row:)),262 workflows: profile == nil ? try connection.query("SELECT * FROM workflows ORDER BY created_at, id").map(Workflow.init(row:)) : [],263 settings: profile == nil ? try Dictionary(uniqueKeysWithValues: connection.query("SELECT key, value FROM settings").map {264 (try $0.get("key", as: String.self), try $0.get("value", as: String.self))265 }) : [:])266 }267 }268269 /// The bundle as pretty-printed JSON with ISO 8601 dates.270 public func exportJSON(profile: ProfileID? = nil, now: Date = .now) async throws -> Data {271 let bundle = try await exportBundle(profile: profile, now: now)272 let encoder = JSONEncoder()273 encoder.dateEncodingStrategy = .iso8601274 encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]275 return try encoder.encode(bundle)276 }277278 /// Writes the JSON bundle to `url` atomically (protected until first unlock on iOS).279 public func exportJSON(to url: URL, profile: ProfileID? = nil, now: Date = .now) async throws {280 let data = try await exportJSON(profile: profile, now: now)281 try await FileWorker.shared.run {282 try data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])283 }284 }285286 /// Decodes a bundle written by `exportJSON`.287 public static func decodeBundle(_ data: Data) throws -> UserDataBundle {288 let decoder = JSONDecoder()289 decoder.dateDecodingStrategy = .iso8601290 return try decoder.decode(UserDataBundle.self, from: data)291 }292}293