From a49b5c6e36967c2c6660fda83b1b481869ca32f2 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Mon, 23 Nov 2026 20:24:24 +0530 Subject: [PATCH 1/3] Protect password vaults and stabilize menu tests for 0.2.4 Keep inaccessible vaults and development keys intact, restrict profile cleanup to owned files, and report locked backups while allowing a backed-up import to finish. Drive nested context menus by their keyboard selection, cover a Finder drop and profile-specific WebKit data removal, and add the 0.2.4 release highlights. --- Config/Early.xcconfig | 2 +- Packaging/ReleaseNotes/0.2.4.md | 8 ++ Sources/Early/BrowserApplication.swift | 23 +++-- Sources/EarlyCore/BackgroundFileIO.swift | 5 + Sources/EarlyCore/PasswordVault.swift | 36 ++++--- Sources/EarlyCore/StateArchiveFiles.swift | 33 +++++-- .../BrowserImportApplicationTests.swift | 23 ++++- .../PasswordApplicationTests.swift | 9 +- .../ProfileApplicationTests.swift | 33 +++++++ .../PasswordVaultCleanupTests.swift | 24 ++++- .../PasswordVaultRecoveryTests.swift | 66 +++++++++++++ Tests/EarlyCoreTests/PasswordVaultTests.swift | 6 +- Tests/EarlyCoreTests/StateArchiveTests.swift | 22 +++++ .../EarlyWebTests/PasswordAutofillTests.swift | 3 +- UITests/EarlyUITests.swift | 99 +++++++++++++------ 15 files changed, 319 insertions(+), 73 deletions(-) create mode 100644 Packaging/ReleaseNotes/0.2.4.md diff --git a/Config/Early.xcconfig b/Config/Early.xcconfig index 5cf6229..55434be 100644 --- a/Config/Early.xcconfig +++ b/Config/Early.xcconfig @@ -22,5 +22,5 @@ GENERATE_INFOPLIST_FILE = YES INFOPLIST_FILE = Config/Info.plist INFOPLIST_KEY_CFBundleDisplayName = Early INFOPLIST_KEY_LSApplicationCategoryType = public.app-category.productivity -MARKETING_VERSION = 0.2.3 +MARKETING_VERSION = 0.2.4 CURRENT_PROJECT_VERSION = 1 diff --git a/Packaging/ReleaseNotes/0.2.4.md b/Packaging/ReleaseNotes/0.2.4.md new file mode 100644 index 0000000..d3e24c0 --- /dev/null +++ b/Packaging/ReleaseNotes/0.2.4.md @@ -0,0 +1,8 @@ +## Fixes + +- Translating a page preserves edits the website makes while translation is running. Find updates its matches when text changes or becomes visible. +- Website icons retry after failed loads. Clearing a profile’s icons waits for pending writes from its windows. +- Downloads report interrupted transfers correctly, and a page saved to disk stays listed after its tab closes. +- Windows opened by extensions include all requested URLs in order. +- Pre-import backups keep the new copy and the four most recent earlier copies. If an older backup is locked, the import finishes with a notice. Exports and imports check the same size and profile limits. +- Early preserves saved passwords when it temporarily loses access to the vault on disk. diff --git a/Sources/Early/BrowserApplication.swift b/Sources/Early/BrowserApplication.swift index 4fe634a..ece3101 100644 --- a/Sources/Early/BrowserApplication.swift +++ b/Sources/Early/BrowserApplication.swift @@ -730,9 +730,9 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { try await BackgroundFileIO.run { try EarlyStateArchive.write(workspace: workspace, settings: settings, to: url, using: input) } } - @ObservationIgnored var archiveBackupWriter: @Sendable (BrowserWorkspace, PortableSettings?, URL, NavigationInput) async throws -> URL = { workspace, settings, directory, input in + @ObservationIgnored var archiveBackupWriter: @Sendable (BrowserWorkspace, PortableSettings?, URL, NavigationInput) async throws -> EarlyStateArchive.Backup = { workspace, settings, directory, input in try await BackgroundFileIO.run { - try EarlyStateArchive.backup(workspace: workspace, settings: settings, in: directory, using: input) + try EarlyStateArchive.writeBackup(workspace: workspace, settings: settings, in: directory, using: input) } } @@ -770,6 +770,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { applyingWorkspace = true defer { applyingWorkspace = false; profileOperationInProgress = false; saveAll(); deliverExternalLinks() } var batch: BrowserImportBatch? + var backup: EarlyStateArchive.Backup? do { guard await persistence?.flush() == true else { throw SessionError.database(persistence?.error ?? "Couldn’t save the current session.") } captureWorkspace() @@ -784,8 +785,8 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { // A recoverable backup must be durable before the first history insertion. guard let backupDirectory = backupsDirectory else { throw CocoaError(.fileWriteUnknown) } let backupBatchID = candidate.batch.id - let backup = try await BackgroundFileIO.run { - try EarlyStateArchive.backup(workspace: current, settings: nil, in: backupDirectory, id: backupBatchID, using: validationInput) + backup = try await BackgroundFileIO.run { + try EarlyStateArchive.writeBackup(workspace: current, settings: nil, in: backupDirectory, id: backupBatchID, using: validationInput) } try await journal.write(.init(batch: candidate.batch, state: .importing)) batch = candidate.batch @@ -833,7 +834,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { browserImportError = "Import recovery is pending. Early will retry safely at its next launch. \(error.localizedDescription)" } } - return .init(message: "Import could not finish. \(error.localizedDescription)", succeeded: false) + return .init(message: "Import could not finish. \(error.localizedDescription)", succeeded: false, backup: backup) } } @@ -907,7 +908,13 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { let message: String let succeeded: Bool /// What was here before, to import again if needed. - var backup: URL? + let backup: URL? + + init(message: String, succeeded: Bool, backup: EarlyStateArchive.Backup? = nil) { + self.message = [message, backup?.retentionWarning].compactMap { $0 }.joined(separator: " ") + self.succeeded = succeeded + self.backup = backup?.url + } } /// The whole result is checked, a backup of what's here is saved, then @@ -923,7 +930,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { return ImportOutcome(message: "Close any open website dialogs, then import again.", succeeded: false) } let validation = input - var prepared: (EarlyStateArchive.ImportResult, URL)? + var prepared: (EarlyStateArchive.ImportResult, EarlyStateArchive.Backup)? // Preparation deliberately leaves browsing usable. Rebase if a title, // tab, profile or settings change arrived while the worker was busy. // The finite retry bound avoids holding an import open indefinitely. @@ -945,7 +952,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { guard canEditProfiles else { return .init(message: "Early can’t import right now. Try again in a moment.", succeeded: false) } captureWorkspace() guard workspace == current, preferences.portableSettings == settings else { continue } - let backup: URL + let backup: EarlyStateArchive.Backup do { guard let directory = backupsDirectory else { throw CocoaError(.fileWriteUnknown) } backup = try await archiveBackupWriter(current, settings, directory, validation) diff --git a/Sources/EarlyCore/BackgroundFileIO.swift b/Sources/EarlyCore/BackgroundFileIO.swift index d8c2886..5ee07dc 100644 --- a/Sources/EarlyCore/BackgroundFileIO.swift +++ b/Sources/EarlyCore/BackgroundFileIO.swift @@ -63,6 +63,11 @@ public enum BackgroundFileIO { } } + /// A matching filename never authorizes recursively deleting a directory. + static func removeFileIfPresent(at url: URL) throws { + guard Darwin.unlink(url.path) == 0 || errno == ENOENT else { throw fileError() } + } + public static func copySynchronously(_ source: URL, to destination: URL) throws { try withAccess([source]) { try Task.checkCancellation() diff --git a/Sources/EarlyCore/PasswordVault.swift b/Sources/EarlyCore/PasswordVault.swift index dcfb8c5..d2fcfe9 100644 --- a/Sources/EarlyCore/PasswordVault.swift +++ b/Sources/EarlyCore/PasswordVault.swift @@ -5,6 +5,13 @@ import Foundation import Observation import Security +/// Only a missing file means the vault or its development key has never been saved. +private func readVaultFile(at url: URL) throws(PasswordVault.KeyError) -> Data? { + do { return try Data(contentsOf: url) } + catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { return nil } + catch { throw .init(status: errSecIO) } +} + /// One saved sign-in for a website's origin (`scheme://host[:port]`). Logins /// saved from an HTTP sign-in prompt also keep the realm it asked for. public struct SavedLogin: Codable, Equatable, Hashable, Identifiable, Sendable { @@ -156,8 +163,7 @@ public struct FileVaultKey: PasswordVaultKey { public func remove() throws {} private func read() throws -> Data? { - guard FileManager.default.fileExists(atPath: file.path) else { return nil } - let data = try Data(contentsOf: file) + guard let data = try readVaultFile(at: file) else { return nil } guard data.count == 32 else { throw PasswordVault.KeyError(status: errSecDecode) } return data } @@ -286,11 +292,8 @@ public final class PasswordVault { let started = generation let task = Task { @MainActor [weak self] () -> Bool in let result = await Task.detached { () -> Result<(contents: Contents?, key: Data?), KeyError> in - guard let data = try? Data(contentsOf: fileURL) else { - // No file: nothing saved yet, and no reason to ask the Keychain. - return FileManager.default.fileExists(atPath: fileURL.path) ? .failure(KeyError(status: errSecIO)) : .success((nil, nil)) - } do { + guard let data = try readVaultFile(at: fileURL) else { return .success((nil, nil)) } let current = try key.existing() if let current, let contents = try? Self.decrypt(data, key: SymmetricKey(data: current)) { return .success((contents, current)) @@ -658,8 +661,8 @@ public final class PasswordVault { public nonisolated static func remove(fileURL: URL?, key: (any PasswordVaultKey)?) async throws { try await Task.detached(priority: .utility) { let recoveryFiles = try fileURL.map { try Self.recoveryFiles(for: $0) } ?? [] - try ProfileDataCleanup.removeItem(at: fileURL) - for recovery in recoveryFiles { try ProfileDataCleanup.removeItem(at: recovery) } + if let fileURL { try BackgroundFileIO.removeFileIfPresent(at: fileURL) } + for recovery in recoveryFiles { try BackgroundFileIO.removeFileIfPresent(at: recovery) } // Retry keys even when an earlier attempt already removed the file. // Shared key implementations deliberately keep other profiles' keys. try key?.remove() @@ -671,20 +674,23 @@ public final class PasswordVault { /// belong to the exact vault stem. Similar names and other profiles stay. private nonisolated static func recoveryFiles(for file: URL) throws -> [URL] { let files: [URL] + let keys: Set = [.isRegularFileKey, .isSymbolicLinkKey] do { - files = try FileManager.default.contentsOfDirectory(at: file.deletingLastPathComponent(), includingPropertiesForKeys: nil) + files = try FileManager.default.contentsOfDirectory(at: file.deletingLastPathComponent(), includingPropertiesForKeys: Array(keys)) } catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { return [] } let prefix = file.deletingPathExtension().lastPathComponent + ".unreadable-" - return files.filter { candidate in + return try files.filter { candidate in let name = candidate.lastPathComponent guard name.hasPrefix(prefix), name.hasSuffix(".vault") else { return false } - let suffix = name.dropFirst(prefix.count).dropLast(".vault".count) - if Int(suffix) != nil { return true } - guard suffix.count > 37, suffix[suffix.index(suffix.endIndex, offsetBy: -37)] == "-", - UUID(uuidString: String(suffix.suffix(36))) != nil else { return false } - return Int(suffix.dropLast(37)) != nil + var stamp = name.dropFirst(prefix.count).dropLast(".vault".count) + if stamp.count > 37, stamp.suffix(37).first == "-", UUID(uuidString: String(stamp.suffix(36))) != nil { + stamp = stamp.dropLast(37) + } + guard let seconds = Int(stamp), String(seconds) == stamp else { return false } + let values = try candidate.resourceValues(forKeys: keys) + return values.isRegularFile == true && values.isSymbolicLink == false } } diff --git a/Sources/EarlyCore/StateArchiveFiles.swift b/Sources/EarlyCore/StateArchiveFiles.swift index 631d169..fa6524b 100644 --- a/Sources/EarlyCore/StateArchiveFiles.swift +++ b/Sources/EarlyCore/StateArchiveFiles.swift @@ -25,9 +25,21 @@ extension EarlyStateArchive { try BackgroundFileIO.writeSynchronously(data, to: url) } + public struct Backup: Sendable { + public let url: URL + public let retentionWarning: String? + } + public static func backup(workspace: BrowserWorkspace, settings: PortableSettings?, in directory: URL, retaining limit: Int = 5, id: UUID = UUID(), using input: NavigationInput = NavigationInput()) throws -> URL { + try writeBackup(workspace: workspace, settings: settings, in: directory, retaining: limit, id: id, using: input).url + } + + /// Once committed, the backup can be used even if an older file is locked. + public static func writeBackup(workspace: BrowserWorkspace, settings: PortableSettings?, in directory: URL, + retaining limit: Int = 5, id: UUID = UUID(), + using input: NavigationInput = NavigationInput()) throws -> Backup { let archive = EarlyStateArchive(workspace: workspace, settings: settings) let data = try archive.encoded(using: input) // Both import paths share one directory. Finish each write and prune @@ -42,8 +54,11 @@ extension EarlyStateArchive { formatter.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss" let file = directory.appendingPathComponent("Before Import \(formatter.string(from: archive.exportedAt)) \(id).json") try BackgroundFileIO.writeSynchronously(data, to: file) - try pruneBackups(in: directory, keeping: file, retaining: limit) - return file + do { try pruneBackups(in: directory, keeping: file, retaining: limit) } + catch { + return Backup(url: file, retentionWarning: "Early saved the new backup but couldn’t finish removing older backups. \(error.localizedDescription)") + } + return Backup(url: file, retentionWarning: nil) } } @@ -56,12 +71,18 @@ extension EarlyStateArchive { let earlier = try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: Array(keys)) .compactMap { url -> (url: URL, modified: Date)? in guard url.lastPathComponent != newest.lastPathComponent, - url.lastPathComponent.range(of: namePattern, options: .regularExpression) != nil, - let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true, - values.isSymbolicLink == false, let modified = values.contentModificationDate else { return nil } + url.lastPathComponent.range(of: namePattern, options: .regularExpression) != nil else { return nil } + let values = try url.resourceValues(forKeys: keys) + guard values.isRegularFile == true, values.isSymbolicLink == false, + let modified = values.contentModificationDate else { return nil } return (url, modified) } .sorted { ($0.modified, $0.url.lastPathComponent) > ($1.modified, $1.url.lastPathComponent) } - for backup in earlier.dropFirst(max(1, limit) - 1) { try? files.removeItem(at: backup.url) } + var removalError: (any Error)? + for backup in earlier.dropFirst(max(1, limit) - 1) { + do { try BackgroundFileIO.removeFileIfPresent(at: backup.url) } + catch { removalError = error } + } + if let removalError { throw removalError } } } diff --git a/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift b/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift index ceff79b..50169c9 100644 --- a/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift +++ b/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift @@ -48,7 +48,8 @@ struct BrowserImportApplicationTests { return ["profile": .init(profileID: session.profileID, profileName: "Default", spaceID: session.activeSpaceID, spaceName: "Personal")] } - @Test func browserImportKeepsTheNewBackupAndFourEarlierBackupsByModificationTime() async throws { + @Test(arguments: [false, true], [false, true]) + func importsKeepRecentBackupsAndReportLockedOlderFiles(stateArchive: Bool, locked: Bool) async throws { let fixture = Fixture() await fixture.start() let app = fixture.application, files = FileManager.default @@ -74,13 +75,27 @@ struct BrowserImportApplicationTests { try files.createDirectory(at: folder, withIntermediateDirectories: false) let link = file(81) try files.createSymbolicLink(at: link, withDestinationURL: note) + if locked { try files.setAttributes([.immutable: true], ofItemAtPath: file(10).path) } + defer { + if locked { + try? files.setAttributes([.immutable: false], ofItemAtPath: file(10).path) + try? files.removeItem(at: fixture.directory) + } + } - let document = source() - let result = await app.importBrowser(document, selected: document.initiallySelected, destinations: destinations(app), flatten: false) + let result: EarlyAppDelegate.ImportOutcome + if stateArchive { + result = await app.importState(before, mode: .addProfiles, includeSettings: false) + } else { + let document = source() + result = await app.importBrowser(document, selected: document.initiallySelected, destinations: destinations(app), flatten: false) + } try #require(result.succeeded, "\(result.message)") let backup = try #require(result.backup) - let expected = Set(([95, 20, 30, 40].map(file) + [backup, note, folder, link]).map(\.lastPathComponent)) + let retained = [95, 20, 30, 40] + (locked ? [10] : []) + let expected = Set((retained.map(file) + [backup, note, folder, link]).map(\.lastPathComponent)) #expect(Set(try files.contentsOfDirectory(atPath: directory.path)) == expected) + #expect(result.message.contains("older backups") == locked) #expect(try await app.readStateArchive(at: backup).workspace == before.workspace) #expect(try Data(contentsOf: note) == Data("unrelated".utf8)) await fixture.cleanup() diff --git a/Tests/EarlyBrowserTests/PasswordApplicationTests.swift b/Tests/EarlyBrowserTests/PasswordApplicationTests.swift index 9e1d75d..540e68a 100644 --- a/Tests/EarlyBrowserTests/PasswordApplicationTests.swift +++ b/Tests/EarlyBrowserTests/PasswordApplicationTests.swift @@ -211,11 +211,10 @@ struct PasswordApplicationTests { let directory = FileManager.default.temporaryDirectory.appending(path: "EarlyPasswordImport-\(UUID())") try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } - // A file where the passwords' folder should be: nothing can be written. let blocker = directory.appending(path: "Passwords") - try Data().write(to: blocker) let vault = PasswordVault(fileURL: blocker.appending(path: "profile.vault"), key: TestKey()) - #expect(await vault.load()) + try #require(await vault.load()) + try Data().write(to: blocker) let file = directory.appending(path: "Passwords.csv") try Data("name,url,username,password,note\nExample,https://example.com/,ada,pw,\n".utf8).write(to: file) @@ -279,11 +278,11 @@ struct PasswordApplicationTests { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let blocker = directory.appending(path: "Passwords") - try Data().write(to: blocker) let saved = PasswordVault(fileURL: directory.appending(path: "other.vault"), key: TestKey()) let unsaved = PasswordVault(fileURL: blocker.appending(path: "profile.vault"), key: TestKey()) let opened = await saved.load(), alsoOpened = await unsaved.load() - #expect(opened && alsoOpened) + try #require(opened && alsoOpened) + try Data().write(to: blocker) saved.save(origin: "https://example.com", username: "grace", password: "kept") unsaved.save(origin: "https://example.com", username: "ada", password: "draft") diff --git a/Tests/EarlyBrowserTests/ProfileApplicationTests.swift b/Tests/EarlyBrowserTests/ProfileApplicationTests.swift index 2a44199..4ea5e52 100644 --- a/Tests/EarlyBrowserTests/ProfileApplicationTests.swift +++ b/Tests/EarlyBrowserTests/ProfileApplicationTests.swift @@ -225,6 +225,39 @@ struct ProfileApplicationTests { await fixture.cleanup() } + @Test func websiteDataRemovalRequiresTheCurrentProfileSnapshot() async throws { + let fixture = Fixture() + _ = await fixture.start() + let app = fixture.application + let personal = try #require(app.windowModel(nil)) + let workID = try #require(app.createProfile(name: "Work", color: .purple)) + app.openProfile(workID) + let work = try #require(fixture.opened.last.flatMap { app.windowModel($0) }) + let site = "example.com" + for (model, value) in [(personal, "personal"), (work, "work")] { + let cookie = try #require(HTTPCookie(properties: [.domain: site, .path: "/", .name: "login", .value: value])) + await model.webViews.websiteDataStore.httpCookieStore.setCookie(cookie) + } + let data = ProfileWebsiteData() + let personalID = personal.coordinator.profileID + await data.load(for: personalID, fetch: app.websiteData) + let old = try #require(data.records(for: personalID)) + await data.load(for: workID, fetch: app.websiteData) + let current = try #require(data.records(for: workID)) + try #require(old.records.contains { $0.displayName == site }) + let record = try #require(current.records.first { $0.displayName == site }) + + await data.remove(old.records, from: old, using: app.removeWebsiteData, fetch: app.websiteData) + let workCookies = work.webViews.websiteDataStore.httpCookieStore + let personalCookies = personal.webViews.websiteDataStore.httpCookieStore + #expect(await workCookies.allCookies().map(\.value) == ["work"]) + #expect(await personalCookies.allCookies().map(\.value) == ["personal"]) + await data.remove([record], from: current, using: app.removeWebsiteData, fetch: app.websiteData) + #expect(await workCookies.allCookies().isEmpty) + #expect(await personalCookies.allCookies().map(\.value) == ["personal"]) + await fixture.cleanup() + } + @Test func defaultMigrationAndSharedWriterKeepProfileWindowsAndWebsiteStoresSeparate() async throws { let fixture = Fixture() let legacy = BrowserSession() diff --git a/Tests/EarlyCoreTests/PasswordVaultCleanupTests.swift b/Tests/EarlyCoreTests/PasswordVaultCleanupTests.swift index a03249e..a006eb5 100644 --- a/Tests/EarlyCoreTests/PasswordVaultCleanupTests.swift +++ b/Tests/EarlyCoreTests/PasswordVaultCleanupTests.swift @@ -30,7 +30,8 @@ struct PasswordVaultCleanupTests { let owned = ["profile.unreadable-1700000000.vault", "profile.unreadable-1700000001-\(UUID().uuidString).vault"] let preserved = ["profile-other.unreadable-1700000000.vault", "profile.unreadable-not-a-timestamp.vault", - "profile.unreadable-1700000000-not-a-uuid.vault", "profile.unreadable-1700000000.vault.notes"] + "profile.unreadable-1700000000-not-a-uuid.vault", "profile.unreadable-1700000000.vault.notes", + "profile.unreadable-+12.vault", "profile.unreadable-00012-\(UUID()).vault"] for name in owned + preserved { try Data(name.utf8).write(to: directory.appendingPathComponent(name)) } if opened { @@ -89,4 +90,25 @@ struct PasswordVaultCleanupTests { try await PasswordVault.remove(fileURL: directory.appendingPathComponent("missing/profile.vault"), key: key) #expect(key.key == nil) } + + @Test func cleanupNeverRecursivelyDeletesADirectoryNamedLikeAVault() async throws { + let files = FileManager.default + let directory = try directory() + defer { try? files.removeItem(at: directory) } + let vault = directory.appendingPathComponent("profile.vault") + let recovery = directory.appendingPathComponent("profile.unreadable-1700000000.vault") + for path in [vault, recovery] { + try files.createDirectory(at: path, withIntermediateDirectories: false) + try Data("keep".utf8).write(to: path.appendingPathComponent("document")) + } + let key = MemoryVaultKey(Data(repeating: 7, count: 32)) + await #expect(throws: (any Error).self) { try await PasswordVault.remove(fileURL: vault, key: key) } + #expect(key.key != nil) + try #require(files.fileExists(atPath: vault.appendingPathComponent("document").path)) + + try files.moveItem(at: vault, to: directory.appendingPathComponent("relocated")) + try await PasswordVault.remove(fileURL: vault, key: key) + #expect(try Data(contentsOf: recovery.appendingPathComponent("document")) == Data("keep".utf8)) + #expect(key.key == nil) + } } diff --git a/Tests/EarlyCoreTests/PasswordVaultRecoveryTests.swift b/Tests/EarlyCoreTests/PasswordVaultRecoveryTests.swift index 2e5cb5c..5aeaafd 100644 --- a/Tests/EarlyCoreTests/PasswordVaultRecoveryTests.swift +++ b/Tests/EarlyCoreTests/PasswordVaultRecoveryTests.swift @@ -126,4 +126,70 @@ struct PasswordVaultRecoveryTests { #expect(await vault.load(retry: true)) #expect(vault.logins.isEmpty) } + + @Test(arguments: [false, true]) + func anInaccessibleVaultDirectoryCannotBeMistakenForAnEmptyVault(blockedByFile: Bool) async throws { + let files = FileManager.default + let root = try directory() + let directory = root.appendingPathComponent("Passwords") + let preserved = root.appendingPathComponent("Original") + try files.createDirectory(at: directory, withIntermediateDirectories: false) + defer { + try? files.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path) + try? files.removeItem(at: root) + } + let file = directory.appendingPathComponent("profile.vault") + let key = MemoryVaultKey() + let original = PasswordVault(fileURL: file, key: key) + try #require(await original.load()) + original.save(origin: "https://example.com", username: "original", password: "synthetic") + try #require(await original.flush()) + let bytes = try Data(contentsOf: file) + + if blockedByFile { + try files.moveItem(at: directory, to: preserved) + try Data().write(to: directory) + } else { + try files.setAttributes([.posixPermissions: 0], ofItemAtPath: directory.path) + } + let reopened = PasswordVault(fileURL: file, key: key) + #expect(await reopened.load() == false) + reopened.resetUnreadable() + #expect(!reopened.isReady) + if blockedByFile { + try files.removeItem(at: directory) + try files.moveItem(at: preserved, to: directory) + } else { + try files.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path) + } + #expect(reopened.save(origin: "https://example.com", username: "new", password: "synthetic") == nil) + await reopened.flush() + #expect(try Data(contentsOf: file) == bytes) + try #require(await reopened.load(retry: true)) + #expect(reopened.logins.map(\.username) == ["original"]) + } + + @Test func anInaccessibleDevelopmentKeyCannotOfferToResetARecoverableVault() async throws { + let files = FileManager.default + let directory = try directory() + let keys = directory.appendingPathComponent("Keys", isDirectory: true) + defer { + try? files.setAttributes([.posixPermissions: 0o700], ofItemAtPath: keys.path) + try? files.removeItem(at: directory) + } + let key = FileVaultKey(file: keys.appendingPathComponent("Key"), profile: UUID()) + let file = directory.appendingPathComponent("profile.vault") + let original = PasswordVault(fileURL: file, key: key) + try #require(await original.load()) + original.save(origin: "https://example.com", username: "original", password: "synthetic") + try #require(await original.flush()) + try files.setAttributes([.posixPermissions: 0], ofItemAtPath: keys.path) + let reopened = PasswordVault(fileURL: file, key: key) + #expect(await reopened.load() == false) + reopened.resetUnreadable() + #expect(!reopened.isReady && files.fileExists(atPath: file.path)) + try files.setAttributes([.posixPermissions: 0o700], ofItemAtPath: keys.path) + try #require(await reopened.load(retry: true)) + #expect(reopened.logins.map(\.username) == ["original"]) + } } diff --git a/Tests/EarlyCoreTests/PasswordVaultTests.swift b/Tests/EarlyCoreTests/PasswordVaultTests.swift index c6b59ec..8355634 100644 --- a/Tests/EarlyCoreTests/PasswordVaultTests.swift +++ b/Tests/EarlyCoreTests/PasswordVaultTests.swift @@ -433,13 +433,13 @@ struct PasswordVaultTests { @Test func failedSavesAreReportedAndCanBeTriedAgain() async throws { let directory = FileManager.default.temporaryDirectory.appending(path: "EarlyPasswords-\(UUID())") defer { try? FileManager.default.removeItem(at: directory) } - // A file where the passwords' folder should be: nothing can be written. try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let blocker = directory.appending(path: "Passwords") - try Data().write(to: blocker) let url = blocker.appending(path: "profile.vault") let vault = PasswordVault(fileURL: url, key: MemoryVaultKey()) - #expect(await vault.load()) + try #require(await vault.load()) + // Make the first write fail after the empty vault was successfully opened. + try Data().write(to: blocker) vault.save(origin: "https://example.com", username: "ada", password: "kept") #expect(await vault.flush() == false) #expect(vault.saveError?.contains("couldn’t be written") == true, "\(vault.saveError ?? "nil")") diff --git a/Tests/EarlyCoreTests/StateArchiveTests.swift b/Tests/EarlyCoreTests/StateArchiveTests.swift index 59d0791..516e7a7 100644 --- a/Tests/EarlyCoreTests/StateArchiveTests.swift +++ b/Tests/EarlyCoreTests/StateArchiveTests.swift @@ -125,6 +125,28 @@ struct StateArchiveTests { #expect(try EarlyStateArchive.read(from: #require(saved.last), using: input).workspace == supported) } + @Test func backupReportsALockedObsoleteFileAndRetentionRecoversOnRetry() throws { + let files = FileManager.default + let directory = files.temporaryDirectory.appendingPathComponent("EarlyLockedBackup-\(UUID())") + let workspace = BrowserWorkspace() + let old = try EarlyStateArchive.backup(workspace: workspace, settings: nil, in: directory, retaining: 1) + defer { + try? files.setAttributes([.immutable: false], ofItemAtPath: old.path) + try? files.removeItem(at: directory) + } + try files.setAttributes([.immutable: true], ofItemAtPath: old.path) + let saved = try EarlyStateArchive.writeBackup(workspace: workspace, settings: nil, in: directory, retaining: 1) + #expect(saved.retentionWarning != nil && saved.url != old) + let both = try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + #expect(both.count == 2) + for file in both { #expect(try EarlyStateArchive.read(from: file, using: input).workspace == workspace) } + + try files.setAttributes([.immutable: false], ofItemAtPath: old.path) + let newest = try EarlyStateArchive.writeBackup(workspace: workspace, settings: nil, in: directory, retaining: 1) + #expect(newest.retentionWarning == nil) + #expect(try files.contentsOfDirectory(atPath: directory.path) == [newest.url.lastPathComponent]) + } + @Test func tabCapacityCountsEveryWindowAndRejectsGrowthAcrossTheLimit() throws { var session = BrowserSession() let limit = EarlyStateArchive.maximumTabs diff --git a/Tests/EarlyWebTests/PasswordAutofillTests.swift b/Tests/EarlyWebTests/PasswordAutofillTests.swift index 152254a..3a1e46a 100644 --- a/Tests/EarlyWebTests/PasswordAutofillTests.swift +++ b/Tests/EarlyWebTests/PasswordAutofillTests.swift @@ -755,12 +755,13 @@ struct PasswordAutofillTests { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let blocker = directory.appending(path: "Passwords") - try Data().write(to: blocker) let fixture = makeFixture(["app": Self.app]) defer { fixture.cleanup() } let manager = fixture.manager let vault = PasswordVault(fileURL: blocker.appending(path: "profile.vault"), key: TestKey()) manager.passwords = vault + try #require(await vault.load()) + try Data().write(to: blocker) var notices: [String] = [] manager.onNotice = { notices.append($0) } let tab = try await fixture.open("app") diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index 97d1bb8..4199361 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -86,6 +86,55 @@ final class EarlyUITests: XCTestCase { expectRuntime(app, tabs: 1, views: 1, created: 1) } + func testDroppingAFinderFileOntoALivePageOpensItInANewTab() throws { + let files = FileManager.default + let directory = files.temporaryDirectory.appendingPathComponent("Early Finder Drop \(UUID())", isDirectory: true) + try files.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? files.removeItem(at: directory) } + let file = directory.appendingPathComponent("Drop Document.html") + try Data("Dropped document

Opened from Finder

".utf8).write(to: file) + + let app = launchFreshApp() + navigate(app, to: "early-test://fixture/one") + expectPage(app, "One") + let original = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'tab.'")).firstMatch.identifier + let viewport = app.webViews.firstMatch.frame.intersection(app.windows["browser"].frame) + XCTAssertFalse(viewport.isEmpty) + let drop = CGPoint(x: viewport.maxX - 32, y: viewport.midY) + + let finder = XCUIApplication(bundleIdentifier: "com.apple.finder") + NSWorkspace.shared.activateFileViewerSelecting([file]) + let window = finder.windows[directory.lastPathComponent] + XCTAssertTrue(window.waitForExistence(timeout: 10)) + defer { + if window.exists { + finder.activate() + window.buttons["_XCUI:CloseWindow"].click() + } + } + finder.typeKey("2", modifierFlags: .command) // List view exposes the filename, including when extensions are hidden. + if window.frame.contains(drop) { + finder.typeKey(.leftArrow, modifierFlags: [.function, .control]) + } + let names = [file.lastPathComponent, file.deletingPathExtension().lastPathComponent] + let item = window.descendants(matching: .any) + .matching(NSPredicate(format: "label IN %@ OR value IN %@ OR title IN %@", names, names, names)).firstMatch + let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + item.exists && item.isHittable && !window.frame.contains(drop) + }, object: nil) + XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 10), .completed, window.debugDescription) + // Anchor both coordinates to Finder so resolving the destination cannot raise Early over the source. + let source = item.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) + let point = source.screenPoint + source.click(forDuration: 0.2, thenDragTo: source.withOffset(CGVector(dx: drop.x - point.x, dy: drop.y - point.y)), + withVelocity: .slow, thenHoldForDuration: 0.2) + app.activate() + XCTAssertTrue(app.webViews.staticTexts["Opened from Finder"].firstMatch.waitForExistence(timeout: 10), app.debugDescription) + expectRuntime(app, tabs: 2, views: 2, created: 2) + app.buttons[original].click() + expectPage(app, "One") + } + func testKeyboardCommandsLeaveEmptyWindowUsable() { let app = launchFreshApp() let query = app.textFields["commandBar.query"] @@ -346,8 +395,8 @@ final class EarlyUITests: XCTestCase { pasteText("keep right", into: app.webViews.textFields["Saved text"], in: app) app.buttons[firstID].rightClick() // The Tab menu has a Split View submenu too; use the open context menu's. - visibleMenuItem("Split View")?.hover() - activateFirstSubmenuItem("Place on Left", in: app) + pressMenuKey(.rightArrow, on: "Split View", in: app) + pressMenuKey(.return, on: "Place on Left", in: app) let divider = app.descendants(matching: .any).matching(identifier: "split.divider").firstMatch XCTAssertTrue(divider.waitForExistence(timeout: 5)) let left = app.descendants(matching: .any).matching(identifier: "browser.pane.\(firstID.dropFirst(4))").firstMatch @@ -364,11 +413,11 @@ final class EarlyUITests: XCTestCase { XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: initiallyResized, object: nil)], timeout: 5), .completed) for reversed in [true, false] { app.buttons[firstID].rightClick() - visibleMenuItem("Split View")?.hover() + pressMenuKey(.rightArrow, on: "Split View", in: app) XCTAssertTrue(app.menuItems["Swap Sides"].waitForExistence(timeout: 3)) XCTAssertTrue(app.menuItems["Exit Split View"].exists) XCTAssertFalse(app.menuItems["Place on Left"].exists || app.menuItems["Place on Right"].exists) - activateFirstSubmenuItem("Swap Sides", in: app) + pressMenuKey(.return, on: "Swap Sides", in: app) let swapped = NSPredicate { _, _ in reversed ? left.frame.midX > right.frame.midX : left.frame.midX < right.frame.midX } XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: swapped, object: nil)], timeout: 5), .completed) XCTAssertEqual(left.textFields["Saved text"].value as? String, "keep left") @@ -732,27 +781,21 @@ final class EarlyUITests: XCTestCase { target.item.click() } - /// Menu bar menus expose their items even while closed, so a title the - /// open menu shares with them must be found among the visible items. - private func visibleMenuItem(_ title: String) -> XCUIElement? { - visibleMenuTarget(title)?.item - } - - /// Right Arrow selects the first enabled item of the highlighted submenu. - /// A mouse click can dismiss a nested AppKit menu while crossing to its child. - private func activateFirstSubmenuItem(_ title: String, in app: XCUIApplication, - file: StaticString = #filePath, line: UInt = #line) { - app.typeKey(.rightArrow, modifierFlags: []) - let selected = app.menuItems.matching(identifier: title) - .matching(NSPredicate(format: "selected == true AND enabled == true")) - let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in - selected.allElementsBoundByIndex.filter { self.usableMenuFrame($0.frame) }.count == 1 - }, object: nil) - guard XCTWaiter.wait(for: [ready], timeout: 5) == .completed else { - XCTFail("Expected the open submenu to select \(title) before Return", file: file, line: line) - return - } - app.typeKey(.return, modifierFlags: []) + /// AppKit can leave the pointer over a submenu without highlighting it. + /// Select the named parent before entering it, and the named child before activating it. + private func pressMenuKey(_ key: XCUIKeyboardKey, on title: String, in app: XCUIApplication, + file: StaticString = #filePath, line: UInt = #line) { + guard let target = visibleMenuTarget(title, file: file, line: line) else { return } + let deadline = ContinuousClock.now.advanced(by: .seconds(10)) + repeat { + guard let item = try? target.item.snapshot(), item.isEnabled, usableMenuFrame(item.frame) else { break } + if item.isSelected { + app.typeKey(key, modifierFlags: []) + return + } + app.typeKey(.downArrow, modifierFlags: []) + } while ContinuousClock.now < deadline + XCTFail("Couldn’t select the visible menu item “\(title)”. \(app.debugDescription)", file: file, line: line) } private func usableMenuFrame(_ frame: CGRect) -> Bool { @@ -1188,10 +1231,8 @@ final class EarlyUITests: XCTestCase { saved.click() saved.typeText("keep through Space moves") func chooseDestination(_ name: String, from menu: String) { - let submenu = app.menuItems[menu] - XCTAssertTrue(submenu.waitForExistence(timeout: 3)) - submenu.hover() - activateFirstSubmenuItem(name, in: app) + pressMenuKey(.rightArrow, on: menu, in: app) + pressMenuKey(.return, on: name, in: app) } func move(_ row: XCUIElement, to name: String) { let contextAction = row.identifier.hasPrefix("folder.") ? "Rename Folder…" : "Rename Tab…" From 80f80041dc48f87c1b0de0893d2f54c7dfaa1645 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Tue, 24 Nov 2026 03:24:55 +0530 Subject: [PATCH 2/3] Give Finder drop tests a clear landing area --- UITests/EarlyUITests.swift | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index 4199361..37c4dd8 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -100,7 +100,6 @@ final class EarlyUITests: XCTestCase { let original = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'tab.'")).firstMatch.identifier let viewport = app.webViews.firstMatch.frame.intersection(app.windows["browser"].frame) XCTAssertFalse(viewport.isEmpty) - let drop = CGPoint(x: viewport.maxX - 32, y: viewport.midY) let finder = XCUIApplication(bundleIdentifier: "com.apple.finder") NSWorkspace.shared.activateFileViewerSelecting([file]) @@ -113,28 +112,44 @@ final class EarlyUITests: XCTestCase { } } finder.typeKey("2", modifierFlags: .command) // List view exposes the filename, including when extensions are hidden. - if window.frame.contains(drop) { + if unobstructedFileDropPoint(in: viewport, outside: window.frame) == nil { finder.typeKey(.leftArrow, modifierFlags: [.function, .control]) } let names = [file.lastPathComponent, file.deletingPathExtension().lastPathComponent] let item = window.descendants(matching: .any) .matching(NSPredicate(format: "label IN %@ OR value IN %@ OR title IN %@", names, names, names)).firstMatch let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in - item.exists && item.isHittable && !window.frame.contains(drop) + item.exists && item.isHittable && self.unobstructedFileDropPoint(in: viewport, outside: window.frame) != nil }, object: nil) XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 10), .completed, window.debugDescription) + let drop = try XCTUnwrap(unobstructedFileDropPoint(in: viewport, outside: window.frame)) // Anchor both coordinates to Finder so resolving the destination cannot raise Early over the source. let source = item.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) let point = source.screenPoint source.click(forDuration: 0.2, thenDragTo: source.withOffset(CGVector(dx: drop.x - point.x, dy: drop.y - point.y)), - withVelocity: .slow, thenHoldForDuration: 0.2) - app.activate() + withVelocity: .slow, thenHoldForDuration: 1) XCTAssertTrue(app.webViews.staticTexts["Opened from Finder"].firstMatch.waitForExistence(timeout: 10), app.debugDescription) expectRuntime(app, tabs: 2, views: 2, created: 2) app.buttons[original].click() expectPage(app, "One") } + private func unobstructedFileDropPoint(in viewport: CGRect, outside finder: CGRect) -> CGPoint? { + // Leave room around Finder's shadow and inside Early's web view so + // the drag spends time over the destination before mouse-up. + let target = viewport.insetBy(dx: 24, dy: 24) + let covered = target.intersection(finder.insetBy(dx: -24, dy: -24)) + let clearAreas = covered.isEmpty ? [target] : [ + CGRect(x: target.minX, y: target.minY, width: covered.minX - target.minX, height: target.height), + CGRect(x: covered.maxX, y: target.minY, width: target.maxX - covered.maxX, height: target.height), + CGRect(x: target.minX, y: target.minY, width: target.width, height: covered.minY - target.minY), + CGRect(x: target.minX, y: covered.maxY, width: target.width, height: target.maxY - covered.maxY) + ] + guard let area = clearAreas.filter({ $0.width >= 80 && $0.height >= 80 }) + .max(by: { $0.width * $0.height < $1.width * $1.height }) else { return nil } + return CGPoint(x: area.midX, y: area.midY) + } + func testKeyboardCommandsLeaveEmptyWindowUsable() { let app = launchFreshApp() let query = app.textFields["commandBar.query"] From 0110a6b266b9d6a23085ea6fd86df1829a1eaa42 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Tue, 24 Nov 2026 05:18:58 +0530 Subject: [PATCH 3/3] Allow WebKit file drops to reach Early's new-tab handler WebKit disables WKDragDestinationActionLoad by default on macOS 10.13+, so dragging a Finder file onto a live page without a DHTML drop zone or file input caused draggingUpdated to return NSDragOperationNone and reject the drop before performDragOperation ran. Opt into WKDragDestinationActionLoad only for drags carrying file URLs so page upload targets still take precedence while unhandled Finder drops reach decideLocalNavigation and open in a new tab. Normalize symlinks when matching dropped file URLs (e.g. /private/var vs /var), handle drops consistently on local pages too, and activate Early before clicking the original tab in the Finder drop UI test. --- Sources/EarlyWeb/BrowserWebView.swift | 12 +- Sources/EarlyWeb/PageNavigation.swift | 29 +++- .../LocalDocumentPolicyTests.swift | 143 ++++++++++++++++++ UITests/EarlyUITests.swift | 1 + 4 files changed, 178 insertions(+), 7 deletions(-) diff --git a/Sources/EarlyWeb/BrowserWebView.swift b/Sources/EarlyWeb/BrowserWebView.swift index 2f9953c..408a4b8 100644 --- a/Sources/EarlyWeb/BrowserWebView.swift +++ b/Sources/EarlyWeb/BrowserWebView.swift @@ -41,6 +41,14 @@ final class BrowserWebView: WKWebView, @preconcurrency NSSharingServicePickerDel return accepted } + static func containsDroppedFiles(in pasteboard: NSPasteboard) -> Bool { + pasteboard.canReadObject(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) + } + + private static func normalizedFilePath(_ url: URL) -> String { + url.standardizedFileURL.resolvingSymlinksInPath().path + } + func noteFileDrop(from pasteboard: NSPasteboard, now: ContinuousClock.Instant = .now) { let files = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? [] fileDrop = files.isEmpty ? nil : (files, now.advanced(by: .seconds(5))) @@ -53,8 +61,8 @@ final class BrowserWebView: WKWebView, @preconcurrency NSSharingServicePickerDel func takeDroppedFile(matching url: URL, now: ContinuousClock.Instant = .now) -> URL? { guard let fileDrop else { return nil } guard now < fileDrop.expires else { clearFileDrop(); return nil } - let path = url.standardizedFileURL.path - guard let file = fileDrop.urls.first(where: { $0.standardizedFileURL.path == path }) else { return nil } + let path = Self.normalizedFilePath(url) + guard let file = fileDrop.urls.first(where: { Self.normalizedFilePath($0) == path }) else { return nil } clearFileDrop() return file } diff --git a/Sources/EarlyWeb/PageNavigation.swift b/Sources/EarlyWeb/PageNavigation.swift index 1a659b8..382f0c8 100644 --- a/Sources/EarlyWeb/PageNavigation.swift +++ b/Sources/EarlyWeb/PageNavigation.swift @@ -97,6 +97,22 @@ extension WebViewManager { } } + /// WebKit disables drop-to-navigate on macOS 10.13+ unless the UI delegate + /// opts in. Enable Load only for native file drags so pages still receive + /// HTML5 uploads and file inputs first, while unhandled Finder drops reach + /// decideLocalNavigation to open in a new tab. + @objc(_webView:dragDestinationActionMaskForDraggingInfo:) + public func webView(_ webView: WKWebView, dragDestinationActionMaskForDraggingInfo info: Any) -> UInt { + // WKDragDestinationAction: DHTML (1) | Edit (2) | Load (4). + let defaultMask: UInt = 1 | 2 + guard webView is BrowserWebView, + let dragging = info as? any NSDraggingInfo, + BrowserWebView.containsDroppedFiles(in: dragging.draggingPasteboard) else { + return defaultMask + } + return defaultMask | 4 + } + /// Local documents load only from Early's own requests (Open File, drops, /// restoration, reload), from another local page, or through history. A /// web page can never open a local file. @@ -106,6 +122,14 @@ extension WebViewManager { decisionHandler(.cancel) return } + // Open an unhandled native drop in a new tab, leaving the current page in place. + if targetIsMainFrame == true, type == .other, + let file = (webView as? BrowserWebView)?.takeDroppedFile(matching: url) { + decisionHandler(.cancel) + cancelForPolicy(id, url: url, mainFrame: true, notice: nil) + onOpenFiles?([file]) + return + } let mainFrame = targetIsMainFrame ?? true let fromLocalPage = webView.url?.isFileURL == true if page.requestedURL == url || fromLocalPage || type == .backForward || type == .reload { @@ -115,11 +139,6 @@ extension WebViewManager { } decisionHandler(.cancel) cancelForPolicy(id, url: url, mainFrame: mainFrame, notice: nil) - // Open an unhandled native drop in a new tab, leaving the page in place. - if targetIsMainFrame == true, type == .other, - let file = (webView as? BrowserWebView)?.takeDroppedFile(matching: url) { - onOpenFiles?([file]) - } } public func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse, diff --git a/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift b/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift index 0802ed7..43d8842 100644 --- a/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift +++ b/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift @@ -29,6 +29,33 @@ struct LocalDocumentPolicyTests { override var modifierFlags: NSEvent.ModifierFlags { [] } } + @MainActor + private final class DraggingInfo: NSObject, @MainActor NSDraggingInfo { + var draggingDestinationWindow: NSWindow? + var draggingSourceOperationMask: NSDragOperation = .copy + var draggingLocation: NSPoint + var draggedImageLocation: NSPoint = .zero + var draggedImage: NSImage? + var draggingPasteboard: NSPasteboard + var draggingSource: Any? + var draggingSequenceNumber = 1 + var draggingFormation: NSDraggingFormation = .default + var animatesToDestination = false + var numberOfValidItemsForDrop = 1 + var springLoadingHighlight: NSSpringLoadingHighlight = .none + + init(window: NSWindow, location: NSPoint, pasteboard: NSPasteboard) { + self.draggingDestinationWindow = window + self.draggingLocation = location + self.draggingPasteboard = pasteboard + } + func slideDraggedImage(to screenPoint: NSPoint) {} + func enumerateDraggingItems(options enumOpts: NSDraggingItemEnumerationOptions, for view: NSView?, + classes classArray: [AnyClass], searchOptions: [NSPasteboard.ReadingOptionKey: Any], + using block: (NSDraggingItem, Int, UnsafeMutablePointer) -> Void) {} + func resetSpringLoading() {} + } + private let input = NavigationInput(allowedSchemes: ["http", "https", "file"]) private func fixture() -> (WebViewManager, BrowserTab, BrowserPage) { @@ -102,6 +129,21 @@ struct LocalDocumentPolicyTests { #expect(opened == [[file]], "The file opens in a different tab") #expect(fileDecision(manager, page, file) == .cancel) #expect(opened == [[file]]) + + // Finder file-reference URLs under /var/folders resolve to /private/var/folders + // while coordinated paths may stay under /var/folders; both refer to the same file. + let tempDir = FileManager.default.temporaryDirectory.appending(path: "early-drop-alias-\(UUID().uuidString)", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + let tempFile = tempDir.appending(path: "Drop Document.html") + try Data("

Alias

".utf8).write(to: tempFile) + let privateFile = URL(filePath: "/private" + tempFile.standardizedFileURL.resolvingSymlinksInPath().path) + let aliasPasteboard = NSPasteboard(name: .init("EarlyFileDropAlias-\(UUID())")) + defer { aliasPasteboard.releaseGlobally() } + try #require(aliasPasteboard.writeObjects([privateFile as NSURL])) + view.noteFileDrop(from: aliasPasteboard) + #expect(fileDecision(manager, page, tempFile) == .cancel) + #expect(opened.count == 2) } @Test func earlysOwnLocalLoadAndHistoryAreAllowed() { @@ -168,4 +210,105 @@ struct LocalDocumentPolicyTests { #expect(WebViewManager.imageName(for: URL(string: "https://example.com/a/photo.png")!) == "photo.png") #expect(WebViewManager.imageName(for: URL(string: "data:image/png;base64,AAAA")!) == "Image") } + + @Test func nativeFileDropAcceptsUnhandledPagesAndPreservesPageUploadZones() async throws { + let (manager, tab, page) = fixture() + defer { manager.discardAll() } + let view = try #require(page.view as? BrowserWebView) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 400), + styleMask: [.titled], backing: .buffered, defer: false) + view.frame = NSRect(x: 0, y: 0, width: 400, height: 400) + window.contentView = view + defer { window.contentView = nil } + + let folder = FileManager.default.temporaryDirectory.appending(path: "early-drop-\(UUID().uuidString)", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let file = folder.appending(path: "Drop Document.html") + try Data("Dropped

Opened

".utf8).write(to: file) + + // Finder puts a file reference URL alongside NSFilenamesPboardType; under /var/folders + // those resolve to /private/var/folders vs /var/folders unless symlinks are normalized. + let filePasteboard = NSPasteboard(name: .init("EarlyFinderDrop-\(UUID())")) + defer { filePasteboard.releaseGlobally() } + filePasteboard.clearContents() + let reference = try #require((file as NSURL).fileReferenceURL()) + try #require(filePasteboard.writeObjects([reference as NSURL])) + filePasteboard.addTypes([NSPasteboard.PasteboardType("NSFilenamesPboardType")], owner: nil) + filePasteboard.setPropertyList([file.path], forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) + + let linkPasteboard = NSPasteboard(name: .init("EarlyLinkDrop-\(UUID())")) + defer { linkPasteboard.releaseGlobally() } + linkPasteboard.clearContents() + try #require(linkPasteboard.writeObjects([URL(string: "https://example.com/other")! as NSURL])) + + func loadHTML(_ html: String, title: String) async throws { + view.loadHTMLString(html, baseURL: tab.currentURL) + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while view.isLoading || view.title != title { + guard ContinuousClock.now < deadline else { break } + try await Task.sleep(for: .milliseconds(20)) + } + #expect(view.title == title) + } + + func settleDragUpdated(_ info: DraggingInfo) async throws -> NSDragOperation { + _ = view.draggingEntered(info) + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + var updated: NSDragOperation = [] + while ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(50)) + updated = view.draggingUpdated(info) + if !updated.isEmpty { break } + } + return updated + } + + var opened: [[URL]] = [] + manager.onOpenFiles = { opened.append($0) } + + // 1. Plain page: WebKit accepts the file drag and routes the unhandled drop to onOpenFiles. + try await loadHTML("Plain

Plain page

", title: "Plain") + let fileDrop = DraggingInfo(window: window, location: NSPoint(x: 200, y: 200), pasteboard: filePasteboard) + let plainUpdated = try await settleDragUpdated(fileDrop) + #expect(!plainUpdated.isEmpty, "Live pages must accept Finder file drops during draggingUpdated") + #expect(view.prepareForDragOperation(fileDrop)) + #expect(view.performDragOperation(fileDrop)) + let dropDeadline = ContinuousClock.now.advanced(by: .seconds(5)) + while opened.isEmpty, ContinuousClock.now < dropDeadline { + try await Task.sleep(for: .milliseconds(20)) + } + #expect(opened.count == 1) + #expect(opened.first?.first?.standardizedFileURL.resolvingSymlinksInPath().path == file.standardizedFileURL.resolvingSymlinksInPath().path) + + // 2. Non-file drag: do not opt into drop-to-navigate on a live page. + let linkDrop = DraggingInfo(window: window, location: NSPoint(x: 200, y: 200), pasteboard: linkPasteboard) + #expect(manager.webView(view, dragDestinationActionMaskForDraggingInfo: linkDrop) == (1 | 2)) + #expect(manager.webView(view, dragDestinationActionMaskForDraggingInfo: fileDrop) == (1 | 2 | 4)) + + // 3. Page upload drop zone: the page handles the drop and Early does not open a new tab. + opened.removeAll() + try await loadHTML(""" + Upload + +
Drop files here
+ + """, title: "Upload") + let uploadUpdated = try await settleDragUpdated(fileDrop) + #expect(!uploadUpdated.isEmpty) + #expect(view.performDragOperation(fileDrop)) + let uploadDeadline = ContinuousClock.now.advanced(by: .seconds(5)) + var droppedCount = 0 + while droppedCount == 0, ContinuousClock.now < uploadDeadline { + try await Task.sleep(for: .milliseconds(30)) + droppedCount = (try? await view.evaluateJavaScript("window.droppedCount") as? Int) ?? 0 + } + #expect(droppedCount == 1, "HTML5 upload zones must still receive dropped files") + #expect(opened.isEmpty, "A file handled by the page must not also open in a new tab") + } } diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index 37c4dd8..a941081 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -130,6 +130,7 @@ final class EarlyUITests: XCTestCase { withVelocity: .slow, thenHoldForDuration: 1) XCTAssertTrue(app.webViews.staticTexts["Opened from Finder"].firstMatch.waitForExistence(timeout: 10), app.debugDescription) expectRuntime(app, tabs: 2, views: 2, created: 2) + app.activate() app.buttons[original].click() expectPage(app, "One") }