Commit 9300add1d8

9300add1d8a7e33f0fc51a6e9a6cf4969be05032

parent: 6e76718b67

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 10:45 UTC

Restore only over our own write; keep hidden clock tasks without the key

A closed file's restore of another writer's version reads the disk first
and leaves a version written after ours in place. A run hashing titles
with a session key keeps history entries hashed with the stored key
unchanged.

Closes #238

Layout: unified · split

Changed files (4)
Sources/OrgApp/DocumentSession.swift +3 −3 · view
@@ -613,13 +613,13 @@ public final class DocumentSession {
613 613
614 /// The saver for a file that isn't open, whose state is thrown away after the save: a 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 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. 616 /// back as it was, and the change fails. A version written after ours is left in place.
617 private var closedFileSaver: Saver { 617 private var closedFileSaver: Saver {
618 var saver = saver 618 var saver = saver
619 let crypt = crypt, disk = diskFileSystem 619 let crypt = crypt, disk = diskFileSystem
620 saver.restoreOverwritten = { url in 620 saver.restoreOverwritten = { url in
621 guard let theirs = crypt.takeReplaced(for: url.path) else { return } 621 guard let last = crypt.takeReplaced(for: url.path), try disk.read(url) == last.written else { return }
622 _ = try disk.replace(url, with: theirs) 622 _ = try disk.replace(url, with: last.replaced)
623 } 623 }
624 return saver 624 return saver
625 } 625 }
Sources/OrgCore/Commands/ClockHistory.swift +7 −1 · view
@@ -90,7 +90,8 @@ public enum ClockHistory {
90 public static let defaultLength = 5 90 public static let defaultLength = 5
91 91
92 /// `org-clock-history-push`: `task` goes first, other entries for the same heading and 92 /// `org-clock-history-push`: `task` goes first, other entries for the same heading and
93 /// entries that are gone leave, and the oldest go past `length`. `text` reads a file. 93 /// entries that are gone leave, and the oldest go past `length`. `text` reads a file. Without
94 /// `ClockTask.titleKey`, hidden entries hashed with it are kept unchanged.
94 public static func push(_ task: ClockTask, onto history: [ClockTask], length: Int, text: (String) -> String?) -> [ClockTask] { 95 public static func push(_ task: ClockTask, onto history: [ClockTask], length: Int, text: (String) -> String?) -> [ClockTask] {
95 let length = max(1, length) 96 let length = max(1, length)
96 var texts: [String: String?] = [:] 97 var texts: [String: String?] = [:]
@@ -103,6 +104,11 @@ public enum ClockHistory {
103 let target = read(task.path).flatMap { task.locate(in: $0) } 104 let target = read(task.path).flatMap { task.locate(in: $0) }
104 var kept: [ClockTask] = [] 105 var kept: [ClockTask] = []
105 for entry in history { 106 for entry in history {
107 // A hidden task hashed with the kept key can't be found with this run's; it stays as it was.
108 if ClockTask.titleKey == nil, entry.titleHash.map({ !$0.hasPrefix("s:") }) == true {
109 kept.append(entry)
110 continue
111 }
106 guard let contents = read(entry.path), let current = entry.refreshed(in: contents) else { continue } 112 guard let contents = read(entry.path), let current = entry.refreshed(in: contents) else { continue }
107 if entry.path == task.path, let target, current.locate(in: contents) == target { continue } 113 if entry.path == task.path, let target, current.locate(in: contents) == target { continue }
108 kept.append(current) 114 kept.append(current)
Sources/OrgDocument/Crypt.swift +7 −7 · view
@@ -40,18 +40,18 @@ 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. 43 /// By file: the bytes the last write replaced and the bytes it wrote, as on disk.
44 private var replacedBytes: [String: [UInt8]] = [:] 44 private var replacedBytes: [String: (replaced: [UInt8], written: [UInt8])] = [:]
45 45
46 /// The bytes the last write to `path` replaced, as they were on disk; given once. 46 /// The bytes the last write to `path` replaced and the bytes it wrote, as on disk; given once.
47 public func takeReplaced(for path: String) -> [UInt8]? { 47 public func takeReplaced(for path: String) -> (replaced: [UInt8], written: [UInt8])? {
48 let key = Self.key(path) 48 let key = Self.key(path)
49 return locked { replacedBytes.removeValue(forKey: key) } 49 return locked { replacedBytes.removeValue(forKey: key) }
50 } 50 }
51 51
52 func noteReplaced(_ bytes: [UInt8]?, for path: String) { 52 func noteReplaced(_ bytes: [UInt8]?, written: [UInt8], for path: String) {
53 let key = Self.key(path) 53 let key = Self.key(path)
54 locked { replacedBytes[key] = bytes } 54 locked { replacedBytes[key] = bytes.map { ($0, written) } }
55 } 55 }
56 56
57 /// 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.
@@ -311,7 +311,7 @@ public struct CryptFileSystem: FileSystem {
311 let known = vault.revealedMessages(for: url.path) 311 let known = vault.revealedMessages(for: url.path)
312 let written = try vault.cipher(bytes, for: url.path) 312 let written = try vault.cipher(bytes, for: url.path)
313 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) 314 vault.noteReplaced(replaced, written: written.bytes, for: url.path)
315 // 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
316 // the encrypted file's last bytes still decrypt from memory). 316 // the encrypted file's last bytes still decrypt from memory).
317 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 }
Tests/OrgAppTests/CryptReviewTests.swift +44 −2 · view
@@ -187,6 +187,19 @@ struct CryptReviewTests {
187 #expect(session.document(of: b.path)?.text.contains("EMACSWORK") == true) 187 #expect(session.document(of: b.path)?.text.contains("EMACSWORK") == true)
188 } 188 }
189 189
190 @Test func aVersionWrittenAfterOursIsntOverwrittenByTheRestore() throws {
191 let files = InjectingFileSystem()
192 let session = DocumentSession(fileSystem: files, recovery: FileRecoveryStore(directory: recoveryFolder))
193 session.encryptsTaggedEntries = true
194 session.hasStoredPassphrase = { _ in false }
195 let b = try notes.write("b.org", "* B\nb\n")
196 files.inject[b.path] = "* B\nb\n* Emacs :crypt:\nemacs secret\n"
197 files.injectAfter[b.path] = "* B\nthird\n"
198 let message = session.applyChanges([TextEdit(range: 4..<5, replacement: "c")], to: b.path, expecting: "* B\nb\n")
199 #expect(message?.contains("changed on disk") == true)
200 #expect(read(b) == "* B\nthird\n")
201 }
202
190 // Final check, 2 203 // Final check, 2
191 @Test func sameFileMovesDontTakeAHeadingOutOfItsEntry() throws { 204 @Test func sameFileMovesDontTakeAHeadingOutOfItsEntry() throws {
192 let text = "#+ARCHIVE: ::* Archive\n* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n" 205 let text = "#+ARCHIVE: ::* Archive\n* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
@@ -227,6 +240,31 @@ struct CryptReviewTests {
227 #expect(!read(clockFile).contains("s:")) 240 #expect(!read(clockFile).contains("s:"))
228 } 241 }
229 242
243 @Test func aRunWithoutTheKeyKeepsHiddenTasksHashedWithIt() throws {
244 let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Plain\n"
245 try notes.write("a.org", text)
246 ClockTask.titleKey = SymmetricKey(size: .bits256)
247 let earlier = ClockTask(path: file.path, title: "Secret task", ordinal: 1, id: nil).hiding("Encrypted entry")
248 ClockTask.titleKey = nil
249 defer { ClockTask.titleKey = nil }
250 let clockFile = notes.url.appendingPathComponent("clock.json")
251 try JSONEncoder().encode(["history": [earlier]]).write(to: clockFile)
252 let clock = ClockModel(file: clockFile)
253 #expect(clock.history == [earlier])
254 session.open(file.path)
255 session.cryptUsed("pw", for: file.path)
256 _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
257 _ = clock.clockOut(session)
258 let now = try #require(session.document(of: file.path)?.text)
259 _ = clock.clockIn(session, path: file.path, at: (now as NSString).range(of: "* Plain").location)
260 _ = clock.clockOut(session)
261 // The earlier entry stays as it was; this run's hidden entry isn't written.
262 #expect(clock.history.count == 3 && clock.history.last == earlier)
263 let saved = read(clockFile)
264 #expect(saved.contains(try #require(earlier.titleHash)) && !saved.contains("s:"))
265 #expect(!saved.contains("Secret task"))
266 }
267
230 // Third review, C 268 // Third review, C
231 @Test func hiddenClockTasksNeedTheirTitle() throws { 269 @Test func hiddenClockTasksNeedTheirTitle() throws {
232 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry") 270 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
@@ -472,15 +510,19 @@ struct CryptReviewTests {
472 } 510 }
473} 511}
474 512
475/// The disk, with another writer that puts `inject[path]` in place just before a replace. 513/// The disk, with another writer that puts `inject[path]` in place just before a replace, and
514/// a third that puts `injectAfter[path]` in place just after one.
476final class InjectingFileSystem: FileSystem, @unchecked Sendable { 515final class InjectingFileSystem: FileSystem, @unchecked Sendable {
477 let base = CoordinatedFileSystem(writesInPlaceWhenDenied: false) 516 let base = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
478 var inject: [String: String] = [:] 517 var inject: [String: String] = [:]
518 var injectAfter: [String: String] = [:]
479 519
480 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) } 520 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
481 521
482 func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? { 522 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) } 523 if let text = inject.removeValue(forKey: url.path) { try Data(text.utf8).write(to: url) }
484 return try base.replace(url, with: bytes) 524 let replaced = try base.replace(url, with: bytes)
525 if let text = injectAfter.removeValue(forKey: url.path) { try Data(text.utf8).write(to: url) }
526 return replaced
485 } 527 }
486} 528}
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