The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
Keep imported extension files until startup verifies their store replacement (#217)
Grigoriy300864989de7
diff --git a/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift b/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swiftindex 8f970ed..7bdea73 100644--- a/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift+++ b/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift@@ -8,8 +8,9 @@ import Foundation/// into an UNPACKED one (location 4), which Chromium turns off without developer mode. A copy/// of a Web Store extension is installed again from the store in each profile it loads in, the/// way the store's "Add to Chrome" does (Cra.installFromWebStore): the signed CRX, location 1-/// (INTERNAL), from the Web Store, updated by Chromium. Once a profile has that install, the-/// folder stops loading there, and the folder goes when no profile loads it any more. A copy+/// (INTERNAL), from the Web Store, updated by Chromium. Once a profile has that install on disk,+/// the folder stops loading there from the next launch, and the folder goes when no profile+/// loads it any more (never while Chromium runs, which may still read it). A copy/// the store doesn't take (offline, delisted, asks for more permissions) keeps loading from/// the folder; the next launch asks again.public enum WebStoreInstalls {@@ -38,6 +39,19 @@ public enum WebStoreInstalls {return (entry["location"] as? Int) == internalLocation && (entry["from_webstore"] as? Bool) == true}+ /// The folder a store install of `extensionID` lives in: Extensions/<id>/<version> in+ /// `profileDirectory`, from the entry's relative or absolute path. nil for anything else,+ /// such as an imported copy whose entry claims the store.+ public static func storeInstallDirectory(settings entry: [String: Any]?, extensionID: String, profileDirectory: URL) -> URL? {+ guard isStoreInstall(settings: entry), isExtensionID(extensionID),+ let path = entry?["path"] as? String, !path.isEmpty else { return nil }+ let extensions = profileDirectory.appendingPathComponent("Extensions", isDirectory: true).standardizedFileURL+ let installed = (path.hasPrefix("/") ? URL(fileURLWithPath: path, isDirectory: true)+ : extensions.appendingPathComponent(path, isDirectory: true)).standardizedFileURL+ guard installed.deletingLastPathComponent() == extensions.appendingPathComponent(extensionID, isDirectory: true) else { return nil }+ return installed+ }+/// The profiles a Web Store copy in `folder` still loads in from the folder, where Chromium/// has no store install of it yet, in `profiles` order.public static func pendingProfiles(folder: String, extensionID: String, scopes: ExtensionProfiles,diff --git a/Packages/CraCore/Tests/CraCoreTests/WebStoreInstallDirectoryTests.swift b/Packages/CraCore/Tests/CraCoreTests/WebStoreInstallDirectoryTests.swiftnew file mode 100644index 0000000..7ea9bcc--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/WebStoreInstallDirectoryTests.swift@@ -0,0 +1,43 @@+import CraCore+import Foundation+import Testing++struct WebStoreInstallDirectoryTests {+ let id = "aaaabbbbccccddddeeeeffffgggghhhh"+ let profile = URL(fileURLWithPath: "/fixture/Chromium/Default", isDirectory: true)++ func installed(_ path: String, location: Int = 1, fromWebStore: Bool = true, extensionID: String? = nil) -> URL? {+ WebStoreInstalls.storeInstallDirectory(settings: ["location": location, "from_webstore": fromWebStore, "path": path],+ extensionID: extensionID ?? id, profileDirectory: profile)+ }++ @Test func resolvesRelativeAndAbsoluteStorePaths() {+ let expected = profile.appendingPathComponent("Extensions/\(id)/1.0_0", isDirectory: true)+ #expect(installed("\(id)/1.0_0") == expected)+ #expect(installed(expected.path) == expected)+ }++ @Test func rejectsImportedDirectoriesDespiteWebStoreFlags() {+ #expect(installed("/fixture/Extensions/\(id)") == nil)+ #expect(installed("/fixture/Extensions/\(id)/1.0_0") == nil)+ #expect(installed("/fixture/Chromium/Profile 1/Extensions/\(id)/1.0_0") == nil)+ }++ @Test func rejectsMissingPathsAndDifferentExtensionDirectories() {+ #expect(WebStoreInstalls.storeInstallDirectory(settings: nil, extensionID: id, profileDirectory: profile) == nil)+ #expect(WebStoreInstalls.storeInstallDirectory(settings: ["location": 1, "from_webstore": true],+ extensionID: id, profileDirectory: profile) == nil)+ #expect(installed("") == nil)+ #expect(installed(id) == nil)+ #expect(installed("bbbbccccddddeeeeffffgggghhhhiiii/1.0_0") == nil)+ #expect(installed("\(id)/1.0_0/icons") == nil)+ #expect(installed("../../Extensions/\(id)/1.0_0") == nil)+ #expect(installed("\(id)/1.0_0", extensionID: "not-an-extension-id") == nil)+ }++ @Test func requiresAStoreInstallation() {+ #expect(installed("\(id)/1.0_0", location: 8) == nil)+ #expect(installed("\(id)/1.0_0", location: 4) == nil)+ #expect(installed("\(id)/1.0_0", fromWebStore: false) == nil)+ }+}diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swiftindex a59b9ce..8e65543 100644--- a/Sources/Cra/App/main.swift+++ b/Sources/Cra/App/main.swift@@ -39,7 +39,7 @@ MainActor.assumeIsolated {NativeMessagingHosts.link(into: AppPaths.chromiumCache)- let extensions = ExtensionStore.loadList()+ let extensions = ExtensionStore.loadList(profileIsFree: profileIsFree)CraCEFRuntime.setExtensionPaths(extensions.paths, profiles: extensions.profiles)if let p = extensions.profiles { CraLog.note("extension profiles: \(p)") }diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swiftindex 8fd2a61..14a2dd8 100644--- a/Sources/Cra/Services/ExtensionStore.swift+++ b/Sources/Cra/Services/ExtensionStore.swift@@ -53,12 +53,16 @@ final class ExtensionStore {/// The folders --load-extension loads at start-up, in name order, and the switch that says/// which profiles load each (CraCEFRuntime.setExtensionPaths).- nonisolated static func loadList() -> (paths: [String], profiles: String?) {+ nonisolated static func loadList(profileIsFree: Bool = true) -> (paths: [String], profiles: String?) {let fm = FileManager.default// Before Chromium starts: a copy the store already installed in a profile must not load// there again, or --load-extension would put the copy back over the store's install.let profiles = chromiumProfiles()- dropWebStoreCopies(profiles: profiles) { ExtensionImporter.settings(inProfile: AppPaths.chromiumCache.appendingPathComponent($0, isDirectory: true)) }+ if profileIsFree {+ dropWebStoreCopies(profiles: profiles) {+ ExtensionImporter.settings(inProfile: AppPaths.chromiumCache.appendingPathComponent($0, isDirectory: true))+ }+ }let names = ((try? fm.contentsOfDirectory(atPath: directory.path)) ?? []).sorted().filter { fm.fileExists(atPath: directory.appendingPathComponent($0).appendingPathComponent("manifest.json").path) }return (names.map { directory.appendingPathComponent($0, isDirectory: true).path }, loadProfiles().commandLineValue(forFolders: names))@@ -126,24 +130,86 @@ final class ExtensionStore {/// Each profile where the store has installed a copy's extension stops loading the copy;/// a copy no profile loads any more is deleted. True when anything changed.@discardableResult- nonisolated static func dropWebStoreCopies(profiles: [String], settings: (String) -> [String: Any]) -> Bool {+ nonisolated private static func dropWebStoreCopies(profiles: [String], settings: (String) -> [String: Any]) -> Bool {var scopes = loadProfiles()var changed = falsefor copy in webStoreCopies() {for profile in profiles where scopes.loads(folder: copy.folder, inProfile: profile)- && WebStoreInstalls.isStoreInstall(settings: settings(profile)[copy.folder] as? [String: Any]) {+ && hasStoreInstall(copy.folder, inProfile: profile, settings: settings(profile)) {+ var next = scopes+ let removeCopy = next.movedToWebStore(folder: copy.folder, profile: profile, allProfiles: Set(profiles))+ if removeCopy {+ do { try FileManager.default.removeItem(at: directory.appendingPathComponent(copy.folder, isDirectory: true)) }+ catch {+ CraLog.note("extension \(copy.folder): could not remove its migrated copy (\(error.localizedDescription))")+ continue+ }+ }+ scopes = nextchanged = trueCraLog.note("extension \(copy.folder) is the Web Store's install in \(profile) now")- if scopes.movedToWebStore(folder: copy.folder, profile: profile, allProfiles: Set(profiles)) {- try? FileManager.default.removeItem(at: directory.appendingPathComponent(copy.folder, isDirectory: true))- break- }+ if removeCopy { break }}}- if changed { try? saveProfiles(scopes) }+ if changed {+ do { try saveProfiles(scopes) }+ catch { CraLog.note("extension migration: could not save profile scopes (\(error.localizedDescription))") }+ }return changed}+ nonisolated private static func hasStoreInstall(_ id: String, inProfile profile: String, settings: [String: Any]) -> Bool {+ let profileDirectory = AppPaths.chromiumCache.appendingPathComponent(profile, isDirectory: true).resolvingSymlinksInPath()+ guard let installed = WebStoreInstalls.storeInstallDirectory(settings: settings[id] as? [String: Any], extensionID: id,+ profileDirectory: profileDirectory)?.resolvingSymlinksInPath(),+ installed.deletingLastPathComponent() == profileDirectory.appendingPathComponent("Extensions/\(id)", isDirectory: true),+ let data = try? Data(contentsOf: installed.appendingPathComponent("manifest.json")),+ let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let version = manifest["version"] as? String, !version.isEmpty,+ manifest["manifest_version"] is Int else { return false }+ return true+ }++ /// Web Store copies whose store install was live this session ("<profile>/<id>"). The copy+ /// keeps its folder until the next launch, when the store install is on disk.+ @ObservationIgnored private var liveStoreInstalls: Set<String> = []++ /// A store install seen this session that has left its profile's live settings was removed+ /// (chrome://extensions deletes an INTERNAL extension's entry), so its copy stops loading+ /// there, or the next launch would bring the extension back. The copy goes once no profile+ /// loads it; Chromium stopped reading it when the store install replaced it.+ private func dropRemovedStoreInstalls(profiles: [String], live: [String: [String: Any]]) {+ var scopes = Self.loadProfiles()+ var changed = false+ for copy in Self.webStoreCopies() {+ for profile in profiles where scopes.loads(folder: copy.folder, inProfile: profile) {+ guard let settings = live[profile] else { continue }+ let key = "\(profile)/\(copy.folder)"+ if Self.hasStoreInstall(copy.folder, inProfile: profile, settings: settings) {+ liveStoreInstalls.insert(key)+ continue+ }+ guard liveStoreInstalls.contains(key), settings[copy.folder] == nil else { continue }+ var next = scopes+ if next.movedToWebStore(folder: copy.folder, profile: profile, allProfiles: Set(profiles)) {+ do { try FileManager.default.removeItem(at: Self.directory.appendingPathComponent(copy.folder, isDirectory: true)) }+ catch {+ CraLog.note("extension \(copy.folder): could not remove its copy (\(error.localizedDescription))")+ continue+ }+ }+ liveStoreInstalls.remove(key)+ scopes = next+ changed = true+ CraLog.note("extension \(copy.folder) was removed from \(profile) after its Web Store install; its copy stops loading there")+ }+ }+ if changed {+ do { try Self.saveProfiles(scopes) }+ catch { CraLog.note("extension migration: could not save profile scopes (\(error.localizedDescription))") }+ }+ }+/// Extension IDs asked of the store in a profile this session ("<profile>/<id>"), each once.@ObservationIgnored private var webStoreAsked: Set<String> = []@@ -179,7 +245,7 @@ final class ExtensionStore {nonisolated private static func saveProfiles(_ profiles: ExtensionProfiles) throws {if profiles.folders.isEmpty {- try? FileManager.default.removeItem(at: profilesFile)+ if FileManager.default.fileExists(atPath: profilesFile.path) { try FileManager.default.removeItem(at: profilesFile) }} else {try JSONEncoder().encode(profiles).write(to: profilesFile, options: .atomic)}@@ -200,9 +266,11 @@ final class ExtensionStore {try? fm.createDirectory(at: ExtensionStore.directory, withIntermediateDirectories: true)let root = AppPaths.chromiumCachelet profiles = Self.chromiumProfiles()- let settings = Dictionary(uniqueKeysWithValues: profiles.map { ($0, Self.extensionSettings(inProfile: $0)) })- // A copy the store just installed (Cra.installFromWebStore) gives way to the store's install.- Self.dropWebStoreCopies(profiles: profiles) { settings[$0] ?? [:] }+ let live = Dictionary(uniqueKeysWithValues: profiles.compactMap { p in Self.liveExtensionSettings(inProfile: p).map { (p, $0) } })+ let settings = Dictionary(uniqueKeysWithValues: profiles.map {+ ($0, live[$0] ?? ExtensionImporter.settings(inProfile: root.appendingPathComponent($0, isDirectory: true)))+ })+ dropRemovedStoreInstalls(profiles: profiles, live: live)let names = (try? fm.contentsOfDirectory(atPath: ExtensionStore.directory.path)) ?? []let disabled = settings.mapValues(ExtensionImporter.disabledIDs(settings:))let scopes = Self.loadProfiles()@@ -210,6 +278,13 @@ final class ExtensionStore {guard var entry = Self.entry(id: name, folder: ExtensionStore.directory.appendingPathComponent(name, isDirectory: true),extensionID: nil) else { return nil }entry.profiles = scopes.profiles(ofFolder: name)+ let migrated = Set(profiles.filter {+ scopes.loads(folder: name, inProfile: $0) && Self.hasStoreInstall(entry.extensionID, inProfile: $0, settings: settings[$0] ?? [:])+ })+ if !migrated.isEmpty {+ entry.profiles = (entry.profiles ?? Set(profiles)).subtracting(migrated)+ if entry.profiles?.isEmpty == true { return nil }+ }entry.disabledProfiles = Set(profiles.filter { disabled[$0]?.contains(entry.extensionID) == true })return entry}@@ -294,12 +369,16 @@ final class ExtensionStore {/// or a switch, so a profile that has loaded answers from memory (and says when it changes);/// the files only for one no space has opened yet, where nothing can have changed.private static func extensionSettings(inProfile name: String) -> [String: Any] {+ liveExtensionSettings(inProfile: name)+ ?? ExtensionImporter.settings(inProfile: AppPaths.chromiumCache.appendingPathComponent(name, isDirectory: true))+ }++ /// A loaded profile's extensions.settings from Chromium's memory; nil before it loads or+ /// once it has shut down.+ private static func liveExtensionSettings(inProfile name: String) -> [String: Any]? {let dir = AppPaths.chromiumCache.appendingPathComponent(name, isDirectory: true)- if let json = CraCEFRuntime.extensionSettings(forProfile: name == "Default" ? nil : dir.path),- let live = try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any] {- return live- }- return ExtensionImporter.settings(inProfile: dir)+ guard let json = CraCEFRuntime.extensionSettings(forProfile: name == "Default" ? nil : dir.path) else { return nil }+ return try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any]}/// The extension whose options page `url` is (its options_ui/options_page, or Chrome'sdiff --git a/Tests/ExtensionStoreMigrationTests.swift b/Tests/ExtensionStoreMigrationTests.swiftnew file mode 100644index 0000000..73aa96b--- /dev/null+++ b/Tests/ExtensionStoreMigrationTests.swift@@ -0,0 +1,239 @@+import CraCEF+import Foundation++@main+@MainActor+enum ExtensionStoreMigrationTests {+ static var checks = 0+ static var failures: [String] = []+ static let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/ExtensionMigration", isDirectory: true)+ static let key = "dGVzdC1leHRlbnNpb24ta2V5"++ @MainActor+ struct Install {+ let id: String+ let copy: URL+ let profile: URL+ var destination: URL { profile.appendingPathComponent("Extensions/\(id)/1.0_0", isDirectory: true) }+ var relativePath: String { "\(id)/1.0_0" }++ func settings(path: String? = nil) -> [String: Any] {+ [id: ["location": 1, "from_webstore": true, "path": path ?? relativePath]]+ }++ func writeSettings(_ settings: [String: Any], in directory: URL? = nil) throws {+ let directory = directory ?? profile+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try JSONSerialization.data(withJSONObject: ["extensions": ["settings": settings]])+ .write(to: directory.appendingPathComponent("Secure Preferences"))+ }++ func liveSettings(_ settings: [String: Any], profile: String = "Default") throws {+ let key = profile == "Default" ? profile : AppPaths.chromiumCache.appendingPathComponent(profile, isDirectory: true).path+ CraCEFRuntime.settingsByProfile[key] = String(decoding: try JSONSerialization.data(withJSONObject: settings), as: UTF8.self)+ }++ func installStoreCopy() throws {+ try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.copyItem(at: fixture, to: destination)+ }+ }++ static func check(_ condition: Bool, _ message: String) {+ checks += 1+ if !condition {+ failures.append(message)+ print("FAIL: \(message)")+ }+ }++ static func run(_ name: String, _ body: (Install) throws -> Void) throws {+ let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["CRA_DATA_DIR"]!, isDirectory: true)+ AppPaths.supportDir = root.appendingPathComponent(name, isDirectory: true)+ CraCEFRuntime.settingsByProfile = [:]+ let id = ExtensionStore.chromiumID(key: key, folder: fixture)+ let copy = ExtensionStore.directory.appendingPathComponent(id, isDirectory: true)+ let profile = AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true)+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.copyItem(at: fixture, to: copy)+ try FileManager.default.createDirectory(at: profile, withIntermediateDirectories: true)+ try body(Install(id: id, copy: copy, profile: profile))+ }++ static func main() throws {+ try run("live-reload") { install in+ try install.installStoreCopy()+ try install.writeSettings(install.settings())+ let store = ExtensionStore()+ store.reload()+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "refreshing the live extension list must not delete files Chromium can still be reading")+ check(store.entries.contains { $0.extensionID == install.id }, "the extension stays listed during migration")+ }++ try run("live-store-ownership") { install in+ try install.writeSettings([install.id: ["location": 8, "path": install.copy.path]])+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ store.reload()+ check(store.entries.first?.managedByChrome == true,+ "a live store installation exposes Chromium's removal flow instead of deleting its backup")+ check(store.entries.first?.url == install.destination, "the displayed entry uses the live store installation")+ check(FileManager.default.fileExists(atPath: install.copy.path), "showing the store entry does not delete the loaded backup")+ }++ try run("stale-import-path") { install in+ try install.writeSettings(install.settings(path: install.copy.path))+ let list = ExtensionStore.loadList()+ check(list.paths == [install.copy.path], "Web Store flags with the original imported path must not delete the only copy")+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "an imported path mislabeled as a store install remains readable")+ }++ try run("missing-store-files") { install in+ try install.writeSettings(install.settings())+ let list = ExtensionStore.loadList()+ check(list.paths == [install.copy.path], "a store record without its installed files keeps the imported copy")+ }++ try run("invalid-store-manifest") { install in+ try install.installStoreCopy()+ try Data("not JSON".utf8).write(to: install.destination.appendingPathComponent("manifest.json"))+ try install.writeSettings(install.settings())+ check(ExtensionStore.loadList().paths == [install.copy.path], "an unreadable store manifest cannot replace an imported copy")+ }++ try run("store-path-aliases-import") { install in+ try FileManager.default.createDirectory(at: install.destination.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(at: install.destination, withDestinationURL: install.copy)+ try install.writeSettings(install.settings())+ check(ExtensionStore.loadList().paths == [install.copy.path], "a symlink to the imported copy is not an independent store installation")+ }++ try run("completed-store-install") { install in+ try install.installStoreCopy()+ try install.writeSettings(install.settings())+ check(ExtensionStore.loadList().paths.isEmpty, "a verified independent store install replaces the imported copy before Chromium starts")+ check(!FileManager.default.fileExists(atPath: install.copy.path), "completed migration removes the redundant copy at startup")+ check(FileManager.default.fileExists(atPath: install.destination.appendingPathComponent("payload.txt").path), "store resources survive cleanup")+ let store = ExtensionStore()+ check(store.entries.first?.managedByChrome == true, "the migrated entry belongs to Chromium")+ }++ try run("migration-finishes-while-running") { install in+ try install.writeSettings([install.id: ["location": 8, "path": install.copy.path]])+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.writeSettings(install.settings())+ store.reload()+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "completing a store install does not invalidate a loaded extension's resource paths")+ _ = ExtensionStore.loadList(profileIsFree: false)+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "another launch must not delete files while a process still owns the profile")+ check(ExtensionStore.loadList(profileIsFree: true).paths.isEmpty,+ "the imported copy is retired only after the profile becomes free")+ let restarted = ExtensionStore()+ check(restarted.entries.first?.extensionID == install.id && restarted.entries.first?.managedByChrome == true,+ "the extension remains installed after the startup handover")+ }++ try run("crash-before-store-preferences-flush") { install in+ try install.writeSettings([install.id: ["location": 8, "path": install.copy.path]])+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ store.reload()+ check(ExtensionStore.loadProfiles().loads(folder: install.id, inProfile: "Default"),+ "live store preferences must not retire an import before the installation is persisted")+ CraCEFRuntime.settingsByProfile = [:]+ let list = ExtensionStore.loadList()+ check(list.paths == [install.copy.path], "a crash before Chromium flushes its store preferences preserves a usable registered import")+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "unflushed store installation metadata cannot delete the imported resources")+ check(ExtensionStore().entries.contains { $0.extensionID == install.id }, "the extension remains visible after an unflushed migration crashes")+ }++ try run("crash-before-first-preferences-flush") { install in+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ store.reload()+ CraCEFRuntime.settingsByProfile = [:]+ check(ExtensionStore.loadList().paths == [install.copy.path], "an absent on-disk record after a crash must not be mistaken for an uninstall")+ }++ try run("live-preferences-unavailable-during-shutdown") { install in+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ store.reload()+ CraCEFRuntime.settingsByProfile = [:]+ store.reload()+ check(ExtensionStore.loadProfiles().loads(folder: install.id, inProfile: "Default"),+ "an unavailable live snapshot is not evidence that the user uninstalled the extension")+ check(ExtensionStore.loadList().paths == [install.copy.path],+ "a queued reload during shutdown must not retire the only persisted extension registration")+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "resources remain available after an interrupted shutdown with unavailable live preferences")+ }++ try run("store-install-removed-before-restart") { install in+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ store.reload()+ check(FileManager.default.fileExists(atPath: install.copy.path), "the copy waits for the next launch while the store install is live")+ try install.liveSettings([:])+ store.reload()+ check(!FileManager.default.fileExists(atPath: install.copy.path),+ "removing the store install in chrome://extensions also retires the copy that waited for the next launch")+ check(ExtensionStore.loadList().paths.isEmpty, "an extension removed after its store install does not come back at the next launch")+ check(store.entries.isEmpty, "the removed extension leaves the list at once")+ }++ try run("store-install-removed-in-one-profile") { install in+ let other = AppPaths.chromiumCache.appendingPathComponent("Profile 1", isDirectory: true)+ try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true)+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ try install.liveSettings([install.id: ["location": 8, "path": install.copy.path]], profile: "Profile 1")+ store.reload()+ try install.liveSettings([:])+ store.reload()+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "a copy another profile still loads stays when the store install is removed in one profile")+ check(ExtensionStore.loadProfiles().profiles(ofFolder: install.id) == ["Profile 1"],+ "only the profile it was removed from stops loading the copy")+ }++ try run("live-settings-gone-after-store-install") { install in+ let store = ExtensionStore()+ try install.installStoreCopy()+ try install.liveSettings(install.settings())+ store.reload()+ CraCEFRuntime.settingsByProfile = [:]+ store.reload()+ check(FileManager.default.fileExists(atPath: install.copy.appendingPathComponent("payload.txt").path),+ "live settings going away (shutdown) is not a removal of the store install")+ }++ try run("one-profile-still-imported") { install in+ try install.installStoreCopy()+ try install.writeSettings(install.settings())+ let other = AppPaths.chromiumCache.appendingPathComponent("Profile 1", isDirectory: true)+ try install.writeSettings([install.id: ["location": 8, "path": install.copy.path]], in: other)+ let list = ExtensionStore.loadList()+ check(list.paths == [install.copy.path], "a copy another profile still loads is retained")+ check(list.profiles == "Profile 1", "only the migrated profile stops loading the imported copy")+ check(ExtensionStore.loadProfiles().profiles(ofFolder: install.id) == ["Profile 1"], "profile migration scope persists")+ let listAgain = ExtensionStore.loadList()+ check(listAgain.paths == list.paths && listAgain.profiles == list.profiles, "a second launch preserves the remaining profile's copy")+ }++ print("ExtensionStoreMigrationTests: \(checks) checks, \(failures.count) failures")+ if !failures.isEmpty { exit(1) }+ }+}diff --git a/Tests/ExtensionStoreSupport/AppServices.swift b/Tests/ExtensionStoreSupport/AppServices.swiftnew file mode 100644index 0000000..f99fc97--- /dev/null+++ b/Tests/ExtensionStoreSupport/AppServices.swift@@ -0,0 +1,25 @@+import Foundation++enum AppPaths {+ static var supportDir: URL = {+ guard let path = ProcessInfo.processInfo.environment["CRA_DATA_DIR"] else {+ fatalError("Extension store tests require CRA_DATA_DIR")+ }+ return URL(fileURLWithPath: path, isDirectory: true)+ }()++ static var chromiumCache: URL { supportDir.appendingPathComponent("Chromium", isDirectory: true) }+ static func file(_ name: String) -> URL { supportDir.appendingPathComponent(name) }+}++struct ImportSource {+ let id: String+ var dataDir: URL { AppPaths.supportDir.appendingPathComponent("source-\(id)", isDirectory: true) }+ static let arc = ImportSource(id: "arc")+ static let dia = ImportSource(id: "dia")+ static let allCases: [ImportSource] = []+}++enum CraLog {+ static func note(_ message: String) {}+}diff --git a/Tests/ExtensionStoreSupport/CraCEF.swift b/Tests/ExtensionStoreSupport/CraCEF.swiftnew file mode 100644index 0000000..d3aac59--- /dev/null+++ b/Tests/ExtensionStoreSupport/CraCEF.swift@@ -0,0 +1,15 @@+import Foundation++@MainActor+public enum CraCEFRuntime {+ public static var settingsByProfile: [String: String] = [:]+ public static func setExtensionSettingsChangeHandler(_ handler: @escaping () -> Void) {}+ public static func extensionSettings(forProfile profile: String?) -> String? { settingsByProfile[profile ?? "Default"] }+}++@MainActor+public final class CraBrowser {+ public init() {}++ public func sendDevToolsMethod(_ method: String, params: String, completion: @escaping (String?, String?) -> Void) {}+}diff --git a/Tests/Fixtures/ExtensionMigration/manifest.json b/Tests/Fixtures/ExtensionMigration/manifest.jsonnew file mode 100644index 0000000..d22acf9--- /dev/null+++ b/Tests/Fixtures/ExtensionMigration/manifest.json@@ -0,0 +1 @@+{"name":"Migration fixture","version":"1.0","manifest_version":3,"key":"dGVzdC1leHRlbnNpb24ta2V5","update_url":"https://clients2.google.com/service/update2/crx"}diff --git a/Tests/Fixtures/ExtensionMigration/payload.txt b/Tests/Fixtures/ExtensionMigration/payload.txtnew file mode 100644index 0000000..72bdea3--- /dev/null+++ b/Tests/Fixtures/ExtensionMigration/payload.txt@@ -0,0 +1 @@+Extension resource that must remain readable while Chromium uses the imported folder.diff --git a/scripts/test-extension-store-migration.sh b/scripts/test-extension-store-migration.shnew file mode 100755index 0000000..56c3cf0--- /dev/null+++ b/scripts/test-extension-store-migration.sh@@ -0,0 +1,21 @@+#!/bin/bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/cra-extension-migration.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+xcrun swiftc -swift-version 5 -emit-module -emit-library -module-name CraCEF \+ Tests/ExtensionStoreSupport/CraCEF.swift -o "$TEST_DIR/libCraCEF.dylib" \+ -emit-module-path "$TEST_DIR/CraCEF.swiftmodule"+xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} \+ -I "$TEST_DIR" -L "$TEST_DIR" -lCraCEF -Xlinker -rpath -Xlinker "$TEST_DIR" \+ Packages/CraCore/Sources/CraCore/ExtensionProfiles.swift \+ Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift \+ Packages/CraCore/Sources/CraCore/PinnedExtensions.swift \+ Packages/CraCore/Sources/CraCore/ExtensionActionState.swift \+ Packages/CraCore/Sources/CraCore/ExtensionBadge.swift \+ Packages/CraCore/Sources/CraCore/ExtensionProxyControl.swift \+ Sources/Cra/Services/Import/ExtensionImporter.swift Sources/Cra/Services/ExtensionStore.swift \+ Tests/ExtensionStoreSupport/AppServices.swift Tests/ExtensionStoreMigrationTests.swift \+ -o "$TEST_DIR/extension-migration-tests"+CRA_DATA_DIR="$TEST_DIR/data" "$TEST_DIR/extension-migration-tests"+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/extension-migration-tests" "$CRA_TEST_KEEP/"diff --git a/scripts/test.sh b/scripts/test.shindex e352f1a..dc68f2d 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -22,6 +22,7 @@ if [ "${1:-}" != core ]; thensuite "Extension popup candidate" scripts/test-extension-popup-candidate.shsuite "Extension popup window" scripts/test-extension-popup-window.shsuite "Extension state" scripts/test-extension-state.sh+ suite "Extension store migration" scripts/test-extension-store-migration.shsuite "Store and importers" scripts/test-store.shsuite "Policies" scripts/test-policies.shsuite "Command bar glyph" scripts/test-command-bar-glyph.sh