Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Config/Early.xcconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions Packaging/ReleaseNotes/0.2.4.md
Original file line number Diff line number Diff line change
@@ -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.
23 changes: 15 additions & 8 deletions Sources/Early/BrowserApplication.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions Sources/EarlyCore/BackgroundFileIO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
36 changes: 21 additions & 15 deletions Sources/EarlyCore/PasswordVault.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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()
Expand All @@ -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<URLResourceKey> = [.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
}
}

Expand Down
33 changes: 27 additions & 6 deletions Sources/EarlyCore/StateArchiveFiles.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
}

Expand All @@ -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 }
}
}
12 changes: 10 additions & 2 deletions Sources/EarlyWeb/BrowserWebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand All @@ -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
}
Expand Down
29 changes: 24 additions & 5 deletions Sources/EarlyWeb/PageNavigation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 {
Expand All @@ -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,
Expand Down
Loading
Loading