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 {
7272
7373 private func save() {
7474 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 }
7577 if running != nil || !history.isEmpty, let data = try? JSONEncoder().encode(Saved(running: running, history: history)) {
7678 try? data.write(to: file, options: .atomic)
7779 } else {
Sources/OrgApp/CryptPassphrases.swift +42 · view
@@ -1,3 +1,4 @@
1import CryptoKit
12import Foundation
23import LocalAuthentication
34import OrgDocument
@@ -147,6 +148,38 @@ public enum CryptPassphrases {
147148 }
148149}
149150
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
150183extension CryptHold {
151184 /// Whether giving the passphrase lets the file be saved.
152185 public var takesPassphrase: Bool {
@@ -166,6 +199,15 @@ extension CryptHold {
166199 }
167200}
168201
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
169211extension CryptHold: LocalizedError {
170212 public var errorDescription: String? {
171213 switch self {
Sources/OrgApp/DocumentSession.swift +28 −9 · view
@@ -611,6 +611,19 @@ public final class DocumentSession {
611611 Saver(fileSystem: WriteReporting(base: fileSystem) { [weak self] url in MainActor.assumeIsolated { self?.fileWritten?(url.path) } }, recovery: recovery)
612612 }
613613
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
614627 private func scheduleAutosave(_ entry: Entry) {
615628 entry.autosave?.cancel()
616629 // A held file whose edits were undone, or whose tagged entries went, isn't held.
@@ -876,7 +889,7 @@ public final class DocumentSession {
876889 @discardableResult
877890 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
878891 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 {
880893 switch prepareMove(path, context: context, to: target.path) {
881894 case .refused(let message): return message
882895 case .sealed(let heading):
@@ -916,7 +929,7 @@ public final class DocumentSession {
916929 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
917930 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
918931 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." }
920933 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
921934 return done
922935 } catch {
@@ -953,7 +966,7 @@ public final class DocumentSession {
953966 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
954967 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
955968 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.")) }
957970 return .success(target(start, level, FileRecord.hash(state.mergeBase)))
958971 } catch {
959972 return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
@@ -1016,6 +1029,12 @@ public final class DocumentSession {
10161029 /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
10171030 /// since the tag they inherit doesn't go with them.
10181031 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 }
10191038 // The target's passphrase, lent by the source for the move, isn't kept after it.
10201039 if Self.isEncryptedFile(target), !isOpen(target) {
10211040 DispatchQueue.main.async { [weak self] in
@@ -1063,7 +1082,7 @@ public final class DocumentSession {
10631082 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") }
10641083 var state = loaded(bytes, path: path)
10651084 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.") }
10671086 } catch {
10681087 return .refused("Can't encrypt the entry: \(error.localizedDescription)")
10691088 }
@@ -1087,8 +1106,8 @@ public final class DocumentSession {
10871106 case .success(let value): destination = value
10881107 case .failure(.message(let message)): return message
10891108 }
1090 if !destination.isSameFile {
1091 switch prepareMove(path, context: context, to: destination.path) {
1109 do {
1110 switch prepareMove(path, context: context, to: destination.isSameFile ? path : destination.path) {
10921111 case .refused(let message): return message
10931112 case .sealed(let heading):
10941113 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 {
11261145 }
11271146 if let archiveEdit = edits.archive {
11281147 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." }
11301149 }
11311150 if let message = applySource(edits.source, path: path, now: now) { return message }
11321151 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
@@ -1196,7 +1215,7 @@ public final class DocumentSession {
11961215 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
11971216 guard matches(state.text) else { return stale }
11981217 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) {
12001219 return .failed("\(name) changed on disk; nothing was changed.")
12011220 }
12021221 if case .commit = step { textChanged?(path) }
@@ -1239,7 +1258,7 @@ public final class DocumentSession {
12391258 guard state.text == expected else { return stale }
12401259 try recovery.keep(bytes, for: url, label: "replace")
12411260 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." }
12431262 textChanged?(path)
12441263 return nil
12451264 } catch {
Sources/OrgCore/Commands/ClockHistory.swift +22 −3 · view
@@ -1,3 +1,4 @@
1import CryptoKit
12import Foundation
23
34// Clock history and task selection (`org-clock-history`, `org-clock-history-push`,
@@ -13,9 +14,27 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
1314 public let ordinal: Int
1415 public let id: String?
1516 /// 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.
1718 public let titleHash: String?
1819
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
1938 public init(path: String, title: String, ordinal: Int, id: String?, titleHash: String? = nil) {
2039 self.path = path
2140 self.title = title
@@ -37,7 +56,7 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
3756 public func index(in model: DocumentModel) -> Int? {
3857 if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index }
3958 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 }
4160 if ordinal < model.headings.count, matches(ordinal) { return ordinal }
4261 return model.headings.indices.first(where: matches)
4362 }
@@ -62,7 +81,7 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
6281 /// The task with `placeholder` for its title, or as it is with nil.
6382 public func hiding(_ placeholder: String?) -> ClockTask {
6483 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))
6685 }
6786}
6887
Sources/OrgDocument/Crypt.swift +15 · view
@@ -40,6 +40,20 @@ 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]] = [:]
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
4357 /// By encrypted file: its bytes on disk and their text, last read or written.
4458 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:]
4559
@@ -297,6 +311,7 @@ public struct CryptFileSystem: FileSystem {
297311 let known = vault.revealedMessages(for: url.path)
298312 let written = try vault.cipher(bytes, for: url.path)
299313 let replaced = try base.replace(url, with: written.bytes)
314 vault.noteReplaced(replaced, for: url.path)
300315 // The version replaced, as it read before this write's messages were known (and while
301316 // the encrypted file's last bytes still decrypt from memory).
302317 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 {
3737
3838public enum SaveError: Error, Equatable {
3939 case fileKeepsChanging
40 /// Another writer's version, replaced by ours and not kept, was put back; ours isn't on disk.
41 case otherVersionRestored
4042}
4143
4244/// The save sequence from the design: read, merge if the file moved, check again, replace,
@@ -46,6 +48,11 @@ public struct Saver: Sendable {
4648 public let fileSystem: FileSystem
4749 public let recovery: RecoveryStore
4850 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)?
4956
5057 public init(fileSystem: FileSystem, recovery: RecoveryStore) {
5158 self.fileSystem = fileSystem
@@ -74,7 +81,7 @@ public struct Saver: Sendable {
7481 let replaced = try fileSystem.replace(url, with: bytes)
7582 state.didWrite(bytes)
7683 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))
7885 }
7986
8087 if let after = try fileSystem.read(url), after != bytes {
@@ -98,7 +105,7 @@ public struct Saver: Sendable {
98105 let replaced = try fileSystem.replace(url, with: bytes)
99106 state.didWrite(bytes)
100107 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)
102109 }
103110 }
104111
@@ -106,7 +113,16 @@ public struct Saver: Sendable {
106113 /// recovery and, when `merge`, merged into the buffer. When recovery can't keep it (it holds
107114 /// text that can only be kept encrypted, without a passphrase) and it isn't merged, it goes
108115 /// 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 }
110126 let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([])
111127 do {
112128 try recovery.keep(replaced, for: url, label: "external")
Sources/Orgstar/OrgstarApp.swift +1 · view
@@ -477,6 +477,7 @@ struct OrgstarApp: App {
477477 @State private var clock = ClockModel()
478478 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
479479 @State private var session: DocumentSession = {
480 ClockTask.titleKey = ClockTitleKey.loadOrCreate()
480481 let session = DocumentSession()
481482 session.defaults = Preferences.orgSettings
482483 // 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 {
2626 #endif
2727 LiveClock.install()
2828 ProStore.shared.start()
29 ClockTask.titleKey = ClockTitleKey.loadOrCreate()
2930 // Read before the app becomes active and clears it.
3031 _ = UnsavedHeldFiles.atLaunch
3132 // 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
12import Foundation
23import OrgCore
34import OrgDocument
@@ -136,6 +137,96 @@ struct CryptReviewTests {
136137 #expect(session.subtreeShare(file.path, at: b) == nil)
137138 }
138139
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
139230 // Third review, C
140231 @Test func hiddenClockTasksNeedTheirTitle() throws {
141232 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
@@ -380,3 +471,16 @@ struct CryptReviewTests {
380471 #expect(item[kSecAttrAccessible as String] == nil)
381472 }
382473}
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
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.
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.
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.
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. 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."
972972- 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.
973973- 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.
975975
976976* Encrypted files
977977
l10n/Localizable.xcstrings +68 · view
@@ -44511,6 +44511,40 @@
4451144511 }
4451244512 }
4451344513 },
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 },
4451444548 "The file has no passphrase yet": {
4451544549 "localizations": {
4451644550 "de": {
@@ -44579,6 +44613,40 @@
4457944613 }
4458044614 }
4458144615 },
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 },
4458244650 "The folder and its files stay on disk.": {
4458344651 "localizations": {
4458444652 "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