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 {
613613
614614 /// The saver for a file that isn't open, whose state is thrown away after the save: a
615615 /// 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.
617617 private var closedFileSaver: Saver {
618618 var saver = saver
619619 let crypt = crypt, disk = diskFileSystem
620620 saver.restoreOverwritten = { url in
621 guard let theirs = crypt.takeReplaced(for: url.path) else { return }
622 _ = try disk.replace(url, with: theirs)
621 guard let last = crypt.takeReplaced(for: url.path), try disk.read(url) == last.written else { return }
622 _ = try disk.replace(url, with: last.replaced)
623623 }
624624 return saver
625625 }
Sources/OrgCore/Commands/ClockHistory.swift +7 −1 · view
@@ -90,7 +90,8 @@ public enum ClockHistory {
9090 public static let defaultLength = 5
9191
9292 /// `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.
9495 public static func push(_ task: ClockTask, onto history: [ClockTask], length: Int, text: (String) -> String?) -> [ClockTask] {
9596 let length = max(1, length)
9697 var texts: [String: String?] = [:]
@@ -103,6 +104,11 @@ public enum ClockHistory {
103104 let target = read(task.path).flatMap { task.locate(in: $0) }
104105 var kept: [ClockTask] = []
105106 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 }
106112 guard let contents = read(entry.path), let current = entry.refreshed(in: contents) else { continue }
107113 if entry.path == task.path, let target, current.locate(in: contents) == target { continue }
108114 kept.append(current)
Sources/OrgDocument/Crypt.swift +7 −7 · view
@@ -40,18 +40,18 @@ public final class CryptVault: @unchecked Sendable {
4040 private var sealing: Set<String> = []
4141 /// Files open in a buffer. Only they keep what the vault knows past a write.
4242 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]] = [:]
43 /// By file: the bytes the last write replaced and the bytes it wrote, as on disk.
44 private var replacedBytes: [String: (replaced: [UInt8], written: [UInt8])] = [:]
4545
46 /// The bytes the last write to `path` replaced, as they were on disk; given once.
47 public func takeReplaced(for path: String) -> [UInt8]? {
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) -> (replaced: [UInt8], written: [UInt8])? {
4848 let key = Self.key(path)
4949 return locked { replacedBytes.removeValue(forKey: key) }
5050 }
5151
52 func noteReplaced(_ bytes: [UInt8]?, for path: String) {
52 func noteReplaced(_ bytes: [UInt8]?, written: [UInt8], for path: String) {
5353 let key = Self.key(path)
54 locked { replacedBytes[key] = bytes }
54 locked { replacedBytes[key] = bytes.map { ($0, written) } }
5555 }
5656
5757 /// By encrypted file: its bytes on disk and their text, last read or written.
@@ -311,7 +311,7 @@ public struct CryptFileSystem: FileSystem {
311311 let known = vault.revealedMessages(for: url.path)
312312 let written = try vault.cipher(bytes, for: url.path)
313313 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)
315315 // The version replaced, as it read before this write's messages were known (and while
316316 // the encrypted file's last bytes still decrypt from memory).
317317 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 {
187187 #expect(session.document(of: b.path)?.text.contains("EMACSWORK") == true)
188188 }
189189
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
190203 // Final check, 2
191204 @Test func sameFileMovesDontTakeAHeadingOutOfItsEntry() throws {
192205 let text = "#+ARCHIVE: ::* Archive\n* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
@@ -227,6 +240,31 @@ struct CryptReviewTests {
227240 #expect(!read(clockFile).contains("s:"))
228241 }
229242
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
230268 // Third review, C
231269 @Test func hiddenClockTasksNeedTheirTitle() throws {
232270 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
@@ -472,15 +510,19 @@ struct CryptReviewTests {
472510 }
473511}
474512
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.
476515final class InjectingFileSystem: FileSystem, @unchecked Sendable {
477516 let base = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
478517 var inject: [String: String] = [:]
518 var injectAfter: [String: String] = [:]
479519
480520 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
481521
482522 func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
483523 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
485527 }
486528}
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