Commit 1e2be994af

1e2be994af63ee234fff2fe60543c62ca3f6905e

parent: 9945f06859

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 09:43 UTC

Encryption second review fixes

Ref #153

Layout: unified · split

Changed files (14)
Sources/OrgApp/ClockModel.swift +10 −4 · view
@@ -100,7 +100,7 @@ public final class ClockModel {
100100 let interrupted = runningTask(session)
101101 let message = clockOut(session, now: now)
102102 if self.running != nil { return message }
103 interruptedTask = interrupted
103 interruptedTask = interrupted.map { Self.shareable($0, session) }
104104 // Clocking out may have moved the entry.
105105 let target = ClockTask(path: path, title: entry.title, ordinal: index, id: entry.id)
106106 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 {
308308
309309 private func push(_ task: ClockTask, _ session: DocumentSession) {
310310 // 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)
313311 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)
314320 }
315321
316322 /// Where a remembered entry's heading is now.
@@ -328,7 +334,7 @@ public final class ClockModel {
328334 public func markDefault(_ session: DocumentSession, path: String, at offset: Int) -> String {
329335 guard let text = Self.text(path, session) else { return "Can't read \(path)" }
330336 guard let task = ClockTask.at(offset, in: text, path: path) else { return "Before first headline" }
331 defaultTask = task
337 defaultTask = Self.shareable(task, session)
332338 return "Default clock task: \(task.title)"
333339 }
334340
Sources/OrgApp/CryptPassphrases.swift +71 −24 · view
@@ -5,28 +5,45 @@ import Security
55
66/// Passphrases for encrypted entries and files, kept in the Keychain by file path when asked.
77/// 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
1012public enum CryptPassphrases {
11 static let service = "sh.krz.orgstar.crypt.v2"
13 nonisolated static let service = "sh.krz.orgstar.crypt.v2"
1214 /// 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"
1418
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 }
1729 let context = LAContext()
18 context.touchIDAuthenticationAllowableReuseDuration = LATouchIDAuthenticationMaximumAllowableReuseDuration
30 contexts[path] = context
1931 return context
20 }()
32 }
2133
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] {
2340 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
2441 if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true }
2542 return query
2643 }
2744
2845 /// 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]? {
3047 guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
3148 var item = query(path)
3249 item[kSecValueData as String] = Data(passphrase.utf8)
@@ -35,25 +52,47 @@ public enum CryptPassphrases {
3552 return item
3653 }
3754
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.")
4781 }
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.")
4886 }
4987
5088 public static func forget(_ path: String) {
89 endSession(for: path)
5190 SecItemDelete(query(path) as CFDictionary)
5291 SecItemDelete(query(path, service: legacyService) as CFDictionary)
5392 }
5493
5594 /// 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 {
5796 var q = query
5897 let quiet = LAContext()
5998 quiet.interactionNotAllowed = true
@@ -70,17 +109,17 @@ public enum CryptPassphrases {
70109 /// The stored passphrase, once the person has proved who they are; nil otherwise.
71110 public static func stored(for path: String) async -> String? {
72111 let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
112 let context = context(for: path)
73113 if exists(query(path)) {
74114 var q = query(path)
75115 q[kSecReturnData as String] = true
76 let context = Self.context
77116 context.localizedReason = reason
78117 q[kSecUseAuthenticationContext as String] = context
79 let request = q
118 let request = Request(query: q)
80119 // The read waits for Touch ID or the password, off the main thread.
81120 return await Task.detached { () -> String? in
82121 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 }
84123 return String(decoding: data, as: UTF8.self)
85124 }.value
86125 }
@@ -92,7 +131,7 @@ public enum CryptPassphrases {
92131 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
93132 let passphrase = String(decoding: data, as: UTF8.self)
94133 // 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 {
96135 SecItemDelete(query(path, service: legacyService) as CFDictionary)
97136 }
98137 return passphrase
@@ -100,6 +139,12 @@ public enum CryptPassphrases {
100139}
101140
102141extension 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
103148 /// What the held file's notice says.
104149 public func notice(for path: String) -> String {
105150 let name = (path as NSString).lastPathComponent
@@ -107,6 +152,7 @@ extension CryptHold {
107152 case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
108153 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
109154 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.")
110156 }
111157 }
112158}
@@ -117,6 +163,7 @@ extension CryptHold: LocalizedError {
117163 case .entries(1): String(localized: "1 tagged entry isn't encrypted")
118164 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
119165 case .file: String(localized: "The file has no passphrase yet")
166 case .blocked(let reason): reason
120167 }
121168 }
122169}
Sources/OrgApp/CryptSheet.swift +6 −3 · view
@@ -67,6 +67,8 @@ public struct CryptSheet: View {
6767 @State private var passphrase = ""
6868 @State private var repeated = ""
6969 @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?
7072 @State private var problem: String?
7173 /// The decrypted entry being edited, and the passphrase it came with.
7274 @State private var editing: (original: String, passphrase: String)?
@@ -187,7 +189,7 @@ public struct CryptSheet: View {
187189 finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered)
188190 case .open:
189191 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) }
191193 session?.cryptUsed(passphrase, for: request.path)
192194 plaintext = plain
193195 editing = (plain, passphrase)
@@ -210,9 +212,10 @@ public struct CryptSheet: View {
210212 }
211213
212214 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) }
214216 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)
216219 }
217220
218221 /// 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 {
182182 /// Open files that aren't saved until a passphrase is given: tagged entries that would be
183183 /// written unencrypted, or an encrypted file without one. Other edits to them wait too.
184184 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] = [:]
185188
186189 /// An encrypted file waiting for its passphrase to open, and the pane to show it in.
187190 public private(set) var unlockRequest: String?
@@ -277,7 +280,8 @@ public final class DocumentSession {
277280
278281 /// Whether `path`'s buffer is held back from disk now.
279282 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
281285 if held[entry.path] != hold { held[entry.path] = hold }
282286 return hold
283287 }
@@ -451,6 +455,7 @@ public final class DocumentSession {
451455 return
452456 }
453457 let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
458 crypt.opened(path)
454459 let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
455460 entries.insert(entry, at: index)
456461 show(entry, in: pane)
@@ -489,7 +494,9 @@ public final class DocumentSession {
489494 entry.autosave?.cancel()
490495 entries.removeAll { $0 === entry }
491496 crypt.close(entry.path)
497 CryptPassphrases.endSession(for: entry.path)
492498 held[entry.path] = nil
499 failedHolds[entry.path] = nil
493500 refusedKeychain.remove(entry.path)
494501 history.removeAll { $0 == path }
495502 outlineUpdates[path]?.cancel()
@@ -641,15 +648,18 @@ public final class DocumentSession {
641648 defer { interval.end((entry.path as NSString).lastPathComponent) }
642649 entry.autosave?.cancel()
643650 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 {
645653 askKeychain(entry)
646654 refresh(entry)
647655 return false
648656 }
649657 guard entry.buffer.document.isDirty else { return true }
650658 guard entry.conflict == nil else { return false }
659 defer { _ = updateHold(entry) }
651660 do {
652661 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
662 failedHolds[entry.path] = nil
653663 switch outcome {
654664 case .saved, .mergedAndSaved:
655665 break
@@ -660,6 +670,12 @@ public final class DocumentSession {
660670 entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
661671 }
662672 }
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)
663679 } catch {
664680 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
665681 }
@@ -989,6 +1005,13 @@ public final class DocumentSession {
9891005 /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
9901006 /// since the tag they inherit doesn't go with them.
9911007 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 }
9921015 let from = (path as NSString).lastPathComponent, to = (target as NSString).lastPathComponent
9931016 if Self.isEncryptedFile(path) {
9941017 guard Self.isEncryptedFile(target) else {
Sources/OrgCore/Commands/ClockHistory.swift +15 −2 · view
@@ -12,12 +12,16 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
1212 /// The heading's index among the file's headings.
1313 public let ordinal: Int
1414 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?
1518
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) {
1720 self.path = path
1821 self.title = title
1922 self.ordinal = ordinal
2023 self.id = id
24 self.titleHidden = titleHidden
2125 }
2226
2327 /// The entry containing `offset`; nil before the first heading.
@@ -28,9 +32,11 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
2832 return ClockTask(path: path, title: heading.title, ordinal: index, id: heading.id)
2933 }
3034
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.
3237 public func index(in model: DocumentModel) -> Int? {
3338 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 }
3440 if ordinal < model.headings.count, model.headings[ordinal].title == title { return ordinal }
3541 return model.headings.firstIndex { $0.title == title }
3642 }
@@ -46,6 +52,13 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
4652 let model = DocumentModel(tree: OrgParser.parse(text))
4753 guard let index = index(in: model) else { return nil }
4854 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)
4962 }
5063}
5164
Sources/OrgCore/Crypto/OrgCrypt.swift +2 −1 · view
@@ -5,9 +5,10 @@ import Foundation
55/// nil: an entry's text after its planning, properties and logbook, through the end of its
66/// subtree, replaced by an armored OpenPGP message under the heading.
77public enum OrgCrypt {
8 public struct Failure: Error, Equatable, CustomStringConvertible {
8 public struct Failure: Error, Equatable, CustomStringConvertible, LocalizedError {
99 public let description: String
1010 public init(_ description: String) { self.description = description }
11 public var errorDescription: String? { description }
1112 }
1213
1314 /// `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 {
77 case entries(Int)
88 /// An encrypted file (`.org.gpg`) whose passphrase isn't known.
99 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)
1013}
1114
1215/// Why an encrypted file can't be read.
@@ -35,6 +38,8 @@ public final class CryptVault: @unchecked Sendable {
3538 /// Files that seal tagged entries until they close, whatever the setting says now: those
3639 /// it was on for, so that turning it off never writes what was encrypted in plaintext.
3740 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> = []
3843 /// By encrypted file: its bytes on disk and their text, last read or written.
3944 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:]
4045
@@ -70,7 +75,7 @@ public final class CryptVault: @unchecked Sendable {
7075 /// Whether saving `key` seals its tagged entries: the setting is on, or was while the
7176 /// file was open. Call with the lock held.
7277 private func seals(_ key: String) -> Bool {
73 if entries { sealing.insert(key) }
78 if entries, open.contains(key) { sealing.insert(key) }
7479 return entries || sealing.contains(key) || !(revealed[key]?.isEmpty ?? true)
7580 }
7681
@@ -103,10 +108,35 @@ public final class CryptVault: @unchecked Sendable {
103108 }
104109 }
105110
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
106135 /// Drops everything kept for `path`, as when its buffer closes.
107136 public func close(_ path: String) {
108137 let key = Self.key(path)
109138 locked {
139 open.remove(key)
110140 passphrases[key] = nil
111141 reuse[key] = nil
112142 revealed[key] = nil
@@ -189,6 +219,9 @@ public final class CryptVault: @unchecked Sendable {
189219 if Self.isEncryptedFile(path) {
190220 guard let passphrase else { throw CryptHold.file }
191221 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) }
192225 let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase)
193226 bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message)
194227 return (bytes, messages, plain)
@@ -202,6 +235,11 @@ public final class CryptVault: @unchecked Sendable {
202235 public func didWrite(_ written: (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?), to path: String) {
203236 let key = Self.key(path)
204237 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 }
205243 revealed[key] = Dictionary(written.messages.map { ($0.message, $0.plaintext) }, uniquingKeysWith: { a, _ in a })
206244 reuse[key] = Dictionary(written.messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) }, uniquingKeysWith: { a, _ in a })
207245 if let plain = written.plain { lastFile[key] = (written.bytes, plain) }
@@ -259,9 +297,11 @@ public struct CryptFileSystem: FileSystem {
259297 let known = vault.revealedMessages(for: url.path)
260298 let written = try vault.cipher(bytes, for: url.path)
261299 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 }
262303 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
265305 }
266306}
267307
Sources/OrgDocument/Saving.swift +29 −5 · view
@@ -74,12 +74,12 @@ public struct Saver: Sendable {
7474 let replaced = try fileSystem.replace(url, with: bytes)
7575 state.didWrite(bytes)
7676 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))
7978 }
8079
8180 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")
8383 return .changedAfterWrite(state.diskChanged(to: after))
8484 }
8585 return merged.map { .mergedAndSaved($0) } ?? .saved
@@ -91,9 +91,33 @@ public struct Saver: Sendable {
9191 /// one. The replaced version goes to recovery unless it is the merge base.
9292 public func overwrite(_ state: inout DocumentState, to url: URL) throws {
9393 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 {
95112 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)
96121 }
97 state.didWrite(bytes)
98122 }
99123}
Sources/Orgstar/CryptHoldBar.swift +1 −1 · view
@@ -14,7 +14,7 @@ struct CryptHoldBar: View {
1414 Image(systemName: "lock.trianglebadge.exclamationmark").foregroundStyle(.orange)
1515 Text(hold.notice(for: path)).lineLimit(3)
1616 Spacer(minLength: 8)
17 Button(hold == .file ? "Set Passphrase…" : "Encrypt…", action: encrypt)
17 if hold.takesPassphrase { Button(hold == .file ? "Set Passphrase…" : "Encrypt…", action: encrypt) }
1818 }
1919 .font(.callout)
2020 .padding(.horizontal, 10)
Sources/Orgstar/OrgstarApp.swift +10 −1 · view
@@ -363,8 +363,17 @@ enum UnsavedChanges {
363363 /// Saves `path`. One held for its passphrase asks for it, or whether to leave without saving.
364364 static func save(_ session: DocumentSession, _ path: String) -> Bool {
365365 if session.save(path) { return true }
366 guard let hold = session.held[path] else { return false }
367366 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 }
368377 // A new passphrase is typed twice; one that must open what's encrypted already, once.
369378 let twice = hold == .file || OrgCrypt.firstMessage(session.document(of: path)?.text ?? "") == nil
370379 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 {
151151 Image(systemName: "lock.trianglebadge.exclamationmark").foregroundStyle(.orange)
152152 Text(hold.notice(for: path)).font(.callout).fixedSize(horizontal: false, vertical: true)
153153 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 }
156158 }
157159 .padding(.horizontal, 14).padding(.vertical, 8)
158160 .glassEffect(.regular, in: .rect(cornerRadius: 18))
Tests/OrgAppTests/CryptReviewTests.swift +71 · view
@@ -174,6 +174,77 @@ struct CryptReviewTests {
174174 #expect(!disk.contains("Secret task") && !disk.contains("intro"))
175175 }
176176
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
177248 // 9
178249 @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
179250 session.open(file.path)
Tests/OrgDocumentTests/CryptSaverTests.swift added +62 · view
@@ -0,0 +1,62 @@
1import Foundation
2import OrgCore
3import 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.
8struct 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
963963- 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.
964964- 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.
965965- 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.
967967- 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.
968968- 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.
969969- 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.
970970- 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.
972974- 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.
973975
974976* Encrypted files
@@ -982,7 +984,7 @@ The decrypted text is kept in memory only:
982984- 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.
983985- 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.
984986- 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.
986988
987989=age= files (=.age=) aren't supported.
988990
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form