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

open opened by cmc on 2026-11-26 08:44 UTC · krz/orgstar:m5-crypt into main

16 files changed, +683 −91

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

Layout: unified · split

Changed files (16)
Sources/OrgApp/ClockModel.swift +6 −2 · view
@@ -114,7 +114,7 @@ public final class ClockModel {
114 guard let updated = Self.text(path, session), let start = ClockIn.runningStart(in: updated, near: heading) else { 114 guard let updated = Self.text(path, session), let start = ClockIn.runningStart(in: updated, near: heading) else {
115 return "The clock line wasn't found after clocking in." 115 return "The clock line wasn't found after clocking in."
116 } 116 }
117 running = Running(path: path, start: start, heading: entry.title, startedAt: now) 117 running = Running(path: path, start: start, heading: session.shareableTitle(entry.title, path: path, heading: heading), startedAt: now)
118 if let task = ClockTask.at(heading, in: updated, path: path) { push(task, session) } 118 if let task = ClockTask.at(heading, in: updated, path: path) { push(task, session) }
119 save() 119 save()
120 watched = clockedHeading(path, session) 120 watched = clockedHeading(path, session)
@@ -307,6 +307,9 @@ public final class ClockModel {
307 // MARK: - History 307 // MARK: - History
308 308
309 private func push(_ task: ClockTask, _ session: DocumentSession) { 309 private func push(_ task: ClockTask, _ session: DocumentSession) {
310 // The history is kept in the clock's file and shown by the widgets.
311 let heading = Self.text(task.path, session).flatMap(task.locate) ?? 0
312 let task = ClockTask(path: task.path, title: session.shareableTitle(task.title, path: task.path, heading: heading), ordinal: task.ordinal, id: task.id)
310 history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) } 313 history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) }
311 } 314 }
312 315
@@ -527,7 +530,8 @@ public final class ClockModel {
527 let headings = DocumentModel(tree: OrgParser.parse(text)).headings 530 let headings = DocumentModel(tree: OrgParser.parse(text)).headings
528 for clock in open { 531 for clock in open {
529 guard let startedAt = ClockResolution.date(of: clock.start) else { continue } 532 guard let startedAt = ClockResolution.date(of: clock.start) else { continue }
530 let heading = headings.last { $0.headingRange.lowerBound <= clock.offset }?.title ?? "" 533 let entry = headings.last { $0.headingRange.lowerBound <= clock.offset }
534 let heading = entry.map { session.shareableTitle($0.title, path: path, heading: $0.headingRange.lowerBound) } ?? ""
531 clocks.append(OpenClock(path: path, start: clock.start, startedAt: startedAt, heading: heading)) 535 clocks.append(OpenClock(path: path, start: clock.start, startedAt: startedAt, heading: heading))
532 } 536 }
533 } 537 }
Sources/OrgApp/CryptPassphrases.swift +70 −15 · view
@@ -3,44 +3,99 @@ import LocalAuthentication
3import OrgDocument 3import OrgDocument
4import Security 4import Security
5 5
6/// Passphrases for encrypted entries, kept in the Keychain by file when asked, and given back 6/// Passphrases for encrypted entries and files, kept in the Keychain by file path when asked.
7/// only after Touch ID, Face ID or the device's password. 7/// Items are readable only on this device while it's unlocked, and only after Touch ID, Face
8/// ID or the device's password (`.userPresence`); one authentication covers the reads that
9/// follow for a while. Items earlier versions stored without that move over at their first read.
8public enum CryptPassphrases { 10public enum CryptPassphrases {
9 static let service = "sh.krz.orgstar.crypt" 11 static let service = "sh.krz.orgstar.crypt.v2"
12 /// Where earlier versions kept passphrases, readable without authentication.
13 static let legacyService = "sh.krz.orgstar.crypt"
10 14
11 static func query(_ path: String) -> [String: Any] { 15 /// The authentication reads share.
12 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path] 16 nonisolated(unsafe) static let context: LAContext = {
17 let context = LAContext()
18 context.touchIDAuthenticationAllowableReuseDuration = LATouchIDAuthenticationMaximumAllowableReuseDuration
19 return context
20 }()
21
22 static func query(_ path: String, service: String = service) -> [String: Any] {
23 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
24 if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true }
25 return query
13 } 26 }
14 27
15 public static func store(_ passphrase: String, for path: String) { 28 /// The new item for `passphrase`: this device only, unlocked, after user presence.
16 forget(path) 29 static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
30 guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
17 var item = query(path) 31 var item = query(path)
18 item[kSecValueData as String] = Data(passphrase.utf8) 32 item[kSecValueData as String] = Data(passphrase.utf8)
33 item[kSecAttrAccessControl as String] = access
19 item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent 34 item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
20 SecItemAdd(item as CFDictionary, nil) 35 return item
36 }
37
38 public static func store(_ passphrase: String, for path: String) {
39 forget(path)
40 guard let item = newItem(passphrase, for: path) else { return }
41 if SecItemAdd(item as CFDictionary, nil) == errSecMissingEntitlement {
42 // A build without a Keychain entitlement (development) keeps the old kind of item.
43 var legacy = query(path, service: legacyService)
44 legacy[kSecValueData as String] = Data(passphrase.utf8)
45 legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
46 SecItemAdd(legacy as CFDictionary, nil)
47 }
21 } 48 }
22 49
23 public static func forget(_ path: String) { 50 public static func forget(_ path: String) {
24 SecItemDelete(query(path) as CFDictionary) 51 SecItemDelete(query(path) as CFDictionary)
52 SecItemDelete(query(path, service: legacyService) as CFDictionary)
25 } 53 }
26 54
27 public static func hasStored(_ path: String) -> Bool { 55 /// Whether an item exists, without asking for authentication.
28 var q = query(path) 56 static func exists(_ query: [String: Any]) -> Bool {
57 var q = query
58 let quiet = LAContext()
59 quiet.interactionNotAllowed = true
60 q[kSecUseAuthenticationContext as String] = quiet
29 q[kSecReturnAttributes as String] = true 61 q[kSecReturnAttributes as String] = true
30 return SecItemCopyMatching(q as CFDictionary, nil) == errSecSuccess 62 let status = SecItemCopyMatching(q as CFDictionary, nil)
63 return status == errSecSuccess || status == errSecInteractionNotAllowed
64 }
65
66 public static func hasStored(_ path: String) -> Bool {
67 exists(query(path)) || exists(query(path, service: legacyService))
31 } 68 }
32 69
33 /// The stored passphrase, once the person has proved who they are; nil otherwise. 70 /// The stored passphrase, once the person has proved who they are; nil otherwise.
34 public static func stored(for path: String) async -> String? { 71 public static func stored(for path: String) async -> String? {
35 guard hasStored(path) else { return nil }
36 let context = LAContext()
37 let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent 72 let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
73 if exists(query(path)) {
74 var q = query(path)
75 q[kSecReturnData as String] = true
76 let context = Self.context
77 context.localizedReason = reason
78 q[kSecUseAuthenticationContext as String] = context
79 let request = q
80 // The read waits for Touch ID or the password, off the main thread.
81 return await Task.detached { () -> String? in
82 var result: AnyObject?
83 guard SecItemCopyMatching(request as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
84 return String(decoding: data, as: UTF8.self)
85 }.value
86 }
87 guard exists(query(path, service: legacyService)) else { return nil }
38 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil } 88 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
39 var q = query(path) 89 var q = query(path, service: legacyService)
40 q[kSecReturnData as String] = true 90 q[kSecReturnData as String] = true
41 var result: AnyObject? 91 var result: AnyObject?
42 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } 92 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
43 return String(decoding: data, as: UTF8.self) 93 let passphrase = String(decoding: data, as: UTF8.self)
94 // Moved to the protected kind of item; kept as it was where that can't be made.
95 if let item = newItem(passphrase, for: path), SecItemAdd(item as CFDictionary, nil) == errSecSuccess {
96 SecItemDelete(query(path, service: legacyService) as CFDictionary)
97 }
98 return passphrase
44 } 99 }
45} 100}
46 101
Sources/OrgApp/DocumentSession.swift +128 −3 · view
@@ -260,6 +260,21 @@ public final class DocumentSession {
260 crypt.forgetPassphrase(for: path) 260 crypt.forgetPassphrase(for: path)
261 } 261 }
262 262
263 /// `title`, of the heading at `heading` in `path`, as it may be shown and kept outside
264 /// the editor (the clock's file, widgets, the Live Activity, the menu bar): a placeholder
265 /// for a heading of an encrypted file or one inside an entry that's encrypted on disk.
266 public func shareableTitle(_ title: String, path: String, heading: Int) -> String {
267 let hidden = Self.isEncryptedFile(path)
268 || (crypt.sealsEntries(for: path) && document(of: path).map { OrgCrypt.isInTaggedText($0.text, at: heading, tag: cryptTag) } == true)
269 return hidden ? String(localized: "Encrypted entry") : title
270 }
271
272 /// Why a copy of the buffer can't be kept, with what to do; the buffer's notice shows.
273 private func keepFailure(_ hold: CryptHold) -> String {
274 if let current { _ = updateHold(current) }
275 return hold.localizedDescription + ". " + String(localized: "Give the passphrase with Encrypt… first, so that a copy of your edits can be kept encrypted.")
276 }
277
263 /// Whether `path`'s buffer is held back from disk now. 278 /// Whether `path`'s buffer is held back from disk now.
264 private func updateHold(_ entry: Entry) -> CryptHold? { 279 private func updateHold(_ entry: Entry) -> CryptHold? {
265 let hold = entry.buffer.document.isDirty ? crypt.hold(entry.buffer.document.text, for: entry.path) : nil 280 let hold = entry.buffer.document.isDirty ? crypt.hold(entry.buffer.document.text, for: entry.path) : nil
@@ -380,6 +395,34 @@ public final class DocumentSession {
380 return Dictionary(shown.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a }) 395 return Dictionary(shown.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
381 } 396 }
382 397
398 /// The text of `path` for an export that writes files (iCalendar, publishing): an open
399 /// buffer's, unless it holds what's encrypted on disk, then what's on disk; nil for an
400 /// encrypted file.
401 public func exportText(of path: String) -> String? {
402 if Self.isEncryptedFile(path) { return nil }
403 if let entry = entry(path), !crypt.isPrivate(entry.buffer.document.text, for: entry.path) { return entry.buffer.document.text }
404 return (try? diskFileSystem.read(URL(fileURLWithPath: path))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
405 }
406
407 /// Whether `exportText` leaves `path` out or reads it from disk for what's encrypted.
408 public func exportLeavesOut(_ path: String) -> Bool {
409 Self.isEncryptedFile(path) || entry(path).map { crypt.isPrivate($0.buffer.document.text, for: $0.path) } == true
410 }
411
412 /// Why the buffer of `path` isn't copied to a temporary file for Emacs (recalculating,
413 /// exporting, `elisp:` links): it's an encrypted file, or holds entries encrypted on disk.
414 public func refusesEmacsCopy(_ path: String) -> String? {
415 let name = (path as NSString).lastPathComponent
416 if Self.isEncryptedFile(path) { return String(localized: "\(name) is encrypted, so Emacs isn't given a copy of it.") }
417 guard let entry = entry(path), crypt.isPrivate(entry.buffer.document.text, for: entry.path) else { return nil }
418 return String(localized: "\(name) has decrypted entries that are encrypted on disk, so Emacs isn't given a copy of it.")
419 }
420
421 /// Said after an export that left out encrypted files or read decrypted entries from disk.
422 public static var exportNote: String {
423 String(localized: "Encrypted files were left out, and encrypted entries were exported as they are on disk.")
424 }
425
383 /// Open buffers, most recently shown first. 426 /// Open buffers, most recently shown first.
384 public var recentPaths: [String] { history.filter(isOpen) } 427 public var recentPaths: [String] { history.filter(isOpen) }
385 428
@@ -646,6 +689,8 @@ public final class DocumentSession {
646 let path = url.path 689 let path = url.path
647 buffer.update { $0 = loaded(bytes, path: path) } 690 buffer.update { $0 = loaded(bytes, path: path) }
648 current?.conflict = nil 691 current?.conflict = nil
692 } catch let hold as CryptHold {
693 showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
649 } catch { 694 } catch {
650 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)") 695 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
651 } 696 }
@@ -673,6 +718,8 @@ public final class DocumentSession {
673 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision) 718 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
674 } 719 }
675 current?.conflict = nil 720 current?.conflict = nil
721 } catch let hold as CryptHold {
722 showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
676 } catch { 723 } catch {
677 showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)") 724 showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)")
678 } 725 }
@@ -750,6 +797,8 @@ public final class DocumentSession {
750 guard let buffer, let url else { return "Can't read that version" } 797 guard let buffer, let url else { return "Can't read that version" }
751 do { 798 do {
752 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") 799 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
800 } catch let hold as CryptHold {
801 return keepFailure(hold)
753 } catch { 802 } catch {
754 return "Can't keep the current version: \(error.localizedDescription)" 803 return "Can't keep the current version: \(error.localizedDescription)"
755 } 804 }
@@ -799,7 +848,16 @@ public final class DocumentSession {
799 /// path; the subtree leaves its file only once it has. Returns a message for the echo area. 848 /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
800 @discardableResult 849 @discardableResult
801 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? { 850 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
802 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } 851 guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
852 if target.path != path {
853 switch prepareMove(path, context: context, to: target.path) {
854 case .refused(let message): return message
855 case .sealed(let heading):
856 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
857 context = again.context
858 case .ready: break
859 }
860 }
803 let done = (keep ? "Copied to " : "Refiled to ") + target.label 861 let done = (keep ? "Copied to " : "Refiled to ") + target.label
804 if target.path == path { 862 if target.path == path {
805 let answers = ["refile": target.start.map(String.init) ?? ""] 863 let answers = ["refile": target.start.map(String.init) ?? ""]
@@ -919,6 +977,61 @@ public final class DocumentSession {
919 return (TextEdit(range: at..<at, replacement: insertion), newStart, level) 977 return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
920 } 978 }
921 979
980 private enum MovePreparation {
981 case ready
982 /// Tagged entries in the subtree were encrypted in its file; its heading starts here.
983 case sealed(Int)
984 case refused(String)
985 }
986
987 /// Before the subtree at the caret of `context`, in `path`, moves to the file `target`: an
988 /// encrypted file's entries go only to another encrypted file, which takes the same
989 /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
990 /// since the tag they inherit doesn't go with them.
991 private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation {
992 let from = (path as NSString).lastPathComponent, to = (target as NSString).lastPathComponent
993 if Self.isEncryptedFile(path) {
994 guard Self.isEncryptedFile(target) else {
995 return .refused(String(localized: "\(from) is encrypted, and \(to) isn't; the entry wasn't moved."))
996 }
997 if crypt.passphrase(for: target) == nil, let passphrase = crypt.passphrase(for: path) {
998 let disk = (try? diskFileSystem.read(URL(fileURLWithPath: target))).flatMap { $0 } ?? []
999 guard CryptVault.opens(disk, passphrase: passphrase) else {
1000 return .refused(String(localized: "\(to) has another passphrase; open it first."))
1001 }
1002 crypt.unlock(passphrase, for: target)
1003 }
1004 }
1005 guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(context.text, at: context.selection.first?.lowerBound ?? 0) else { return .ready }
1006 let end = OrgCrypt.bodyRange(context.text, at: heading)?.upperBound ?? heading
1007 let subtree = heading..<max(heading + 1, end)
1008 guard !OrgCrypt.unencrypted(context.text, tag: cryptTag, within: subtree).isEmpty else { return .ready }
1009 guard let passphrase = crypt.passphrase(for: path) else {
1010 return .refused(String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first."))
1011 }
1012 let sealed: String
1013 do {
1014 sealed = try OrgCrypt.seal(context.text, passphrase: passphrase, tag: cryptTag, within: subtree).text
1015 } catch {
1016 return .refused("\(error)")
1017 }
1018 let edit = EditResult(baseRevision: context.revision, edits: lineEdits(from: context.text, to: sealed))
1019 if let open = entry(path) {
1020 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: Date(), answers: [:]) { return .refused(message) }
1021 changed(open)
1022 } else {
1023 do {
1024 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") }
1025 var state = loaded(bytes, path: path)
1026 try state.apply(edit.edits, baseRevision: state.revision)
1027 if case .conflict = try saver.save(&state, to: URL(fileURLWithPath: path)) { return .refused("\(from) changed on disk; nothing was moved.") }
1028 } catch {
1029 return .refused("Can't encrypt the entry: \(error.localizedDescription)")
1030 }
1031 }
1032 return .sealed(heading)
1033 }
1034
922 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell. 1035 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell.
923 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? { 1036 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
924 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil } 1037 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil }
@@ -929,12 +1042,21 @@ public final class DocumentSession {
929 /// Returns a message. 1042 /// Returns a message.
930 @discardableResult 1043 @discardableResult
931 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? { 1044 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
932 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } 1045 guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
933 let destination: Archive.Destination 1046 let destination: Archive.Destination
934 switch Archive.destination(context, sourcePath: path) { 1047 switch Archive.destination(context, sourcePath: path) {
935 case .success(let value): destination = value 1048 case .success(let value): destination = value
936 case .failure(.message(let message)): return message 1049 case .failure(.message(let message)): return message
937 } 1050 }
1051 if !destination.isSameFile {
1052 switch prepareMove(path, context: context, to: destination.path) {
1053 case .refused(let message): return message
1054 case .sealed(let heading):
1055 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
1056 context = again.context
1057 case .ready: break
1058 }
1059 }
938 // An archive file open in a buffer takes the subtree there. 1060 // An archive file open in a buffer takes the subtree there.
939 if !destination.isSameFile, let open = entry(destination.path) { 1061 if !destination.isSameFile, let open = entry(destination.path) {
940 let state = open.buffer.document 1062 let state = open.buffer.document
@@ -1059,7 +1181,9 @@ public final class DocumentSession {
1059 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." } 1181 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1060 guard state.text == expected else { return stale } 1182 guard state.text == expected else { return stale }
1061 if entry.buffer is StateBuffer { 1183 if entry.buffer is StateBuffer {
1062 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch { 1184 // A buffer held for its passphrase keeps no copy: it can't be kept encrypted,
1185 // and the replacement can be undone in the buffer.
1186 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch is CryptHold {} catch {
1063 return "Can't keep a copy of \(name): \(error.localizedDescription)" 1187 return "Can't keep a copy of \(name): \(error.localizedDescription)"
1064 } 1188 }
1065 } 1189 }
@@ -1098,6 +1222,7 @@ public final class DocumentSession {
1098 } 1222 }
1099 guard let entry = current else { return "No file is open." } 1223 guard let entry = current else { return "No file is open." }
1100 let path = entry.path 1224 let path = entry.path
1225 if let refusal = refusesEmacsCopy(path) { return refusal }
1101 let snapshot = entry.buffer.document.text as NSString 1226 let snapshot = entry.buffer.document.text as NSString
1102 guard table.upperBound <= snapshot.length else { return "The table moved; try again." } 1227 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
1103 let old = snapshot.substring(with: NSRange(table)) 1228 let old = snapshot.substring(with: NSRange(table))
Sources/OrgApp/LinkFollow.swift +1 −1 · view
@@ -82,7 +82,7 @@ extension DocumentSession {
82 /// Evaluates an `elisp:` link's form as `org-link--open-elisp` does: in Emacs, in a copy of 82 /// Evaluates an `elisp:` link's form as `org-link--open-elisp` does: in Emacs, in a copy of
83 /// the open file, when `programs` has it, otherwise in `Elisp`. Returns the message to show. 83 /// the open file, when `programs` has it, otherwise in `Elisp`. Returns the message to show.
84 public func evaluateLink(_ form: String) async -> String { 84 public func evaluateLink(_ form: String) async -> String {
85 if let programs = Self.runner, let path, let text = document?.text { 85 if let programs = Self.runner, let path, let text = document?.text, refusesEmacsCopy(path) == nil {
86 let directory = URL(fileURLWithPath: path).deletingLastPathComponent() 86 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
87 do { 87 do {
88 if let value = try await programs.evaluateLisp(form, text: text, point: caret(of: path) ?? 0, directory: directory) { 88 if let value = try await programs.evaluateLisp(form, text: text, point: caret(of: path) ?? 0, directory: directory) {
Sources/OrgCore/Commands/Archive.swift +6 −1 · view
@@ -195,7 +195,7 @@ public enum Archive {
195 let name = (sourcePath as NSString).lastPathComponent 195 let name = (sourcePath as NSString).lastPathComponent
196 let fileFormat = String(spec[..<separator.lowerBound]) 196 let fileFormat = String(spec[..<separator.lowerBound])
197 let headingFormat = String(spec[separator.upperBound...]) 197 let headingFormat = String(spec[separator.upperBound...])
198 let path: String 198 var path: String
199 if fileFormat.contains(where: { !$0.isWhitespace }) { 199 if fileFormat.contains(where: { !$0.isWhitespace }) {
200 let file = fileFormat.replacingOccurrences(of: "%s", with: name) 200 let file = fileFormat.replacingOccurrences(of: "%s", with: name)
201 let directory = (sourcePath as NSString).deletingLastPathComponent 201 let directory = (sourcePath as NSString).deletingLastPathComponent
@@ -203,6 +203,11 @@ public enum Archive {
203 } else { 203 } else {
204 path = sourcePath 204 path = sourcePath
205 } 205 }
206 // An encrypted file archives to an encrypted file: `diary.org.gpg` to
207 // `diary_archive.org.gpg`, not Org's `diary.org.gpg_archive`.
208 if sourcePath.hasSuffix(".gpg"), !path.hasSuffix(".gpg") {
209 path = path.hasSuffix(".org.gpg_archive") ? String(path.dropLast(".org.gpg_archive".count)) + "_archive.org.gpg" : path + ".gpg"
210 }
206 let heading = headingFormat.replacingOccurrences(of: "%s", with: name) 211 let heading = headingFormat.replacingOccurrences(of: "%s", with: name)
207 return .success(Destination(path: (path as NSString).standardizingPath, heading: heading.isEmpty ? nil : heading, isSameFile: path == sourcePath)) 212 return .success(Destination(path: (path as NSString).standardizingPath, heading: heading.isEmpty ? nil : heading, isSameFile: path == sourcePath))
208 } 213 }
Sources/OrgCore/Crypto/OpenPGP.swift +76 −12 · view
@@ -194,27 +194,81 @@ public enum OpenPGP {
194 } 194 }
195 195
196 /// RFC 4880 3.7.1: as many hashes as the key needs, each preloaded with one more zero. 196 /// RFC 4880 3.7.1: as many hashes as the key needs, each preloaded with one more zero.
197 /// The iterated input is hashed as it's made, a block at a time.
197 func key(_ passphrase: String, size: Int) throws -> Data { 198 func key(_ passphrase: String, size: Int) throws -> Data {
198 let material = salt + Data(passphrase.utf8) 199 let material = salt + Data(passphrase.utf8)
199 var key = Data() 200 var key = Data()
200 var round = 0 201 var round = 0
201 while key.count < size { 202 while key.count < size {
202 var input = Data(repeating: 0, count: round) 203 var hasher = try Hasher(hash)
204 hasher.update(Data(repeating: 0, count: round))
203 if type == 3 { 205 if type == 3 {
204 let total = max(count, material.count) 206 let total = max(count, material.count)
205 var stream = Data(capacity: total) 207 // Whole copies of the material, about 64 KB of them, then what's left.
206 while stream.count < total { stream.append(material.prefix(total - stream.count)) } 208 var block = Data()
207 input.append(stream) 209 let copies = max(1, 65_536 / max(1, material.count))
210 for _ in 0..<copies { block.append(material) }
211 var left = total
212 while left >= block.count {
213 hasher.update(block)
214 left -= block.count
215 }
216 if left > 0 { hasher.update(block.prefix(left)) }
208 } else { 217 } else {
209 input.append(material) 218 hasher.update(material)
210 } 219 }
211 key.append(try OpenPGP.hash(hash, input)) 220 key.append(hasher.finish())
212 round += 1 221 round += 1
213 } 222 }
214 return key.prefix(size) 223 return key.prefix(size)
215 } 224 }
216 } 225 }
217 226
227 /// One of the hashes `hash` supports, fed in parts.
228 struct Hasher {
229 private var md5: Insecure.MD5?
230 private var sha1: Insecure.SHA1?
231 private var sha256: SHA256?
232 private var sha384: SHA384?
233 private var sha512: SHA512?
234 private var sha224: CC_SHA256_CTX?
235
236 init(_ algorithm: Int) throws {
237 switch algorithm {
238 case 1: md5 = Insecure.MD5()
239 case 2: sha1 = Insecure.SHA1()
240 case 8: sha256 = SHA256()
241 case 9: sha384 = SHA384()
242 case 10: sha512 = SHA512()
243 case 11:
244 var context = CC_SHA256_CTX()
245 CC_SHA224_Init(&context)
246 sha224 = context
247 default: throw Failure("Hash algorithm \(algorithm) isn't supported")
248 }
249 }
250
251 mutating func update(_ data: Data) {
252 if md5 != nil { md5!.update(data: data) }
253 if sha1 != nil { sha1!.update(data: data) }
254 if sha256 != nil { sha256!.update(data: data) }
255 if sha384 != nil { sha384!.update(data: data) }
256 if sha512 != nil { sha512!.update(data: data) }
257 if sha224 != nil { data.withUnsafeBytes { _ = CC_SHA224_Update(&sha224!, $0.baseAddress, CC_LONG(data.count)) } }
258 }
259
260 mutating func finish() -> Data {
261 if let md5 { return Data(md5.finalize()) }
262 if let sha1 { return Data(sha1.finalize()) }
263 if let sha256 { return Data(sha256.finalize()) }
264 if let sha384 { return Data(sha384.finalize()) }
265 if let sha512 { return Data(sha512.finalize()) }
266 var digest = [UInt8](repeating: 0, count: Int(CC_SHA224_DIGEST_LENGTH))
267 _ = CC_SHA224_Final(&digest, &sha224!)
268 return Data(digest)
269 }
270 }
271
218 // MARK: - AES in CFB 272 // MARK: - AES in CFB
219 273
220 static func cfb(_ data: Data, key: Data, iv: Data = Data(repeating: 0, count: 16), encrypt: Bool) throws -> Data { 274 static func cfb(_ data: Data, key: Data, iv: Data = Data(repeating: 0, count: 16), encrypt: Bool) throws -> Data {
@@ -234,12 +288,21 @@ public enum OpenPGP {
234 return Data(out.prefix(moved)) 288 return Data(out.prefix(moved))
235 } 289 }
236 290
237 static func random(_ count: Int) -> Data { 291 static func random(_ count: Int) throws -> Data {
238 var bytes = [UInt8](repeating: 0, count: count) 292 var bytes = [UInt8](repeating: 0, count: count)
239 _ = SecRandomCopyBytes(kSecRandomDefault, count, &bytes) 293 guard SecRandomCopyBytes(kSecRandomDefault, count, &bytes) == errSecSuccess else { throw Failure("No random bytes for the salt") }
240 return Data(bytes) 294 return Data(bytes)
241 } 295 }
242 296
297 /// The coded iteration count new messages use: 65,011,712 bytes hashed, GnuPG's most.
298 static let codedCount: UInt8 = 0xFF
299
300 /// Whether `message` (packets) is encrypted with a passphrase: its first packet is a
301 /// symmetric-key session packet, not one for a public key.
302 public static func isSymmetric(_ message: Data) -> Bool {
303 (try? packets(message))?.first?.tag == 3
304 }
305
243 // MARK: - Messages 306 // MARK: - Messages
244 307
245 public static let wrongPassphrase = Failure("Bad session key") 308 public static let wrongPassphrase = Failure("Bad session key")
@@ -345,13 +408,14 @@ public enum OpenPGP {
345 408
346 /// `gpg --symmetric` without `--armor`: the packets of `encrypt`. 409 /// `gpg --symmetric` without `--armor`: the packets of `encrypt`.
347 public static func encryptedMessage(_ data: Data, passphrase: String, now: Date = Date()) throws -> Data { 410 public static func encryptedMessage(_ data: Data, passphrase: String, now: Date = Date()) throws -> Data {
348 let salt = random(8) 411 let salt = try random(8)
349 let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (96 & 15)) << ((96 >> 4) + 6)) 412 let c = Int(codedCount)
413 let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (c & 15)) << ((c >> 4) + 6))
350 let key = try s2k.key(passphrase, size: 32) 414 let key = try s2k.key(passphrase, size: 32)
351 let skesk = packet(3, Data([4, 9, 3, 8]) + salt + Data([96])) 415 let skesk = packet(3, Data([4, 9, 3, 8]) + salt + Data([codedCount]))
352 let date = UInt32(max(0, now.timeIntervalSince1970)) 416 let date = UInt32(max(0, now.timeIntervalSince1970))
353 let literal = packet(11, Data([0x62, 0]) + Data((0..<4).reversed().map { UInt8((date >> ($0 * 8)) & 0xff) }) + data) 417 let literal = packet(11, Data([0x62, 0]) + Data((0..<4).reversed().map { UInt8((date >> ($0 * 8)) & 0xff) }) + data)
354 var prefix = random(16) 418 var prefix = try random(16)
355 prefix.append(prefix.suffix(2)) 419 prefix.append(prefix.suffix(2))
356 var plain = prefix + literal + Data([0xD3, 0x14]) 420 var plain = prefix + literal + Data([0xD3, 0x14])
357 plain.append(Data(Insecure.SHA1.hash(data: plain))) 421 plain.append(Data(Insecure.SHA1.hash(data: plain)))
Sources/OrgCore/Crypto/OrgCrypt.swift +55 −15 · view
@@ -136,41 +136,69 @@ public enum OrgCrypt {
136 return (text, count) 136 return (text, count)
137 } 137 }
138 138
139 /// What saving does with the tagged entry at `heading`: nil when nothing (its text is a
140 /// message, or it has no text), else its text's range, the message at its start if any,
141 /// and whether it has text that isn't blank outside a message.
142 static func pending(_ text: String, at heading: Int) -> (body: Range<Int>, message: Range<Int>?, hasText: Bool)? {
143 guard let body = bodyRange(text, at: heading) else { return nil }
144 let ns = text as NSString
145 func blank(_ range: Range<Int>) -> Bool {
146 range.isEmpty || ns.substring(with: NSRange(range)).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
147 }
148 if let message = encryptedRange(text, at: heading) {
149 // Text typed below the message isn't encrypted.
150 let tail = min(message.upperBound, body.upperBound)..<max(message.upperBound, body.upperBound)
151 return blank(tail) ? nil : (body, message, true)
152 }
153 return (body, nil, !blank(body))
154 }
155
139 /// The tagged entries `seal` encrypts whose text isn't blank: those a save can't write 156 /// The tagged entries `seal` encrypts whose text isn't blank: those a save can't write
140 /// without the passphrase. Their headings' offsets. 157 /// without the passphrase, text below a message included. Their headings' offsets.
141 public static func unencrypted(_ text: String, tag: String = "crypt", settings: OrgSettings = .default) -> [Int] { 158 public static func unencrypted(_ text: String, tag: String = "crypt", settings: OrgSettings = .default, within: Range<Int>? = nil) -> [Int] {
142 guard text.contains(tag) else { return [] } 159 guard text.contains(tag) else { return [] }
143 let ns = text as NSString
144 var found: [Int] = [] 160 var found: [Int] = []
145 var covered = 0 161 var covered = 0
146 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered { 162 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered && within?.contains(heading) ?? true {
147 guard encryptedRange(text, at: heading) == nil, let range = bodyRange(text, at: heading) else { continue } 163 guard let entry = pending(text, at: heading) else { continue }
148 // Tagged children go inside this entry's message. 164 // Tagged children go inside this entry's message.
149 covered = range.upperBound 165 covered = entry.body.upperBound
150 if !ns.substring(with: NSRange(range)).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { found.append(heading) } 166 if entry.hasText { found.append(heading) }
151 } 167 }
152 return found 168 return found
153 } 169 }
154 170
155 /// `org-encrypt-entries` as `org-crypt-use-before-save-magic` runs it before a save. An 171 /// `org-encrypt-entries` as `org-crypt-use-before-save-magic` runs it before a save. An
156 /// entry whose text `reuse` knows by its `checksum` gets that message again, as org-crypt 172 /// entry whose text `reuse` knows by its `checksum` gets that message again, as org-crypt
157 /// keeps an entry decrypted and left unchanged byte for byte. The text, and each message 173 /// keeps an entry decrypted and left unchanged byte for byte. Text below an entry's message
158 /// with the text it holds. 174 /// goes into one message with what the old one held. The text, and each message with the
175 /// text the entry had.
159 public static func seal( 176 public static func seal(
160 _ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default, 177 _ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default,
161 reuse: (String) -> String? = { _ in nil }, now: Date = Date() 178 reuse: (String) -> String? = { _ in nil }, within: Range<Int>? = nil, now: Date = Date()
162 ) throws -> (text: String, messages: [(message: String, plaintext: String)]) { 179 ) throws -> (text: String, messages: [(message: String, plaintext: String)]) {
163 guard text.contains(tag) else { return (text, []) } 180 guard text.contains(tag) else { return (text, []) }
164 var result = text as NSString 181 var result = text as NSString
165 var messages: [(String, String)] = [] 182 var messages: [(String, String)] = []
166 var shift = 0 183 var shift = 0
167 var covered = 0 184 var covered = 0
168 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered { 185 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered && within?.contains(heading) ?? true {
169 let current = result as String 186 let current = result as String
170 guard encryptedRange(current, at: heading + shift) == nil, let range = bodyRange(current, at: heading + shift) else { continue } 187 guard let entry = pending(current, at: heading + shift) else { continue }
188 let range = entry.body
171 covered = range.upperBound - shift 189 covered = range.upperBound - shift
172 let contents = result.substring(with: NSRange(range)) 190 let contents = result.substring(with: NSRange(range))
173 let message = try reuse(checksum(contents)) ?? OpenPGP.encrypt(Data(contents.utf8), passphrase: passphrase, now: now) 191 var plaintext = contents
192 if let old = entry.message {
193 let opened: String
194 do {
195 opened = try decrypt(current, at: heading + shift, passphrase: passphrase).plaintext
196 } catch {
197 throw Failure("An entry has text below a message that this passphrase doesn't open; entries encrypted to a public key aren't supported")
198 }
199 plaintext = opened + result.substring(with: NSRange(old.upperBound..<range.upperBound))
200 }
201 let message = try reuse(checksum(contents)) ?? OpenPGP.encrypt(Data(plaintext.utf8), passphrase: passphrase, now: now)
174 result = result.replacingCharacters(in: NSRange(range), with: message) as NSString 202 result = result.replacingCharacters(in: NSRange(range), with: message) as NSString
175 shift += (message as NSString).length - range.count 203 shift += (message as NSString).length - range.count
176 messages.append((message, contents)) 204 messages.append((message, contents))
@@ -178,12 +206,21 @@ public enum OrgCrypt {
178 return (result as String, messages) 206 return (result as String, messages)
179 } 207 }
180 208
209 /// Whether `offset` is in the text of an entry with `tag`, which a message holds on disk.
210 public static func isInTaggedText(_ text: String, at offset: Int, tag: String = "crypt", settings: OrgSettings = .default) -> Bool {
211 guard text.contains(tag) else { return false }
212 return taggedHeadings(text, tag: tag, settings: settings).contains { heading in
213 heading < offset && (bodyRange(text, at: heading)?.contains(offset) ?? false)
214 }
215 }
216
181 /// What an entry's text is known by, as `org-crypt-checksum` is. 217 /// What an entry's text is known by, as `org-crypt-checksum` is.
182 public static func checksum(_ contents: String) -> String { 218 public static func checksum(_ contents: String) -> String {
183 SHA256.hash(data: Data(contents.utf8)).map { String(format: "%02x", $0) }.joined() 219 SHA256.hash(data: Data(contents.utf8)).map { String(format: "%02x", $0) }.joined()
184 } 220 }
185 221
186 /// The first encrypted entry's message in `text`. 222 /// The first entry's message in `text` encrypted with a passphrase; entries encrypted to a
223 /// public key are passed over.
187 public static func firstMessage(_ text: String) -> String? { 224 public static func firstMessage(_ text: String) -> String? {
188 let ns = text as NSString 225 let ns = text as NSString
189 var search = NSRange(location: 0, length: ns.length) 226 var search = NSRange(location: 0, length: ns.length)
@@ -191,7 +228,10 @@ public enum OrgCrypt {
191 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", options: [], range: search) 228 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", options: [], range: search)
192 guard begin.location != NSNotFound else { return nil } 229 guard begin.location != NSNotFound else { return nil }
193 let lineStart = ns.lineRange(for: NSRange(location: begin.location, length: 0)).location 230 let lineStart = ns.lineRange(for: NSRange(location: begin.location, length: 0)).location
194 if let range = encryptedRange(text, at: lineStart), range.lowerBound == lineStart { return ns.substring(with: NSRange(range)) } 231 if let range = encryptedRange(text, at: lineStart), range.lowerBound == lineStart {
232 let message = ns.substring(with: NSRange(range))
233 if let data = try? OpenPGP.dearmor(message), OpenPGP.isSymmetric(data) { return message }
234 }
195 search = NSRange(location: NSMaxRange(begin), length: ns.length - NSMaxRange(begin)) 235 search = NSRange(location: NSMaxRange(begin), length: ns.length - NSMaxRange(begin))
196 } 236 }
197 } 237 }
Sources/OrgDocument/Crypt.swift +61 −21 · view
@@ -32,6 +32,11 @@ public final class CryptVault: @unchecked Sendable {
32 private var revealed: [String: [String: String]] = [:] 32 private var revealed: [String: [String: String]] = [:]
33 /// By file: whether the encrypted file was armored when read. 33 /// By file: whether the encrypted file was armored when read.
34 private var armored: [String: Bool] = [:] 34 private var armored: [String: Bool] = [:]
35 /// Files that seal tagged entries until they close, whatever the setting says now: those
36 /// it was on for, so that turning it off never writes what was encrypted in plaintext.
37 private var sealing: Set<String> = []
38 /// By encrypted file: its bytes on disk and their text, last read or written.
39 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:]
35 40
36 public init() {} 41 public init() {}
37 42
@@ -62,13 +67,30 @@ public final class CryptVault: @unchecked Sendable {
62 locked { passphrases[Self.key(path)] } 67 locked { passphrases[Self.key(path)] }
63 } 68 }
64 69
70 /// Whether saving `key` seals its tagged entries: the setting is on, or was while the
71 /// file was open. Call with the lock held.
72 private func seals(_ key: String) -> Bool {
73 if entries { sealing.insert(key) }
74 return entries || sealing.contains(key) || !(revealed[key]?.isEmpty ?? true)
75 }
76
77 /// Whether saving `path` encrypts its tagged entries.
78 public func sealsEntries(for path: String) -> Bool {
79 let key = Self.key(path)
80 return locked { seals(key) }
81 }
82
65 /// `passphrase` encrypts and decrypts `path` until it's forgotten. Messages kept for reuse 83 /// `passphrase` encrypts and decrypts `path` until it's forgotten. Messages kept for reuse
66 /// under another passphrase are dropped. 84 /// under another passphrase are dropped.
67 public func unlock(_ passphrase: String, for path: String) { 85 public func unlock(_ passphrase: String, for path: String) {
68 let key = Self.key(path) 86 let key = Self.key(path)
69 locked { 87 locked {
70 if passphrases[key] != passphrase { reuse[key] = nil } 88 if passphrases[key] != passphrase {
89 reuse[key] = nil
90 lastFile[key] = nil
91 }
71 passphrases[key] = passphrase 92 passphrases[key] = passphrase
93 _ = seals(key)
72 } 94 }
73 } 95 }
74 96
@@ -89,6 +111,8 @@ public final class CryptVault: @unchecked Sendable {
89 reuse[key] = nil 111 reuse[key] = nil
90 revealed[key] = nil 112 revealed[key] = nil
91 armored[key] = nil 113 armored[key] = nil
114 sealing.remove(key)
115 lastFile[key] = nil
92 } 116 }
93 } 117 }
94 118
@@ -96,13 +120,17 @@ public final class CryptVault: @unchecked Sendable {
96 /// so, saving writes `message` back unchanged. 120 /// so, saving writes `message` back unchanged.
97 public func remember(message: String, plaintext: String, for path: String) { 121 public func remember(message: String, plaintext: String, for path: String) {
98 let key = Self.key(path) 122 let key = Self.key(path)
99 locked { reuse[key, default: [:]][OrgCrypt.checksum(plaintext)] = message } 123 locked {
124 reuse[key, default: [:]][OrgCrypt.checksum(plaintext)] = message
125 _ = seals(key)
126 }
100 } 127 }
101 128
102 /// What keeps `text`, the buffer of `path`, from being written: tagged entries without a 129 /// What keeps `text`, the buffer of `path`, from being written: tagged entries without a
103 /// known passphrase, or an encrypted file without one. Nil when it can be written. 130 /// known passphrase, or an encrypted file without one. Nil when it can be written.
104 public func hold(_ text: String, for path: String) -> CryptHold? { 131 public func hold(_ text: String, for path: String) -> CryptHold? {
105 let (passphrase, entries, tag) = locked { (passphrases[Self.key(path)], self.entries, entryTag) } 132 let key = Self.key(path)
133 let (passphrase, entries, tag) = locked { (passphrases[key], seals(key), entryTag) }
106 guard passphrase == nil else { return nil } 134 guard passphrase == nil else { return nil }
107 if Self.isEncryptedFile(path) { return .file } 135 if Self.isEncryptedFile(path) { return .file }
108 guard entries else { return nil } 136 guard entries else { return nil }
@@ -115,8 +143,9 @@ public final class CryptVault: @unchecked Sendable {
115 /// of what other views read and keep (`DocumentSession.openTexts`). 143 /// of what other views read and keep (`DocumentSession.openTexts`).
116 public func isPrivate(_ text: String, for path: String) -> Bool { 144 public func isPrivate(_ text: String, for path: String) -> Bool {
117 if Self.isEncryptedFile(path) { return true } 145 if Self.isEncryptedFile(path) { return true }
118 let (entries, tag) = locked { (self.entries, entryTag) } 146 let key = Self.key(path)
119 return entries && !OrgCrypt.unencrypted(text, tag: tag).isEmpty 147 let (entries, tag, revealing) = locked { (seals(key), entryTag, !(revealed[key]?.isEmpty ?? true)) }
148 return revealing || (entries && !OrgCrypt.unencrypted(text, tag: tag).isEmpty)
120 } 149 }
121 150
122 // MARK: - Reading and writing 151 // MARK: - Reading and writing
@@ -142,9 +171,9 @@ public final class CryptVault: @unchecked Sendable {
142 /// `bytes`, the buffer of `path`, as the file holds them: tagged entries encrypted, then 171 /// `bytes`, the buffer of `path`, as the file holds them: tagged entries encrypted, then
143 /// the file encrypted, and the messages written for entries. Throws `CryptHold` when a 172 /// the file encrypted, and the messages written for entries. Throws `CryptHold` when a
144 /// passphrase is needed and not known. 173 /// passphrase is needed and not known.
145 public func cipher(_ bytes: [UInt8], for path: String) throws -> (bytes: [UInt8], messages: [(message: String, plaintext: String)]) { 174 public func cipher(_ bytes: [UInt8], for path: String) throws -> (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?) {
146 let key = Self.key(path) 175 let key = Self.key(path)
147 let (passphrase, entries, tag, known) = locked { (passphrases[key], self.entries, entryTag, reuse[key] ?? [:]) } 176 let (passphrase, entries, tag, known) = locked { (passphrases[key], seals(key), entryTag, reuse[key] ?? [:]) }
148 var bytes = bytes 177 var bytes = bytes
149 var messages: [(String, String)] = [] 178 var messages: [(String, String)] = []
150 if entries, let text = Self.text(bytes), text.contains(tag) { 179 if entries, let text = Self.text(bytes), text.contains(tag) {
@@ -159,17 +188,23 @@ public final class CryptVault: @unchecked Sendable {
159 } 188 }
160 if Self.isEncryptedFile(path) { 189 if Self.isEncryptedFile(path) {
161 guard let passphrase else { throw CryptHold.file } 190 guard let passphrase else { throw CryptHold.file }
191 let plain = bytes
162 let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase) 192 let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase)
163 bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message) 193 bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message)
194 return (bytes, messages, plain)
164 } 195 }
165 return (bytes, messages) 196 return (bytes, messages, nil)
166 } 197 }
167 198
168 /// The messages in a file `cipher` gave were written: reading it back gives their text. 199 /// `cipher`'s result was written to `path`: reading it back gives the messages' text, and
169 public func didWrite(_ messages: [(message: String, plaintext: String)], to path: String) { 200 /// an unchanged entry keeps its message at the next save. Messages no longer in the file
201 /// are forgotten.
202 public func didWrite(_ written: (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?), to path: String) {
170 let key = Self.key(path) 203 let key = Self.key(path)
171 locked { 204 locked {
172 for (message, plaintext) in messages { revealed[key, default: [:]][message] = plaintext } 205 revealed[key] = Dictionary(written.messages.map { ($0.message, $0.plaintext) }, uniquingKeysWith: { a, _ in a })
206 reuse[key] = Dictionary(written.messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) }, uniquingKeysWith: { a, _ in a })
207 if let plain = written.plain { lastFile[key] = (written.bytes, plain) }
173 } 208 }
174 } 209 }
175 210
@@ -183,11 +218,16 @@ public final class CryptVault: @unchecked Sendable {
183 guard !bytes.isEmpty else { return [] } 218 guard !bytes.isEmpty else { return [] }
184 let key = Self.key(path) 219 let key = Self.key(path)
185 guard let passphrase = locked({ passphrases[key] }) else { throw CryptReadError.locked } 220 guard let passphrase = locked({ passphrases[key] }) else { throw CryptReadError.locked }
221 // Saving reads the file two or three times; each key costs 65 MB of hashing.
222 if let last = locked({ lastFile[key] }), last.encrypted == bytes { return last.plain }
186 let data = Data(bytes) 223 let data = Data(bytes)
187 do { 224 do {
188 let plain = try OpenPGP.decryptFile(data, passphrase: passphrase) 225 let plain = [UInt8](try OpenPGP.decryptFile(data, passphrase: passphrase))
189 locked { armored[key] = OpenPGP.isArmored(data) } 226 locked {
190 return [UInt8](plain) 227 armored[key] = OpenPGP.isArmored(data)
228 lastFile[key] = (bytes, plain)
229 }
230 return plain
191 } catch let failure as OpenPGP.Failure { 231 } catch let failure as OpenPGP.Failure {
192 throw failure == OpenPGP.wrongPassphrase ? CryptReadError.wrongPassphrase : CryptReadError.failed(failure.description) 232 throw failure == OpenPGP.wrongPassphrase ? CryptReadError.wrongPassphrase : CryptReadError.failed(failure.description)
193 } 233 }
@@ -217,16 +257,17 @@ public struct CryptFileSystem: FileSystem {
217 257
218 public func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? { 258 public func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
219 let known = vault.revealedMessages(for: url.path) 259 let known = vault.revealedMessages(for: url.path)
220 let (encrypted, messages) = try vault.cipher(bytes, for: url.path) 260 let written = try vault.cipher(bytes, for: url.path)
221 let replaced = try base.replace(url, with: encrypted) 261 let replaced = try base.replace(url, with: written.bytes)
222 vault.didWrite(messages, to: url.path) 262 vault.didWrite(written, to: url.path)
223 // The version replaced, as it read before this write's messages were known. 263 // The version replaced, as it read before this write's messages were known.
224 return replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 } 264 return replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 }
225 } 265 }
226} 266}
227 267
228/// Recovery versions and snapshots through a `CryptVault`: kept encrypted as the file is, or 268/// Recovery versions and snapshots through a `CryptVault`: kept encrypted as the file is. When
229/// not kept when that needs a passphrase that isn't known. 269/// that needs a passphrase that isn't known, `keep` throws `CryptHold`, so a caller that
270/// promises a copy stops; a snapshot is skipped.
230public struct CryptRecoveryStore: RecoveryStore { 271public struct CryptRecoveryStore: RecoveryStore {
231 public let base: RecoveryStore 272 public let base: RecoveryStore
232 public let vault: CryptVault 273 public let vault: CryptVault
@@ -237,8 +278,7 @@ public struct CryptRecoveryStore: RecoveryStore {
237 } 278 }
238 279
239 public func keep(_ bytes: [UInt8], for url: URL, label: String) throws { 280 public func keep(_ bytes: [UInt8], for url: URL, label: String) throws {
240 guard let encrypted = try? vault.cipher(bytes, for: url.path).bytes else { return } 281 try base.keep(try vault.cipher(bytes, for: url.path).bytes, for: url, label: label)
241 try base.keep(encrypted, for: url, label: label)
242 } 282 }
243 283
244 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws { 284 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
Sources/Orgstar/ContentView.swift +9 −8 · view
@@ -760,6 +760,7 @@ struct ContentView: View {
760 #if !APPSTORE 760 #if !APPSTORE
761 let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"] 761 let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
762 guard let function = functions[format] else { return } 762 guard let function = functions[format] else { return }
763 if let refusal = session.refusesEmacsCopy(path) { return commands.show(refusal) }
763 commands.show(String(localized: "Exporting with Emacs…")) 764 commands.show(String(localized: "Exporting with Emacs…"))
764 commands.runInEmacs { 765 commands.runInEmacs {
765 do { 766 do {
@@ -889,17 +890,18 @@ struct ContentView: View {
889 let paths = workspace.agendaFilePaths() 890 let paths = workspace.agendaFilePaths()
890 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return } 891 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
891 let read = { (path: String) -> (text: String, settings: OrgSettings)? in 892 let read = { (path: String) -> (text: String, settings: OrgSettings)? in
892 guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil } 893 guard let text = session.exportText(of: path) else { return nil }
893 return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)) 894 return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
894 } 895 }
896 let note = paths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
895 do { 897 do {
896 let options = OrgPreferences.icalendarOptions() 898 let options = OrgPreferences.icalendarOptions()
897 if combined { 899 if combined {
898 let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read) 900 let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
899 commands.show(String(localized: "Exported \(paths.count) agenda files to \(url.lastPathComponent)")) 901 commands.show(String(localized: "Exported \(paths.count) agenda files to \(url.lastPathComponent)") + note)
900 } else { 902 } else {
901 let written = try ICalendarFiles.exportEach(paths, options: options, read: read) 903 let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
902 commands.show(String(localized: "Exported \(written.count) agenda files to iCalendar")) 904 commands.show(String(localized: "Exported \(written.count) agenda files to iCalendar") + note)
903 } 905 }
904 } catch { 906 } catch {
905 commands.show(String(localized: "Can't export: \(error.localizedDescription)")) 907 commands.show(String(localized: "Can't export: \(error.localizedDescription)"))
@@ -1092,9 +1094,8 @@ struct ContentView: View {
1092 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first) 1094 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
1093 if let problem = loaded.problems.first { commands.show(problem) } 1095 if let problem = loaded.problems.first { commands.show(problem) }
1094 guard !loaded.projects.isEmpty else { return commands.show(String(localized: "No [[publish]] projects in config.toml")) } 1096 guard !loaded.projects.isEmpty else { return commands.show(String(localized: "No [[publish]] projects in config.toml")) }
1095 let read = { (path: String) -> String? in 1097 let read = { (path: String) -> String? in session.exportText(of: path) }
1096 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) 1098 let note = session.openPaths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
1097 }
1098 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme) 1099 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
1099 func run(_ chosen: [PublishProject], only: String? = nil) { 1100 func run(_ chosen: [PublishProject], only: String? = nil) {
1100 // The chosen projects and their components read and write these folders. 1101 // The chosen projects and their components read and write these folders.
@@ -1104,8 +1105,8 @@ struct ContentView: View {
1104 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in 1105 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
1105 try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle) 1106 try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle)
1106 } 1107 }
1107 commands.show(report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files") 1108 commands.show((report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
1108 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) 1109 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) + note)
1109 } catch { 1110 } catch {
1110 commands.show("\(error)") 1111 commands.show("\(error)")
1111 } 1112 }
Sources/Orgstar/OrgstarApp.swift +3 · view
@@ -470,6 +470,9 @@ struct OrgstarApp: App {
470 @State private var session: DocumentSession = { 470 @State private var session: DocumentSession = {
471 let session = DocumentSession() 471 let session = DocumentSession()
472 session.defaults = Preferences.orgSettings 472 session.defaults = Preferences.orgSettings
473 // Before any window: capture and agenda edits can save before the main window opens.
474 session.encryptsTaggedEntries = OrgPreferences.cryptBeforeSave()
475 session.cryptTag = OrgPreferences.cryptTag()
473 return session 476 return session
474 }() 477 }()
475 478
Sources/OrgstarMobile/EditorScreen.swift +4 −3 · view
@@ -758,15 +758,16 @@ extension EditorScreen {
758 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))" 758 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
759 } 759 }
760 let read = { (file: String) -> String? in 760 let read = { (file: String) -> String? in
761 session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8)) 761 session.exportText(of: file)
762 } 762 }
763 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme) 763 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
764 // As the Export menu: no author unless the file has #+AUTHOR:. 764 // As the Export menu: no author unless the file has #+AUTHOR:.
765 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in 765 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
766 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "") 766 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
767 } 767 }
768 message = report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files") 768 let note = session.openPaths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
769 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date") 769 message = (report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
770 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) + note
770 } catch { 771 } catch {
771 message = "\(error)" 772 message = "\(error)"
772 } 773 }
Sources/OrgstarMobile/ExportMenu.swift +10 −5 · view
@@ -272,20 +272,25 @@ struct ExportItems: View {
272/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is. 272/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
273struct AgendaCalendars: Transferable { 273struct AgendaCalendars: Transferable {
274 let paths: [String] 274 let paths: [String]
275 /// The open files' text, which may not be saved yet. 275 /// The files' text for the export: open buffers', or what's on disk for those holding
276 let open: [String: String] 276 /// what's encrypted there; encrypted files are left out.
277 let texts: [String: String]
278 /// Said after the export when it left something out.
279 let note: String
277 280
278 /// Nil without agenda files. 281 /// Nil without agenda files.
279 @MainActor init?(model: MobileModel) { 282 @MainActor init?(model: MobileModel) {
280 guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil } 283 guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
281 self.paths = paths 284 self.paths = paths
282 open = Dictionary(model.session.openDocuments.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first }) 285 let session = model.session
286 texts = Dictionary(paths.compactMap { path in session.exportText(of: path).map { (path, $0) } }, uniquingKeysWith: { first, _ in first })
287 note = paths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
283 } 288 }
284 289
285 var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent } 290 var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
286 291
287 private func read(_ path: String) -> (text: String, settings: OrgSettings)? { 292 private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
288 guard let text = open[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil } 293 guard let text = texts[path] else { return nil }
289 return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)) 294 return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
290 } 295 }
291 296
@@ -293,7 +298,7 @@ struct AgendaCalendars: Transferable {
293 func exportEach() -> String { 298 func exportEach() -> String {
294 do { 299 do {
295 let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read) 300 let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
296 return String(localized: "Exported \(written.count) agenda files to iCalendar") 301 return String(localized: "Exported \(written.count) agenda files to iCalendar") + note
297 } catch { 302 } catch {
298 return "Can't export: \(error.localizedDescription)" 303 return "Can't export: \(error.localizedDescription)"
299 } 304 }
Tests/OrgAppTests/CryptReviewTests.swift added +213 · view
@@ -0,0 +1,213 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// What an encrypted entry or file must not leak, nor lose, past the save path.
8@MainActor
9struct CryptReviewTests {
10 static let secret = "Account 12345"
11 static let file = "* Plain\nOpen text.\n* Bank :crypt:\n\(secret)\n* Last\n"
12
13 let notes: Folder
14 let file: URL
15 let recoveryFolder: URL
16 let session: DocumentSession
17
18 init() throws {
19 notes = try Folder()
20 file = try notes.write("a.org", "* Plain\nOpen text.\n* Last\n")
21 recoveryFolder = notes.url.appendingPathComponent(".recovery")
22 session = DocumentSession(recovery: FileRecoveryStore(directory: recoveryFolder))
23 session.saveMode = .explicit
24 session.encryptsTaggedEntries = true
25 session.hasStoredPassphrase = { _ in false }
26 }
27
28 func replace(with text: String) throws {
29 let buffer = StateBuffer(session.document!)
30 session.attach(buffer)
31 try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: text)], baseRevision: $0.revision) }
32 session.bufferChanged()
33 }
34
35 func type(_ text: String, at offset: Int) throws {
36 let buffer = StateBuffer(session.document!)
37 session.attach(buffer)
38 try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
39 session.bufferChanged()
40 }
41
42 func read(_ url: URL) -> String { (try? String(contentsOf: url, encoding: .utf8)) ?? "" }
43 var disk: String { read(file) }
44
45 var recoveryFiles: [String] {
46 let files = FileManager.default.enumerator(at: recoveryFolder, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
47 return files.compactMap { try? Data(contentsOf: $0) }.map { String(decoding: $0, as: UTF8.self) }
48 }
49
50 func offset(of needle: String) -> Int { (session.document!.text as NSString).range(of: needle).location }
51
52 // 1
53 @Test func turningTheSettingOffKeepsSealingOpenFiles() throws {
54 session.open(file.path)
55 session.cryptUsed("pw", for: file.path)
56 try replace(with: Self.file)
57 #expect(session.save())
58 #expect(!disk.contains(Self.secret))
59 session.encryptsTaggedEntries = false
60 try type("x", at: 0)
61 #expect(session.save())
62 #expect(!disk.contains(Self.secret))
63 #expect(session.openTexts[file.path] == nil)
64 // A file opened after it was turned off is as before.
65 let other = try notes.write("b.org", Self.file)
66 session.open(other.path)
67 try type("y", at: 0)
68 #expect(session.save())
69 #expect(read(other).contains(Self.secret))
70 }
71
72 // 2
73 @Test func useDiskVersionOnAHeldFileKeepsTheEdits() throws {
74 session.open(file.path)
75 try replace(with: Self.file)
76 #expect(!session.save())
77 session.useDiskVersion()
78 #expect(session.document?.text == Self.file)
79 #expect(session.lastError?.contains("Encrypt…") == true)
80 #expect(session.restore(text: "* Plain\n")?.contains("Encrypt…") == true)
81 #expect(session.document?.text == Self.file)
82 #expect(recoveryFiles.isEmpty && disk == "* Plain\nOpen text.\n* Last\n")
83 }
84
85 // 3a
86 @Test func archivingAChildOfATaggedEntryEncryptsItFirst() throws {
87 let text = "* Parent :crypt:\nparent text\n** Child\nchild secret\n* Last\n"
88 try notes.write("a.org", text)
89 session.open(file.path)
90 let child = (text as NSString).range(of: "** Child").location
91 let archive = notes.url.appendingPathComponent("a.org_archive")
92 #expect(session.archive(from: (file.path, child))?.contains("Encrypt…") == true)
93 #expect(!FileManager.default.fileExists(atPath: archive.path))
94 session.cryptUsed("pw", for: file.path)
95 #expect(session.archive(from: (file.path, child)) == "Archived to a.org_archive")
96 #expect(!read(archive).contains("child secret") && read(archive).contains("-----BEGIN PGP MESSAGE-----"))
97 #expect(session.save())
98 #expect(!disk.contains("child secret") && !disk.contains("parent text"))
99 }
100
101 // 3b
102 @Test func encryptedFilesArchiveToEncryptedFilesAndRefileOnlyThere() throws {
103 let path = notes.url.appendingPathComponent("diary.org.gpg")
104 try OpenPGP.encryptedMessage(Data("* Monday\nDear diary.\n* Tuesday\nMore.\n".utf8), passphrase: "pw").write(to: path)
105 session.open(path.path)
106 #expect(session.unlock("pw", for: path.path) == nil)
107 let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
108 #expect(session.refile(to: target, from: (path.path, 0))?.contains("isn't") == true)
109 #expect(!disk.contains("Dear diary"))
110 #expect(session.archive(from: (path.path, 0)) == "Archived to diary_archive.org.gpg")
111 let archive = notes.url.appendingPathComponent("diary_archive.org.gpg")
112 #expect(!FileManager.default.fileExists(atPath: notes.url.appendingPathComponent("diary.org.gpg_archive").path))
113 let bytes = try Data(contentsOf: archive)
114 #expect(bytes.range(of: Data("Dear diary".utf8)) == nil)
115 #expect(String(decoding: try OpenPGP.decryptFile(bytes, passphrase: "pw"), as: UTF8.self).contains("Dear diary."))
116 // Capture into an encrypted file that isn't open writes nothing.
117 session.kill(path.path)
118 let template = CaptureTemplate(key: "d", name: "Diary", target: .file(path.path), template: "* %?")
119 if case .success = session.capture("* Captured secret\n", template: template, root: nil) { Issue.record("captured into a locked file") }
120 #expect(try Data(contentsOf: path).range(of: Data("Captured".utf8)) == nil)
121 }
122
123 // 5
124 @Test func textBelowAMessageIsHeldThenSealedWithIt() throws {
125 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
126 try notes.write("a.org", encrypted)
127 session.open(file.path)
128 try type("typed below\n", at: offset(of: "* Last"))
129 #expect(!session.save())
130 #expect(session.held[file.path] == .entries(1))
131 #expect(!disk.contains("typed below"))
132 #expect(session.unlock("pw", for: file.path) == nil)
133 #expect(!disk.contains("typed below"))
134 let bank = (disk as NSString).range(of: "* Bank").location
135 #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\ntyped below\n")
136 }
137
138 // 7
139 @Test func exportsLeaveOutWhatIsEncryptedOnDisk() throws {
140 session.open(file.path)
141 session.cryptUsed("pw", for: file.path)
142 try replace(with: Self.file)
143 #expect(session.save())
144 #expect(session.exportLeavesOut(file.path))
145 #expect(session.exportText(of: file.path) == disk)
146 #expect(session.exportText(of: file.path)?.contains(Self.secret) == false)
147 let gpg = notes.url.appendingPathComponent("d.org.gpg")
148 try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
149 session.open(gpg.path)
150 #expect(session.unlock("pw", for: gpg.path) == nil)
151 #expect(session.exportText(of: gpg.path) == nil && session.exportLeavesOut(gpg.path))
152 // Nor is either copied for Emacs.
153 #expect(session.refusesEmacsCopy(gpg.path) != nil && session.refusesEmacsCopy(file.path) != nil)
154 let plain = try notes.write("c.org", "* C\n")
155 session.open(plain.path)
156 #expect(session.exportText(of: plain.path) == "* C\n" && session.refusesEmacsCopy(plain.path) == nil)
157 }
158
159 // 8
160 @Test func clockingInDoesntKeepEncryptedTitles() throws {
161 let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Open task\n"
162 try notes.write("a.org", text)
163 session.open(file.path)
164 session.cryptUsed("pw", for: file.path)
165 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
166 _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
167 #expect(clock.running?.heading == "Encrypted entry")
168 #expect(clock.history.allSatisfy { $0.title != "Secret task" })
169 #expect(!read(notes.url.appendingPathComponent("clock.json")).contains("Secret task"))
170 #expect(session.shareableTitle("Bank", path: file.path, heading: 0) == "Bank")
171 #expect(session.shareableTitle("Monday", path: "/x/d.org.gpg", heading: 0) == "Encrypted entry")
172 _ = clock.clockOut(session)
173 #expect(session.save())
174 #expect(!disk.contains("Secret task") && !disk.contains("intro"))
175 }
176
177 // 9
178 @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
179 session.open(file.path)
180 session.cryptUsed("pw", for: file.path)
181 try replace(with: Self.file)
182 #expect(session.save())
183 let message = try #require(OrgCrypt.firstMessage(disk))
184 for n in 0..<5 {
185 try type("\(n)", at: 0)
186 #expect(session.save())
187 #expect(disk.contains(message))
188 }
189 #expect(session.crypt.revealedMessages(for: file.path).count == 1)
190 }
191
192 // 10
193 @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
194 // A public-key session packet (tag 1) where a message's packets start.
195 let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
196 try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
197 session.open(file.path)
198 try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
199 #expect(!session.save())
200 #expect(session.unlock("pw", for: file.path) == nil)
201 #expect(!disk.contains("new secret"))
202 #expect(disk.contains(publicKey))
203 }
204
205 // 6
206 @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
207 let item = try #require(CryptPassphrases.newItem("pw", for: "/x/a.org"))
208 #expect(item[kSecAttrAccessControl as String] != nil)
209 #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
210 #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
211 #expect(item[kSecAttrAccessible as String] == nil)
212 }
213}
Tests/OrgAppTests/CryptSaveTests.swift +5 −1 · view
@@ -130,8 +130,12 @@ struct CryptSaveTests {
130 session.open(file.path) 130 session.open(file.path)
131 try replace(with: Self.file) 131 try replace(with: Self.file)
132 #expect(!session.save()) 132 #expect(!session.save())
133 #expect(session.restore(text: "* Plain\nOpen text.\n* Other\n") == nil) 133 // No copy of the buffer can be kept, so the version isn't restored.
134 #expect(session.restore(text: "* Plain\nOpen text.\n* Other\n")?.contains("Encrypt…") == true)
135 #expect(session.document?.text == Self.file)
134 #expect(recoveryFiles.isEmpty) 136 #expect(recoveryFiles.isEmpty)
137 #expect(session.unlock("pw", for: file.path) == nil)
138 #expect(session.restore(text: "* Plain\nOpen text.\n* Other\n") == nil)
135 #expect(session.save()) 139 #expect(session.save())
136 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) }) 140 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
137 } 141 }
Tests/OrgCoreTests/CryptFileTests.swift +26 · view
@@ -29,6 +29,32 @@ struct CryptFileTests {
29 #expect(try OrgCrypt.seal("* A\ntext\n", passphrase: "pw").text == "* A\ntext\n") 29 #expect(try OrgCrypt.seal("* A\ntext\n", passphrase: "pw").text == "* A\ntext\n")
30 } 30 }
31 31
32 @Test func newMessagesUseGnuPGsIterationCount() throws {
33 let clock = ContinuousClock()
34 var message = Data()
35 let time = try clock.measure { message = try OpenPGP.encryptedMessage(Data("x".utf8), passphrase: "pw") }
36 let first = try #require(try OpenPGP.packets(message).first)
37 // Version 4, AES-256, iterated and salted SHA-256, 8 bytes of salt, coded count 0xFF.
38 #expect(first.tag == 3 && Array(first.body.prefix(4)) == [4, 9, 3, 8] && first.body[12] == 0xFF)
39 #expect(OpenPGP.isSymmetric(message))
40 #expect(!OpenPGP.isSymmetric(Data([0xC1, 0x02, 0x03, 0x00])))
41 let read = try clock.measure { _ = try OpenPGP.decrypt(message, passphrase: "pw") }
42 print("S2K with coded count 0xFF: encrypt \(time), decrypt \(read)")
43 }
44
45 @Test func textBelowAMessageIsSealedWithIt() throws {
46 let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location
47 let one = try #require(try OrgCrypt.encrypt(OrgCryptTests.file, at: bank, passphrase: "pw"))
48 let typed = one.replacingOccurrences(of: "\n* Diary", with: "\nTyped below.\n* Diary")
49 #expect(OrgCrypt.unencrypted(typed).count == 2)
50 let (sealed, messages) = try OrgCrypt.seal(typed, passphrase: "pw")
51 #expect(!sealed.contains("Typed below."))
52 #expect(try OrgCrypt.decrypt(sealed, at: bank, passphrase: "pw").plaintext == "Account 12345, ünïcödé.\n** Child\nChild text.\n\nTyped below.\n")
53 // What reads back for the message is the text the entry had, message and all.
54 #expect(messages.first?.plaintext.contains("-----BEGIN PGP MESSAGE-----") == true)
55 #expect(throws: OrgCrypt.Failure.self) { try OrgCrypt.seal(typed, passphrase: "wrong") }
56 }
57
32 @Test func unencryptedEntriesWithText() throws { 58 @Test func unencryptedEntriesWithText() throws {
33 #expect(OrgCrypt.unencrypted(OrgCryptTests.file).count == 2) 59 #expect(OrgCrypt.unencrypted(OrgCryptTests.file).count == 2)
34 let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location 60 let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location
docs/manual/guide/04-outlines.org +10 −4 · view
@@ -960,12 +960,16 @@ Messages are written with AES-256 and an iterated and salted SHA-256 key, which
960With =org-crypt-use-before-save-magic = true= in =config.toml=, every save, the automatic one included, encrypts the tagged entries that aren't encrypted, as =org-crypt-use-before-save-magic= does in Emacs. It is off by default. 960With =org-crypt-use-before-save-magic = true= in =config.toml=, every save, the automatic one included, encrypts the tagged entries that aren't encrypted, as =org-crypt-use-before-save-magic= does in Emacs. It is off by default.
961 961
962- The editor keeps the entries' text; the file gets the messages. Emacs leaves the encrypted messages in its buffer after a save; orgstar doesn't, since it saves a second after typing stops. 962- The editor keeps the entries' text; the file gets the messages. Emacs leaves the encrypted messages in its buffer after a save; orgstar doesn't, since it saves a second after typing stops.
963- An entry decrypted with Decrypt Entry in File… and saved unchanged gets its old message back, byte for byte, as org-crypt does. Only entries that changed get a new message, so syncing and git see no other change. 963- An entry decrypted with Decrypt Entry in File… and saved unchanged gets its old message back, byte for byte, as org-crypt does, and so does an entry left unchanged between saves. Only entries that changed get a new message, so syncing and git see no other change. A new message takes GnuPG's key iterations (about 65 MB of hashing); each changed entry adds a few hundredths of a second to its save.
964- Text typed below an entry's message isn't encrypted until it goes into the message: the save opens the old message with the passphrase and encrypts it with the new text as one.
965- Turning the setting off while a file is open doesn't write what it encrypted in plaintext: the file keeps encrypting its tagged entries until it's closed. Files opened afterwards are saved as they are.
964- The passphrase comes from the Keychain when it was remembered for the file, after Touch ID, Face ID or the device password. That is asked once while the file is open, at the first save that needs it; a passphrase typed for an org-crypt command on the file is used too. Closing the file or Forget Encryption Passphrase forgets it. 966- The passphrase comes from the Keychain when it was remembered for the file, after Touch ID, Face ID or the device password. That is asked once while the file is open, at the first save that needs it; a passphrase typed for an org-crypt command on the file is used too. Closing the file or Forget Encryption Passphrase forgets it.
965- 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.
966- When the file has encrypted entries already, the passphrase must open them. A first passphrase is asked twice. 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.
970- Archiving, refiling or copying an entry that has the tag, its own or inherited, to another file encrypts it in place first, since the tag it inherits doesn't go with it; without the passphrase it isn't moved.
967- Closing the file, its window, or quitting while it's held asks for the passphrase, or whether to leave without saving. On iOS, the edits stay in memory while orgstar is in the background, and the notice is there on return; if iOS ends orgstar meanwhile, the edits are lost, and orgstar says so when it next opens. 971- Closing the file, its window, or quitting while it's held asks for the passphrase, or whether to leave without saving. On iOS, the edits stay in memory while orgstar is in the background, and the notice is there on return; if iOS ends orgstar meanwhile, the edits are lost, and orgstar says so when it next opens.
968- 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. 972- 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.
969 973
970* Encrypted files 974* Encrypted files
971 975
@@ -976,7 +980,9 @@ Opening one asks for its passphrase, or takes it from the Keychain after Touch I
976The decrypted text is kept in memory only: 980The decrypted text is kept in memory only:
977- Files are written with AES-256 and an iterated and salted SHA-256 key, binary, or armored when the file was armored. 981- Files are written with AES-256 and an iterated and salted SHA-256 key, binary, or armored when the file was armored.
978- Recovery versions and hourly snapshots are kept encrypted with the file's passphrase, and Recovery Versions… shows them decrypted. Changes made to the file elsewhere are merged in memory, and a conflict is compared in memory. 982- Recovery versions and hourly snapshots are kept encrypted with the file's passphrase, and Recovery Versions… shows them decrypted. Changes made to the file elsewhere are merged in memory, and a conflict is compared in memory.
979- The index, search, Spotlight, Quick Look, the agenda, widgets and the watch don't read the file's text. 983- The index, search, Spotlight, Quick Look, the agenda, widgets and the watch don't read the file's text. iCalendar export and publishing leave it out, and Emacs isn't given a copy of it. A clocked heading shows as "Encrypted entry" outside the editor.
984- Archiving from =NAME.org.gpg= goes to =NAME_archive.org.gpg=, encrypted with the same passphrase (Org would write =NAME.org.gpg_archive=, unencrypted). Entries aren't refiled or copied from it to a file that isn't encrypted.
985- Remembered passphrases are kept by the file's path, on this device only, readable while it's unlocked and after Touch ID, Face ID or the device password; renaming the file forgets it. Passphrases remembered by earlier versions move to this kind of item the first time they're used.
980 986
981=age= files (=.age=) aren't supported. 987=age= files (=.age=) aren't supported.
982 988
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