Encrypt tagged entries on save; whole-file encryption !489
14 files changed, +354 −51
Changed files (14)
- Sources/OrgApp/ClockModel.swift +10 −4
- Sources/OrgApp/CryptPassphrases.swift +71 −24
- Sources/OrgApp/CryptSheet.swift +6 −3
- Sources/OrgApp/DocumentSession.swift +25 −2
- Sources/OrgCore/Commands/ClockHistory.swift +15 −2
- Sources/OrgCore/Crypto/OrgCrypt.swift +2 −1
- Sources/OrgDocument/Crypt.swift +43 −3
- Sources/OrgDocument/Saving.swift +29 −5
- Sources/Orgstar/CryptHoldBar.swift +1 −1
- Sources/Orgstar/OrgstarApp.swift +10 −1
- Sources/OrgstarMobile/EditorScreen.swift +4 −2
- Tests/OrgAppTests/CryptReviewTests.swift +71
- Tests/OrgDocumentTests/CryptSaverTests.swift added +62
- docs/manual/guide/04-outlines.org +5 −3
Sources/OrgApp/ClockModel.swift +10 −4 · view
| @@ -100,7 +100,7 @@ public final class ClockModel { | ||
| 100 | 100 | let interrupted = runningTask(session) |
| 101 | 101 | let message = clockOut(session, now: now) |
| 102 | 102 | if self.running != nil { return message } |
| 103 | interruptedTask = interrupted | |
| 103 | interruptedTask = interrupted.map { Self.shareable($0, session) } | |
| 104 | 104 | // Clocking out may have moved the entry. |
| 105 | 105 | let target = ClockTask(path: path, title: entry.title, ordinal: index, id: entry.id) |
| 106 | 106 | guard let moved = Self.text(path, session).flatMap(target.locate) else { return "Can't find \(entry.title) after clocking out." } |
| @@ -308,9 +308,15 @@ public final class ClockModel { | ||
| 308 | 308 | |
| 309 | 309 | private func push(_ task: ClockTask, _ session: DocumentSession) { |
| 310 | 310 | // The history is kept in the clock's file and shown by the widgets. |
| 311 | let heading = Self.text(task.path, session).flatMap(task.locate) ?? 0 | |
| 312 | let task = ClockTask(path: task.path, title: session.shareableTitle(task.title, path: task.path, heading: heading), ordinal: task.ordinal, id: task.id) | |
| 313 | 311 | history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) } |
| 312 | .map { Self.shareable($0, session) } | |
| 313 | } | |
| 314 | ||
| 315 | /// `task` with a placeholder title when its heading is encrypted on disk. | |
| 316 | static func shareable(_ task: ClockTask, _ session: DocumentSession) -> ClockTask { | |
| 317 | guard task.titleHidden != true, let heading = text(task.path, session).flatMap(task.locate) else { return task } | |
| 318 | let shown = session.shareableTitle(task.title, path: task.path, heading: heading) | |
| 319 | return shown == task.title ? task : task.hiding(shown) | |
| 314 | 320 | } |
| 315 | 321 | |
| 316 | 322 | /// Where a remembered entry's heading is now. |
| @@ -328,7 +334,7 @@ public final class ClockModel { | ||
| 328 | 334 | public func markDefault(_ session: DocumentSession, path: String, at offset: Int) -> String { |
| 329 | 335 | guard let text = Self.text(path, session) else { return "Can't read \(path)" } |
| 330 | 336 | guard let task = ClockTask.at(offset, in: text, path: path) else { return "Before first headline" } |
| 331 | defaultTask = task | |
| 337 | defaultTask = Self.shareable(task, session) | |
| 332 | 338 | return "Default clock task: \(task.title)" |
| 333 | 339 | } |
| 334 | 340 | |
Sources/OrgApp/CryptPassphrases.swift +71 −24 · view
| @@ -5,28 +5,45 @@ import Security | ||
| 5 | 5 | |
| 6 | 6 | /// Passphrases for encrypted entries and files, kept in the Keychain by file path when asked. |
| 7 | 7 | /// Items are readable only on this device while it's unlocked, and only after Touch ID, Face |
| 8 | /// ID or the device's password (`.userPresence`); one authentication covers the reads that | |
| 9 | /// follow for a while. Items earlier versions stored without that move over at their first read. | |
| 8 | /// ID or the device's password (`.userPresence`), asked once per file while it's open. Items | |
| 9 | /// earlier versions stored without that move over at their first read. A build without a | |
| 10 | /// Keychain entitlement (the Developer ID Mac app) can't make such items and keeps the old kind. | |
| 11 | @MainActor | |
| 10 | 12 | public enum CryptPassphrases { |
| 11 | static let service = "sh.krz.orgstar.crypt.v2" | |
| 13 | nonisolated static let service = "sh.krz.orgstar.crypt.v2" | |
| 12 | 14 | /// Where earlier versions kept passphrases, readable without authentication. |
| 13 | static let legacyService = "sh.krz.orgstar.crypt" | |
| 15 | nonisolated static let legacyService = "sh.krz.orgstar.crypt" | |
| 16 | /// Set once the person was told this build keeps passphrases the old way. | |
| 17 | static let toldLegacyKey = "cryptKeychainLegacyTold" | |
| 14 | 18 | |
| 15 | /// The authentication reads share. | |
| 16 | nonisolated(unsafe) static let context: LAContext = { | |
| 19 | /// A Keychain query handed to the thread that waits on it; nothing else uses it meanwhile. | |
| 20 | struct Request: @unchecked Sendable { | |
| 21 | let query: [String: Any] | |
| 22 | } | |
| 23 | ||
| 24 | /// One authentication per file while it's open; `endSession` ends it. | |
| 25 | private static var contexts: [String: LAContext] = [:] | |
| 26 | ||
| 27 | static func context(for path: String) -> LAContext { | |
| 28 | if let context = contexts[path] { return context } | |
| 17 | 29 | let context = LAContext() |
| 18 | context.touchIDAuthenticationAllowableReuseDuration = LATouchIDAuthenticationMaximumAllowableReuseDuration | |
| 30 | contexts[path] = context | |
| 19 | 31 | return context |
| 20 | }() | |
| 32 | } | |
| 21 | 33 | |
| 22 | static func query(_ path: String, service: String = service) -> [String: Any] { | |
| 34 | /// The file closed: its authentication no longer reads its passphrase. | |
| 35 | public static func endSession(for path: String) { | |
| 36 | contexts.removeValue(forKey: path)?.invalidate() | |
| 37 | } | |
| 38 | ||
| 39 | nonisolated static func query(_ path: String, service: String = service) -> [String: Any] { | |
| 23 | 40 | var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path] |
| 24 | 41 | if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true } |
| 25 | 42 | return query |
| 26 | 43 | } |
| 27 | 44 | |
| 28 | 45 | /// The new item for `passphrase`: this device only, unlocked, after user presence. |
| 29 | static func newItem(_ passphrase: String, for path: String) -> [String: Any]? { | |
| 46 | nonisolated static func newItem(_ passphrase: String, for path: String) -> [String: Any]? { | |
| 30 | 47 | guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil } |
| 31 | 48 | var item = query(path) |
| 32 | 49 | item[kSecValueData as String] = Data(passphrase.utf8) |
| @@ -35,25 +52,47 @@ public enum CryptPassphrases { | ||
| 35 | 52 | return item |
| 36 | 53 | } |
| 37 | 54 | |
| 38 | public static func store(_ passphrase: String, for path: String) { | |
| 39 | forget(path) | |
| 40 | guard let item = newItem(passphrase, for: path) else { return } | |
| 41 | if SecItemAdd(item as CFDictionary, nil) == errSecMissingEntitlement { | |
| 42 | // A build without a Keychain entitlement (development) keeps the old kind of item. | |
| 43 | var legacy = query(path, service: legacyService) | |
| 44 | legacy[kSecValueData as String] = Data(passphrase.utf8) | |
| 45 | legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String] | |
| 46 | SecItemAdd(legacy as CFDictionary, nil) | |
| 55 | /// Adds `item`, in place of one there already. | |
| 56 | nonisolated static func add(_ item: [String: Any], replacing query: [String: Any]) -> OSStatus { | |
| 57 | var status = SecItemAdd(item as CFDictionary, nil) | |
| 58 | if status == errSecDuplicateItem { | |
| 59 | SecItemDelete(query as CFDictionary) | |
| 60 | status = SecItemAdd(item as CFDictionary, nil) | |
| 61 | } | |
| 62 | return status | |
| 63 | } | |
| 64 | ||
| 65 | /// Remembers `passphrase` for `path`. A message to show when it wasn't kept, or (once) when | |
| 66 | /// this build keeps it without device-only protection; nil otherwise. | |
| 67 | @discardableResult | |
| 68 | public static func store(_ passphrase: String, for path: String, defaults: UserDefaults = .standard) -> String? { | |
| 69 | guard let item = newItem(passphrase, for: path) else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") } | |
| 70 | let status = add(item, replacing: query(path)) | |
| 71 | if status == errSecSuccess { | |
| 72 | SecItemDelete(query(path, service: legacyService) as CFDictionary) | |
| 73 | return nil | |
| 74 | } | |
| 75 | guard status == errSecMissingEntitlement else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") } | |
| 76 | var legacy = query(path, service: legacyService) | |
| 77 | legacy[kSecValueData as String] = Data(passphrase.utf8) | |
| 78 | legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String] | |
| 79 | guard add(legacy, replacing: query(path, service: legacyService)) == errSecSuccess else { | |
| 80 | return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") | |
| 47 | 81 | } |
| 82 | SecItemDelete(query(path) as CFDictionary) | |
| 83 | guard !defaults.bool(forKey: toldLegacyKey) else { return nil } | |
| 84 | defaults.set(true, forKey: toldLegacyKey) | |
| 85 | return String(localized: "This version of orgstar keeps remembered passphrases in your login keychain without limiting them to this Mac; Touch ID or your password is still asked before one is used.") | |
| 48 | 86 | } |
| 49 | 87 | |
| 50 | 88 | public static func forget(_ path: String) { |
| 89 | endSession(for: path) | |
| 51 | 90 | SecItemDelete(query(path) as CFDictionary) |
| 52 | 91 | SecItemDelete(query(path, service: legacyService) as CFDictionary) |
| 53 | 92 | } |
| 54 | 93 | |
| 55 | 94 | /// Whether an item exists, without asking for authentication. |
| 56 | static func exists(_ query: [String: Any]) -> Bool { | |
| 95 | nonisolated static func exists(_ query: [String: Any]) -> Bool { | |
| 57 | 96 | var q = query |
| 58 | 97 | let quiet = LAContext() |
| 59 | 98 | quiet.interactionNotAllowed = true |
| @@ -70,17 +109,17 @@ public enum CryptPassphrases { | ||
| 70 | 109 | /// The stored passphrase, once the person has proved who they are; nil otherwise. |
| 71 | 110 | public static func stored(for path: String) async -> String? { |
| 72 | 111 | let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent |
| 112 | let context = context(for: path) | |
| 73 | 113 | if exists(query(path)) { |
| 74 | 114 | var q = query(path) |
| 75 | 115 | q[kSecReturnData as String] = true |
| 76 | let context = Self.context | |
| 77 | 116 | context.localizedReason = reason |
| 78 | 117 | q[kSecUseAuthenticationContext as String] = context |
| 79 | let request = q | |
| 118 | let request = Request(query: q) | |
| 80 | 119 | // The read waits for Touch ID or the password, off the main thread. |
| 81 | 120 | return await Task.detached { () -> String? in |
| 82 | 121 | var result: AnyObject? |
| 83 | guard SecItemCopyMatching(request as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } | |
| 122 | guard SecItemCopyMatching(request.query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } | |
| 84 | 123 | return String(decoding: data, as: UTF8.self) |
| 85 | 124 | }.value |
| 86 | 125 | } |
| @@ -92,7 +131,7 @@ public enum CryptPassphrases { | ||
| 92 | 131 | guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } |
| 93 | 132 | let passphrase = String(decoding: data, as: UTF8.self) |
| 94 | 133 | // Moved to the protected kind of item; kept as it was where that can't be made. |
| 95 | if let item = newItem(passphrase, for: path), SecItemAdd(item as CFDictionary, nil) == errSecSuccess { | |
| 134 | if let item = newItem(passphrase, for: path), add(item, replacing: query(path)) == errSecSuccess { | |
| 96 | 135 | SecItemDelete(query(path, service: legacyService) as CFDictionary) |
| 97 | 136 | } |
| 98 | 137 | return passphrase |
| @@ -100,6 +139,12 @@ public enum CryptPassphrases { | ||
| 100 | 139 | } |
| 101 | 140 | |
| 102 | 141 | extension CryptHold { |
| 142 | /// Whether giving the passphrase lets the file be saved. | |
| 143 | public var takesPassphrase: Bool { | |
| 144 | if case .blocked = self { return false } | |
| 145 | return true | |
| 146 | } | |
| 147 | ||
| 103 | 148 | /// What the held file's notice says. |
| 104 | 149 | public func notice(for path: String) -> String { |
| 105 | 150 | let name = (path as NSString).lastPathComponent |
| @@ -107,6 +152,7 @@ extension CryptHold { | ||
| 107 | 152 | case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.") |
| 108 | 153 | case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.") |
| 109 | 154 | case .file: String(localized: "\(name) isn't saved until it has a passphrase.") |
| 155 | case .blocked(let reason): reason + ". " + String(localized: "Changes to \(name) aren't saved until that's fixed.") | |
| 110 | 156 | } |
| 111 | 157 | } |
| 112 | 158 | } |
| @@ -117,6 +163,7 @@ extension CryptHold: LocalizedError { | ||
| 117 | 163 | case .entries(1): String(localized: "1 tagged entry isn't encrypted") |
| 118 | 164 | case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted") |
| 119 | 165 | case .file: String(localized: "The file has no passphrase yet") |
| 166 | case .blocked(let reason): reason | |
| 120 | 167 | } |
| 121 | 168 | } |
| 122 | 169 | } |
Sources/OrgApp/CryptSheet.swift +6 −3 · view
| @@ -67,6 +67,8 @@ public struct CryptSheet: View { | ||
| 67 | 67 | @State private var passphrase = "" |
| 68 | 68 | @State private var repeated = "" |
| 69 | 69 | @State private var remember = false |
| 70 | /// What the Keychain said when the passphrase was remembered, shown with the result. | |
| 71 | @State private var keychainNote: String? | |
| 70 | 72 | @State private var problem: String? |
| 71 | 73 | /// The decrypted entry being edited, and the passphrase it came with. |
| 72 | 74 | @State private var editing: (original: String, passphrase: String)? |
| @@ -187,7 +189,7 @@ public struct CryptSheet: View { | ||
| 187 | 189 | finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered) |
| 188 | 190 | case .open: |
| 189 | 191 | let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext |
| 190 | if remember, !remembered { CryptPassphrases.store(passphrase, for: request.path) } | |
| 192 | if remember, !remembered { keychainNote = CryptPassphrases.store(passphrase, for: request.path) } | |
| 191 | 193 | session?.cryptUsed(passphrase, for: request.path) |
| 192 | 194 | plaintext = plain |
| 193 | 195 | editing = (plain, passphrase) |
| @@ -210,9 +212,10 @@ public struct CryptSheet: View { | ||
| 210 | 212 | } |
| 211 | 213 | |
| 212 | 214 | private func finish(_ message: String?, passphrase: String, remembered: Bool) { |
| 213 | if remember, !remembered { CryptPassphrases.store(passphrase, for: request.path) } | |
| 215 | if remember, !remembered { keychainNote = CryptPassphrases.store(passphrase, for: request.path) } | |
| 214 | 216 | if !request.unlocks { session?.cryptUsed(passphrase, for: request.path) } |
| 215 | done(message) | |
| 217 | let text = [message, keychainNote].compactMap { $0 }.joined(separator: " ") | |
| 218 | done(text.isEmpty ? nil : text) | |
| 216 | 219 | } |
| 217 | 220 | |
| 218 | 221 | /// The edited text encrypted again in the message's place; nothing changes if it wasn't edited. |
Sources/OrgApp/DocumentSession.swift +25 −2 · view
| @@ -182,6 +182,9 @@ public final class DocumentSession { | ||
| 182 | 182 | /// Open files that aren't saved until a passphrase is given: tagged entries that would be |
| 183 | 183 | /// written unencrypted, or an encrypted file without one. Other edits to them wait too. |
| 184 | 184 | public private(set) var held: [String: CryptHold] = [:] |
| 185 | /// Holds from saves that failed: a version on disk with tagged entries that can't be kept | |
| 186 | /// encrypted, or an entry the passphrase can't encrypt. Kept until a save succeeds. | |
| 187 | @ObservationIgnored private var failedHolds: [String: CryptHold] = [:] | |
| 185 | 188 | |
| 186 | 189 | /// An encrypted file waiting for its passphrase to open, and the pane to show it in. |
| 187 | 190 | public private(set) var unlockRequest: String? |
| @@ -277,7 +280,8 @@ public final class DocumentSession { | ||
| 277 | 280 | |
| 278 | 281 | /// Whether `path`'s buffer is held back from disk now. |
| 279 | 282 | private func updateHold(_ entry: Entry) -> CryptHold? { |
| 280 | let hold = entry.buffer.document.isDirty ? crypt.hold(entry.buffer.document.text, for: entry.path) : nil | |
| 283 | let dirty = entry.buffer.document.isDirty | |
| 284 | let hold = dirty ? crypt.hold(entry.buffer.document.text, for: entry.path) ?? failedHolds[entry.path] : nil | |
| 281 | 285 | if held[entry.path] != hold { held[entry.path] = hold } |
| 282 | 286 | return hold |
| 283 | 287 | } |
| @@ -451,6 +455,7 @@ public final class DocumentSession { | ||
| 451 | 455 | return |
| 452 | 456 | } |
| 453 | 457 | let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path))) |
| 458 | crypt.opened(path) | |
| 454 | 459 | let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count |
| 455 | 460 | entries.insert(entry, at: index) |
| 456 | 461 | show(entry, in: pane) |
| @@ -489,7 +494,9 @@ public final class DocumentSession { | ||
| 489 | 494 | entry.autosave?.cancel() |
| 490 | 495 | entries.removeAll { $0 === entry } |
| 491 | 496 | crypt.close(entry.path) |
| 497 | CryptPassphrases.endSession(for: entry.path) | |
| 492 | 498 | held[entry.path] = nil |
| 499 | failedHolds[entry.path] = nil | |
| 493 | 500 | refusedKeychain.remove(entry.path) |
| 494 | 501 | history.removeAll { $0 == path } |
| 495 | 502 | outlineUpdates[path]?.cancel() |
| @@ -641,15 +648,18 @@ public final class DocumentSession { | ||
| 641 | 648 | defer { interval.end((entry.path as NSString).lastPathComponent) } |
| 642 | 649 | entry.autosave?.cancel() |
| 643 | 650 | let name = (entry.path as NSString).lastPathComponent |
| 644 | guard updateHold(entry) == nil else { | |
| 651 | // A failed save is tried again: what failed may be fixed by now. | |
| 652 | guard updateHold(entry) == nil || held[entry.path] == failedHolds[entry.path] else { | |
| 645 | 653 | askKeychain(entry) |
| 646 | 654 | refresh(entry) |
| 647 | 655 | return false |
| 648 | 656 | } |
| 649 | 657 | guard entry.buffer.document.isDirty else { return true } |
| 650 | 658 | guard entry.conflict == nil else { return false } |
| 659 | defer { _ = updateHold(entry) } | |
| 651 | 660 | do { |
| 652 | 661 | let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) } |
| 662 | failedHolds[entry.path] = nil | |
| 653 | 663 | switch outcome { |
| 654 | 664 | case .saved, .mergedAndSaved: |
| 655 | 665 | break |
| @@ -660,6 +670,12 @@ public final class DocumentSession { | ||
| 660 | 670 | entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours." |
| 661 | 671 | } |
| 662 | 672 | } |
| 673 | } catch let hold as CryptHold { | |
| 674 | // A version on disk with tagged entries in plaintext can be kept only encrypted. | |
| 675 | failedHolds[entry.path] = hold | |
| 676 | askKeychain(entry) | |
| 677 | } catch let failure as OrgCrypt.Failure { | |
| 678 | failedHolds[entry.path] = .blocked(failure.description) | |
| 663 | 679 | } catch { |
| 664 | 680 | showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)") |
| 665 | 681 | } |
| @@ -989,6 +1005,13 @@ public final class DocumentSession { | ||
| 989 | 1005 | /// passphrase; tagged entries with text in the subtree are encrypted where they are first, |
| 990 | 1006 | /// since the tag they inherit doesn't go with them. |
| 991 | 1007 | private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation { |
| 1008 | // The target's passphrase, lent by the source for the move, isn't kept after it. | |
| 1009 | if Self.isEncryptedFile(target), !isOpen(target) { | |
| 1010 | DispatchQueue.main.async { [weak self] in | |
| 1011 | guard let self, !self.isOpen(target) else { return } | |
| 1012 | self.crypt.close(target) | |
| 1013 | } | |
| 1014 | } | |
| 992 | 1015 | let from = (path as NSString).lastPathComponent, to = (target as NSString).lastPathComponent |
| 993 | 1016 | if Self.isEncryptedFile(path) { |
| 994 | 1017 | guard Self.isEncryptedFile(target) else { |
Sources/OrgCore/Commands/ClockHistory.swift +15 −2 · view
| @@ -12,12 +12,16 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable { | ||
| 12 | 12 | /// The heading's index among the file's headings. |
| 13 | 13 | public let ordinal: Int |
| 14 | 14 | public let id: String? |
| 15 | /// The title is a placeholder for one that isn't kept (an encrypted heading's): the task | |
| 16 | /// is found by its ID or position. | |
| 17 | public let titleHidden: Bool? | |
| 15 | 18 | |
| 16 | public init(path: String, title: String, ordinal: Int, id: String?) { | |
| 19 | public init(path: String, title: String, ordinal: Int, id: String?, titleHidden: Bool? = nil) { | |
| 17 | 20 | self.path = path |
| 18 | 21 | self.title = title |
| 19 | 22 | self.ordinal = ordinal |
| 20 | 23 | self.id = id |
| 24 | self.titleHidden = titleHidden | |
| 21 | 25 | } |
| 22 | 26 | |
| 23 | 27 | /// The entry containing `offset`; nil before the first heading. |
| @@ -28,9 +32,11 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable { | ||
| 28 | 32 | return ClockTask(path: path, title: heading.title, ordinal: index, id: heading.id) |
| 29 | 33 | } |
| 30 | 34 | |
| 31 | /// The heading's index in `model`, or nil when the entry is gone. | |
| 35 | /// The heading's index in `model`, or nil when the entry is gone: by ID, then by position | |
| 36 | /// and title, or by title; a task kept without its title by position alone. | |
| 32 | 37 | public func index(in model: DocumentModel) -> Int? { |
| 33 | 38 | if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index } |
| 39 | if titleHidden == true { return ordinal < model.headings.count ? ordinal : nil } | |
| 34 | 40 | if ordinal < model.headings.count, model.headings[ordinal].title == title { return ordinal } |
| 35 | 41 | return model.headings.firstIndex { $0.title == title } |
| 36 | 42 | } |
| @@ -46,6 +52,13 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable { | ||
| 46 | 52 | let model = DocumentModel(tree: OrgParser.parse(text)) |
| 47 | 53 | guard let index = index(in: model) else { return nil } |
| 48 | 54 | return ClockTask(path: path, title: model.headings[index].title, ordinal: index, id: model.headings[index].id) |
| 55 | .hiding(titleHidden == true ? title : nil) | |
| 56 | } | |
| 57 | ||
| 58 | /// The task with `placeholder` for its title, or as it is with nil. | |
| 59 | public func hiding(_ placeholder: String?) -> ClockTask { | |
| 60 | guard let placeholder else { return self } | |
| 61 | return ClockTask(path: path, title: placeholder, ordinal: ordinal, id: id, titleHidden: true) | |
| 49 | 62 | } |
| 50 | 63 | } |
| 51 | 64 | |
Sources/OrgCore/Crypto/OrgCrypt.swift +2 −1 · view
| @@ -5,9 +5,10 @@ import Foundation | ||
| 5 | 5 | /// nil: an entry's text after its planning, properties and logbook, through the end of its |
| 6 | 6 | /// subtree, replaced by an armored OpenPGP message under the heading. |
| 7 | 7 | public enum OrgCrypt { |
| 8 | public struct Failure: Error, Equatable, CustomStringConvertible { | |
| 8 | public struct Failure: Error, Equatable, CustomStringConvertible, LocalizedError { | |
| 9 | 9 | public let description: String |
| 10 | 10 | public init(_ description: String) { self.description = description } |
| 11 | public var errorDescription: String? { description } | |
| 11 | 12 | } |
| 12 | 13 | |
| 13 | 14 | /// `org-end-of-meta-data 'standard`: past planning, the property drawer, clock lines, |
Sources/OrgDocument/Crypt.swift +43 −3 · view
| @@ -7,6 +7,9 @@ public enum CryptHold: Error, Equatable, Sendable { | ||
| 7 | 7 | case entries(Int) |
| 8 | 8 | /// An encrypted file (`.org.gpg`) whose passphrase isn't known. |
| 9 | 9 | case file |
| 10 | /// Saving failed for a reason a passphrase can't fix, said here: an entry with text below | |
| 11 | /// a message that the file's passphrase doesn't open. | |
| 12 | case blocked(String) | |
| 10 | 13 | } |
| 11 | 14 | |
| 12 | 15 | /// Why an encrypted file can't be read. |
| @@ -35,6 +38,8 @@ public final class CryptVault: @unchecked Sendable { | ||
| 35 | 38 | /// Files that seal tagged entries until they close, whatever the setting says now: those |
| 36 | 39 | /// it was on for, so that turning it off never writes what was encrypted in plaintext. |
| 37 | 40 | private var sealing: Set<String> = [] |
| 41 | /// Files open in a buffer. Only they keep what the vault knows past a write. | |
| 42 | private var open: Set<String> = [] | |
| 38 | 43 | /// By encrypted file: its bytes on disk and their text, last read or written. |
| 39 | 44 | private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:] |
| 40 | 45 | |
| @@ -70,7 +75,7 @@ public final class CryptVault: @unchecked Sendable { | ||
| 70 | 75 | /// Whether saving `key` seals its tagged entries: the setting is on, or was while the |
| 71 | 76 | /// file was open. Call with the lock held. |
| 72 | 77 | private func seals(_ key: String) -> Bool { |
| 73 | if entries { sealing.insert(key) } | |
| 78 | if entries, open.contains(key) { sealing.insert(key) } | |
| 74 | 79 | return entries || sealing.contains(key) || !(revealed[key]?.isEmpty ?? true) |
| 75 | 80 | } |
| 76 | 81 | |
| @@ -103,10 +108,35 @@ public final class CryptVault: @unchecked Sendable { | ||
| 103 | 108 | } |
| 104 | 109 | } |
| 105 | 110 | |
| 111 | private func dropIfClosed(_ key: String) { | |
| 112 | locked { | |
| 113 | guard !open.contains(key) else { return } | |
| 114 | passphrases[key] = nil | |
| 115 | reuse[key] = nil | |
| 116 | revealed[key] = nil | |
| 117 | armored[key] = nil | |
| 118 | lastFile[key] = nil | |
| 119 | sealing.remove(key) | |
| 120 | } | |
| 121 | } | |
| 122 | ||
| 123 | /// Whether the vault keeps anything for `path`. | |
| 124 | public func keepsAnything(for path: String) -> Bool { | |
| 125 | let key = Self.key(path) | |
| 126 | return locked { passphrases[key] != nil || !(revealed[key]?.isEmpty ?? true) || !(reuse[key]?.isEmpty ?? true) || lastFile[key] != nil || sealing.contains(key) } | |
| 127 | } | |
| 128 | ||
| 129 | /// `path` is open in a buffer. | |
| 130 | public func opened(_ path: String) { | |
| 131 | let key = Self.key(path) | |
| 132 | locked { _ = open.insert(key) } | |
| 133 | } | |
| 134 | ||
| 106 | 135 | /// Drops everything kept for `path`, as when its buffer closes. |
| 107 | 136 | public func close(_ path: String) { |
| 108 | 137 | let key = Self.key(path) |
| 109 | 138 | locked { |
| 139 | open.remove(key) | |
| 110 | 140 | passphrases[key] = nil |
| 111 | 141 | reuse[key] = nil |
| 112 | 142 | revealed[key] = nil |
| @@ -189,6 +219,9 @@ public final class CryptVault: @unchecked Sendable { | ||
| 189 | 219 | if Self.isEncryptedFile(path) { |
| 190 | 220 | guard let passphrase else { throw CryptHold.file } |
| 191 | 221 | let plain = bytes |
| 222 | // The text the file holds already (a snapshot of it) is its bytes on disk, without | |
| 223 | // another key's 65 MB of hashing. | |
| 224 | if let last = locked({ lastFile[key] }), last.plain == plain { return (last.encrypted, messages, plain) } | |
| 192 | 225 | let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase) |
| 193 | 226 | bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message) |
| 194 | 227 | return (bytes, messages, plain) |
| @@ -202,6 +235,11 @@ public final class CryptVault: @unchecked Sendable { | ||
| 202 | 235 | public func didWrite(_ written: (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?), to path: String) { |
| 203 | 236 | let key = Self.key(path) |
| 204 | 237 | locked { |
| 238 | // A file that isn't open keeps nothing (passphrase, messages, text) once the | |
| 239 | // write's own reads are done. | |
| 240 | if !open.contains(key) { | |
| 241 | DispatchQueue.main.async { [weak self] in self?.dropIfClosed(key) } | |
| 242 | } | |
| 205 | 243 | revealed[key] = Dictionary(written.messages.map { ($0.message, $0.plaintext) }, uniquingKeysWith: { a, _ in a }) |
| 206 | 244 | reuse[key] = Dictionary(written.messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) }, uniquingKeysWith: { a, _ in a }) |
| 207 | 245 | if let plain = written.plain { lastFile[key] = (written.bytes, plain) } |
| @@ -259,9 +297,11 @@ public struct CryptFileSystem: FileSystem { | ||
| 259 | 297 | let known = vault.revealedMessages(for: url.path) |
| 260 | 298 | let written = try vault.cipher(bytes, for: url.path) |
| 261 | 299 | let replaced = try base.replace(url, with: written.bytes) |
| 300 | // The version replaced, as it read before this write's messages were known (and while | |
| 301 | // the encrypted file's last bytes still decrypt from memory). | |
| 302 | let previous = replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 } | |
| 262 | 303 | vault.didWrite(written, to: url.path) |
| 263 | // The version replaced, as it read before this write's messages were known. | |
| 264 | return replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 } | |
| 304 | return previous | |
| 265 | 305 | } |
| 266 | 306 | } |
| 267 | 307 | |
Sources/OrgDocument/Saving.swift +29 −5 · view
| @@ -74,12 +74,12 @@ public struct Saver: Sendable { | ||
| 74 | 74 | let replaced = try fileSystem.replace(url, with: bytes) |
| 75 | 75 | state.didWrite(bytes) |
| 76 | 76 | if replaced != disk, let replaced { |
| 77 | try recovery.keep(replaced, for: url, label: "external") | |
| 78 | return .overwroteExternalChange(state.mergeOverwritten(replaced, base: disk ?? [])) | |
| 77 | return .overwroteExternalChange(keepOverwritten(replaced, base: disk ?? [], in: &state, url: url)) | |
| 79 | 78 | } |
| 80 | 79 | |
| 81 | 80 | if let after = try fileSystem.read(url), after != bytes { |
| 82 | try recovery.keep(bytes, for: url, label: "local") | |
| 81 | // Ours is in the buffer whether or not a copy can be kept. | |
| 82 | try? recovery.keep(bytes, for: url, label: "local") | |
| 83 | 83 | return .changedAfterWrite(state.diskChanged(to: after)) |
| 84 | 84 | } |
| 85 | 85 | return merged.map { .mergedAndSaved($0) } ?? .saved |
| @@ -91,9 +91,33 @@ public struct Saver: Sendable { | ||
| 91 | 91 | /// one. The replaced version goes to recovery unless it is the merge base. |
| 92 | 92 | public func overwrite(_ state: inout DocumentState, to url: URL) throws { |
| 93 | 93 | let bytes = try state.encodedText() |
| 94 | if let replaced = try fileSystem.replace(url, with: bytes), replaced != state.mergeBase { | |
| 94 | // The version Keep Mine replaces goes to recovery first; when it can't, nothing is written. | |
| 95 | let disk = try fileSystem.read(url) | |
| 96 | if let disk, disk != state.mergeBase { try recovery.keep(disk, for: url, label: "external") } | |
| 97 | let base = state.mergeBase | |
| 98 | let replaced = try fileSystem.replace(url, with: bytes) | |
| 99 | state.didWrite(bytes) | |
| 100 | if let replaced, replaced != disk, replaced != base { | |
| 101 | _ = keepOverwritten(replaced, base: base, in: &state, url: url, merge: false) | |
| 102 | } | |
| 103 | } | |
| 104 | ||
| 105 | /// `replaced`, a version another writer put on disk just before ours replaced it, kept: in | |
| 106 | /// recovery and, when `merge`, merged into the buffer. When recovery can't keep it (it holds | |
| 107 | /// text that can only be kept encrypted, without a passphrase) and it isn't merged, it goes | |
| 108 | /// into the buffer beside ours between conflict markers, so it's never lost. | |
| 109 | func keepOverwritten(_ replaced: [UInt8], base: [UInt8], in state: inout DocumentState, url: URL, merge: Bool = true) -> DocumentState.ExternalChange { | |
| 110 | let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([]) | |
| 111 | do { | |
| 95 | 112 | try recovery.keep(replaced, for: url, label: "external") |
| 113 | return merge ? change : .unchanged | |
| 114 | } catch { | |
| 115 | if case .merged = change { return change } | |
| 116 | let theirs = SourceText(bytes: replaced).text | |
| 117 | let both = mergeWithMarkers(base: SourceText(bytes: base).text, ours: state.text, theirs: theirs, oursLabel: "yours", theirsLabel: "disk") | |
| 118 | let edits = lineEdits(from: state.text, to: both) | |
| 119 | guard (try? state.apply(edits, baseRevision: state.revision)) != nil else { return change } | |
| 120 | return .merged(edits) | |
| 96 | 121 | } |
| 97 | state.didWrite(bytes) | |
| 98 | 122 | } |
| 99 | 123 | } |
Sources/Orgstar/CryptHoldBar.swift +1 −1 · view
| @@ -14,7 +14,7 @@ struct CryptHoldBar: View { | ||
| 14 | 14 | Image(systemName: "lock.trianglebadge.exclamationmark").foregroundStyle(.orange) |
| 15 | 15 | Text(hold.notice(for: path)).lineLimit(3) |
| 16 | 16 | Spacer(minLength: 8) |
| 17 | Button(hold == .file ? "Set Passphrase…" : "Encrypt…", action: encrypt) | |
| 17 | if hold.takesPassphrase { Button(hold == .file ? "Set Passphrase…" : "Encrypt…", action: encrypt) } | |
| 18 | 18 | } |
| 19 | 19 | .font(.callout) |
| 20 | 20 | .padding(.horizontal, 10) |
Sources/Orgstar/OrgstarApp.swift +10 −1 · view
| @@ -363,8 +363,17 @@ enum UnsavedChanges { | ||
| 363 | 363 | /// Saves `path`. One held for its passphrase asks for it, or whether to leave without saving. |
| 364 | 364 | static func save(_ session: DocumentSession, _ path: String) -> Bool { |
| 365 | 365 | if session.save(path) { return true } |
| 366 | guard let hold = session.held[path] else { return false } | |
| 367 | 366 | let name = (path as NSString).lastPathComponent |
| 367 | guard let hold = session.held[path], hold.takesPassphrase else { | |
| 368 | // A save that failed otherwise (a conflict, an error, an entry the passphrase can't | |
| 369 | // encrypt) still lets the file be left without saving. | |
| 370 | let alert = NSAlert() | |
| 371 | alert.messageText = String(localized: "Changes to \(name) aren't saved") | |
| 372 | alert.informativeText = session.held[path]?.notice(for: path) ?? session.conflict ?? session.lastError ?? "" | |
| 373 | alert.addButton(withTitle: String(localized: "Cancel")) | |
| 374 | alert.addButton(withTitle: String(localized: "Don't Save")) | |
| 375 | return alert.runModal() == .alertSecondButtonReturn | |
| 376 | } | |
| 368 | 377 | // A new passphrase is typed twice; one that must open what's encrypted already, once. |
| 369 | 378 | let twice = hold == .file || OrgCrypt.firstMessage(session.document(of: path)?.text ?? "") == nil |
| 370 | 379 | let fields = (twice ? [String(localized: "Passphrase"), String(localized: "Repeat passphrase")] : [String(localized: "Passphrase")]).map { placeholder in |
Sources/OrgstarMobile/EditorScreen.swift +4 −2 · view
| @@ -151,8 +151,10 @@ struct EditorScreen: View { | ||
| 151 | 151 | Image(systemName: "lock.trianglebadge.exclamationmark").foregroundStyle(.orange) |
| 152 | 152 | Text(hold.notice(for: path)).font(.callout).fixedSize(horizontal: false, vertical: true) |
| 153 | 153 | Spacer(minLength: 4) |
| 154 | Button(hold == .file ? "Set Passphrase…" : "Encrypt…") { sheet = .crypt(CryptRequest.save(path, hold: hold)) } | |
| 155 | .buttonStyle(.borderedProminent) | |
| 154 | if hold.takesPassphrase { | |
| 155 | Button(hold == .file ? "Set Passphrase…" : "Encrypt…") { sheet = .crypt(CryptRequest.save(path, hold: hold)) } | |
| 156 | .buttonStyle(.borderedProminent) | |
| 157 | } | |
| 156 | 158 | } |
| 157 | 159 | .padding(.horizontal, 14).padding(.vertical, 8) |
| 158 | 160 | .glassEffect(.regular, in: .rect(cornerRadius: 18)) |
Tests/OrgAppTests/CryptReviewTests.swift +71 · view
| @@ -174,6 +174,77 @@ struct CryptReviewTests { | ||
| 174 | 174 | #expect(!disk.contains("Secret task") && !disk.contains("intro")) |
| 175 | 175 | } |
| 176 | 176 | |
| 177 | // Second review, 2 | |
| 178 | @Test func clockHistoryKeepsNoEncryptedTitle() throws { | |
| 179 | let text = "* Bank :crypt:\nintro\n** Secret task\n:PROPERTIES:\n:ID: s-1\n:END:\nbody\n** Hidden no id\nmore\n* Open task\n" | |
| 180 | try notes.write("a.org", text) | |
| 181 | session.open(file.path) | |
| 182 | session.cryptUsed("pw", for: file.path) | |
| 183 | let clockFile = notes.url.appendingPathComponent("clock.json") | |
| 184 | let clock = ClockModel(file: clockFile) | |
| 185 | _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location) | |
| 186 | _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "** Hidden").location) | |
| 187 | _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "* Open").location) | |
| 188 | #expect(!read(clockFile).contains("Secret task") && !read(clockFile).contains("Hidden no id")) | |
| 189 | #expect(clock.history.map(\.title) == ["Open task", "Encrypted entry", "Encrypted entry"]) | |
| 190 | } | |
| 191 | ||
| 192 | // Second review, 3 | |
| 193 | @Test func eachFileHasItsOwnAuthentication() throws { | |
| 194 | let a = CryptPassphrases.context(for: "/x/a.org"), b = CryptPassphrases.context(for: "/x/b.org") | |
| 195 | #expect(a !== b && CryptPassphrases.context(for: "/x/a.org") === a) | |
| 196 | #expect(a.touchIDAuthenticationAllowableReuseDuration == 0) | |
| 197 | CryptPassphrases.endSession(for: "/x/a.org") | |
| 198 | #expect(CryptPassphrases.context(for: "/x/a.org") !== a) | |
| 199 | } | |
| 200 | ||
| 201 | // Second review, 4a | |
| 202 | @Test func anEntryThePassphraseCantEncryptHoldsTheFile() throws { | |
| 203 | let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n" | |
| 204 | var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one")) | |
| 205 | both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two")) | |
| 206 | try notes.write("a.org", both) | |
| 207 | session.open(file.path) | |
| 208 | #expect(session.unlock("one", for: file.path) == nil) | |
| 209 | try type("typed below b\n", at: offset(of: "* End")) | |
| 210 | #expect(!session.save()) | |
| 211 | guard case .blocked(let reason)? = session.held[file.path] else { Issue.record("\(String(describing: session.held[file.path]))"); return } | |
| 212 | #expect(reason.contains("public key") && session.lastError == nil) | |
| 213 | #expect(OrgCrypt.Failure("x").localizedDescription == "x") | |
| 214 | #expect(!disk.contains("typed below b")) | |
| 215 | } | |
| 216 | ||
| 217 | // Second review, 4b | |
| 218 | @Test func plaintextEntriesOnDiskHoldTheFileUntilThePassphrase() throws { | |
| 219 | session.open(file.path) | |
| 220 | try type("x", at: 0) | |
| 221 | // Written elsewhere, with no file event. | |
| 222 | try notes.write("a.org", "* Plain\nOpen text.\n* Last\n* Theirs :crypt:\ntheir secret\n") | |
| 223 | #expect(!session.save()) | |
| 224 | #expect(session.held[file.path] == .entries(1) && session.lastError == nil) | |
| 225 | #expect(session.unlock("pw", for: file.path) == nil) | |
| 226 | #expect(!session.isDirty && !disk.contains("their secret") && session.document?.text.contains("their secret") == true) | |
| 227 | #expect(recoveryFiles.allSatisfy { !$0.contains("their secret") }) | |
| 228 | } | |
| 229 | ||
| 230 | // Second review, 6 | |
| 231 | @Test func anEncryptedFileSavesWithOneKey() throws { | |
| 232 | let path = notes.url.appendingPathComponent("d.org.gpg") | |
| 233 | try OpenPGP.encryptedMessage(Data("* D\nbody\n".utf8), passphrase: "pw").write(to: path) | |
| 234 | session.open(path.path) | |
| 235 | #expect(session.unlock("pw", for: path.path) == nil) | |
| 236 | try type("x", at: 0) | |
| 237 | #expect(session.save()) | |
| 238 | let clock = ContinuousClock() | |
| 239 | var took: [Duration] = [] | |
| 240 | for n in 0..<3 { | |
| 241 | try type("\(n)", at: 0) | |
| 242 | took.append(clock.measure { _ = session.save() }) | |
| 243 | } | |
| 244 | print("Autosave of an .org.gpg file: \(took)") | |
| 245 | #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data("210x* D\nbody\n".utf8)) | |
| 246 | } | |
| 247 | ||
| 177 | 248 | // 9 |
| 178 | 249 | @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws { |
| 179 | 250 | session.open(file.path) |
Tests/OrgDocumentTests/CryptSaverTests.swift added +62 · view
| @@ -0,0 +1,62 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import Testing | |
| 4 | @testable import OrgDocument | |
| 5 | ||
| 6 | /// A version another writer puts on disk just before ours, with crypt-tagged entries in | |
| 7 | /// plaintext and no passphrase known: recovery can't keep it, and it must not be lost. | |
| 8 | struct CryptSaverTests { | |
| 9 | static let theirs = "a\nb\nc\n* Theirs :crypt:\ntheir secret\n" | |
| 10 | ||
| 11 | func saver(_ files: FaultyFileSystem, _ recovery: MemoryRecovery) -> (Saver, CryptVault) { | |
| 12 | let vault = CryptVault() | |
| 13 | vault.encryptsTaggedEntries = true | |
| 14 | return (Saver(fileSystem: CryptFileSystem(base: files, vault: vault), recovery: CryptRecoveryStore(base: recovery, vault: vault)), vault) | |
| 15 | } | |
| 16 | ||
| 17 | @Test func anOverwrittenVersionMergesIntoTheBuffer() throws { | |
| 18 | let files = FaultyFileSystem("a\nb\nc\n") | |
| 19 | files.beforeReplace = Array(Self.theirs.utf8) | |
| 20 | let recovery = MemoryRecovery() | |
| 21 | var doc = try editedState() | |
| 22 | let outcome = try saver(files, recovery).0.save(&doc, to: url) | |
| 23 | guard case .overwroteExternalChange(.merged) = outcome else { Issue.record("\(outcome)"); return } | |
| 24 | #expect(doc.text.contains("their secret")) | |
| 25 | #expect(recovery.kept.allSatisfy { !$0.text.contains("their secret") }) | |
| 26 | } | |
| 27 | ||
| 28 | @Test func aConflictingOverwrittenVersionGoesIntoTheBufferWithMarkers() throws { | |
| 29 | let files = FaultyFileSystem("a\nb\nc\n") | |
| 30 | files.beforeReplace = Array("Z\nb\nc\n* Theirs :crypt:\ntheir secret\n".utf8) | |
| 31 | let recovery = MemoryRecovery() | |
| 32 | var doc = try editedState() | |
| 33 | _ = try saver(files, recovery).0.save(&doc, to: url) | |
| 34 | #expect(doc.text.contains("their secret") && doc.text.contains("Z") && doc.text.contains("A")) | |
| 35 | #expect(recovery.kept.allSatisfy { !$0.text.contains("their secret") }) | |
| 36 | } | |
| 37 | ||
| 38 | @Test func keepMineDoesntReplaceAVersionItCantKeep() throws { | |
| 39 | let files = FaultyFileSystem(Self.theirs) | |
| 40 | let recovery = MemoryRecovery() | |
| 41 | var doc = try editedState() | |
| 42 | #expect(throws: CryptHold.self) { try saver(files, recovery).0.overwrite(&doc, to: url) } | |
| 43 | #expect(files.text == Self.theirs) | |
| 44 | } | |
| 45 | ||
| 46 | @Test func closedFilesKeepNothingAfterTheirWrite() async throws { | |
| 47 | let files = FaultyFileSystem("a\n") | |
| 48 | let recovery = MemoryRecovery() | |
| 49 | let (saver, vault) = saver(files, recovery) | |
| 50 | vault.unlock("pw", for: url.path) | |
| 51 | var doc = state("a\n") | |
| 52 | try doc.apply([TextEdit(range: 2..<2, replacement: "* S :crypt:\nsecret\n")], baseRevision: 0) | |
| 53 | #expect(try saver.save(&doc, to: url) == .saved) | |
| 54 | #expect(files.text?.contains("secret") == false) | |
| 55 | await MainActor.run {} | |
| 56 | try await Task.sleep(for: .milliseconds(50)) | |
| 57 | #expect(!vault.keepsAnything(for: url.path)) | |
| 58 | // Only open files keep sealing after the setting goes off. | |
| 59 | vault.encryptsTaggedEntries = false | |
| 60 | #expect(!vault.sealsEntries(for: url.path)) | |
| 61 | } | |
| 62 | } | |
docs/manual/guide/04-outlines.org +5 −3 · view
| @@ -963,12 +963,14 @@ With =org-crypt-use-before-save-magic = true= in =config.toml=, every save, the | ||
| 963 | 963 | - An entry decrypted with Decrypt Entry in File… and saved unchanged gets its old message back, byte for byte, as org-crypt does, and so does an entry left unchanged between saves. Only entries that changed get a new message, so syncing and git see no other change. A new message takes GnuPG's key iterations (about 65 MB of hashing); each changed entry adds a few hundredths of a second to its save. |
| 964 | 964 | - Text typed below an entry's message isn't encrypted until it goes into the message: the save opens the old message with the passphrase and encrypts it with the new text as one. |
| 965 | 965 | - Turning the setting off while a file is open doesn't write what it encrypted in plaintext: the file keeps encrypting its tagged entries until it's closed. Files opened afterwards are saved as they are. |
| 966 | - The passphrase comes from the Keychain when it was remembered for the file, after Touch ID, Face ID or the device password. That is asked once while the file is open, at the first save that needs it; a passphrase typed for an org-crypt command on the file is used too. Closing the file or Forget Encryption Passphrase forgets it. | |
| 966 | - The passphrase comes from the Keychain when it was remembered for the file, after Touch ID, Face ID or the device password. That is asked once for each file while it's open, at the first save that needs it; another file asks again, and so does the same file after it was closed. A passphrase typed for an org-crypt command on the file is used too. Closing the file or Forget Encryption Passphrase forgets it. | |
| 967 | 967 | - Without the passphrase, or when Touch ID is declined, the file isn't saved at all, and no recovery version or snapshot of it is kept, until the entries can be encrypted. A notice above the mode line (on iOS, at the top of the editor) says how many tagged entries aren't encrypted, and stays while that's so; its Encrypt… button asks for the passphrase and saves. Other edits to the file wait meanwhile. An entry with no text doesn't keep the file from being saved. |
| 968 | 968 | - When the file has encrypted entries already, the passphrase must open them. A first passphrase is asked twice. Entries encrypted to a public key (=org-crypt-key=) are left as they are and aren't checked; text typed below one can't be encrypted, and saving says so. |
| 969 | 969 | - Use Disk Version, Merge with Markers, restoring an earlier version and resolving a sync conflict keep a copy of the editor's text first; while the file is held that copy can't be kept encrypted, so they stop and ask for the passphrase first. Replace in Files on a held file that has no editor open replaces without keeping a copy; the replacement can be undone in the file. |
| 970 | 970 | - Archiving, refiling or copying an entry that has the tag, its own or inherited, to another file encrypts it in place first, since the tag it inherits doesn't go with it; without the passphrase it isn't moved. |
| 971 | - Closing the file, its window, or quitting while it's held asks for the passphrase, or whether to leave without saving. On iOS, the edits stay in memory while orgstar is in the background, and the notice is there on return; if iOS ends orgstar meanwhile, the edits are lost, and orgstar says so when it next opens. | |
| 971 | - When another program saves the file with tagged entries in plaintext, the file is held the same way until the passphrase lets orgstar keep a copy of that version encrypted and merge it. A version another program writes in the moment orgstar saves goes into the editor, between conflict markers if it conflicts, when no copy of it can be kept. | |
| 972 | - An entry that the passphrase can't encrypt (text typed below a message encrypted with another passphrase, or to a public key) holds the file too; the notice says why, without an Encrypt… button. | |
| 973 | - Closing the file, its window, or quitting while it's held asks for the passphrase, or whether to leave without saving; any other save that fails then offers Don't Save. On iOS, the edits stay in memory while orgstar is in the background, and the notice is there on return; if iOS ends orgstar meanwhile, the edits are lost, and orgstar says so when it next opens. | |
| 972 | 974 | - While an entry is decrypted in the editor, the agenda, widgets, the watch and reminders read the file from disk, where the entry is encrypted. The index, Spotlight and Quick Look read files from disk too. iCalendar export and publishing read such a file from disk and say so. Recalculating a table in Emacs, exporting with Emacs and =elisp:= links in Emacs aren't given a copy of the file. Clocking in to a heading inside such an entry shows "Encrypted entry" in the clock's history, widgets, the Live Activity and the menu bar. |
| 973 | 975 | |
| 974 | 976 | * Encrypted files |
| @@ -982,7 +984,7 @@ The decrypted text is kept in memory only: | ||
| 982 | 984 | - Recovery versions and hourly snapshots are kept encrypted with the file's passphrase, and Recovery Versions… shows them decrypted. Changes made to the file elsewhere are merged in memory, and a conflict is compared in memory. |
| 983 | 985 | - The index, search, Spotlight, Quick Look, the agenda, widgets and the watch don't read the file's text. iCalendar export and publishing leave it out, and Emacs isn't given a copy of it. A clocked heading shows as "Encrypted entry" outside the editor. |
| 984 | 986 | - Archiving from =NAME.org.gpg= goes to =NAME_archive.org.gpg=, encrypted with the same passphrase (Org would write =NAME.org.gpg_archive=, unencrypted). Entries aren't refiled or copied from it to a file that isn't encrypted. |
| 985 | - Remembered passphrases are kept by the file's path, on this device only, readable while it's unlocked and after Touch ID, Face ID or the device password; renaming the file forgets it. Passphrases remembered by earlier versions move to this kind of item the first time they're used. | |
| 987 | - Remembered passphrases are kept by the file's path, on this device only, readable while it's unlocked and after Touch ID, Face ID or the device password; renaming the file forgets it. Passphrases remembered by earlier versions move to this kind of item the first time they're used. The version of orgstar downloaded from the website can't make such items (it has no Keychain entitlement): it keeps remembered passphrases in the login keychain, not limited to this Mac, still asking for Touch ID or the password before one is used, and says so the first time. | |
| 986 | 988 | |
| 987 | 989 | =age= files (=.age=) aren't supported. |
| 988 | 990 | |