Encrypt tagged entries on save; whole-file encryption !489

merged merged by cmc on 2026-11-26 10:40 UTC · krz/orgstar:m5-crypt into main

11 files changed, +305 −18

One commit's changes, read-only. Review comments go on all commits.

Layout: unified · split

Changed files (11)
Sources/OrgApp/ClockModel.swift +2 · view
@@ -72,6 +72,8 @@ public final class ClockModel {
72 72
73 private func save() { 73 private func save() {
74 try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) 74 try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
75 // Hidden tasks that can be found only in this run aren't kept past it.
76 let history = history.filter { !$0.isSessionOnly }
75 if running != nil || !history.isEmpty, let data = try? JSONEncoder().encode(Saved(running: running, history: history)) { 77 if running != nil || !history.isEmpty, let data = try? JSONEncoder().encode(Saved(running: running, history: history)) {
76 try? data.write(to: file, options: .atomic) 78 try? data.write(to: file, options: .atomic)
77 } else { 79 } else {
Sources/OrgApp/CryptPassphrases.swift +42 · view
@@ -1,3 +1,4 @@
1import CryptoKit
1import Foundation 2import Foundation
2import LocalAuthentication 3import LocalAuthentication
3import OrgDocument 4import OrgDocument
@@ -147,6 +148,38 @@ public enum CryptPassphrases {
147 } 148 }
148} 149}
149 150
151/// The key clock history hashes encrypted headings' titles with, made once and kept in the
152/// Keychain, on this device only, without asking for authentication.
153public enum ClockTitleKey {
154 static let service = "sh.krz.orgstar.clock-title-key"
155
156 static func query(dataProtection: Bool) -> [String: Any] {
157 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: "key"]
158 if dataProtection { query[kSecUseDataProtectionKeychain as String] = true }
159 return query
160 }
161
162 /// The key, made and kept the first time; nil when the Keychain keeps none.
163 public static func loadOrCreate() -> SymmetricKey? {
164 for dataProtection in [true, false] {
165 var q = query(dataProtection: dataProtection)
166 q[kSecReturnData as String] = true
167 var result: AnyObject?
168 if SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data, data.count == 32 { return SymmetricKey(data: data) }
169 }
170 let key = SymmetricKey(size: .bits256)
171 let data = key.withUnsafeBytes { Data($0) }
172 for dataProtection in [true, false] {
173 var item = query(dataProtection: dataProtection)
174 item[kSecValueData as String] = data
175 item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
176 item[kSecAttrLabel as String] = "orgstar: clock history key"
177 if SecItemAdd(item as CFDictionary, nil) == errSecSuccess { return key }
178 }
179 return nil
180 }
181}
182
150extension CryptHold { 183extension CryptHold {
151 /// Whether giving the passphrase lets the file be saved. 184 /// Whether giving the passphrase lets the file be saved.
152 public var takesPassphrase: Bool { 185 public var takesPassphrase: Bool {
@@ -166,6 +199,15 @@ extension CryptHold {
166 } 199 }
167} 200}
168 201
202extension SaveError: LocalizedError {
203 public var errorDescription: String? {
204 switch self {
205 case .fileKeepsChanging: String(localized: "The file keeps changing on disk; nothing was saved.")
206 case .otherVersionRestored: String(localized: "The file changed on disk; nothing was changed.")
207 }
208 }
209}
210
169extension CryptHold: LocalizedError { 211extension CryptHold: LocalizedError {
170 public var errorDescription: String? { 212 public var errorDescription: String? {
171 switch self { 213 switch self {
Sources/OrgApp/DocumentSession.swift +28 −9 · view
@@ -611,6 +611,19 @@ public final class DocumentSession {
611 Saver(fileSystem: WriteReporting(base: fileSystem) { [weak self] url in MainActor.assumeIsolated { self?.fileWritten?(url.path) } }, recovery: recovery) 611 Saver(fileSystem: WriteReporting(base: fileSystem) { [weak self] url in MainActor.assumeIsolated { self?.fileWritten?(url.path) } }, recovery: recovery)
612 } 612 }
613 613
614 /// The saver for a file that isn't open, whose state is thrown away after the save: a
615 /// version another writer put on disk just before ours, which recovery can't keep, is put
616 /// back as it was, and the change fails.
617 private var closedFileSaver: Saver {
618 var saver = saver
619 let crypt = crypt, disk = diskFileSystem
620 saver.restoreOverwritten = { url in
621 guard let theirs = crypt.takeReplaced(for: url.path) else { return }
622 _ = try disk.replace(url, with: theirs)
623 }
624 return saver
625 }
626
614 private func scheduleAutosave(_ entry: Entry) { 627 private func scheduleAutosave(_ entry: Entry) {
615 entry.autosave?.cancel() 628 entry.autosave?.cancel()
616 // A held file whose edits were undone, or whose tagged entries went, isn't held. 629 // A held file whose edits were undone, or whose tagged entries went, isn't held.
@@ -876,7 +889,7 @@ public final class DocumentSession {
876 @discardableResult 889 @discardableResult
877 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? { 890 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
878 guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } 891 guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
879 if target.path != path { 892 do {
880 switch prepareMove(path, context: context, to: target.path) { 893 switch prepareMove(path, context: context, to: target.path) {
881 case .refused(let message): return message 894 case .refused(let message): return message
882 case .sealed(let heading): 895 case .sealed(let heading):
@@ -916,7 +929,7 @@ public final class DocumentSession {
916 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." } 929 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
917 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." } 930 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
918 try state.apply([result.target], baseRevision: state.revision) 931 try state.apply([result.target], baseRevision: state.revision)
919 if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." } 932 if case .conflict = try closedFileSaver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
920 if !keep, let message = applySource(result.source, path: path, now: now) { return message } 933 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
921 return done 934 return done
922 } catch { 935 } catch {
@@ -953,7 +966,7 @@ public final class DocumentSession {
953 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) } 966 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
954 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) } 967 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
955 try state.apply([edit], baseRevision: state.revision) 968 try state.apply([edit], baseRevision: state.revision)
956 if case .conflict = try saver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) } 969 if case .conflict = try closedFileSaver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
957 return .success(target(start, level, FileRecord.hash(state.mergeBase))) 970 return .success(target(start, level, FileRecord.hash(state.mergeBase)))
958 } catch { 971 } catch {
959 return .failure(.message("Can't add \(title): \(error.localizedDescription)")) 972 return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
@@ -1016,6 +1029,12 @@ public final class DocumentSession {
1016 /// passphrase; tagged entries with text in the subtree are encrypted where they are first, 1029 /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
1017 /// since the tag they inherit doesn't go with them. 1030 /// since the tag they inherit doesn't go with them.
1018 private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation { 1031 private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation {
1032 // Within the file, an entry keeps its own tag; one inside an encrypted entry would leave it.
1033 if target == path {
1034 guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(context.text, at: context.selection.first?.lowerBound ?? 0),
1035 OrgCrypt.isInTaggedText(context.text, at: heading, tag: cryptTag) else { return .ready }
1036 return .refused(String(localized: "This heading is inside an encrypted entry, so it isn't moved on its own; move the encrypted entry."))
1037 }
1019 // The target's passphrase, lent by the source for the move, isn't kept after it. 1038 // The target's passphrase, lent by the source for the move, isn't kept after it.
1020 if Self.isEncryptedFile(target), !isOpen(target) { 1039 if Self.isEncryptedFile(target), !isOpen(target) {
1021 DispatchQueue.main.async { [weak self] in 1040 DispatchQueue.main.async { [weak self] in
@@ -1063,7 +1082,7 @@ public final class DocumentSession {
1063 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") } 1082 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") }
1064 var state = loaded(bytes, path: path) 1083 var state = loaded(bytes, path: path)
1065 try state.apply(edit.edits, baseRevision: state.revision) 1084 try state.apply(edit.edits, baseRevision: state.revision)
1066 if case .conflict = try saver.save(&state, to: URL(fileURLWithPath: path)) { return .refused("\(from) changed on disk; nothing was moved.") } 1085 if case .conflict = try closedFileSaver.save(&state, to: URL(fileURLWithPath: path)) { return .refused("\(from) changed on disk; nothing was moved.") }
1067 } catch { 1086 } catch {
1068 return .refused("Can't encrypt the entry: \(error.localizedDescription)") 1087 return .refused("Can't encrypt the entry: \(error.localizedDescription)")
1069 } 1088 }
@@ -1087,8 +1106,8 @@ public final class DocumentSession {
1087 case .success(let value): destination = value 1106 case .success(let value): destination = value
1088 case .failure(.message(let message)): return message 1107 case .failure(.message(let message)): return message
1089 } 1108 }
1090 if !destination.isSameFile { 1109 do {
1091 switch prepareMove(path, context: context, to: destination.path) { 1110 switch prepareMove(path, context: context, to: destination.isSameFile ? path : destination.path) {
1092 case .refused(let message): return message 1111 case .refused(let message): return message
1093 case .sealed(let heading): 1112 case .sealed(let heading):
1094 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." } 1113 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
@@ -1126,7 +1145,7 @@ public final class DocumentSession {
1126 } 1145 }
1127 if let archiveEdit = edits.archive { 1146 if let archiveEdit = edits.archive {
1128 try state.apply([archiveEdit], baseRevision: state.revision) 1147 try state.apply([archiveEdit], baseRevision: state.revision)
1129 if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." } 1148 if case .conflict = try closedFileSaver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
1130 } 1149 }
1131 if let message = applySource(edits.source, path: path, now: now) { return message } 1150 if let message = applySource(edits.source, path: path, now: now) { return message }
1132 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)" 1151 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
@@ -1196,7 +1215,7 @@ public final class DocumentSession {
1196 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") } 1215 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
1197 guard matches(state.text) else { return stale } 1216 guard matches(state.text) else { return stale }
1198 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) 1217 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
1199 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) { 1218 if case .commit = step, state.isDirty, case .conflict = try closedFileSaver.save(&state, to: url) {
1200 return .failed("\(name) changed on disk; nothing was changed.") 1219 return .failed("\(name) changed on disk; nothing was changed.")
1201 } 1220 }
1202 if case .commit = step { textChanged?(path) } 1221 if case .commit = step { textChanged?(path) }
@@ -1239,7 +1258,7 @@ public final class DocumentSession {
1239 guard state.text == expected else { return stale } 1258 guard state.text == expected else { return stale }
1240 try recovery.keep(bytes, for: url, label: "replace") 1259 try recovery.keep(bytes, for: url, label: "replace")
1241 try state.apply(edits, baseRevision: state.revision) 1260 try state.apply(edits, baseRevision: state.revision)
1242 if case .conflict = try saver.save(&state, to: url) { return "\(name) changed on disk; nothing was changed." } 1261 if case .conflict = try closedFileSaver.save(&state, to: url) { return "\(name) changed on disk; nothing was changed." }
1243 textChanged?(path) 1262 textChanged?(path)
1244 return nil 1263 return nil
1245 } catch { 1264 } catch {
Sources/OrgCore/Commands/ClockHistory.swift +22 −3 · view
@@ -1,3 +1,4 @@
1import CryptoKit
1import Foundation 2import Foundation
2 3
3// Clock history and task selection (`org-clock-history`, `org-clock-history-push`, 4// Clock history and task selection (`org-clock-history`, `org-clock-history-push`,
@@ -13,9 +14,27 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
13 public let ordinal: Int 14 public let ordinal: Int
14 public let id: String? 15 public let id: String?
15 /// For a task whose title is a placeholder for one that isn't kept (an encrypted 16 /// For a task whose title is a placeholder for one that isn't kept (an encrypted
16 /// heading's): a checksum of the real title, which finds it with its ID or position. 17 /// heading's): an HMAC of the real title, which finds it with its ID or position.
17 public let titleHash: String? 18 public let titleHash: String?
18 19
20 /// The key titles are hashed with, kept by the app; without one, a key of this run's
21 /// only, and such tasks (`isSessionOnly`) aren't kept past it.
22 nonisolated(unsafe) public static var titleKey: SymmetricKey?
23 static let sessionKey = SymmetricKey(size: .bits256)
24
25 /// `title`'s HMAC-SHA256, hex, prefixed `s:` when made with this run's key.
26 public static func titleDigest(_ title: String) -> String {
27 func hex(_ key: SymmetricKey) -> String {
28 HMAC<SHA256>.authenticationCode(for: Data(title.utf8), using: key).map { String(format: "%02x", $0) }.joined()
29 }
30 if let titleKey { return hex(titleKey) }
31 return "s:" + hex(sessionKey)
32 }
33
34 /// Whether the task can be found only in this run: hidden, without an ID, hashed with this
35 /// run's key.
36 public var isSessionOnly: Bool { id == nil && titleHash?.hasPrefix("s:") == true }
37
19 public init(path: String, title: String, ordinal: Int, id: String?, titleHash: String? = nil) { 38 public init(path: String, title: String, ordinal: Int, id: String?, titleHash: String? = nil) {
20 self.path = path 39 self.path = path
21 self.title = title 40 self.title = title
@@ -37,7 +56,7 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
37 public func index(in model: DocumentModel) -> Int? { 56 public func index(in model: DocumentModel) -> Int? {
38 if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index } 57 if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index }
39 if let titleHash { 58 if let titleHash {
40 func matches(_ index: Int) -> Bool { OrgCrypt.checksum(model.headings[index].title) == titleHash } 59 func matches(_ index: Int) -> Bool { Self.titleDigest(model.headings[index].title) == titleHash }
41 if ordinal < model.headings.count, matches(ordinal) { return ordinal } 60 if ordinal < model.headings.count, matches(ordinal) { return ordinal }
42 return model.headings.indices.first(where: matches) 61 return model.headings.indices.first(where: matches)
43 } 62 }
@@ -62,7 +81,7 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
62 /// The task with `placeholder` for its title, or as it is with nil. 81 /// The task with `placeholder` for its title, or as it is with nil.
63 public func hiding(_ placeholder: String?) -> ClockTask { 82 public func hiding(_ placeholder: String?) -> ClockTask {
64 guard let placeholder else { return self } 83 guard let placeholder else { return self }
65 return ClockTask(path: path, title: placeholder, ordinal: ordinal, id: id, titleHash: titleHash ?? OrgCrypt.checksum(title)) 84 return ClockTask(path: path, title: placeholder, ordinal: ordinal, id: id, titleHash: titleHash ?? Self.titleDigest(title))
66 } 85 }
67} 86}
68 87
Sources/OrgDocument/Crypt.swift +15 · view
@@ -40,6 +40,20 @@ public final class CryptVault: @unchecked Sendable {
40 private var sealing: Set<String> = [] 40 private var sealing: Set<String> = []
41 /// Files open in a buffer. Only they keep what the vault knows past a write. 41 /// Files open in a buffer. Only they keep what the vault knows past a write.
42 private var open: Set<String> = [] 42 private var open: Set<String> = []
43 /// By file: the bytes the last write replaced, as they were on disk.
44 private var replacedBytes: [String: [UInt8]] = [:]
45
46 /// The bytes the last write to `path` replaced, as they were on disk; given once.
47 public func takeReplaced(for path: String) -> [UInt8]? {
48 let key = Self.key(path)
49 return locked { replacedBytes.removeValue(forKey: key) }
50 }
51
52 func noteReplaced(_ bytes: [UInt8]?, for path: String) {
53 let key = Self.key(path)
54 locked { replacedBytes[key] = bytes }
55 }
56
43 /// By encrypted file: its bytes on disk and their text, last read or written. 57 /// By encrypted file: its bytes on disk and their text, last read or written.
44 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:] 58 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:]
45 59
@@ -297,6 +311,7 @@ public struct CryptFileSystem: FileSystem {
297 let known = vault.revealedMessages(for: url.path) 311 let known = vault.revealedMessages(for: url.path)
298 let written = try vault.cipher(bytes, for: url.path) 312 let written = try vault.cipher(bytes, for: url.path)
299 let replaced = try base.replace(url, with: written.bytes) 313 let replaced = try base.replace(url, with: written.bytes)
314 vault.noteReplaced(replaced, for: url.path)
300 // The version replaced, as it read before this write's messages were known (and while 315 // 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). 316 // 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 } 317 let previous = replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 }
Sources/OrgDocument/Saving.swift +19 −3 · view
@@ -37,6 +37,8 @@ public enum SaveOutcome: Sendable, Equatable {
37 37
38public enum SaveError: Error, Equatable { 38public enum SaveError: Error, Equatable {
39 case fileKeepsChanging 39 case fileKeepsChanging
40 /// Another writer's version, replaced by ours and not kept, was put back; ours isn't on disk.
41 case otherVersionRestored
40} 42}
41 43
42/// The save sequence from the design: read, merge if the file moved, check again, replace, 44/// The save sequence from the design: read, merge if the file moved, check again, replace,
@@ -46,6 +48,11 @@ public struct Saver: Sendable {
46 public let fileSystem: FileSystem 48 public let fileSystem: FileSystem
47 public let recovery: RecoveryStore 49 public let recovery: RecoveryStore
48 public var maxAttempts = 3 50 public var maxAttempts = 3
51 /// For a state that's thrown away after the save (a file that isn't open): puts back, as it
52 /// was, the version another writer had on disk just before ours replaced it. Set, a version
53 /// that recovery can't keep is restored and the save throws `otherVersionRestored`, rather
54 /// than merged into the state.
55 public var restoreOverwritten: (@Sendable (URL) throws -> Void)?
49 56
50 public init(fileSystem: FileSystem, recovery: RecoveryStore) { 57 public init(fileSystem: FileSystem, recovery: RecoveryStore) {
51 self.fileSystem = fileSystem 58 self.fileSystem = fileSystem
@@ -74,7 +81,7 @@ public struct Saver: Sendable {
74 let replaced = try fileSystem.replace(url, with: bytes) 81 let replaced = try fileSystem.replace(url, with: bytes)
75 state.didWrite(bytes) 82 state.didWrite(bytes)
76 if replaced != disk, let replaced { 83 if replaced != disk, let replaced {
77 return .overwroteExternalChange(keepOverwritten(replaced, base: disk ?? [], in: &state, url: url)) 84 return .overwroteExternalChange(try keepOverwritten(replaced, base: disk ?? [], in: &state, url: url))
78 } 85 }
79 86
80 if let after = try fileSystem.read(url), after != bytes { 87 if let after = try fileSystem.read(url), after != bytes {
@@ -98,7 +105,7 @@ public struct Saver: Sendable {
98 let replaced = try fileSystem.replace(url, with: bytes) 105 let replaced = try fileSystem.replace(url, with: bytes)
99 state.didWrite(bytes) 106 state.didWrite(bytes)
100 if let replaced, replaced != disk, replaced != base { 107 if let replaced, replaced != disk, replaced != base {
101 _ = keepOverwritten(replaced, base: base, in: &state, url: url, merge: false) 108 _ = try keepOverwritten(replaced, base: base, in: &state, url: url, merge: false)
102 } 109 }
103 } 110 }
104 111
@@ -106,7 +113,16 @@ public struct Saver: Sendable {
106 /// recovery and, when `merge`, merged into the buffer. When recovery can't keep it (it holds 113 /// 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 114 /// 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. 115 /// 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 { 116 func keepOverwritten(_ replaced: [UInt8], base: [UInt8], in state: inout DocumentState, url: URL, merge: Bool = true) throws -> DocumentState.ExternalChange {
117 if let restoreOverwritten {
118 do {
119 try recovery.keep(replaced, for: url, label: "external")
120 return merge ? state.mergeOverwritten(replaced, base: base) : .unchanged
121 } catch {
122 try restoreOverwritten(url)
123 throw SaveError.otherVersionRestored
124 }
125 }
110 let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([]) 126 let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([])
111 do { 127 do {
112 try recovery.keep(replaced, for: url, label: "external") 128 try recovery.keep(replaced, for: url, label: "external")
Sources/Orgstar/OrgstarApp.swift +1 · view
@@ -477,6 +477,7 @@ struct OrgstarApp: App {
477 @State private var clock = ClockModel() 477 @State private var clock = ClockModel()
478 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil 478 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
479 @State private var session: DocumentSession = { 479 @State private var session: DocumentSession = {
480 ClockTask.titleKey = ClockTitleKey.loadOrCreate()
480 let session = DocumentSession() 481 let session = DocumentSession()
481 session.defaults = Preferences.orgSettings 482 session.defaults = Preferences.orgSettings
482 // Before any window: capture and agenda edits can save before the main window opens. 483 // Before any window: capture and agenda edits can save before the main window opens.
Sources/OrgstarMobile/OrgstarMobileApp.swift +1 · view
@@ -26,6 +26,7 @@ struct OrgstarMobileApp: App {
26 #endif 26 #endif
27 LiveClock.install() 27 LiveClock.install()
28 ProStore.shared.start() 28 ProStore.shared.start()
29 ClockTask.titleKey = ClockTitleKey.loadOrCreate()
29 // Read before the app becomes active and clears it. 30 // Read before the app becomes active and clears it.
30 _ = UnsavedHeldFiles.atLaunch 31 _ = UnsavedHeldFiles.atLaunch
31 // Early, so that the watch's actions are taken when iOS wakes the app for them. 32 // Early, so that the watch's actions are taken when iOS wakes the app for them.
Tests/OrgAppTests/CryptReviewTests.swift +104 · view
@@ -1,3 +1,4 @@
1import CryptoKit
1import Foundation 2import Foundation
2import OrgCore 3import OrgCore
3import OrgDocument 4import OrgDocument
@@ -136,6 +137,96 @@ struct CryptReviewTests {
136 #expect(session.subtreeShare(file.path, at: b) == nil) 137 #expect(session.subtreeShare(file.path, at: b) == nil)
137 } 138 }
138 139
140 // Final check, 1
141 @Test func closedFilesPutBackAVersionTheyCantKeep() throws {
142 let files = InjectingFileSystem()
143 let session = DocumentSession(fileSystem: files, recovery: FileRecoveryStore(directory: recoveryFolder))
144 session.encryptsTaggedEntries = true
145 session.hasStoredPassphrase = { _ in false }
146 let theirs = "* B\nb\n* Emacs :crypt:\nemacs secret\n* Work\nEMACSWORK\n"
147 let b = try notes.write("b.org", "* B\nb\n")
148 func check(_ message: String?, _ what: String) {
149 #expect(message?.contains("changed on disk") == true, "\(what): \(String(describing: message))")
150 #expect(read(b) == theirs, "\(what)")
151 #expect(recoveryFiles.allSatisfy { !$0.contains("emacs secret") }, "\(what)")
152 try? notes.write("b.org", "* B\nb\n")
153 }
154 // Replace in Files.
155 files.inject[b.path] = theirs
156 check(session.applyChanges([TextEdit(range: 4..<5, replacement: "c")], to: b.path, expecting: "* B\nb\n"), "replace")
157 // Agenda actions, the clock and capture run commands on the file.
158 files.inject[b.path] = theirs
159 if case .failed(let message) = session.perform(PrecomputedEdit(EditResult(baseRevision: 0, edits: [TextEdit(range: 4..<5, replacement: "c")])), path: b.path, at: 0, expect: nil) {
160 check(message, "perform")
161 } else {
162 Issue.record("perform succeeded")
163 }
164 // Refile into it, and a new heading under its heading.
165 try notes.write("a.org", "* Moved\nmoved text\n")
166 session.open(file.path)
167 files.inject[b.path] = theirs
168 let target = RefileTarget(label: "b.org", path: b.path, start: nil, title: "", level: 0, contentHash: "")
169 check(session.refile(to: target, from: (file.path, 0)), "refile")
170 #expect(disk == "* Moved\nmoved text\n")
171 files.inject[b.path] = theirs
172 if case .failure(.message(let message)) = session.createRefileChild(under: target, title: "New") { check(message, "child") } else { Issue.record("child added") }
173 // Archive into it.
174 try notes.write("a.org", "#+ARCHIVE: b.org::\n* Old\nold text\n")
175 session.kill(file.path)
176 session.open(file.path)
177 files.inject[b.path] = theirs
178 check(session.archive(from: (file.path, 19)), "archive")
179 // An open file merges it as before.
180 session.open(b.path)
181 let buffer = StateBuffer(session.document(of: b.path)!)
182 session.attach(buffer, for: b.path)
183 try buffer.update { try $0.apply([TextEdit(range: 0..<0, replacement: "x")], baseRevision: $0.revision) }
184 session.bufferChanged(b.path)
185 files.inject[b.path] = theirs
186 _ = session.save(b.path)
187 #expect(session.document(of: b.path)?.text.contains("EMACSWORK") == true)
188 }
189
190 // Final check, 2
191 @Test func sameFileMovesDontTakeAHeadingOutOfItsEntry() throws {
192 let text = "#+ARCHIVE: ::* Archive\n* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
193 try notes.write("a.org", text)
194 session.open(file.path)
195 session.cryptUsed("pw", for: file.path)
196 let child = (text as NSString).range(of: "** SECRETTITLE").location
197 let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
198 #expect(session.refile(to: target, from: (file.path, child))?.contains("inside an encrypted entry") == true)
199 #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
200 #expect(session.document?.text == text)
201 // An entry not inside one moves as before.
202 #expect(session.refile(to: target, from: (file.path, (text as NSString).range(of: "* Last").location)) != nil)
203 }
204
205 // Final check, 3
206 @Test func hiddenTitlesAreHashedWithAKey() throws {
207 ClockTask.titleKey = nil
208 let session = ClockTask(path: "/x", title: "Real", ordinal: 0, id: nil).hiding("Encrypted entry")
209 #expect(session.isSessionOnly && session.titleHash != OrgCrypt.checksum("Real"))
210 #expect(session.locate(in: "* Real\n") == 0)
211 let key = SymmetricKey(size: .bits256)
212 ClockTask.titleKey = key
213 defer { ClockTask.titleKey = nil }
214 let kept = ClockTask(path: "/x", title: "Real", ordinal: 0, id: nil).hiding("Encrypted entry")
215 #expect(!kept.isSessionOnly && kept.titleHash != OrgCrypt.checksum("Real") && kept.locate(in: "* Real\n") == 0)
216 // Hidden tasks that can be found only in this run aren't written to the clock's file.
217 ClockTask.titleKey = nil
218 let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n"
219 try notes.write("a.org", text)
220 self.session.open(file.path)
221 self.session.cryptUsed("pw", for: file.path)
222 let clockFile = notes.url.appendingPathComponent("clock.json")
223 let clock = ClockModel(file: clockFile)
224 _ = clock.clockIn(self.session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
225 _ = clock.clockOut(self.session)
226 #expect(clock.history.count == 1)
227 #expect(!read(clockFile).contains("s:"))
228 }
229
139 // Third review, C 230 // Third review, C
140 @Test func hiddenClockTasksNeedTheirTitle() throws { 231 @Test func hiddenClockTasksNeedTheirTitle() throws {
141 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry") 232 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
@@ -380,3 +471,16 @@ struct CryptReviewTests {
380 #expect(item[kSecAttrAccessible as String] == nil) 471 #expect(item[kSecAttrAccessible as String] == nil)
381 } 472 }
382} 473}
474
475/// The disk, with another writer that puts `inject[path]` in place just before a replace.
476final class InjectingFileSystem: FileSystem, @unchecked Sendable {
477 let base = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
478 var inject: [String: String] = [:]
479
480 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
481
482 func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
483 if let text = inject.removeValue(forKey: url.path) { try Data(text.utf8).write(to: url) }
484 return try base.replace(url, with: bytes)
485 }
486}
docs/manual/guide/04-outlines.org +3 −3 · view
@@ -967,11 +967,11 @@ With =org-crypt-use-before-save-magic = true= in =config.toml=, every save, the
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. 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- 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. 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- 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. 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- Archiving, refiling or copying an entry with the tag to another file encrypts it in place first; without the passphrase it isn't moved. A heading inside an encrypted entry (in its message on disk) isn't archived, refiled or copied on its own; move the encrypted entry. 970- Archiving, refiling or copying an entry with the tag to another file encrypts it in place first; without the passphrase it isn't moved. A heading inside an encrypted entry (in its message on disk) isn't archived, refiled or copied on its own, to another file or within its own; move the encrypted entry.
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 when no copy of it can be kept; if it conflicts, both versions are there between conflict markers, and the file is marked as in conflict. Keep Mine on such a file is held until the passphrase is given. 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 when no copy of it can be kept; if it conflicts, both versions are there between conflict markers, and the file is marked as in conflict. Keep Mine on such a file is held until the passphrase is given. For a file that isn't open (Replace in Files, agenda actions, the clock, capture, refile and archive into it), that version is put back as the other program wrote it, and the change isn't made: "The file changed on disk; nothing was changed."
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. 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. 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.
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. Handoff doesn't offer the file, and Share Subtree… shares tagged entries encrypted as they are on disk, or, without the passphrase or when they can't be encrypted, not at all. Shared from inside an encrypted entry, a heading is shared as an entry titled "Encrypted entry" with the tag, whose one message holds the heading and everything under it. 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; the history finds the heading again by a keyed hash of its title, with a key orgstar keeps in the Keychain on this device, or, without one, only until orgstar quits. Handoff doesn't offer the file, and Share Subtree… shares tagged entries encrypted as they are on disk, or, without the passphrase or when they can't be encrypted, not at all. Shared from inside an encrypted entry, a heading is shared as an entry titled "Encrypted entry" with the tag, whose one message holds the heading and everything under it.
975 975
976* Encrypted files 976* Encrypted files
977 977
l10n/Localizable.xcstrings +68 · view
@@ -44511,6 +44511,40 @@
44511 } 44511 }
44512 } 44512 }
44513 }, 44513 },
44514 "The file changed on disk; nothing was changed.": {
44515 "localizations": {
44516 "de": {
44517 "stringUnit": {
44518 "state": "translated",
44519 "value": "Die Datei wurde auf dem Datenträger geändert; nichts wurde geändert."
44520 }
44521 },
44522 "es": {
44523 "stringUnit": {
44524 "state": "translated",
44525 "value": "El archivo cambió en el disco; no se cambió nada."
44526 }
44527 },
44528 "fr": {
44529 "stringUnit": {
44530 "state": "translated",
44531 "value": "Le fichier a changé sur le disque ; rien n'a été modifié."
44532 }
44533 },
44534 "ja": {
44535 "stringUnit": {
44536 "state": "translated",
44537 "value": "ファイルがディスク上で変更されたため、何も変更されませんでした。"
44538 }
44539 },
44540 "pt-BR": {
44541 "stringUnit": {
44542 "state": "translated",
44543 "value": "O arquivo mudou no disco; nada foi alterado."
44544 }
44545 }
44546 }
44547 },
44514 "The file has no passphrase yet": { 44548 "The file has no passphrase yet": {
44515 "localizations": { 44549 "localizations": {
44516 "de": { 44550 "de": {
@@ -44579,6 +44613,40 @@
44579 } 44613 }
44580 } 44614 }
44581 }, 44615 },
44616 "The file keeps changing on disk; nothing was saved.": {
44617 "localizations": {
44618 "de": {
44619 "stringUnit": {
44620 "state": "translated",
44621 "value": "Die Datei ändert sich laufend auf dem Datenträger; nichts wurde gesichert."
44622 }
44623 },
44624 "es": {
44625 "stringUnit": {
44626 "state": "translated",
44627 "value": "El archivo sigue cambiando en el disco; no se guardó nada."
44628 }
44629 },
44630 "fr": {
44631 "stringUnit": {
44632 "state": "translated",
44633 "value": "Le fichier change sans cesse sur le disque ; rien n'a été enregistré."
44634 }
44635 },
44636 "ja": {
44637 "stringUnit": {
44638 "state": "translated",
44639 "value": "ファイルがディスク上で変更され続けているため、何も保存されませんでした。"
44640 }
44641 },
44642 "pt-BR": {
44643 "stringUnit": {
44644 "state": "translated",
44645 "value": "O arquivo continua mudando no disco; nada foi salvo."
44646 }
44647 }
44648 }
44649 },
44582 "The folder and its files stay on disk.": { 44650 "The folder and its files stay on disk.": {
44583 "localizations": { 44651 "localizations": {
44584 "de": { 44652 "de": {
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