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

35 files changed, +3664 −100

Layout: unified · split

Changed files (35)
Sources/OrgApp/ClockModel.swift +14 −4 · view
@@ -100,7 +100,7 @@ public final class ClockModel {
100 let interrupted = runningTask(session) 100 let interrupted = runningTask(session)
101 let message = clockOut(session, now: now) 101 let message = clockOut(session, now: now)
102 if self.running != nil { return message } 102 if self.running != nil { return message }
103 interruptedTask = interrupted 103 interruptedTask = interrupted.map { Self.shareable($0, session) }
104 // Clocking out may have moved the entry. 104 // Clocking out may have moved the entry.
105 let target = ClockTask(path: path, title: entry.title, ordinal: index, id: entry.id) 105 let target = ClockTask(path: path, title: entry.title, ordinal: index, id: entry.id)
106 guard let moved = Self.text(path, session).flatMap(target.locate) else { return "Can't find \(entry.title) after clocking out." } 106 guard let moved = Self.text(path, session).flatMap(target.locate) else { return "Can't find \(entry.title) after clocking out." }
@@ -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,7 +307,16 @@ 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.
310 history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) } 311 history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) }
312 .map { Self.shareable($0, session) }
313 }
314
315 /// `task` with a placeholder title when its heading is encrypted on disk.
316 static func shareable(_ task: ClockTask, _ session: DocumentSession) -> ClockTask {
317 guard task.titleHidden != true, let heading = text(task.path, session).flatMap(task.locate) else { return task }
318 let shown = session.shareableTitle(task.title, path: task.path, heading: heading)
319 return shown == task.title ? task : task.hiding(shown)
311 } 320 }
312 321
313 /// Where a remembered entry's heading is now. 322 /// Where a remembered entry's heading is now.
@@ -325,7 +334,7 @@ public final class ClockModel {
325 public func markDefault(_ session: DocumentSession, path: String, at offset: Int) -> String { 334 public func markDefault(_ session: DocumentSession, path: String, at offset: Int) -> String {
326 guard let text = Self.text(path, session) else { return "Can't read \(path)" } 335 guard let text = Self.text(path, session) else { return "Can't read \(path)" }
327 guard let task = ClockTask.at(offset, in: text, path: path) else { return "Before first headline" } 336 guard let task = ClockTask.at(offset, in: text, path: path) else { return "Before first headline" }
328 defaultTask = task 337 defaultTask = Self.shareable(task, session)
329 return "Default clock task: \(task.title)" 338 return "Default clock task: \(task.title)"
330 } 339 }
331 340
@@ -527,7 +536,8 @@ public final class ClockModel {
527 let headings = DocumentModel(tree: OrgParser.parse(text)).headings 536 let headings = DocumentModel(tree: OrgParser.parse(text)).headings
528 for clock in open { 537 for clock in open {
529 guard let startedAt = ClockResolution.date(of: clock.start) else { continue } 538 guard let startedAt = ClockResolution.date(of: clock.start) else { continue }
530 let heading = headings.last { $0.headingRange.lowerBound <= clock.offset }?.title ?? "" 539 let entry = headings.last { $0.headingRange.lowerBound <= clock.offset }
540 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)) 541 clocks.append(OpenClock(path: path, start: clock.start, startedAt: startedAt, heading: heading))
532 } 542 }
533 } 543 }
Sources/OrgApp/CryptPassphrases.swift +152 −17 · view
@@ -1,44 +1,179 @@
1import Foundation 1import Foundation
2import LocalAuthentication 2import LocalAuthentication
3import OrgDocument
3import Security 4import Security
4 5
5/// 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.
6/// 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`), asked once per file while it's open. Items
9/// earlier versions stored without that move over at their first read. A build without a
10/// Keychain entitlement (the Developer ID Mac app) can't make such items and keeps the old kind.
11@MainActor
7public enum CryptPassphrases { 12public enum CryptPassphrases {
8 static let service = "sh.krz.orgstar.crypt" 13 nonisolated static let service = "sh.krz.orgstar.crypt.v2"
14 /// Where earlier versions kept passphrases, readable without authentication.
15 nonisolated static let legacyService = "sh.krz.orgstar.crypt"
16 /// Set once the person was told this build keeps passphrases the old way.
17 static let toldLegacyKey = "cryptKeychainLegacyTold"
9 18
10 static func query(_ path: String) -> [String: Any] { 19 /// A Keychain query handed to the thread that waits on it; nothing else uses it meanwhile.
11 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path] 20 struct Request: @unchecked Sendable {
21 let query: [String: Any]
12 } 22 }
13 23
14 public static func store(_ passphrase: String, for path: String) { 24 /// One authentication per file while it's open; `endSession` ends it.
15 forget(path) 25 private static var contexts: [String: LAContext] = [:]
26
27 static func context(for path: String) -> LAContext {
28 if let context = contexts[path] { return context }
29 let context = LAContext()
30 contexts[path] = context
31 return context
32 }
33
34 /// The file closed: its authentication no longer reads its passphrase.
35 public static func endSession(for path: String) {
36 contexts.removeValue(forKey: path)?.invalidate()
37 }
38
39 nonisolated static func query(_ path: String, service: String = service) -> [String: Any] {
40 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
41 if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true }
42 return query
43 }
44
45 /// The new item for `passphrase`: this device only, unlocked, after user presence.
46 nonisolated static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
47 guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
16 var item = query(path) 48 var item = query(path)
17 item[kSecValueData as String] = Data(passphrase.utf8) 49 item[kSecValueData as String] = Data(passphrase.utf8)
18 item[kSecAttrLabel as String] = "orgstar: encrypted entries in " + (path as NSString).lastPathComponent 50 item[kSecAttrAccessControl as String] = access
19 SecItemAdd(item as CFDictionary, nil) 51 item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
52 return item
53 }
54
55 /// Adds `item`, in place of one there already.
56 nonisolated static func add(_ item: [String: Any], replacing query: [String: Any]) -> OSStatus {
57 var status = SecItemAdd(item as CFDictionary, nil)
58 if status == errSecDuplicateItem {
59 SecItemDelete(query as CFDictionary)
60 status = SecItemAdd(item as CFDictionary, nil)
61 }
62 return status
63 }
64
65 /// Remembers `passphrase` for `path`. A message to show when it wasn't kept, or (once) when
66 /// this build keeps it without device-only protection; nil otherwise.
67 @discardableResult
68 public static func store(_ passphrase: String, for path: String, defaults: UserDefaults = .standard) -> String? {
69 guard let item = newItem(passphrase, for: path) else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") }
70 let status = add(item, replacing: query(path))
71 if status == errSecSuccess {
72 SecItemDelete(query(path, service: legacyService) as CFDictionary)
73 return nil
74 }
75 guard status == errSecMissingEntitlement else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") }
76 var legacy = query(path, service: legacyService)
77 legacy[kSecValueData as String] = Data(passphrase.utf8)
78 legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
79 guard add(legacy, replacing: query(path, service: legacyService)) == errSecSuccess else {
80 return String(localized: "The passphrase wasn't remembered: the Keychain refused it.")
81 }
82 SecItemDelete(query(path) as CFDictionary)
83 guard !defaults.bool(forKey: toldLegacyKey) else { return nil }
84 defaults.set(true, forKey: toldLegacyKey)
85 return String(localized: "This version of orgstar keeps remembered passphrases in your login keychain without limiting them to this Mac; Touch ID or your password is still asked before one is used.")
20 } 86 }
21 87
22 public static func forget(_ path: String) { 88 public static func forget(_ path: String) {
89 endSession(for: path)
23 SecItemDelete(query(path) as CFDictionary) 90 SecItemDelete(query(path) as CFDictionary)
91 SecItemDelete(query(path, service: legacyService) as CFDictionary)
24 } 92 }
25 93
26 public static func hasStored(_ path: String) -> Bool { 94 /// Whether an item exists, without asking for authentication.
27 var q = query(path) 95 nonisolated static func exists(_ query: [String: Any]) -> Bool {
96 var q = query
97 let quiet = LAContext()
98 quiet.interactionNotAllowed = true
99 q[kSecUseAuthenticationContext as String] = quiet
28 q[kSecReturnAttributes as String] = true 100 q[kSecReturnAttributes as String] = true
29 return SecItemCopyMatching(q as CFDictionary, nil) == errSecSuccess 101 let status = SecItemCopyMatching(q as CFDictionary, nil)
102 return status == errSecSuccess || status == errSecInteractionNotAllowed
103 }
104
105 public static func hasStored(_ path: String) -> Bool {
106 exists(query(path)) || exists(query(path, service: legacyService))
30 } 107 }
31 108
32 /// The stored passphrase, once the person has proved who they are; nil otherwise. 109 /// The stored passphrase, once the person has proved who they are; nil otherwise.
33 public static func stored(for path: String) async -> String? { 110 public static func stored(for path: String) async -> String? {
34 guard hasStored(path) else { return nil } 111 let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
35 let context = LAContext() 112 let context = context(for: path)
36 let reason = "unlock the passphrase for encrypted entries in " + (path as NSString).lastPathComponent 113 if exists(query(path)) {
114 var q = query(path)
115 q[kSecReturnData as String] = true
116 context.localizedReason = reason
117 q[kSecUseAuthenticationContext as String] = context
118 let request = Request(query: q)
119 // The read waits for Touch ID or the password, off the main thread.
120 return await Task.detached { () -> String? in
121 var result: AnyObject?
122 guard SecItemCopyMatching(request.query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
123 return String(decoding: data, as: UTF8.self)
124 }.value
125 }
126 guard exists(query(path, service: legacyService)) else { return nil }
37 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil } 127 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
38 var q = query(path) 128 var q = query(path, service: legacyService)
39 q[kSecReturnData as String] = true 129 q[kSecReturnData as String] = true
40 var result: AnyObject? 130 var result: AnyObject?
41 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } 131 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
42 return String(decoding: data, as: UTF8.self) 132 let passphrase = String(decoding: data, as: UTF8.self)
133 // Moved to the protected kind of item; kept as it was where that can't be made.
134 if let item = newItem(passphrase, for: path), add(item, replacing: query(path)) == errSecSuccess {
135 SecItemDelete(query(path, service: legacyService) as CFDictionary)
136 }
137 return passphrase
138 }
139}
140
141extension CryptHold {
142 /// Whether giving the passphrase lets the file be saved.
143 public var takesPassphrase: Bool {
144 if case .blocked = self { return false }
145 return true
146 }
147
148 /// What the held file's notice says.
149 public func notice(for path: String) -> String {
150 let name = (path as NSString).lastPathComponent
151 return switch self {
152 case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
153 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
154 case .file: String(localized: "\(name) isn't saved until it has a passphrase.")
155 case .blocked(let reason): reason + ". " + String(localized: "Changes to \(name) aren't saved until that's fixed.")
156 }
157 }
158}
159
160extension CryptHold: LocalizedError {
161 public var errorDescription: String? {
162 switch self {
163 case .entries(1): String(localized: "1 tagged entry isn't encrypted")
164 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
165 case .file: String(localized: "The file has no passphrase yet")
166 case .blocked(let reason): reason
167 }
168 }
169}
170
171extension CryptReadError: LocalizedError {
172 public var errorDescription: String? {
173 switch self {
174 case .locked: String(localized: "The file is encrypted, and its passphrase isn't known")
175 case .wrongPassphrase: String(localized: "Wrong passphrase")
176 case .failed(let reason): reason
177 }
43 } 178 }
44} 179}
Sources/OrgApp/CryptSheet.swift +84 −11 · view
@@ -1,5 +1,6 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3import OrgDocument
3import SwiftUI 4import SwiftUI
4 5
5/// What an org-crypt command does with the entry at `offset` in the file at `path`. 6/// What an org-crypt command does with the entry at `offset` in the file at `path`.
@@ -13,6 +14,12 @@ public struct CryptRequest: Identifiable, Sendable {
13 case open 14 case open
14 /// `org-decrypt-entry`: the decrypted text in the file. 15 /// `org-decrypt-entry`: the decrypted text in the file.
15 case decryptInPlace 16 case decryptInPlace
17 /// The passphrase a held save needs, to encrypt the tagged entries as the file is saved.
18 case encryptOnSave
19 /// The passphrase of an encrypted file (`.org.gpg`), to open it.
20 case openFile
21 /// The passphrase a new encrypted file is saved with.
22 case newFile
16 } 23 }
17 24
18 public let id = UUID() 25 public let id = UUID()
@@ -28,30 +35,48 @@ public struct CryptRequest: Identifiable, Sendable {
28 35
29 var encrypting: Bool { 36 var encrypting: Bool {
30 switch mode { 37 switch mode {
31 case .encrypt, .encryptAll: true 38 case .encrypt, .encryptAll, .encryptOnSave, .newFile: true
32 default: false 39 default: false
33 } 40 }
34 } 41 }
42
43 /// The passphrase goes to the session, which checks it and saves or opens the file.
44 var unlocks: Bool {
45 switch mode {
46 case .encryptOnSave, .openFile, .newFile: true
47 default: false
48 }
49 }
50
51 /// The request for what keeps `path` from being saved.
52 public static func save(_ path: String, hold: CryptHold) -> CryptRequest {
53 CryptRequest(mode: hold == .file ? .newFile : .encryptOnSave, path: path, offset: 0)
54 }
35} 55}
36 56
37/// The passphrase for an org-crypt command, from the Keychain when it was remembered, then for 57/// The passphrase for an org-crypt command, from the Keychain when it was remembered, then for
38/// `open` the decrypted entry to edit. `text` is the file's text now; `apply` puts a new text 58/// `open` the decrypted entry to edit. `text` is the file's text now; `apply` puts a new text
39/// in its place; `done` closes the sheet with a message. 59/// in its place; `done` closes the sheet with a message. `session` learns the passphrase, so
60/// saves encrypt with it without asking again.
40public struct CryptSheet: View { 61public struct CryptSheet: View {
41 let request: CryptRequest 62 let request: CryptRequest
63 let session: DocumentSession?
42 let text: () -> String 64 let text: () -> String
43 let apply: (String) -> Void 65 let apply: (String) -> Void
44 let done: (String?) -> Void 66 let done: (String?) -> Void
45 @State private var passphrase = "" 67 @State private var passphrase = ""
46 @State private var repeated = "" 68 @State private var repeated = ""
47 @State private var remember = false 69 @State private var remember = false
70 /// What the Keychain said when the passphrase was remembered, shown with the result.
71 @State private var keychainNote: String?
48 @State private var problem: String? 72 @State private var problem: String?
49 /// The decrypted entry being edited, and the passphrase it came with. 73 /// The decrypted entry being edited, and the passphrase it came with.
50 @State private var editing: (original: String, passphrase: String)? 74 @State private var editing: (original: String, passphrase: String)?
51 @State private var plaintext = "" 75 @State private var plaintext = ""
52 76
53 public init(request: CryptRequest, text: @escaping () -> String, apply: @escaping (String) -> Void, done: @escaping (String?) -> Void) { 77 public init(request: CryptRequest, session: DocumentSession? = nil, text: @escaping () -> String, apply: @escaping (String) -> Void, done: @escaping (String?) -> Void) {
54 self.request = request 78 self.request = request
79 self.session = session
55 self.text = text 80 self.text = text
56 self.apply = apply 81 self.apply = apply
57 self.done = done 82 self.done = done
@@ -73,13 +98,14 @@ public struct CryptSheet: View {
73 } 98 }
74 } else { 99 } else {
75 Text(title).font(.headline) 100 Text(title).font(.headline)
101 if let explanation { Text(explanation).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }
76 SecureField("Passphrase", text: $passphrase).onSubmit(submit) 102 SecureField("Passphrase", text: $passphrase).onSubmit(submit)
77 if request.encrypting { SecureField("Repeat passphrase", text: $repeated).onSubmit(submit) } 103 if asksTwice { SecureField("Repeat passphrase", text: $repeated).onSubmit(submit) }
78 Toggle("Remember in the Keychain", isOn: $remember) 104 Toggle("Remember in the Keychain", isOn: $remember)
79 if let problem { Text(problem).foregroundStyle(.red).font(.callout) } 105 if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
80 HStack { 106 HStack {
81 Spacer() 107 Spacer()
82 Button("Cancel", role: .cancel) { done(nil) }.keyboardShortcut(.cancelAction) 108 Button("Cancel", role: .cancel) { cancel() }.keyboardShortcut(.cancelAction)
83 Button(request.encrypting ? "Encrypt" : "Decrypt") { submit() } 109 Button(request.encrypting ? "Encrypt" : "Decrypt") { submit() }
84 .keyboardShortcut(.defaultAction) 110 .keyboardShortcut(.defaultAction)
85 .disabled(passphrase.isEmpty) 111 .disabled(passphrase.isEmpty)
@@ -102,16 +128,52 @@ public struct CryptSheet: View {
102 case .encrypt: "Encrypt Entry" 128 case .encrypt: "Encrypt Entry"
103 case .encryptAll: "Encrypt Tagged Entries" 129 case .encryptAll: "Encrypt Tagged Entries"
104 case .open, .decryptInPlace: "Decrypt Entry" 130 case .open, .decryptInPlace: "Decrypt Entry"
131 case .encryptOnSave: String(localized: "Encrypt Tagged Entries")
132 case .openFile: String(localized: "Decrypt File")
133 case .newFile: String(localized: "Set Passphrase")
134 }
135 }
136
137 private var name: String { (request.path as NSString).lastPathComponent }
138
139 private var explanation: String? {
140 switch request.mode {
141 case .encryptOnSave: String(localized: "\(name) is saved with its tagged entries encrypted.")
142 case .openFile: String(localized: "\(name) is encrypted.")
143 case .newFile: String(localized: "\(name) is saved encrypted with this passphrase.")
144 default: nil
145 }
146 }
147
148 /// A new passphrase is typed twice; one that must open what's encrypted already, once.
149 private var asksTwice: Bool {
150 switch request.mode {
151 case .encryptOnSave: OrgCrypt.firstMessage(text()) == nil
152 case .openFile: false
153 default: request.encrypting
105 } 154 }
106 } 155 }
107 156
108 private func submit() { 157 private func submit() {
109 guard !passphrase.isEmpty else { return } 158 guard !passphrase.isEmpty else { return }
110 if request.encrypting, passphrase != repeated { return problem = "The passphrases differ" } 159 if asksTwice, passphrase != repeated { return problem = "The passphrases differ" }
111 run(passphrase, remembered: false) 160 run(passphrase, remembered: false)
112 } 161 }
113 162
163 private func cancel() {
164 if case .openFile = request.mode { session?.cancelUnlock() }
165 done(nil)
166 }
167
114 private func run(_ passphrase: String, remembered: Bool) { 168 private func run(_ passphrase: String, remembered: Bool) {
169 if request.unlocks {
170 if let failure = session?.unlock(passphrase, for: request.path) { return problem = failure }
171 switch request.mode {
172 case .encryptOnSave: return finish(String(localized: "Tagged entries encrypted and saved"), passphrase: passphrase, remembered: remembered)
173 case .newFile: return finish(String(localized: "Saved encrypted"), passphrase: passphrase, remembered: remembered)
174 default: return finish(nil, passphrase: passphrase, remembered: remembered)
175 }
176 }
115 let current = text() 177 let current = text()
116 do { 178 do {
117 switch request.mode { 179 switch request.mode {
@@ -127,22 +189,33 @@ public struct CryptSheet: View {
127 finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered) 189 finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered)
128 case .open: 190 case .open:
129 let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext 191 let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext
130 if remember, !remembered { CryptPassphrases.store(passphrase, for: request.path) } 192 if remember, !remembered { keychainNote = CryptPassphrases.store(passphrase, for: request.path) }
193 session?.cryptUsed(passphrase, for: request.path)
131 plaintext = plain 194 plaintext = plain
132 editing = (plain, passphrase) 195 editing = (plain, passphrase)
133 problem = nil 196 problem = nil
134 case .decryptInPlace: 197 case .decryptInPlace:
135 apply(try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase)) 198 let message = OrgCrypt.encryptedRange(current, at: request.offset).map { (current as NSString).substring(with: NSRange($0)) }
199 let decrypted = try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase)
200 // Saved unchanged with org-crypt-use-before-save-magic, the entry gets its message back.
201 if let message, let body = OrgCrypt.bodyRange(decrypted, at: request.offset) {
202 session?.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: request.path)
203 }
204 apply(decrypted)
136 finish("Entry decrypted", passphrase: passphrase, remembered: remembered) 205 finish("Entry decrypted", passphrase: passphrase, remembered: remembered)
206 case .encryptOnSave, .openFile, .newFile:
207 break
137 } 208 }
138 } catch { 209 } catch {
139 problem = "\(error)" 210 problem = "\(error)"
140 } 211 }
141 } 212 }
142 213
143 private func finish(_ message: String, passphrase: String, remembered: Bool) { 214 private func finish(_ message: String?, passphrase: String, remembered: Bool) {
144 if remember, !remembered { CryptPassphrases.store(passphrase, for: request.path) } 215 if remember, !remembered { keychainNote = CryptPassphrases.store(passphrase, for: request.path) }
145 done(message) 216 if !request.unlocks { session?.cryptUsed(passphrase, for: request.path) }
217 let text = [message, keychainNote].compactMap { $0 }.joined(separator: " ")
218 done(text.isEmpty ? nil : text)
146 } 219 }
147 220
148 /// The edited text encrypted again in the message's place; nothing changes if it wasn't edited. 221 /// The edited text encrypted again in the message's place; nothing changes if it wasn't edited.
Sources/OrgApp/DocumentSession.swift +305 −11 · view
@@ -137,8 +137,13 @@ public final class DocumentSession {
137 } 137 }
138 } 138 }
139 139
140 /// Files and recovery through `crypt`, and as they are on disk.
140 private let fileSystem: FileSystem 141 private let fileSystem: FileSystem
141 private let recovery: RecoveryStore 142 private let recovery: RecoveryStore
143 private let diskFileSystem: FileSystem
144 private let diskRecovery: RecoveryStore
145 /// Passphrases and encrypted entries of the open files.
146 @ObservationIgnored public let crypt = CryptVault()
142 @ObservationIgnored private var entries: [Entry] = [] 147 @ObservationIgnored private var entries: [Entry] = []
143 /// The focused pane's buffer. 148 /// The focused pane's buffer.
144 private var current: Entry? { focused.path.flatMap(entry) } 149 private var current: Entry? { focused.path.flatMap(entry) }
@@ -151,13 +156,151 @@ public final class DocumentSession {
151 fileSystem: FileSystem = CoordinatedFileSystem(), 156 fileSystem: FileSystem = CoordinatedFileSystem(),
152 recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery")) 157 recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
153 ) { 158 ) {
154 self.fileSystem = fileSystem 159 diskFileSystem = fileSystem
155 self.recovery = recovery 160 diskRecovery = recovery
161 self.fileSystem = CryptFileSystem(base: fileSystem, vault: crypt)
162 self.recovery = CryptRecoveryStore(base: recovery, vault: crypt)
156 let pane = EditorPane() 163 let pane = EditorPane()
157 panes = [pane] 164 panes = [pane]
158 focused = pane 165 focused = pane
159 } 166 }
160 167
168 // MARK: - Encryption
169
170 /// `org-crypt-use-before-save-magic`: entries with `cryptTag` are encrypted on every save.
171 public var encryptsTaggedEntries: Bool {
172 get { crypt.encryptsTaggedEntries }
173 set { crypt.encryptsTaggedEntries = newValue }
174 }
175
176 /// `org-crypt-tag-matcher`.
177 public var cryptTag: String {
178 get { crypt.tag }
179 set { crypt.tag = newValue }
180 }
181
182 /// Open files that aren't saved until a passphrase is given: tagged entries that would be
183 /// written unencrypted, or an encrypted file without one. Other edits to them wait too.
184 public private(set) var held: [String: CryptHold] = [:]
185 /// Holds from saves that failed: a version on disk with tagged entries that can't be kept
186 /// encrypted, or an entry the passphrase can't encrypt. Kept until a save succeeds.
187 @ObservationIgnored private var failedHolds: [String: CryptHold] = [:]
188
189 /// An encrypted file waiting for its passphrase to open, and the pane to show it in.
190 public private(set) var unlockRequest: String?
191 @ObservationIgnored private var unlockPane: EditorPane?
192
193 /// The passphrase remembered in the Keychain, after Touch ID, Face ID or the device's
194 /// password; nil when there's none or it wasn't given.
195 @ObservationIgnored public var storedPassphrase: (String) async -> String? = { await CryptPassphrases.stored(for: $0) }
196 @ObservationIgnored public var hasStoredPassphrase: (String) -> Bool = { CryptPassphrases.hasStored($0) }
197 /// Files whose remembered passphrase is being asked for, and those where it was refused:
198 /// the Keychain is asked once per file until the file closes or Encrypt is chosen.
199 @ObservationIgnored private var askingKeychain: Set<String> = []
200 @ObservationIgnored private var refusedKeychain: Set<String> = []
201
202 public static func isEncryptedFile(_ path: String) -> Bool { CryptVault.isEncryptedFile(path) }
203
204 /// An encrypted org file, which lists with the org files.
205 public static func isEncryptedOrgFile(_ path: String) -> Bool { path.hasSuffix(".org.gpg") }
206
207 /// Gives `passphrase` for `path`: an encrypted file opens with it, and a held file is saved.
208 /// It must open the file, or the file's encrypted entries if it has any. A message when it
209 /// doesn't.
210 public func unlock(_ passphrase: String, for path: String) -> String? {
211 if let entry = entry(path) {
212 if let message = OrgCrypt.firstMessage(entry.buffer.document.text), !OrgCrypt.opens(message, passphrase: passphrase) {
213 return String(localized: "Wrong passphrase")
214 }
215 // An encrypted file on disk keeps its passphrase: a passphrase given after Forget
216 // must open it.
217 if Self.isEncryptedFile(entry.path), let disk = try? diskFileSystem.read(URL(fileURLWithPath: entry.path)),
218 !CryptVault.opens(disk, passphrase: passphrase) {
219 return String(localized: "Wrong passphrase")
220 }
221 crypt.unlock(passphrase, for: entry.path)
222 refusedKeychain.remove(entry.path)
223 save(entry)
224 return nil
225 }
226 guard Self.isEncryptedFile(path) else { return nil }
227 let bytes: [UInt8]
228 do {
229 guard let read = try diskFileSystem.read(URL(fileURLWithPath: path)) else { return "\((path as NSString).lastPathComponent) no longer exists." }
230 bytes = read
231 } catch {
232 return error.localizedDescription
233 }
234 guard CryptVault.opens(bytes, passphrase: passphrase) else { return String(localized: "Wrong passphrase") }
235 crypt.unlock(passphrase, for: path)
236 let pane = unlockPane.flatMap { pane in panes.contains { $0 === pane } ? pane : nil } ?? focused
237 unlockRequest = nil
238 unlockPane = nil
239 open(path, in: pane)
240 return nil
241 }
242
243 /// The encrypted file waiting for its passphrase stays closed.
244 public func cancelUnlock() {
245 unlockRequest = nil
246 unlockPane = nil
247 }
248
249 /// A crypt command used `passphrase` for `path`: saves use it from now on, without asking.
250 public func cryptUsed(_ passphrase: String, for path: String) {
251 crypt.unlock(passphrase, for: path)
252 refusedKeychain.remove(path)
253 }
254
255 /// The entry holding `plaintext` in `path`'s buffer was decrypted from `message`.
256 public func cryptDecrypted(message: String, plaintext: String, for path: String) {
257 crypt.remember(message: message, plaintext: plaintext, for: path)
258 }
259
260 /// Forget Encryption Passphrase: the passphrase leaves the Keychain and the session.
261 public func forgetPassphrase(for path: String) {
262 CryptPassphrases.forget(path)
263 crypt.forgetPassphrase(for: path)
264 }
265
266 /// `title`, of the heading at `heading` in `path`, as it may be shown and kept outside
267 /// the editor (the clock's file, widgets, the Live Activity, the menu bar): a placeholder
268 /// for a heading of an encrypted file or one inside an entry that's encrypted on disk.
269 public func shareableTitle(_ title: String, path: String, heading: Int) -> String {
270 let hidden = Self.isEncryptedFile(path)
271 || (crypt.sealsEntries(for: path) && document(of: path).map { OrgCrypt.isInTaggedText($0.text, at: heading, tag: cryptTag) } == true)
272 return hidden ? String(localized: "Encrypted entry") : title
273 }
274
275 /// Why a copy of the buffer can't be kept, with what to do; the buffer's notice shows.
276 private func keepFailure(_ hold: CryptHold) -> String {
277 if let current { _ = updateHold(current) }
278 return hold.localizedDescription + ". " + String(localized: "Give the passphrase with Encrypt… first, so that a copy of your edits can be kept encrypted.")
279 }
280
281 /// Whether `path`'s buffer is held back from disk now.
282 private func updateHold(_ entry: Entry) -> CryptHold? {
283 let dirty = entry.buffer.document.isDirty
284 let hold = dirty ? crypt.hold(entry.buffer.document.text, for: entry.path) ?? failedHolds[entry.path] : nil
285 if held[entry.path] != hold { held[entry.path] = hold }
286 return hold
287 }
288
289 /// Asks the Keychain for `entry`'s passphrase, once, and saves with it.
290 private func askKeychain(_ entry: Entry) {
291 let path = entry.path
292 guard !askingKeychain.contains(path), !refusedKeychain.contains(path), hasStoredPassphrase(path) else { return }
293 askingKeychain.insert(path)
294 Task { [weak self, weak entry] in
295 guard let self else { return }
296 let passphrase = await self.storedPassphrase(path)
297 self.askingKeychain.remove(path)
298 guard let entry, self.entries.contains(where: { $0 === entry }) else { return }
299 if let passphrase, self.unlock(passphrase, for: path) == nil { return }
300 self.refusedKeychain.insert(path)
301 }
302 }
303
161 // MARK: - Panes 304 // MARK: - Panes
162 305
163 /// A new, empty pane. 306 /// A new, empty pane.
@@ -187,7 +330,7 @@ public final class DocumentSession {
187 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false } 330 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
188 331
189 public static func isOrgPath(_ path: String) -> Bool { 332 public static func isOrgPath(_ path: String) -> Bool {
190 path.hasSuffix(".org") || path.hasSuffix(".org_archive") 333 path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg")
191 } 334 }
192 335
193 /// The caret in the open file. 336 /// The caret in the open file.
@@ -248,9 +391,40 @@ public final class DocumentSession {
248 entries.map { ($0.path, $0.buffer.document) } 391 entries.map { ($0.path, $0.buffer.document) }
249 } 392 }
250 393
251 /// The text of every open file by path, for the agenda. 394 /// The text of every open file by path, for the agenda and what it writes (widgets, the
395 /// watch, reminders). Encrypted files, and files with entries decrypted that saving
396 /// encrypts, are left out: those views read them from disk.
252 public var openTexts: [String: String] { 397 public var openTexts: [String: String] {
253 Dictionary(entries.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a }) 398 let shown = entries.filter { !crypt.isPrivate($0.buffer.document.text, for: $0.path) }
399 return Dictionary(shown.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
400 }
401
402 /// The text of `path` for an export that writes files (iCalendar, publishing): an open
403 /// buffer's, unless it holds what's encrypted on disk, then what's on disk; nil for an
404 /// encrypted file.
405 public func exportText(of path: String) -> String? {
406 if Self.isEncryptedFile(path) { return nil }
407 if let entry = entry(path), !crypt.isPrivate(entry.buffer.document.text, for: entry.path) { return entry.buffer.document.text }
408 return (try? diskFileSystem.read(URL(fileURLWithPath: path))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
409 }
410
411 /// Whether `exportText` leaves `path` out or reads it from disk for what's encrypted.
412 public func exportLeavesOut(_ path: String) -> Bool {
413 Self.isEncryptedFile(path) || entry(path).map { crypt.isPrivate($0.buffer.document.text, for: $0.path) } == true
414 }
415
416 /// Why the buffer of `path` isn't copied to a temporary file for Emacs (recalculating,
417 /// exporting, `elisp:` links): it's an encrypted file, or holds entries encrypted on disk.
418 public func refusesEmacsCopy(_ path: String) -> String? {
419 let name = (path as NSString).lastPathComponent
420 if Self.isEncryptedFile(path) { return String(localized: "\(name) is encrypted, so Emacs isn't given a copy of it.") }
421 guard let entry = entry(path), crypt.isPrivate(entry.buffer.document.text, for: entry.path) else { return nil }
422 return String(localized: "\(name) has decrypted entries that are encrypted on disk, so Emacs isn't given a copy of it.")
423 }
424
425 /// Said after an export that left out encrypted files or read decrypted entries from disk.
426 public static var exportNote: String {
427 String(localized: "Encrypted files were left out, and encrypted entries were exported as they are on disk.")
254 } 428 }
255 429
256 /// Open buffers, most recently shown first. 430 /// Open buffers, most recently shown first.
@@ -269,12 +443,19 @@ public final class DocumentSession {
269 show(existing, in: pane) 443 show(existing, in: pane)
270 return 444 return
271 } 445 }
446 if Self.isEncryptedFile(path), crypt.passphrase(for: path) == nil,
447 (try? diskFileSystem.read(URL(fileURLWithPath: path)))??.isEmpty == false {
448 unlockRequest = path
449 unlockPane = pane
450 return
451 }
272 do { 452 do {
273 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { 453 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
274 showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "\((path as NSString).lastPathComponent) no longer exists.") 454 showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "\((path as NSString).lastPathComponent) no longer exists.")
275 return 455 return
276 } 456 }
277 let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path))) 457 let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
458 crypt.opened(path)
278 let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count 459 let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
279 entries.insert(entry, at: index) 460 entries.insert(entry, at: index)
280 show(entry, in: pane) 461 show(entry, in: pane)
@@ -312,6 +493,11 @@ public final class DocumentSession {
312 guard let entry = entry(path) else { return } 493 guard let entry = entry(path) else { return }
313 entry.autosave?.cancel() 494 entry.autosave?.cancel()
314 entries.removeAll { $0 === entry } 495 entries.removeAll { $0 === entry }
496 crypt.close(entry.path)
497 CryptPassphrases.endSession(for: entry.path)
498 held[entry.path] = nil
499 failedHolds[entry.path] = nil
500 refusedKeychain.remove(entry.path)
315 history.removeAll { $0 == path } 501 history.removeAll { $0 == path }
316 outlineUpdates[path]?.cancel() 502 outlineUpdates[path]?.cancel()
317 outlineUpdates[path] = nil 503 outlineUpdates[path] = nil
@@ -426,6 +612,8 @@ public final class DocumentSession {
426 612
427 private func scheduleAutosave(_ entry: Entry) { 613 private func scheduleAutosave(_ entry: Entry) {
428 entry.autosave?.cancel() 614 entry.autosave?.cancel()
615 // A held file whose edits were undone, or whose tagged entries went, isn't held.
616 if held[entry.path] != nil, updateHold(entry) == nil { refresh(entry) }
429 guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return } 617 guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
430 entry.autosave = Task { [weak self, weak entry, autosaveDelay] in 618 entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
431 try? await Task.sleep(for: autosaveDelay) 619 try? await Task.sleep(for: autosaveDelay)
@@ -460,10 +648,18 @@ public final class DocumentSession {
460 defer { interval.end((entry.path as NSString).lastPathComponent) } 648 defer { interval.end((entry.path as NSString).lastPathComponent) }
461 entry.autosave?.cancel() 649 entry.autosave?.cancel()
462 let name = (entry.path as NSString).lastPathComponent 650 let name = (entry.path as NSString).lastPathComponent
651 // A failed save is tried again: what failed may be fixed by now.
652 guard updateHold(entry) == nil || held[entry.path] == failedHolds[entry.path] else {
653 askKeychain(entry)
654 refresh(entry)
655 return false
656 }
463 guard entry.buffer.document.isDirty else { return true } 657 guard entry.buffer.document.isDirty else { return true }
464 guard entry.conflict == nil else { return false } 658 guard entry.conflict == nil else { return false }
659 defer { _ = updateHold(entry) }
465 do { 660 do {
466 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) } 661 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
662 failedHolds[entry.path] = nil
467 switch outcome { 663 switch outcome {
468 case .saved, .mergedAndSaved: 664 case .saved, .mergedAndSaved:
469 break 665 break
@@ -474,6 +670,12 @@ public final class DocumentSession {
474 entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours." 670 entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
475 } 671 }
476 } 672 }
673 } catch let hold as CryptHold {
674 // A version on disk with tagged entries in plaintext can be kept only encrypted.
675 failedHolds[entry.path] = hold
676 askKeychain(entry)
677 } catch let failure as OrgCrypt.Failure {
678 failedHolds[entry.path] = .blocked(failure.description)
477 } catch { 679 } catch {
478 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)") 680 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
479 } 681 }
@@ -484,6 +686,7 @@ public final class DocumentSession {
484 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery. 686 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
485 public func keepMine() { 687 public func keepMine() {
486 guard let buffer, let url else { return } 688 guard let buffer, let url else { return }
689 if let current, updateHold(current) != nil { return refresh() }
487 do { 690 do {
488 try buffer.update { try saver.overwrite(&$0, to: url) } 691 try buffer.update { try saver.overwrite(&$0, to: url) }
489 current?.conflict = nil 692 current?.conflict = nil
@@ -502,6 +705,8 @@ public final class DocumentSession {
502 let path = url.path 705 let path = url.path
503 buffer.update { $0 = loaded(bytes, path: path) } 706 buffer.update { $0 = loaded(bytes, path: path) }
504 current?.conflict = nil 707 current?.conflict = nil
708 } catch let hold as CryptHold {
709 showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
505 } catch { 710 } catch {
506 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)") 711 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
507 } 712 }
@@ -529,6 +734,8 @@ public final class DocumentSession {
529 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision) 734 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
530 } 735 }
531 current?.conflict = nil 736 current?.conflict = nil
737 } catch let hold as CryptHold {
738 showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
532 } catch { 739 } catch {
533 showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)") 740 showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)")
534 } 741 }
@@ -553,7 +760,7 @@ public final class DocumentSession {
553 public func resolve(copy: URL, _ resolution: CopyResolution) -> String? { 760 public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
554 guard let buffer, let url else { return "No file is open" } 761 guard let buffer, let url else { return "No file is open" }
555 do { 762 do {
556 guard let bytes = try fileSystem.read(copy) else { return "\(copy.lastPathComponent) is gone" } 763 guard let bytes = try diskFileSystem.read(copy).map({ try crypt.plain($0, for: url.path) }) else { return "\(copy.lastPathComponent) is gone" }
557 let copyText = SourceText(bytes: bytes).text 764 let copyText = SourceText(bytes: bytes).text
558 let mine = buffer.document.text 765 let mine = buffer.document.text
559 let new: String? = switch resolution { 766 let new: String? = switch resolution {
@@ -577,7 +784,7 @@ public final class DocumentSession {
577 /// Versions of the open file kept in recovery, newest first, with when and why each was 784 /// Versions of the open file kept in recovery, newest first, with when and why each was
578 /// kept. 785 /// kept.
579 public func recoveryVersions() -> [(url: URL, date: Date, label: String)] { 786 public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
580 guard let url, let store = recovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] } 787 guard let url, let store = diskRecovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
581 // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them. 788 // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
582 return versions.reversed().map { version in 789 return versions.reversed().map { version in
583 let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/) 790 let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
@@ -588,7 +795,9 @@ public final class DocumentSession {
588 795
589 /// The text of a kept version. 796 /// The text of a kept version.
590 public func recoveryText(_ version: URL) -> String? { 797 public func recoveryText(_ version: URL) -> String? {
591 (try? fileSystem.read(version)).flatMap { $0 }.map { SourceText(bytes: $0).text } 798 guard let bytes = (try? diskFileSystem.read(version)).flatMap({ $0 }) else { return nil }
799 // Kept as the open file is: encrypted with its passphrase, its entries' messages known.
800 return (try? path.map { try crypt.plain(bytes, for: $0) } ?? bytes).map { SourceText(bytes: $0).text }
592 } 801 }
593 802
594 /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it 803 /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
@@ -604,6 +813,8 @@ public final class DocumentSession {
604 guard let buffer, let url else { return "Can't read that version" } 813 guard let buffer, let url else { return "Can't read that version" }
605 do { 814 do {
606 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") 815 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
816 } catch let hold as CryptHold {
817 return keepFailure(hold)
607 } catch { 818 } catch {
608 return "Can't keep the current version: \(error.localizedDescription)" 819 return "Can't keep the current version: \(error.localizedDescription)"
609 } 820 }
@@ -653,7 +864,16 @@ public final class DocumentSession {
653 /// path; the subtree leaves its file only once it has. Returns a message for the echo area. 864 /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
654 @discardableResult 865 @discardableResult
655 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? { 866 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
656 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } 867 guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
868 if target.path != path {
869 switch prepareMove(path, context: context, to: target.path) {
870 case .refused(let message): return message
871 case .sealed(let heading):
872 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
873 context = again.context
874 case .ready: break
875 }
876 }
657 let done = (keep ? "Copied to " : "Refiled to ") + target.label 877 let done = (keep ? "Copied to " : "Refiled to ") + target.label
658 if target.path == path { 878 if target.path == path {
659 let answers = ["refile": target.start.map(String.init) ?? ""] 879 let answers = ["refile": target.start.map(String.init) ?? ""]
@@ -773,6 +993,68 @@ public final class DocumentSession {
773 return (TextEdit(range: at..<at, replacement: insertion), newStart, level) 993 return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
774 } 994 }
775 995
996 private enum MovePreparation {
997 case ready
998 /// Tagged entries in the subtree were encrypted in its file; its heading starts here.
999 case sealed(Int)
1000 case refused(String)
1001 }
1002
1003 /// Before the subtree at the caret of `context`, in `path`, moves to the file `target`: an
1004 /// encrypted file's entries go only to another encrypted file, which takes the same
1005 /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
1006 /// since the tag they inherit doesn't go with them.
1007 private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation {
1008 // The target's passphrase, lent by the source for the move, isn't kept after it.
1009 if Self.isEncryptedFile(target), !isOpen(target) {
1010 DispatchQueue.main.async { [weak self] in
1011 guard let self, !self.isOpen(target) else { return }
1012 self.crypt.close(target)
1013 }
1014 }
1015 let from = (path as NSString).lastPathComponent, to = (target as NSString).lastPathComponent
1016 if Self.isEncryptedFile(path) {
1017 guard Self.isEncryptedFile(target) else {
1018 return .refused(String(localized: "\(from) is encrypted, and \(to) isn't; the entry wasn't moved."))
1019 }
1020 if crypt.passphrase(for: target) == nil, let passphrase = crypt.passphrase(for: path) {
1021 let disk = (try? diskFileSystem.read(URL(fileURLWithPath: target))).flatMap { $0 } ?? []
1022 guard CryptVault.opens(disk, passphrase: passphrase) else {
1023 return .refused(String(localized: "\(to) has another passphrase; open it first."))
1024 }
1025 crypt.unlock(passphrase, for: target)
1026 }
1027 }
1028 guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(context.text, at: context.selection.first?.lowerBound ?? 0) else { return .ready }
1029 let end = OrgCrypt.bodyRange(context.text, at: heading)?.upperBound ?? heading
1030 let subtree = heading..<max(heading + 1, end)
1031 guard !OrgCrypt.unencrypted(context.text, tag: cryptTag, within: subtree).isEmpty else { return .ready }
1032 guard let passphrase = crypt.passphrase(for: path) else {
1033 return .refused(String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first."))
1034 }
1035 let sealed: String
1036 do {
1037 sealed = try OrgCrypt.seal(context.text, passphrase: passphrase, tag: cryptTag, within: subtree).text
1038 } catch {
1039 return .refused("\(error)")
1040 }
1041 let edit = EditResult(baseRevision: context.revision, edits: lineEdits(from: context.text, to: sealed))
1042 if let open = entry(path) {
1043 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: Date(), answers: [:]) { return .refused(message) }
1044 changed(open)
1045 } else {
1046 do {
1047 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") }
1048 var state = loaded(bytes, path: path)
1049 try state.apply(edit.edits, baseRevision: state.revision)
1050 if case .conflict = try saver.save(&state, to: URL(fileURLWithPath: path)) { return .refused("\(from) changed on disk; nothing was moved.") }
1051 } catch {
1052 return .refused("Can't encrypt the entry: \(error.localizedDescription)")
1053 }
1054 }
1055 return .sealed(heading)
1056 }
1057
776 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell. 1058 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell.
777 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? { 1059 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
778 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil } 1060 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil }
@@ -783,12 +1065,21 @@ public final class DocumentSession {
783 /// Returns a message. 1065 /// Returns a message.
784 @discardableResult 1066 @discardableResult
785 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? { 1067 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
786 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." } 1068 guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
787 let destination: Archive.Destination 1069 let destination: Archive.Destination
788 switch Archive.destination(context, sourcePath: path) { 1070 switch Archive.destination(context, sourcePath: path) {
789 case .success(let value): destination = value 1071 case .success(let value): destination = value
790 case .failure(.message(let message)): return message 1072 case .failure(.message(let message)): return message
791 } 1073 }
1074 if !destination.isSameFile {
1075 switch prepareMove(path, context: context, to: destination.path) {
1076 case .refused(let message): return message
1077 case .sealed(let heading):
1078 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
1079 context = again.context
1080 case .ready: break
1081 }
1082 }
792 // An archive file open in a buffer takes the subtree there. 1083 // An archive file open in a buffer takes the subtree there.
793 if !destination.isSameFile, let open = entry(destination.path) { 1084 if !destination.isSameFile, let open = entry(destination.path) {
794 let state = open.buffer.document 1085 let state = open.buffer.document
@@ -913,7 +1204,9 @@ public final class DocumentSession {
913 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." } 1204 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
914 guard state.text == expected else { return stale } 1205 guard state.text == expected else { return stale }
915 if entry.buffer is StateBuffer { 1206 if entry.buffer is StateBuffer {
916 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch { 1207 // A buffer held for its passphrase keeps no copy: it can't be kept encrypted,
1208 // and the replacement can be undone in the buffer.
1209 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch is CryptHold {} catch {
917 return "Can't keep a copy of \(name): \(error.localizedDescription)" 1210 return "Can't keep a copy of \(name): \(error.localizedDescription)"
918 } 1211 }
919 } 1212 }
@@ -952,6 +1245,7 @@ public final class DocumentSession {
952 } 1245 }
953 guard let entry = current else { return "No file is open." } 1246 guard let entry = current else { return "No file is open." }
954 let path = entry.path 1247 let path = entry.path
1248 if let refusal = refusesEmacsCopy(path) { return refusal }
955 let snapshot = entry.buffer.document.text as NSString 1249 let snapshot = entry.buffer.document.text as NSString
956 guard table.upperBound <= snapshot.length else { return "The table moved; try again." } 1250 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
957 let old = snapshot.substring(with: NSRange(table)) 1251 let old = snapshot.substring(with: NSRange(table))
Sources/OrgApp/Handoff.swift +2 · view
@@ -246,6 +246,8 @@ extension DocumentSession {
246 /// in none of `roots` or an encrypted one. 246 /// in none of `roots` or an encrypted one.
247 public func handoffPlace(_ path: String? = nil, roots: [String]) -> HandoffPlace? { 247 public func handoffPlace(_ path: String? = nil, roots: [String]) -> HandoffPlace? {
248 guard let path = path ?? self.path, let text = document(of: path)?.text else { return nil } 248 guard let path = path ?? self.path, let text = document(of: path)?.text else { return nil }
249 // The outline and ID could name decrypted headings.
250 guard !crypt.isPrivate(text, for: path) else { return nil }
249 return HandoffPlace.make(path: path, text: text, caret: caret(of: path) ?? 0, roots: roots, settings: defaults) 251 return HandoffPlace.make(path: path, text: text, caret: caret(of: path) ?? 0, roots: roots, settings: defaults)
250 } 252 }
251} 253}
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/OrgApp/OrgPreferences.swift +4 · view
@@ -236,6 +236,10 @@ public enum OrgPreferences {
236 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces) 236 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces)
237 return tag.isEmpty ? "crypt" : tag 237 return tag.isEmpty ? "crypt" : tag
238 } 238 }
239 /// `org-crypt-use-before-save-magic`.
240 public static func cryptBeforeSave(_ defaults: UserDefaults = .standard) -> Bool {
241 bool("cryptBeforeSave", defaults)
242 }
239 /// `org-icalendar-combined-agenda-file`, `~` expanded. 243 /// `org-icalendar-combined-agenda-file`, `~` expanded.
240 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String { 244 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String {
241 OrgPaths.expandingTilde(string("icalendarCombinedAgendaFile", defaults)) 245 OrgPaths.expandingTilde(string("icalendarCombinedAgendaFile", defaults))
Sources/OrgApp/SubtreeShare.swift +31 −2 · view
@@ -62,9 +62,38 @@ public struct SubtreeShare: Sendable, Identifiable {
62} 62}
63 63
64extension DocumentSession { 64extension DocumentSession {
65 /// Share Subtree… for the entry at `offset` in the open file at `path`. 65 /// Share Subtree… for the entry at `offset` in the open file at `path`, its tagged entries
66 /// encrypted as they are on disk. Nil when there's no entry there, or `refusesSubtreeShare`.
66 public func subtreeShare(_ path: String, at offset: Int) -> SubtreeShare? { 67 public func subtreeShare(_ path: String, at offset: Int) -> SubtreeShare? {
67 guard let text = document(of: path)?.text else { return nil } 68 guard refusesSubtreeShare(path, at: offset) == nil, var text = document(of: path)?.text else { return nil }
69 var offset = offset
70 if let (sealed, heading) = sealedSubtree(path, text: text, at: offset) {
71 text = sealed
72 offset = heading
73 }
68 return SubtreeShare(text: text, at: offset, path: path, settings: defaults) 74 return SubtreeShare(text: text, at: offset, path: path, settings: defaults)
69 } 75 }
76
77 /// Why the entry at `offset` in `path` isn't shared: its file is encrypted, or it has tagged
78 /// entries the file encrypts on disk and their passphrase isn't known.
79 public func refusesSubtreeShare(_ path: String, at offset: Int) -> String? {
80 let name = (path as NSString).lastPathComponent
81 if Self.isEncryptedFile(path) { return String(localized: "\(name) is encrypted; its entries aren't shared.") }
82 guard let text = document(of: path)?.text, crypt.sealsEntries(for: path), crypt.passphrase(for: path) == nil,
83 let range = subtreeRange(text, at: offset), !OrgCrypt.unencrypted(text, tag: cryptTag, within: range).isEmpty else { return nil }
84 return String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first.")
85 }
86
87 private func subtreeRange(_ text: String, at offset: Int) -> Range<Int>? {
88 guard let heading = OrgCrypt.heading(text, at: offset) else { return nil }
89 return heading..<max(heading + 1, OrgCrypt.bodyRange(text, at: heading)?.upperBound ?? heading)
90 }
91
92 /// `text` with the subtree's tagged entries encrypted, and where its heading starts.
93 private func sealedSubtree(_ path: String, text: String, at offset: Int) -> (String, Int)? {
94 guard crypt.sealsEntries(for: path), let passphrase = crypt.passphrase(for: path), let range = subtreeRange(text, at: offset),
95 !OrgCrypt.unencrypted(text, tag: cryptTag, within: range).isEmpty,
96 let sealed = try? OrgCrypt.seal(text, passphrase: passphrase, tag: cryptTag, within: range).text else { return nil }
97 return (sealed, range.lowerBound)
98 }
70} 99}
Sources/OrgApp/UserConfig.swift +2 · view
@@ -222,6 +222,8 @@ public enum UserConfig {
222 comment: "files dropped on the editor: ask, attach, open or file-link", legacy: ""), 222 comment: "files dropped on the editor: ask, attach, open or file-link", legacy: ""),
223 Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"), 223 Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"),
224 comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""), 224 comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""),
225 Setting(section: "", key: "org-crypt-use-before-save-magic", defaultsKey: "cryptBeforeSave", kind: .bool, fallback: .bool(false),
226 comment: "encrypt entries with org-crypt-tag-matcher's tag on every save; without their passphrase the file isn't saved", legacy: ""),
225 Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages", 227 Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages",
226 kind: .choice([("skip", "skip"), ("download", "download"), ("cache", "cache")]), fallback: .string("skip"), 228 kind: .choice([("skip", "skip"), ("download", "download"), ("cache", "cache")]), fallback: .string("skip"),
227 comment: "images at http(s) links: skip, download (each run) or cache (kept on disk)", legacy: ""), 229 comment: "images at http(s) links: skip, download (each run) or cache (kept on disk)", legacy: ""),
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/Commands/ClockHistory.swift +15 −2 · view
@@ -12,12 +12,16 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
12 /// The heading's index among the file's headings. 12 /// The heading's index among the file's headings.
13 public let ordinal: Int 13 public let ordinal: Int
14 public let id: String? 14 public let id: String?
15 /// The title is a placeholder for one that isn't kept (an encrypted heading's): the task
16 /// is found by its ID or position.
17 public let titleHidden: Bool?
15 18
16 public init(path: String, title: String, ordinal: Int, id: String?) { 19 public init(path: String, title: String, ordinal: Int, id: String?, titleHidden: Bool? = nil) {
17 self.path = path 20 self.path = path
18 self.title = title 21 self.title = title
19 self.ordinal = ordinal 22 self.ordinal = ordinal
20 self.id = id 23 self.id = id
24 self.titleHidden = titleHidden
21 } 25 }
22 26
23 /// The entry containing `offset`; nil before the first heading. 27 /// The entry containing `offset`; nil before the first heading.
@@ -28,9 +32,11 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
28 return ClockTask(path: path, title: heading.title, ordinal: index, id: heading.id) 32 return ClockTask(path: path, title: heading.title, ordinal: index, id: heading.id)
29 } 33 }
30 34
31 /// The heading's index in `model`, or nil when the entry is gone. 35 /// The heading's index in `model`, or nil when the entry is gone: by ID, then by position
36 /// and title, or by title; a task kept without its title by position alone.
32 public func index(in model: DocumentModel) -> Int? { 37 public func index(in model: DocumentModel) -> Int? {
33 if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index } 38 if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index }
39 if titleHidden == true { return ordinal < model.headings.count ? ordinal : nil }
34 if ordinal < model.headings.count, model.headings[ordinal].title == title { return ordinal } 40 if ordinal < model.headings.count, model.headings[ordinal].title == title { return ordinal }
35 return model.headings.firstIndex { $0.title == title } 41 return model.headings.firstIndex { $0.title == title }
36 } 42 }
@@ -46,6 +52,13 @@ public struct ClockTask: Codable, Equatable, Hashable, Sendable {
46 let model = DocumentModel(tree: OrgParser.parse(text)) 52 let model = DocumentModel(tree: OrgParser.parse(text))
47 guard let index = index(in: model) else { return nil } 53 guard let index = index(in: model) else { return nil }
48 return ClockTask(path: path, title: model.headings[index].title, ordinal: index, id: model.headings[index].id) 54 return ClockTask(path: path, title: model.headings[index].title, ordinal: index, id: model.headings[index].id)
55 .hiding(titleHidden == true ? title : nil)
56 }
57
58 /// The task with `placeholder` for its title, or as it is with nil.
59 public func hiding(_ placeholder: String?) -> ClockTask {
60 guard let placeholder else { return self }
61 return ClockTask(path: path, title: placeholder, ordinal: ordinal, id: id, titleHidden: true)
49 } 62 }
50} 63}
51 64
Sources/OrgCore/Crypto/OpenPGP.swift +93 −13 · 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")
@@ -329,17 +392,34 @@ public enum OpenPGP {
329 /// `gpg --symmetric --armor`: AES-256, an iterated and salted SHA-256 key, integrity 392 /// `gpg --symmetric --armor`: AES-256, an iterated and salted SHA-256 key, integrity
330 /// protection, binary literal data without a name. 393 /// protection, binary literal data without a name.
331 public static func encrypt(_ data: Data, passphrase: String, now: Date = Date()) throws -> String { 394 public static func encrypt(_ data: Data, passphrase: String, now: Date = Date()) throws -> String {
332 let salt = random(8) 395 armor(try encryptedMessage(data, passphrase: passphrase, now: now))
333 let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (96 & 15)) << ((96 >> 4) + 6)) 396 }
397
398 /// Whether `data` is an armored message rather than packets.
399 public static func isArmored(_ data: Data) -> Bool {
400 let head = String(decoding: data.prefix(64), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
401 return head.hasPrefix("-----BEGIN PGP MESSAGE")
402 }
403
404 /// The literal data of a passphrase-encrypted file, armored or not, as `gpg --decrypt` reads it.
405 public static func decryptFile(_ data: Data, passphrase: String) throws -> Data {
406 try decrypt(isArmored(data) ? dearmor(String(decoding: data, as: UTF8.self)) : data, passphrase: passphrase)
407 }
408
409 /// `gpg --symmetric` without `--armor`: the packets of `encrypt`.
410 public static func encryptedMessage(_ data: Data, passphrase: String, now: Date = Date()) throws -> Data {
411 let salt = try random(8)
412 let c = Int(codedCount)
413 let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (c & 15)) << ((c >> 4) + 6))
334 let key = try s2k.key(passphrase, size: 32) 414 let key = try s2k.key(passphrase, size: 32)
335 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]))
336 let date = UInt32(max(0, now.timeIntervalSince1970)) 416 let date = UInt32(max(0, now.timeIntervalSince1970))
337 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)
338 var prefix = random(16) 418 var prefix = try random(16)
339 prefix.append(prefix.suffix(2)) 419 prefix.append(prefix.suffix(2))
340 var plain = prefix + literal + Data([0xD3, 0x14]) 420 var plain = prefix + literal + Data([0xD3, 0x14])
341 plain.append(Data(Insecure.SHA1.hash(data: plain))) 421 plain.append(Data(Insecure.SHA1.hash(data: plain)))
342 let seipd = packet(18, Data([1]) + (try cfb(plain, key: key, encrypt: true))) 422 let seipd = packet(18, Data([1]) + (try cfb(plain, key: key, encrypt: true)))
343 return armor(skesk + seipd) 423 return skesk + seipd
344 } 424 }
345} 425}
Sources/OrgCore/Crypto/OrgCrypt.swift +108 −1 · view
@@ -1,12 +1,14 @@
1import CryptoKit
1import Foundation 2import Foundation
2 3
3/// org-crypt (org-crypt.el, Org 9.8.7) with symmetric encryption, as with `org-crypt-key` 4/// org-crypt (org-crypt.el, Org 9.8.7) with symmetric encryption, as with `org-crypt-key`
4/// nil: an entry's text after its planning, properties and logbook, through the end of its 5/// nil: an entry's text after its planning, properties and logbook, through the end of its
5/// subtree, replaced by an armored OpenPGP message under the heading. 6/// subtree, replaced by an armored OpenPGP message under the heading.
6public enum OrgCrypt { 7public enum OrgCrypt {
7 public struct Failure: Error, Equatable, CustomStringConvertible { 8 public struct Failure: Error, Equatable, CustomStringConvertible, LocalizedError {
8 public let description: String 9 public let description: String
9 public init(_ description: String) { self.description = description } 10 public init(_ description: String) { self.description = description }
11 public var errorDescription: String? { description }
10 } 12 }
11 13
12 /// `org-end-of-meta-data 'standard`: past planning, the property drawer, clock lines, 14 /// `org-end-of-meta-data 'standard`: past planning, the property drawer, clock lines,
@@ -134,4 +136,109 @@ public enum OrgCrypt {
134 } 136 }
135 return (text, count) 137 return (text, count)
136 } 138 }
139
140 /// What saving does with the tagged entry at `heading`: nil when nothing (its text is a
141 /// message, or it has no text), else its text's range, the message at its start if any,
142 /// and whether it has text that isn't blank outside a message.
143 static func pending(_ text: String, at heading: Int) -> (body: Range<Int>, message: Range<Int>?, hasText: Bool)? {
144 guard let body = bodyRange(text, at: heading) else { return nil }
145 let ns = text as NSString
146 func blank(_ range: Range<Int>) -> Bool {
147 range.isEmpty || ns.substring(with: NSRange(range)).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
148 }
149 if let message = encryptedRange(text, at: heading) {
150 // Text typed below the message isn't encrypted.
151 let tail = min(message.upperBound, body.upperBound)..<max(message.upperBound, body.upperBound)
152 return blank(tail) ? nil : (body, message, true)
153 }
154 return (body, nil, !blank(body))
155 }
156
157 /// The tagged entries `seal` encrypts whose text isn't blank: those a save can't write
158 /// without the passphrase, text below a message included. Their headings' offsets.
159 public static func unencrypted(_ text: String, tag: String = "crypt", settings: OrgSettings = .default, within: Range<Int>? = nil) -> [Int] {
160 guard text.contains(tag) else { return [] }
161 var found: [Int] = []
162 var covered = 0
163 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered && within?.contains(heading) ?? true {
164 guard let entry = pending(text, at: heading) else { continue }
165 // Tagged children go inside this entry's message.
166 covered = entry.body.upperBound
167 if entry.hasText { found.append(heading) }
168 }
169 return found
170 }
171
172 /// `org-encrypt-entries` as `org-crypt-use-before-save-magic` runs it before a save. An
173 /// entry whose text `reuse` knows by its `checksum` gets that message again, as org-crypt
174 /// keeps an entry decrypted and left unchanged byte for byte. Text below an entry's message
175 /// goes into one message with what the old one held. The text, and each message with the
176 /// text the entry had.
177 public static func seal(
178 _ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default,
179 reuse: (String) -> String? = { _ in nil }, within: Range<Int>? = nil, now: Date = Date()
180 ) throws -> (text: String, messages: [(message: String, plaintext: String)]) {
181 guard text.contains(tag) else { return (text, []) }
182 var result = text as NSString
183 var messages: [(String, String)] = []
184 var shift = 0
185 var covered = 0
186 for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered && within?.contains(heading) ?? true {
187 let current = result as String
188 guard let entry = pending(current, at: heading + shift) else { continue }
189 let range = entry.body
190 covered = range.upperBound - shift
191 let contents = result.substring(with: NSRange(range))
192 var plaintext = contents
193 if let old = entry.message {
194 let opened: String
195 do {
196 opened = try decrypt(current, at: heading + shift, passphrase: passphrase).plaintext
197 } catch {
198 throw Failure("An entry has text below a message that this passphrase doesn't open; entries encrypted to a public key aren't supported")
199 }
200 plaintext = opened + result.substring(with: NSRange(old.upperBound..<range.upperBound))
201 }
202 let message = try reuse(checksum(contents)) ?? OpenPGP.encrypt(Data(plaintext.utf8), passphrase: passphrase, now: now)
203 result = result.replacingCharacters(in: NSRange(range), with: message) as NSString
204 shift += (message as NSString).length - range.count
205 messages.append((message, contents))
206 }
207 return (result as String, messages)
208 }
209
210 /// Whether `offset` is in the text of an entry with `tag`, which a message holds on disk.
211 public static func isInTaggedText(_ text: String, at offset: Int, tag: String = "crypt", settings: OrgSettings = .default) -> Bool {
212 guard text.contains(tag) else { return false }
213 return taggedHeadings(text, tag: tag, settings: settings).contains { heading in
214 heading < offset && (bodyRange(text, at: heading)?.contains(offset) ?? false)
215 }
216 }
217
218 /// What an entry's text is known by, as `org-crypt-checksum` is.
219 public static func checksum(_ contents: String) -> String {
220 SHA256.hash(data: Data(contents.utf8)).map { String(format: "%02x", $0) }.joined()
221 }
222
223 /// The first entry's message in `text` encrypted with a passphrase; entries encrypted to a
224 /// public key are passed over.
225 public static func firstMessage(_ text: String) -> String? {
226 let ns = text as NSString
227 var search = NSRange(location: 0, length: ns.length)
228 while true {
229 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", options: [], range: search)
230 guard begin.location != NSNotFound else { return nil }
231 let lineStart = ns.lineRange(for: NSRange(location: begin.location, length: 0)).location
232 if let range = encryptedRange(text, at: lineStart), range.lowerBound == lineStart {
233 let message = ns.substring(with: NSRange(range))
234 if let data = try? OpenPGP.dearmor(message), OpenPGP.isSymmetric(data) { return message }
235 }
236 search = NSRange(location: NSMaxRange(begin), length: ns.length - NSMaxRange(begin))
237 }
238 }
239
240 /// Whether `passphrase` opens `message`.
241 public static func opens(_ message: String, passphrase: String) -> Bool {
242 (try? OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)) != nil
243 }
137} 244}
Sources/OrgDocument/Crypt.swift added +328 · view
@@ -0,0 +1,328 @@
1import Foundation
2import OrgCore
3
4/// Why a file can't be written: what it would put on disk unencrypted.
5public enum CryptHold: Error, Equatable, Sendable {
6 /// This many crypt-tagged entries with text aren't encrypted, and their passphrase isn't known.
7 case entries(Int)
8 /// An encrypted file (`.org.gpg`) whose passphrase isn't known.
9 case file
10 /// Saving failed for a reason a passphrase can't fix, said here: an entry with text below
11 /// a message that the file's passphrase doesn't open.
12 case blocked(String)
13}
14
15/// Why an encrypted file can't be read.
16public enum CryptReadError: Error, Equatable, Sendable {
17 /// Its passphrase isn't known.
18 case locked
19 case wrongPassphrase
20 case failed(String)
21}
22
23/// What the session knows about encrypted text, by file: the passphrases unlocked while the
24/// file is open, and for entries org-crypt encrypts on save (`org-crypt-use-before-save-magic`)
25/// the messages and the text each holds. Through `CryptFileSystem`, buffers keep the
26/// decrypted text while the file holds messages.
27public final class CryptVault: @unchecked Sendable {
28 private let lock = NSLock()
29 private var entries = false
30 private var entryTag = "crypt"
31 private var passphrases: [String: String] = [:]
32 /// By file: messages for entry texts by checksum, to give an unchanged entry its message again.
33 private var reuse: [String: [String: String]] = [:]
34 /// By file: the text of each message this session wrote, to read the file back as the buffer has it.
35 private var revealed: [String: [String: String]] = [:]
36 /// By file: whether the encrypted file was armored when read.
37 private var armored: [String: Bool] = [:]
38 /// Files that seal tagged entries until they close, whatever the setting says now: those
39 /// it was on for, so that turning it off never writes what was encrypted in plaintext.
40 private var sealing: Set<String> = []
41 /// Files open in a buffer. Only they keep what the vault knows past a write.
42 private var open: Set<String> = []
43 /// By encrypted file: its bytes on disk and their text, last read or written.
44 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:]
45
46 public init() {}
47
48 private func locked<T>(_ body: () throws -> T) rethrows -> T {
49 lock.lock()
50 defer { lock.unlock() }
51 return try body()
52 }
53
54 private static func key(_ path: String) -> String { URL(fileURLWithPath: path).standardizedFileURL.path }
55
56 /// Whether `path` is a whole encrypted file, as EasyPG's `epa-file` opens `.gpg` files.
57 public static func isEncryptedFile(_ path: String) -> Bool { path.hasSuffix(".gpg") }
58
59 /// `org-crypt-use-before-save-magic`.
60 public var encryptsTaggedEntries: Bool {
61 get { locked { entries } }
62 set { locked { entries = newValue } }
63 }
64
65 /// `org-crypt-tag-matcher`.
66 public var tag: String {
67 get { locked { entryTag } }
68 set { locked { entryTag = newValue } }
69 }
70
71 public func passphrase(for path: String) -> String? {
72 locked { passphrases[Self.key(path)] }
73 }
74
75 /// Whether saving `key` seals its tagged entries: the setting is on, or was while the
76 /// file was open. Call with the lock held.
77 private func seals(_ key: String) -> Bool {
78 if entries, open.contains(key) { sealing.insert(key) }
79 return entries || sealing.contains(key) || !(revealed[key]?.isEmpty ?? true)
80 }
81
82 /// Whether saving `path` encrypts its tagged entries.
83 public func sealsEntries(for path: String) -> Bool {
84 let key = Self.key(path)
85 return locked { seals(key) }
86 }
87
88 /// `passphrase` encrypts and decrypts `path` until it's forgotten. Messages kept for reuse
89 /// under another passphrase are dropped.
90 public func unlock(_ passphrase: String, for path: String) {
91 let key = Self.key(path)
92 locked {
93 if passphrases[key] != passphrase {
94 reuse[key] = nil
95 lastFile[key] = nil
96 }
97 passphrases[key] = passphrase
98 _ = seals(key)
99 }
100 }
101
102 /// Drops the passphrase of `path`; the next save that needs it is held.
103 public func forgetPassphrase(for path: String) {
104 let key = Self.key(path)
105 locked {
106 passphrases[key] = nil
107 reuse[key] = nil
108 }
109 }
110
111 private func dropIfClosed(_ key: String) {
112 locked {
113 guard !open.contains(key) else { return }
114 passphrases[key] = nil
115 reuse[key] = nil
116 revealed[key] = nil
117 armored[key] = nil
118 lastFile[key] = nil
119 sealing.remove(key)
120 }
121 }
122
123 /// Whether the vault keeps anything for `path`.
124 public func keepsAnything(for path: String) -> Bool {
125 let key = Self.key(path)
126 return locked { passphrases[key] != nil || !(revealed[key]?.isEmpty ?? true) || !(reuse[key]?.isEmpty ?? true) || lastFile[key] != nil || sealing.contains(key) }
127 }
128
129 /// `path` is open in a buffer.
130 public func opened(_ path: String) {
131 let key = Self.key(path)
132 locked { _ = open.insert(key) }
133 }
134
135 /// Drops everything kept for `path`, as when its buffer closes.
136 public func close(_ path: String) {
137 let key = Self.key(path)
138 locked {
139 open.remove(key)
140 passphrases[key] = nil
141 reuse[key] = nil
142 revealed[key] = nil
143 armored[key] = nil
144 sealing.remove(key)
145 lastFile[key] = nil
146 }
147 }
148
149 /// The entry of `path` holding `plaintext` was decrypted from `message`: while it stays
150 /// so, saving writes `message` back unchanged.
151 public func remember(message: String, plaintext: String, for path: String) {
152 let key = Self.key(path)
153 locked {
154 reuse[key, default: [:]][OrgCrypt.checksum(plaintext)] = message
155 _ = seals(key)
156 }
157 }
158
159 /// What keeps `text`, the buffer of `path`, from being written: tagged entries without a
160 /// known passphrase, or an encrypted file without one. Nil when it can be written.
161 public func hold(_ text: String, for path: String) -> CryptHold? {
162 let key = Self.key(path)
163 let (passphrase, entries, tag) = locked { (passphrases[key], seals(key), entryTag) }
164 guard passphrase == nil else { return nil }
165 if Self.isEncryptedFile(path) { return .file }
166 guard entries else { return nil }
167 let count = OrgCrypt.unencrypted(text, tag: tag).count
168 return count > 0 ? .entries(count) : nil
169 }
170
171 /// Whether `text`, the buffer of `path`, holds anything that isn't on disk as it shows:
172 /// an encrypted file, or entries decrypted that saving encrypts. Such a buffer is left out
173 /// of what other views read and keep (`DocumentSession.openTexts`).
174 public func isPrivate(_ text: String, for path: String) -> Bool {
175 if Self.isEncryptedFile(path) { return true }
176 let key = Self.key(path)
177 let (entries, tag, revealing) = locked { (seals(key), entryTag, !(revealed[key]?.isEmpty ?? true)) }
178 return revealing || (entries && !OrgCrypt.unencrypted(text, tag: tag).isEmpty)
179 }
180
181 // MARK: - Reading and writing
182
183 /// The text of messages this session wrote for `path`.
184 public func revealedMessages(for path: String) -> [String: String] {
185 locked { revealed[Self.key(path)] ?? [:] }
186 }
187
188 /// `bytes` from disk as the buffer of `path` has them: the file decrypted, and the
189 /// messages this session wrote (`messages`, by default those known now) back to their text.
190 public func plain(_ bytes: [UInt8], for path: String, messages: [String: String]? = nil) throws -> [UInt8] {
191 var bytes = bytes
192 if Self.isEncryptedFile(path) { bytes = try decryptFile(bytes, for: path) }
193 let known = messages ?? revealedMessages(for: path)
194 guard !known.isEmpty, var text = Self.text(bytes), text.contains("-----BEGIN PGP MESSAGE-----") else { return bytes }
195 for (message, plaintext) in known where text.contains(message) {
196 text = text.replacingOccurrences(of: message, with: plaintext)
197 }
198 return Array(text.utf8)
199 }
200
201 /// `bytes`, the buffer of `path`, as the file holds them: tagged entries encrypted, then
202 /// the file encrypted, and the messages written for entries. Throws `CryptHold` when a
203 /// passphrase is needed and not known.
204 public func cipher(_ bytes: [UInt8], for path: String) throws -> (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?) {
205 let key = Self.key(path)
206 let (passphrase, entries, tag, known) = locked { (passphrases[key], seals(key), entryTag, reuse[key] ?? [:]) }
207 var bytes = bytes
208 var messages: [(String, String)] = []
209 if entries, let text = Self.text(bytes), text.contains(tag) {
210 if let passphrase {
211 let sealed = try OrgCrypt.seal(text, passphrase: passphrase, tag: tag, reuse: { known[$0] })
212 bytes = Array(sealed.text.utf8)
213 messages = sealed.messages
214 } else {
215 let count = OrgCrypt.unencrypted(text, tag: tag).count
216 if count > 0 { throw CryptHold.entries(count) }
217 }
218 }
219 if Self.isEncryptedFile(path) {
220 guard let passphrase else { throw CryptHold.file }
221 let plain = bytes
222 // The text the file holds already (a snapshot of it) is its bytes on disk, without
223 // another key's 65 MB of hashing.
224 if let last = locked({ lastFile[key] }), last.plain == plain { return (last.encrypted, messages, plain) }
225 let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase)
226 bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message)
227 return (bytes, messages, plain)
228 }
229 return (bytes, messages, nil)
230 }
231
232 /// `cipher`'s result was written to `path`: reading it back gives the messages' text, and
233 /// an unchanged entry keeps its message at the next save. Messages no longer in the file
234 /// are forgotten.
235 public func didWrite(_ written: (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?), to path: String) {
236 let key = Self.key(path)
237 locked {
238 // A file that isn't open keeps nothing (passphrase, messages, text) once the
239 // write's own reads are done.
240 if !open.contains(key) {
241 DispatchQueue.main.async { [weak self] in self?.dropIfClosed(key) }
242 }
243 revealed[key] = Dictionary(written.messages.map { ($0.message, $0.plaintext) }, uniquingKeysWith: { a, _ in a })
244 reuse[key] = Dictionary(written.messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) }, uniquingKeysWith: { a, _ in a })
245 if let plain = written.plain { lastFile[key] = (written.bytes, plain) }
246 }
247 }
248
249 /// Whether `passphrase` opens the encrypted file `bytes`; an empty file takes any.
250 public static func opens(_ bytes: [UInt8], passphrase: String) -> Bool {
251 bytes.isEmpty || (try? OpenPGP.decryptFile(Data(bytes), passphrase: passphrase)) != nil
252 }
253
254 private func decryptFile(_ bytes: [UInt8], for path: String) throws -> [UInt8] {
255 // New File makes an empty file: it has no passphrase until it's first saved.
256 guard !bytes.isEmpty else { return [] }
257 let key = Self.key(path)
258 guard let passphrase = locked({ passphrases[key] }) else { throw CryptReadError.locked }
259 // Saving reads the file two or three times; each key costs 65 MB of hashing.
260 if let last = locked({ lastFile[key] }), last.encrypted == bytes { return last.plain }
261 let data = Data(bytes)
262 do {
263 let plain = [UInt8](try OpenPGP.decryptFile(data, passphrase: passphrase))
264 locked {
265 armored[key] = OpenPGP.isArmored(data)
266 lastFile[key] = (bytes, plain)
267 }
268 return plain
269 } catch let failure as OpenPGP.Failure {
270 throw failure == OpenPGP.wrongPassphrase ? CryptReadError.wrongPassphrase : CryptReadError.failed(failure.description)
271 }
272 }
273
274 /// `bytes` as text when they are UTF-8 exactly, a BOM included.
275 private static func text(_ bytes: [UInt8]) -> String? {
276 let text = String(decoding: bytes, as: UTF8.self)
277 return text.utf8.elementsEqual(bytes) ? text : nil
278 }
279}
280
281/// Files read and written through a `CryptVault`: what the buffer holds decrypted goes to
282/// disk encrypted, and comes back as the buffer has it.
283public struct CryptFileSystem: FileSystem {
284 public let base: FileSystem
285 public let vault: CryptVault
286
287 public init(base: FileSystem, vault: CryptVault) {
288 self.base = base
289 self.vault = vault
290 }
291
292 public func read(_ url: URL) throws -> [UInt8]? {
293 try base.read(url).map { try vault.plain($0, for: url.path) }
294 }
295
296 public func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
297 let known = vault.revealedMessages(for: url.path)
298 let written = try vault.cipher(bytes, for: url.path)
299 let replaced = try base.replace(url, with: written.bytes)
300 // The version replaced, as it read before this write's messages were known (and while
301 // the encrypted file's last bytes still decrypt from memory).
302 let previous = replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 }
303 vault.didWrite(written, to: url.path)
304 return previous
305 }
306}
307
308/// Recovery versions and snapshots through a `CryptVault`: kept encrypted as the file is. When
309/// that needs a passphrase that isn't known, `keep` throws `CryptHold`, so a caller that
310/// promises a copy stops; a snapshot is skipped.
311public struct CryptRecoveryStore: RecoveryStore {
312 public let base: RecoveryStore
313 public let vault: CryptVault
314
315 public init(base: RecoveryStore, vault: CryptVault) {
316 self.base = base
317 self.vault = vault
318 }
319
320 public func keep(_ bytes: [UInt8], for url: URL, label: String) throws {
321 try base.keep(try vault.cipher(bytes, for: url.path).bytes, for: url, label: label)
322 }
323
324 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
325 guard let encrypted = try? vault.cipher(bytes, for: url.path).bytes else { return }
326 try base.keepSnapshot(encrypted, for: url)
327 }
328}
Sources/OrgDocument/Saving.swift +29 −5 · view
@@ -74,12 +74,12 @@ public struct Saver: Sendable {
74 let replaced = try fileSystem.replace(url, with: bytes) 74 let replaced = try fileSystem.replace(url, with: bytes)
75 state.didWrite(bytes) 75 state.didWrite(bytes)
76 if replaced != disk, let replaced { 76 if replaced != disk, let replaced {
77 try recovery.keep(replaced, for: url, label: "external") 77 return .overwroteExternalChange(keepOverwritten(replaced, base: disk ?? [], in: &state, url: url))
78 return .overwroteExternalChange(state.mergeOverwritten(replaced, base: disk ?? []))
79 } 78 }
80 79
81 if let after = try fileSystem.read(url), after != bytes { 80 if let after = try fileSystem.read(url), after != bytes {
82 try recovery.keep(bytes, for: url, label: "local") 81 // Ours is in the buffer whether or not a copy can be kept.
82 try? recovery.keep(bytes, for: url, label: "local")
83 return .changedAfterWrite(state.diskChanged(to: after)) 83 return .changedAfterWrite(state.diskChanged(to: after))
84 } 84 }
85 return merged.map { .mergedAndSaved($0) } ?? .saved 85 return merged.map { .mergedAndSaved($0) } ?? .saved
@@ -91,9 +91,33 @@ public struct Saver: Sendable {
91 /// one. The replaced version goes to recovery unless it is the merge base. 91 /// one. The replaced version goes to recovery unless it is the merge base.
92 public func overwrite(_ state: inout DocumentState, to url: URL) throws { 92 public func overwrite(_ state: inout DocumentState, to url: URL) throws {
93 let bytes = try state.encodedText() 93 let bytes = try state.encodedText()
94 if let replaced = try fileSystem.replace(url, with: bytes), replaced != state.mergeBase { 94 // The version Keep Mine replaces goes to recovery first; when it can't, nothing is written.
95 let disk = try fileSystem.read(url)
96 if let disk, disk != state.mergeBase { try recovery.keep(disk, for: url, label: "external") }
97 let base = state.mergeBase
98 let replaced = try fileSystem.replace(url, with: bytes)
99 state.didWrite(bytes)
100 if let replaced, replaced != disk, replaced != base {
101 _ = keepOverwritten(replaced, base: base, in: &state, url: url, merge: false)
102 }
103 }
104
105 /// `replaced`, a version another writer put on disk just before ours replaced it, kept: in
106 /// recovery and, when `merge`, merged into the buffer. When recovery can't keep it (it holds
107 /// text that can only be kept encrypted, without a passphrase) and it isn't merged, it goes
108 /// 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 {
110 let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([])
111 do {
95 try recovery.keep(replaced, for: url, label: "external") 112 try recovery.keep(replaced, for: url, label: "external")
113 return merge ? change : .unchanged
114 } catch {
115 if case .merged = change { return change }
116 let theirs = SourceText(bytes: replaced).text
117 let both = mergeWithMarkers(base: SourceText(bytes: base).text, ours: state.text, theirs: theirs, oursLabel: "yours", theirsLabel: "disk")
118 let edits = lineEdits(from: state.text, to: both)
119 guard (try? state.apply(edits, baseRevision: state.revision)) != nil else { return change }
120 return .merged(edits)
96 } 121 }
97 state.didWrite(bytes)
98 } 122 }
99} 123}
Sources/Orgstar/ContentView.swift +25 −10 · view
@@ -35,6 +35,8 @@ struct ContentView: View {
35 @State private var menuToday: [AgendaSnapshot.Row] = [] 35 @State private var menuToday: [AgendaSnapshot.Row] = []
36 @State private var hour = 0 36 @State private var hour = 0
37 @AppStorage("saveMode") private var saveMode = SaveMode.automatic 37 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
38 @AppStorage("cryptBeforeSave") private var cryptBeforeSave = false
39 @AppStorage("cryptTagMatcher") private var cryptTagMatcher = "crypt"
38 @AppStorage("keymap") private var preset = KeymapPreset.emacs 40 @AppStorage("keymap") private var preset = KeymapPreset.emacs
39 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue 41 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
40 @State private var keymap = KeymapPreset.emacs.keymap 42 @State private var keymap = KeymapPreset.emacs.keymap
@@ -194,6 +196,7 @@ struct ContentView: View {
194 .frame(height: 190) 196 .frame(height: 190)
195 Divider() 197 Divider()
196 } 198 }
199 CryptHoldBar(session: session) { commands.run("app.crypt.save") }
197 ModeLine(session: session, commands: commands) 200 ModeLine(session: session, commands: commands)
198 EchoArea(commands: commands) 201 EchoArea(commands: commands)
199 } 202 }
@@ -404,6 +407,9 @@ struct ContentView: View {
404 commands.editor = nil 407 commands.editor = nil
405 } 408 }
406 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode } 409 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
410 .modifier(CryptSettings(session: session, cryptBeforeSave: cryptBeforeSave, cryptTagMatcher: cryptTagMatcher) { path in
411 panel = .crypt(UUID(), CryptRequest(mode: .openFile, path: path, offset: 0))
412 })
407 .onChange(of: options, initial: true) { _, options in session.options = options } 413 .onChange(of: options, initial: true) { _, options in session.options = options }
408 .onAppear { TimerModel.shared.onDone = { [commands] in commands.show($0) } } 414 .onAppear { TimerModel.shared.onDone = { [commands] in commands.show($0) } }
409 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 } 415 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
@@ -754,6 +760,7 @@ struct ContentView: View {
754 #if !APPSTORE 760 #if !APPSTORE
755 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"]
756 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) }
757 commands.show(String(localized: "Exporting with Emacs…")) 764 commands.show(String(localized: "Exporting with Emacs…"))
758 commands.runInEmacs { 765 commands.runInEmacs {
759 do { 766 do {
@@ -883,17 +890,18 @@ struct ContentView: View {
883 let paths = workspace.agendaFilePaths() 890 let paths = workspace.agendaFilePaths()
884 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return } 891 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
885 let read = { (path: String) -> (text: String, settings: OrgSettings)? in 892 let read = { (path: String) -> (text: String, settings: OrgSettings)? in
886 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 }
887 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))
888 } 895 }
896 let note = paths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
889 do { 897 do {
890 let options = OrgPreferences.icalendarOptions() 898 let options = OrgPreferences.icalendarOptions()
891 if combined { 899 if combined {
892 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)
893 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)
894 } else { 902 } else {
895 let written = try ICalendarFiles.exportEach(paths, options: options, read: read) 903 let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
896 commands.show(String(localized: "Exported \(written.count) agenda files to iCalendar")) 904 commands.show(String(localized: "Exported \(written.count) agenda files to iCalendar") + note)
897 } 905 }
898 } catch { 906 } catch {
899 commands.show(String(localized: "Can't export: \(error.localizedDescription)")) 907 commands.show(String(localized: "Can't export: \(error.localizedDescription)"))
@@ -902,12 +910,17 @@ struct ContentView: View {
902 910
903 /// org-crypt's commands at the caret, through the passphrase sheet. 911 /// org-crypt's commands at the caret, through the passphrase sheet.
904 private func crypt(_ id: String) { 912 private func crypt(_ id: String) {
913 if id == "app.crypt.save" {
914 guard let path = session.path, let hold = session.held[path] else { return }
915 panel = .crypt(UUID(), CryptRequest.save(path, hold: hold))
916 return
917 }
905 guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No file is open")) } 918 guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No file is open")) }
906 let caret = editor.context().caret 919 let caret = editor.context().caret
907 let text = editor.context().text 920 let text = editor.context().text
908 switch id { 921 switch id {
909 case "app.crypt.forget-passphrase": 922 case "app.crypt.forget-passphrase":
910 CryptPassphrases.forget(path) 923 session.forgetPassphrase(for: path)
911 commands.show(String(localized: "Passphrase forgotten for \((path as NSString).lastPathComponent)")) 924 commands.show(String(localized: "Passphrase forgotten for \((path as NSString).lastPathComponent)"))
912 case "app.crypt.encrypt-entries": 925 case "app.crypt.encrypt-entries":
913 panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret)) 926 panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
@@ -996,8 +1009,10 @@ struct ContentView: View {
996 case .shareSubtree(_, let share): 1009 case .shareSubtree(_, let share):
997 ShareSubtreeSheet(share: share) { commands.show($0) } 1010 ShareSubtreeSheet(share: share) { commands.show($0) }
998 case .crypt(_, let request): 1011 case .crypt(_, let request):
999 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in 1012 CryptSheet(request: request, session: session, text: { session.document(of: request.path)?.text ?? "" }, apply: { applyText($0) }) { message in
1000 self.panel = nil 1013 self.panel = nil
1014 // An encrypted file left closed: the sidebar shows the open file again.
1015 if case .openFile = request.mode, !session.isOpen(request.path) { selectedFile = session.path }
1001 if let message { commands.show(message) } 1016 if let message { commands.show(message) }
1002 } 1017 }
1003 case .conflict: 1018 case .conflict:
@@ -1079,9 +1094,8 @@ struct ContentView: View {
1079 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first) 1094 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
1080 if let problem = loaded.problems.first { commands.show(problem) } 1095 if let problem = loaded.problems.first { commands.show(problem) }
1081 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")) }
1082 let read = { (path: String) -> String? in 1097 let read = { (path: String) -> String? in session.exportText(of: path) }
1083 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 : ""
1084 }
1085 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme) 1099 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
1086 func run(_ chosen: [PublishProject], only: String? = nil) { 1100 func run(_ chosen: [PublishProject], only: String? = nil) {
1087 // The chosen projects and their components read and write these folders. 1101 // The chosen projects and their components read and write these folders.
@@ -1091,8 +1105,8 @@ struct ContentView: View {
1091 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
1092 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)
1093 } 1107 }
1094 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")
1095 : 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)
1096 } catch { 1110 } catch {
1097 commands.show("\(error)") 1111 commands.show("\(error)")
1098 } 1112 }
@@ -1524,6 +1538,7 @@ struct ContentView: View {
1524 copyRichText() 1538 copyRichText()
1525 case "app.share-subtree": 1539 case "app.share-subtree":
1526 guard let path = session.path else { return commands.show(String(localized: "No file is open")) } 1540 guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1541 if let refusal = session.refusesSubtreeShare(path, at: session.caret) { return commands.show(refusal) }
1527 guard let share = session.subtreeShare(path, at: session.caret) else { return commands.show(String(localized: "Not in a subtree")) } 1542 guard let share = session.subtreeShare(path, at: session.caret) else { return commands.show(String(localized: "Not in a subtree")) }
1528 panel = .shareSubtree(UUID(), share) 1543 panel = .shareSubtree(UUID(), share)
1529 case "app.export-dialog": 1544 case "app.export-dialog":
Sources/Orgstar/CryptHoldBar.swift added +45 · view
@@ -0,0 +1,45 @@
1import OrgApp
2import OrgDocument
3import SwiftUI
4
5/// Above the mode line while the focused file isn't saved because it would put text on disk
6/// unencrypted: why, and the button that asks for the passphrase. Stays while it applies.
7struct CryptHoldBar: View {
8 let session: DocumentSession
9 let encrypt: () -> Void
10
11 var body: some View {
12 if let path = session.path, let hold = session.held[path] {
13 HStack(spacing: 8) {
14 Image(systemName: "lock.trianglebadge.exclamationmark").foregroundStyle(.orange)
15 Text(hold.notice(for: path)).lineLimit(3)
16 Spacer(minLength: 8)
17 if hold.takesPassphrase { Button(hold == .file ? "Set Passphrase…" : "Encrypt…", action: encrypt) }
18 }
19 .font(.callout)
20 .padding(.horizontal, 10)
21 .padding(.vertical, 5)
22 .frame(maxWidth: .infinity, alignment: .leading)
23 .background(Color.orange.opacity(0.12))
24 .accessibilityElement(children: .combine)
25 }
26 }
27}
28
29/// The session follows the org-crypt settings, and asks for the passphrase of an encrypted file
30/// it was asked to open.
31struct CryptSettings: ViewModifier {
32 let session: DocumentSession
33 let cryptBeforeSave: Bool
34 let cryptTagMatcher: String
35 let unlock: (String) -> Void
36
37 func body(content: Content) -> some View {
38 content
39 .onChange(of: cryptBeforeSave, initial: true) { _, on in session.encryptsTaggedEntries = on }
40 .onChange(of: cryptTagMatcher, initial: true) { session.cryptTag = OrgPreferences.cryptTag() }
41 .onChange(of: session.unlockRequest, initial: true) { _, path in
42 if let path { unlock(path) }
43 }
44 }
45}
Sources/Orgstar/EditorWindowView.swift +1 · view
@@ -24,6 +24,7 @@ struct EditorWindowView: View {
24 } 24 }
25 .safeAreaInset(edge: .bottom, spacing: 0) { 25 .safeAreaInset(edge: .bottom, spacing: 0) {
26 VStack(spacing: 0) { 26 VStack(spacing: 0) {
27 CryptHoldBar(session: session) { run("app.crypt.save") }
27 ModeLine(session: session, commands: commands) 28 ModeLine(session: session, commands: commands)
28 EchoArea(commands: commands) 29 EchoArea(commands: commands)
29 } 30 }
Sources/Orgstar/OrgstarApp.swift +62 −5 · view
@@ -324,8 +324,8 @@ enum UnsavedChanges {
324 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in 324 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
325 /// explicit mode. A save that fails or conflicts keeps the file open. 325 /// explicit mode. A save that fails or conflicts keeps the file open.
326 static func resolve(_ session: DocumentSession) -> Bool { 326 static func resolve(_ session: DocumentSession) -> Bool {
327 guard session.isDirty else { return true } 327 guard session.isDirty, let path = session.path else { return true }
328 if session.saveMode == .automatic { return session.save() } 328 if session.saveMode == .automatic { return save(session, path) }
329 let alert = NSAlert() 329 let alert = NSAlert()
330 alert.messageText = session.path.map { String(localized: "Save changes to \(($0 as NSString).lastPathComponent)?") } 330 alert.messageText = session.path.map { String(localized: "Save changes to \(($0 as NSString).lastPathComponent)?") }
331 ?? String(localized: "Save changes to this file?") 331 ?? String(localized: "Save changes to this file?")
@@ -334,7 +334,7 @@ enum UnsavedChanges {
334 alert.addButton(withTitle: String(localized: "Don't Save")) 334 alert.addButton(withTitle: String(localized: "Don't Save"))
335 alert.addButton(withTitle: String(localized: "Cancel")) 335 alert.addButton(withTitle: String(localized: "Cancel"))
336 switch alert.runModal() { 336 switch alert.runModal() {
337 case .alertFirstButtonReturn: return session.save() 337 case .alertFirstButtonReturn: return save(session, path)
338 case .alertSecondButtonReturn: return true 338 case .alertSecondButtonReturn: return true
339 default: return false 339 default: return false
340 } 340 }
@@ -345,7 +345,7 @@ enum UnsavedChanges {
345 static func resolve(_ session: DocumentSession, paths: [String]) -> Bool { 345 static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
346 let dirty = paths.filter(session.dirtyPaths.contains) 346 let dirty = paths.filter(session.dirtyPaths.contains)
347 guard !dirty.isEmpty else { return true } 347 guard !dirty.isEmpty else { return true }
348 if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } } 348 if session.saveMode == .automatic { return dirty.map { save(session, $0) }.allSatisfy { $0 } }
349 if dirty == [session.path] { return resolve(session) } 349 if dirty == [session.path] { return resolve(session) }
350 let alert = NSAlert() 350 let alert = NSAlert()
351 alert.messageText = String(localized: "Save changes to \(dirty.count) files?") 351 alert.messageText = String(localized: "Save changes to \(dirty.count) files?")
@@ -354,11 +354,65 @@ enum UnsavedChanges {
354 alert.addButton(withTitle: String(localized: "Don't Save")) 354 alert.addButton(withTitle: String(localized: "Don't Save"))
355 alert.addButton(withTitle: String(localized: "Cancel")) 355 alert.addButton(withTitle: String(localized: "Cancel"))
356 switch alert.runModal() { 356 switch alert.runModal() {
357 case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 } 357 case .alertFirstButtonReturn: return dirty.map { save(session, $0) }.allSatisfy { $0 }
358 case .alertSecondButtonReturn: return true 358 case .alertSecondButtonReturn: return true
359 default: return false 359 default: return false
360 } 360 }
361 } 361 }
362
363 /// Saves `path`. One held for its passphrase asks for it, or whether to leave without saving.
364 static func save(_ session: DocumentSession, _ path: String) -> Bool {
365 if session.save(path) { return true }
366 let name = (path as NSString).lastPathComponent
367 guard let hold = session.held[path], hold.takesPassphrase else {
368 // A save that failed otherwise (a conflict, an error, an entry the passphrase can't
369 // encrypt) still lets the file be left without saving.
370 let alert = NSAlert()
371 alert.messageText = String(localized: "Changes to \(name) aren't saved")
372 alert.informativeText = session.held[path]?.notice(for: path) ?? session.conflict ?? session.lastError ?? ""
373 alert.addButton(withTitle: String(localized: "Cancel"))
374 alert.addButton(withTitle: String(localized: "Don't Save"))
375 return alert.runModal() == .alertSecondButtonReturn
376 }
377 // A new passphrase is typed twice; one that must open what's encrypted already, once.
378 let twice = hold == .file || OrgCrypt.firstMessage(session.document(of: path)?.text ?? "") == nil
379 let fields = (twice ? [String(localized: "Passphrase"), String(localized: "Repeat passphrase")] : [String(localized: "Passphrase")]).map { placeholder in
380 let field = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 22))
381 field.placeholderString = placeholder
382 return field
383 }
384 let stack = NSStackView(views: fields)
385 stack.orientation = .vertical
386 stack.spacing = 6
387 stack.frame = NSRect(x: 0, y: 0, width: 260, height: CGFloat(fields.count) * 28)
388 var problem: String?
389 while true {
390 let alert = NSAlert()
391 alert.messageText = String(localized: "Changes to \(name) aren't saved")
392 alert.informativeText = (problem.map { $0 + "\n\n" } ?? "") + hold.notice(for: path) + " "
393 + String(localized: "Enter the passphrase to encrypt and save them, or leave without saving.")
394 alert.accessoryView = stack
395 alert.addButton(withTitle: String(localized: "Encrypt and Save"))
396 alert.addButton(withTitle: String(localized: "Don't Save"))
397 alert.addButton(withTitle: String(localized: "Cancel"))
398 alert.window.initialFirstResponder = fields[0]
399 switch alert.runModal() {
400 case .alertFirstButtonReturn:
401 let passphrase = fields[0].stringValue
402 if passphrase.isEmpty {
403 problem = String(localized: "Enter a passphrase.")
404 } else if twice, fields[1].stringValue != passphrase {
405 problem = String(localized: "The passphrases differ")
406 } else if let failure = session.unlock(passphrase, for: path) {
407 problem = failure
408 } else {
409 return !session.dirtyPaths.contains(path)
410 }
411 case .alertSecondButtonReturn: return true
412 default: return false
413 }
414 }
415 }
362} 416}
363 417
364/// The open buffers, their order and carets, kept for the next launch. 418/// The open buffers, their order and carets, kept for the next launch.
@@ -425,6 +479,9 @@ struct OrgstarApp: App {
425 @State private var session: DocumentSession = { 479 @State private var session: DocumentSession = {
426 let session = DocumentSession() 480 let session = DocumentSession()
427 session.defaults = Preferences.orgSettings 481 session.defaults = Preferences.orgSettings
482 // Before any window: capture and agenda edits can save before the main window opens.
483 session.encryptsTaggedEntries = OrgPreferences.cryptBeforeSave()
484 session.cryptTag = OrgPreferences.cryptTag()
428 return session 485 return session
429 }() 486 }()
430 487
Sources/OrgstarMobile/EditorScreen.swift +39 −6 · view
@@ -134,10 +134,34 @@ struct EditorScreen: View {
134 if let editor, let textView { 134 if let editor, let textView {
135 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette }) 135 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette })
136 .ignoresSafeArea(.container, edges: .bottom) 136 .ignoresSafeArea(.container, edges: .bottom)
137 } else if DocumentSession.isEncryptedFile(path), !session.isOpen(path) {
138 ContentUnavailableView {
139 Label("\((path as NSString).lastPathComponent) is encrypted", systemImage: "lock")
140 } actions: {
141 Button("Decrypt…") { sheet = .crypt(CryptRequest(mode: .openFile, path: path, offset: 0)) }
142 }
137 } else { 143 } else {
138 ProgressView() 144 ProgressView()
139 } 145 }
140 } 146 }
147 // While the file isn't saved for want of a passphrase, and why; stays while it applies.
148 .safeAreaInset(edge: .top, spacing: 0) {
149 if let hold = session.held[path] {
150 HStack(spacing: 10) {
151 Image(systemName: "lock.trianglebadge.exclamationmark").foregroundStyle(.orange)
152 Text(hold.notice(for: path)).font(.callout).fixedSize(horizontal: false, vertical: true)
153 Spacer(minLength: 4)
154 if hold.takesPassphrase {
155 Button(hold == .file ? "Set Passphrase…" : "Encrypt…") { sheet = .crypt(CryptRequest.save(path, hold: hold)) }
156 .buttonStyle(.borderedProminent)
157 }
158 }
159 .padding(.horizontal, 14).padding(.vertical, 8)
160 .glassEffect(.regular, in: .rect(cornerRadius: 18))
161 .padding(8)
162 .accessibilityElement(children: .combine)
163 }
164 }
141 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit)) 165 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit))
142 .toolbar(.hidden, for: .tabBar) 166 .toolbar(.hidden, for: .tabBar)
143 .toolbar { 167 .toolbar {
@@ -190,6 +214,8 @@ struct EditorScreen: View {
190 } 214 }
191 } 215 }
192 .sheet(item: $sheet, onDismiss: { 216 .sheet(item: $sheet, onDismiss: {
217 // An encrypted file opened with its passphrase.
218 if editor == nil, session.isOpen(path) { start() }
193 countVersions() 219 countVersions()
194 // After the sheet has gone, so a command's own prompt can show. 220 // After the sheet has gone, so a command's own prompt can show.
195 if let id = chosen { 221 if let id = chosen {
@@ -394,6 +420,10 @@ struct EditorScreen: View {
394 } 420 }
395 } 421 }
396 if pane.path != path { session.open(path, in: pane) } 422 if pane.path != path { session.open(path, in: pane) }
423 if session.unlockRequest == path {
424 sheet = .crypt(CryptRequest(mode: .openFile, path: path, offset: 0))
425 return
426 }
397 model.editors.prune(session) 427 model.editors.prune(session)
398 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return } 428 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
399 let view = model.editors.view(for: pane.id, of: editor) 429 let view = model.editors.view(for: pane.id, of: editor)
@@ -479,7 +509,9 @@ struct EditorScreen: View {
479 } else if id == EditorScreen.exportSubtreeCommand { 509 } else if id == EditorScreen.exportSubtreeCommand {
480 exportSubtree() 510 exportSubtree()
481 } else if id == "app.share-subtree" { 511 } else if id == "app.share-subtree" {
482 if let caret = self.editor?.editContext().caret, let share = session.subtreeShare(path, at: caret) { 512 if let caret = self.editor?.editContext().caret, let refusal = session.refusesSubtreeShare(path, at: caret) {
513 message = refusal
514 } else if let caret = self.editor?.editContext().caret, let share = session.subtreeShare(path, at: caret) {
483 sheet = .shareSubtree(share) 515 sheet = .shareSubtree(share)
484 } else { 516 } else {
485 message = String(localized: "Not in a subtree") 517 message = String(localized: "Not in a subtree")
@@ -730,15 +762,16 @@ extension EditorScreen {
730 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))" 762 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
731 } 763 }
732 let read = { (file: String) -> String? in 764 let read = { (file: String) -> String? in
733 session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8)) 765 session.exportText(of: file)
734 } 766 }
735 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme) 767 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
736 // As the Export menu: no author unless the file has #+AUTHOR:. 768 // As the Export menu: no author unless the file has #+AUTHOR:.
737 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in 769 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
738 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "") 770 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
739 } 771 }
740 message = report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files") 772 let note = session.openPaths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
741 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date") 773 message = (report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
774 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) + note
742 } catch { 775 } catch {
743 message = "\(error)" 776 message = "\(error)"
744 } 777 }
@@ -751,7 +784,7 @@ extension EditorScreen {
751 let context = editor.editContext() 784 let context = editor.editContext()
752 switch id { 785 switch id {
753 case "app.crypt.forget-passphrase": 786 case "app.crypt.forget-passphrase":
754 CryptPassphrases.forget(path) 787 session.forgetPassphrase(for: path)
755 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)" 788 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
756 case "app.crypt.encrypt-entries": 789 case "app.crypt.encrypt-entries":
757 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret)) 790 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
@@ -1227,7 +1260,7 @@ struct CryptScreen: View {
1227 1260
1228 var body: some View { 1261 var body: some View {
1229 NavigationStack { 1262 NavigationStack {
1230 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in 1263 CryptSheet(request: request, session: session, text: { session.document(of: request.path)?.text ?? "" }, apply: apply) { message in
1231 dismiss() 1264 dismiss()
1232 if let message { report(message) } 1265 if let message { report(message) }
1233 } 1266 }
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 }
Sources/OrgstarMobile/FoldersScreen.swift +1 −1 · view
@@ -332,7 +332,7 @@ private struct FolderContents: View {
332 } 332 }
333 333
334 var body: some View { 334 var body: some View {
335 let files = workspace.files.filter { $0.root == root && $0.kind == .org && $0.relativePath.hasPrefix(prefix) } 335 let files = workspace.files.filter { $0.root == root && ($0.kind == .org || DocumentSession.isEncryptedOrgFile($0.path)) && $0.relativePath.hasPrefix(prefix) }
336 let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) }) 336 let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) })
337 let empty = Set(emptySubfolders()) 337 let empty = Set(emptySubfolders())
338 let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in 338 let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in
Sources/OrgstarMobile/MobileModel.swift +2 · view
@@ -167,6 +167,8 @@ final class MobileModel {
167 let settings = OrgPreferences.orgSettings() 167 let settings = OrgPreferences.orgSettings()
168 session.defaults = settings 168 session.defaults = settings
169 session.options = OrgPreferences.options() 169 session.options = OrgPreferences.options()
170 session.encryptsTaggedEntries = OrgPreferences.cryptBeforeSave()
171 session.cryptTag = OrgPreferences.cryptTag()
170 session.options.snippets = SnippetLibrary.shared.snippets 172 session.options.snippets = SnippetLibrary.shared.snippets
171 workspace?.settings = .with(todoKeywords: settings) 173 workspace?.settings = .with(todoKeywords: settings)
172 if let agenda { 174 if let agenda {
Sources/OrgstarMobile/OrgstarMobileApp.swift +8 −1 · view
@@ -26,6 +26,8 @@ struct OrgstarMobileApp: App {
26 #endif 26 #endif
27 LiveClock.install() 27 LiveClock.install()
28 ProStore.shared.start() 28 ProStore.shared.start()
29 // Read before the app becomes active and clears it.
30 _ = UnsavedHeldFiles.atLaunch
29 // Early, so that the watch's actions are taken when iOS wakes the app for them. 31 // Early, so that the watch's actions are taken when iOS wakes the app for them.
30 WatchLink.shared.activate(MobileModel.shared) 32 WatchLink.shared.activate(MobileModel.shared)
31 } 33 }
@@ -406,6 +408,7 @@ struct RootView: View {
406 } 408 }
407 .task { 409 .task {
408 TimerModel.shared.onDone = { message = $0 } 410 TimerModel.shared.onDone = { message = $0 }
411 if let lost = UnsavedHeldFiles.atLaunch { message = lost }
409 takeShared() 412 takeShared()
410 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac. 413 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
411 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) } 414 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
@@ -430,10 +433,14 @@ struct RootView: View {
430 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) } 433 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
431 } 434 }
432 .onChange(of: scenePhase) { _, phase in 435 .onChange(of: scenePhase) { _, phase in
433 // Unsaved edits are written before the app may be stopped. 436 // Unsaved edits are written before the app may be stopped. A file held for its
437 // passphrase stays in memory; its name is kept so that, if iOS ends the app
438 // meanwhile, the next launch says its edits were lost.
434 if phase == .background { 439 if phase == .background {
435 for path in session.dirtyPaths { _ = session.save(path) } 440 for path in session.dirtyPaths { _ = session.save(path) }
441 UnsavedHeldFiles.record(session.held.keys.filter(session.dirtyPaths.contains).sorted())
436 } 442 }
443 if phase == .active { UnsavedHeldFiles.record([]) }
437 // Files and settings synced while away; not every sync tool tells file presenters. 444 // Files and settings synced while away; not every sync tool tells file presenters.
438 guard phase == .active else { return } 445 guard phase == .active else { return }
439 // iOS has no idle time: time away from the app while a clock ran stands in for it. 446 // iOS has no idle time: time away from the app while a clock ran stands in for it.
Sources/OrgstarMobile/ReaderScreen.swift +23 · view
@@ -45,6 +45,8 @@ struct ReaderScreen: View {
45 /// The command chosen in Commands, run once the list is gone. 45 /// The command chosen in Commands, run once the list is gone.
46 @State private var chosenCommand: String? 46 @State private var chosenCommand: String?
47 @State private var message: String? 47 @State private var message: String?
48 /// The passphrase sheet for an encrypted file.
49 @State private var unlocking: CryptRequest?
48 /// A file a link opened, shown in Quick Look. 50 /// A file a link opened, shown in Quick Look.
49 @State private var previewed: URL? 51 @State private var previewed: URL?
50 /// The pane the reader shows its file in, closed with the reader. 52 /// The pane the reader shows its file in, closed with the reader.
@@ -151,6 +153,27 @@ struct ReaderScreen: View {
151 if let path = shownPath, let tree = document?.tree { ExportScreen(path: path, tree: tree) { message = $0 } } 153 if let path = shownPath, let tree = document?.tree { ExportScreen(path: path, tree: tree) { message = $0 } }
152 } 154 }
153 .message($message) 155 .message($message)
156 .overlay {
157 if DocumentSession.isEncryptedFile(path), !session.isOpen(path), unlocking == nil {
158 ContentUnavailableView {
159 Label("\((path as NSString).lastPathComponent) is encrypted", systemImage: "lock")
160 } actions: {
161 Button("Decrypt…") { unlocking = CryptRequest(mode: .openFile, path: path, offset: 0) }
162 }
163 }
164 }
165 .onChange(of: session.unlockRequest, initial: true) { _, request in
166 if request == path { unlocking = CryptRequest(mode: .openFile, path: path, offset: 0) }
167 }
168 .sheet(item: $unlocking) { request in
169 NavigationStack {
170 CryptSheet(request: request, session: session, text: { "" }, apply: { _ in }) { text in
171 unlocking = nil
172 if let text { message = text }
173 }
174 .navigationBarTitleDisplayMode(.inline)
175 }
176 }
154 .environment(\.openURL, OpenURLAction { url in follow(url) }) 177 .environment(\.openURL, OpenURLAction { url in follow(url) })
155 .background { FindHost(find: find, request: findRequest) } 178 .background { FindHost(find: find, request: findRequest) }
156 .onAppear(perform: open) 179 .onAppear(perform: open)
Sources/OrgstarMobile/UnsavedHeldFiles.swift added +23 · view
@@ -0,0 +1,23 @@
1import Foundation
2
3/// The files held for their passphrase when the app went to the background. iOS may end the
4/// app there without asking, and their edits, kept only in memory, are lost: the next launch
5/// says so.
6enum UnsavedHeldFiles {
7 static let key = "heldFilesInBackground"
8
9 static func record(_ paths: [String]) {
10 if paths.isEmpty {
11 UserDefaults.standard.removeObject(forKey: key)
12 } else {
13 UserDefaults.standard.set(paths.map { ($0 as NSString).lastPathComponent }, forKey: key)
14 }
15 }
16
17 /// The message for files whose edits were lost when the app last ended; read once, at launch.
18 static let atLaunch: String? = {
19 guard let names = UserDefaults.standard.stringArray(forKey: key), !names.isEmpty else { return nil }
20 UserDefaults.standard.removeObject(forKey: key)
21 return String(localized: "Edits to \(names.joined(separator: ", ")) weren't saved: they were waiting for a passphrase when orgstar was closed.")
22 }()
23}
Tests/OrgAppTests/CryptReviewTests.swift added +312 · view
@@ -0,0 +1,312 @@
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 // Second review, 2
178 @Test func clockHistoryKeepsNoEncryptedTitle() throws {
179 let text = "* Bank :crypt:\nintro\n** Secret task\n:PROPERTIES:\n:ID: s-1\n:END:\nbody\n** Hidden no id\nmore\n* Open task\n"
180 try notes.write("a.org", text)
181 session.open(file.path)
182 session.cryptUsed("pw", for: file.path)
183 let clockFile = notes.url.appendingPathComponent("clock.json")
184 let clock = ClockModel(file: clockFile)
185 _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
186 _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "** Hidden").location)
187 _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "* Open").location)
188 #expect(!read(clockFile).contains("Secret task") && !read(clockFile).contains("Hidden no id"))
189 #expect(clock.history.map(\.title) == ["Open task", "Encrypted entry", "Encrypted entry"])
190 }
191
192 // Second review, 3
193 @Test func eachFileHasItsOwnAuthentication() throws {
194 let a = CryptPassphrases.context(for: "/x/a.org"), b = CryptPassphrases.context(for: "/x/b.org")
195 #expect(a !== b && CryptPassphrases.context(for: "/x/a.org") === a)
196 #expect(a.touchIDAuthenticationAllowableReuseDuration == 0)
197 CryptPassphrases.endSession(for: "/x/a.org")
198 #expect(CryptPassphrases.context(for: "/x/a.org") !== a)
199 }
200
201 // Second review, 4a
202 @Test func anEntryThePassphraseCantEncryptHoldsTheFile() throws {
203 let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
204 var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
205 both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
206 try notes.write("a.org", both)
207 session.open(file.path)
208 #expect(session.unlock("one", for: file.path) == nil)
209 try type("typed below b\n", at: offset(of: "* End"))
210 #expect(!session.save())
211 guard case .blocked(let reason)? = session.held[file.path] else { Issue.record("\(String(describing: session.held[file.path]))"); return }
212 #expect(reason.contains("public key") && session.lastError == nil)
213 #expect(OrgCrypt.Failure("x").localizedDescription == "x")
214 #expect(!disk.contains("typed below b"))
215 }
216
217 // Second review, 4b
218 @Test func plaintextEntriesOnDiskHoldTheFileUntilThePassphrase() throws {
219 session.open(file.path)
220 try type("x", at: 0)
221 // Written elsewhere, with no file event.
222 try notes.write("a.org", "* Plain\nOpen text.\n* Last\n* Theirs :crypt:\ntheir secret\n")
223 #expect(!session.save())
224 #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
225 #expect(session.unlock("pw", for: file.path) == nil)
226 #expect(!session.isDirty && !disk.contains("their secret") && session.document?.text.contains("their secret") == true)
227 #expect(recoveryFiles.allSatisfy { !$0.contains("their secret") })
228 }
229
230 // Second review, 6
231 @Test func anEncryptedFileSavesWithOneKey() throws {
232 let path = notes.url.appendingPathComponent("d.org.gpg")
233 try OpenPGP.encryptedMessage(Data("* D\nbody\n".utf8), passphrase: "pw").write(to: path)
234 session.open(path.path)
235 #expect(session.unlock("pw", for: path.path) == nil)
236 try type("x", at: 0)
237 #expect(session.save())
238 let clock = ContinuousClock()
239 var took: [Duration] = []
240 for n in 0..<3 {
241 try type("\(n)", at: 0)
242 took.append(clock.measure { _ = session.save() })
243 }
244 print("Autosave of an .org.gpg file: \(took)")
245 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data("210x* D\nbody\n".utf8))
246 }
247
248 // MR 490 hooks
249 @Test func handoffAndShareSubtreeKeepWhatIsEncrypted() throws {
250 let text = "* Bank :crypt:\nintro\n** Secret child\nbody\n* Open\n"
251 try notes.write("a.org", text)
252 session.open(file.path)
253 let child = (text as NSString).range(of: "** Secret").location
254 // Without the passphrase, the subtree isn't shared.
255 #expect(session.handoffPlace(file.path, roots: [notes.url.path]) == nil)
256 #expect(session.refusesSubtreeShare(file.path, at: child)?.contains("Encrypt…") == true)
257 #expect(session.subtreeShare(file.path, at: child) == nil)
258 session.cryptUsed("pw", for: file.path)
259 let share = try #require(session.subtreeShare(file.path, at: child))
260 #expect(!share.text.contains("body") && share.text.contains("-----BEGIN PGP MESSAGE-----"))
261 #expect(session.document?.text == text)
262 let bank = try #require(session.subtreeShare(file.path, at: 0))
263 #expect(!bank.text.contains("intro") && !bank.text.contains("Secret child"))
264 // An open file without tagged entries is advertised as before.
265 let plain = try notes.write("b.org", "* Plain\n")
266 session.open(plain.path)
267 #expect(session.handoffPlace(plain.path, roots: [notes.url.path]) != nil)
268 // An encrypted file's entries aren't shared.
269 let gpg = notes.url.appendingPathComponent("d.org.gpg")
270 try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
271 session.open(gpg.path)
272 #expect(session.unlock("pw", for: gpg.path) == nil)
273 #expect(session.refusesSubtreeShare(gpg.path, at: 0) != nil && session.subtreeShare(gpg.path, at: 0) == nil)
274 }
275
276 // 9
277 @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
278 session.open(file.path)
279 session.cryptUsed("pw", for: file.path)
280 try replace(with: Self.file)
281 #expect(session.save())
282 let message = try #require(OrgCrypt.firstMessage(disk))
283 for n in 0..<5 {
284 try type("\(n)", at: 0)
285 #expect(session.save())
286 #expect(disk.contains(message))
287 }
288 #expect(session.crypt.revealedMessages(for: file.path).count == 1)
289 }
290
291 // 10
292 @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
293 // A public-key session packet (tag 1) where a message's packets start.
294 let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
295 try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
296 session.open(file.path)
297 try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
298 #expect(!session.save())
299 #expect(session.unlock("pw", for: file.path) == nil)
300 #expect(!disk.contains("new secret"))
301 #expect(disk.contains(publicKey))
302 }
303
304 // 6
305 @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
306 let item = try #require(CryptPassphrases.newItem("pw", for: "/x/a.org"))
307 #expect(item[kSecAttrAccessControl as String] != nil)
308 #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
309 #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
310 #expect(item[kSecAttrAccessible as String] == nil)
311 }
312}
Tests/OrgAppTests/CryptSaveTests.swift added +346 · view
@@ -0,0 +1,346 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// Saving with `org-crypt-use-before-save-magic`, and `.org.gpg` files: what reaches disk.
8@MainActor
9struct CryptSaveTests {
10 static let secret = "Account 12345"
11 static let file = "#+TITLE: Notes\n* 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", Self.file)
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 /// Types `text` at `offset` in the open file, as the editor would.
29 func type(_ text: String, at offset: Int) throws {
30 let buffer = StateBuffer(session.document!)
31 session.attach(buffer)
32 try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
33 session.bufferChanged()
34 }
35
36 /// Puts `text` in place of the open file's text.
37 func replace(with text: String) throws {
38 let buffer = StateBuffer(session.document!)
39 session.attach(buffer)
40 try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: text)], baseRevision: $0.revision) }
41 session.bufferChanged()
42 }
43
44 var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
45
46 /// Every file the recovery folder holds, as text.
47 var recoveryFiles: [String] {
48 let files = FileManager.default.enumerator(at: recoveryFolder, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
49 return files.compactMap { try? Data(contentsOf: $0) }.map { String(decoding: $0, as: UTF8.self) }
50 }
51
52 func offset(of needle: String) -> Int {
53 (session.document!.text as NSString).range(of: needle).location
54 }
55
56 /// Waits for `condition`, as the Keychain's answer comes back on a task.
57 func wait(_ condition: () -> Bool) async throws {
58 for _ in 0..<200 where !condition() { try await Task.sleep(for: .milliseconds(10)) }
59 }
60
61 @Test func savesTaggedEntriesEncryptedWithTheRememberedPassphrase() async throws {
62 try notes.write("a.org", "* Bank :crypt:\nold\n* Last\n")
63 session.hasStoredPassphrase = { _ in true }
64 var asked = 0
65 session.storedPassphrase = { _ in asked += 1; return "pw" }
66 var written: [String] = []
67 session.fileWritten = { written.append($0) }
68 session.open(file.path)
69 try replace(with: Self.file)
70 #expect(!session.save())
71 try await wait { !session.isDirty }
72 #expect(session.held.isEmpty)
73 #expect(asked == 1)
74 #expect(written == [file.path])
75 // The buffer keeps the text; the file has a message in its place.
76 #expect(session.document?.text == Self.file)
77 #expect(!disk.contains(Self.secret) && !disk.contains("old"))
78 #expect(disk.contains("* Bank :crypt:\n-----BEGIN PGP MESSAGE-----\n"))
79 let bank = (disk as NSString).range(of: "* Bank").location
80 #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\n")
81 // The version the save replaced went to recovery encrypted too.
82 #expect(!recoveryFiles.isEmpty)
83 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) && !$0.contains("old") })
84 // Later saves don't ask again.
85 try type("More. ", at: offset(of: "Open text."))
86 #expect(session.save())
87 #expect(asked == 1)
88 #expect(written.count == 2)
89 #expect(!disk.contains(Self.secret))
90 // The index reads the file from disk and keeps no text of the entry.
91 let workspace = try WorkspaceModel(directory: notes.url.appendingPathComponent(".index"))
92 try await workspace.addRoot(notes.url)
93 let database = try Data(contentsOf: notes.url.appendingPathComponent(".index/index.sqlite"))
94 #expect(database.range(of: Data(Self.secret.utf8)) == nil)
95 #expect(try workspace.search("12345").isEmpty)
96 #expect(try workspace.search("Open").map(\.title).contains("Plain"))
97 }
98
99 @Test func holdsTheWholeFileWithoutThePassphrase() throws {
100 try notes.write("a.org", "* Plain\nOpen text.\n")
101 var written: [String] = []
102 session.fileWritten = { written.append($0) }
103 session.open(file.path)
104 try replace(with: Self.file)
105 #expect(!session.save())
106 #expect(session.held[file.path] == .entries(1))
107 #expect(written.isEmpty)
108 #expect(disk == "* Plain\nOpen text.\n")
109 #expect(recoveryFiles.isEmpty)
110 #expect(session.isDirty)
111 // Nothing reads the held text from the session for the agenda or widgets.
112 #expect(session.openTexts[file.path] == nil)
113 // Keep Mine holds too.
114 session.keepMine()
115 #expect(disk == "* Plain\nOpen text.\n")
116 #expect(recoveryFiles.isEmpty)
117 // The passphrase, when given, encrypts and saves.
118 #expect(written.isEmpty)
119 #expect(session.unlock("pw", for: file.path) == nil)
120 #expect(session.held.isEmpty)
121 #expect(!session.isDirty)
122 #expect(written == [file.path])
123 #expect(!disk.contains(Self.secret))
124 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
125 #expect(session.openTexts[file.path] == nil)
126 }
127
128 @Test func restoringAVersionOfAHeldFileKeepsNoPlaintext() throws {
129 try notes.write("a.org", "* Plain\nOpen text.\n")
130 session.open(file.path)
131 try replace(with: Self.file)
132 #expect(!session.save())
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)
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)
139 #expect(session.save())
140 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
141 }
142
143 @Test func replaceInFilesKeepsNoPlaintextAndIsHeld() throws {
144 try notes.write("a.org", "* Plain\nOpen text.\n")
145 session.open(file.path)
146 try replace(with: Self.file)
147 // The buffer has no editor: Replace in Files keeps a copy first, and can't keep one now.
148 let changed = (Self.file as NSString).replacingOccurrences(of: "Open text.", with: "Shut text.")
149 #expect(session.applyChanges(lineEdits(from: Self.file, to: changed), to: file.path, expecting: Self.file) == nil)
150 #expect(!session.save())
151 #expect(session.held[file.path] == .entries(1))
152 #expect(recoveryFiles.isEmpty)
153 #expect(disk == "* Plain\nOpen text.\n")
154 // With the passphrase, the copy is kept encrypted.
155 session.cryptUsed("pw", for: file.path)
156 #expect(session.applyChanges(lineEdits(from: changed, to: Self.file), to: file.path, expecting: changed) == nil)
157 #expect(session.save())
158 #expect(!recoveryFiles.isEmpty && recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
159 #expect(!disk.contains(Self.secret))
160 // A file that isn't open, with an unencrypted tagged entry on disk, isn't written.
161 session.cryptUsed("other", for: "/nowhere")
162 let closed = try notes.write("b.org", Self.file)
163 let message = session.applyChanges(lineEdits(from: Self.file, to: changed), to: closed.path, expecting: Self.file)
164 #expect(message?.contains("1 tagged entry isn't encrypted") == true)
165 #expect((try String(contentsOf: closed, encoding: .utf8)) == Self.file)
166 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
167 }
168
169 @Test func aHeldFileIsReleasedWhenTheEntryGoes() throws {
170 session.saveMode = .automatic
171 session.autosaveDelay = .seconds(60)
172 session.open(file.path)
173 try type("x", at: 0)
174 #expect(!session.save())
175 #expect(session.held[file.path] == .entries(1))
176 let text = session.document!.text as NSString
177 try replace(with: text.replacingOccurrences(of: " :crypt:", with: ""))
178 #expect(session.held.isEmpty)
179 }
180
181 @Test func aWrongPassphraseForTheFilesEntriesIsRefused() throws {
182 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
183 try notes.write("a.org", encrypted + "* New :crypt:\nNew secret\n")
184 session.open(file.path)
185 try type("x", at: 0)
186 #expect(!session.save())
187 #expect(session.held[file.path] == .entries(1))
188 #expect(session.unlock("other", for: file.path) == "Wrong passphrase")
189 #expect(session.isDirty && disk.hasPrefix(encrypted))
190 #expect(session.unlock("pw", for: file.path) == nil)
191 #expect(!disk.contains("New secret") && !session.isDirty)
192 }
193
194 @Test func blankTaggedEntriesDontHoldTheFile() throws {
195 try notes.write("a.org", "* Plain\n")
196 session.open(file.path)
197 try type("* Empty :crypt:\n", at: 8)
198 #expect(session.save())
199 #expect(disk == "* Plain\n* Empty :crypt:\n")
200 }
201
202 @Test func unchangedEncryptedEntriesStayByteForByte() throws {
203 let bank = (Self.file as NSString).range(of: "* Bank").location
204 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: bank, passphrase: "pw"))
205 try notes.write("a.org", encrypted)
206 session.open(file.path)
207 // Decrypt Entry in File, as the passphrase sheet runs it.
208 let message = try #require(OrgCrypt.firstMessage(encrypted))
209 let decrypted = try OrgCrypt.decryptInPlace(encrypted, at: bank, passphrase: "pw")
210 session.cryptUsed("pw", for: file.path)
211 let body = try #require(OrgCrypt.bodyRange(decrypted, at: bank))
212 session.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: file.path)
213 try replace(with: decrypted)
214 #expect(session.document?.text.contains(Self.secret) == true)
215 // Saving writes the entry's message as it was.
216 #expect(session.save())
217 #expect(disk == encrypted)
218 try type("More. ", at: offset(of: "Open text."))
219 #expect(session.save())
220 #expect(disk == (encrypted as NSString).replacingOccurrences(of: "Open text.", with: "More. Open text."))
221 #expect(disk.contains(message))
222 // A changed entry gets a new message.
223 try type("Changed. ", at: offset(of: Self.secret))
224 #expect(session.save())
225 #expect(!disk.contains(message) && !disk.contains("Changed."))
226 let saved = disk
227 #expect(try OrgCrypt.decrypt(saved, at: (saved as NSString).range(of: "* Bank").location, passphrase: "pw").plaintext == "Changed. \(Self.secret)\n")
228 // An entry left encrypted in the buffer stays as it is.
229 let other = try notes.write("b.org", encrypted)
230 session.open(other.path)
231 try type("x", at: 0)
232 #expect(session.save())
233 #expect((try String(contentsOf: other, encoding: .utf8)) == "x" + encrypted)
234 }
235
236 @Test func offWritesWhatTheBufferHas() throws {
237 session.encryptsTaggedEntries = false
238 try notes.write("a.org", "* Plain\n")
239 session.open(file.path)
240 try replace(with: Self.file)
241 #expect(session.save())
242 #expect(disk == Self.file)
243 #expect(session.openTexts[file.path] == Self.file)
244 }
245
246 @Test func aFileChangedOnDiskMergesWithTheDecryptedBuffer() throws {
247 try notes.write("a.org", "* Plain\nOpen text.\n")
248 session.open(file.path)
249 session.cryptUsed("pw", for: file.path)
250 try replace(with: Self.file)
251 #expect(session.save())
252 // Another program appends to the file; the buffer keeps its decrypted entry.
253 try notes.write("a.org", disk + "* From Emacs\n")
254 session.fileChanged(file.path)
255 #expect(session.document?.text == Self.file + "* From Emacs\n")
256 #expect(!session.isDirty)
257 try type("y", at: 0)
258 #expect(session.save())
259 #expect(!disk.contains(Self.secret) && disk.hasSuffix("* From Emacs\n"))
260 }
261
262 // MARK: - Encrypted files
263
264 static let gpgText = "* Diary\nDear diary, \(secret).\n"
265
266 @Test func encryptedFilesOpenWithThePassphraseAndSaveEncrypted() throws {
267 let message = try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw")
268 let path = notes.url.appendingPathComponent("diary.org.gpg")
269 try message.write(to: path)
270 var written: [String] = []
271 session.fileWritten = { written.append($0) }
272 session.open(path.path)
273 #expect(session.unlockRequest == path.path)
274 #expect(!session.isOpen(path.path))
275 #expect(session.unlock("wrong", for: path.path) == "Wrong passphrase")
276 #expect(try Data(contentsOf: path) == message)
277 #expect(session.unlock("pw", for: path.path) == nil)
278 #expect(session.unlockRequest == nil)
279 #expect(session.path == path.path && session.document?.text == Self.gpgText)
280 #expect(session.isOrg)
281 #expect(session.openTexts[path.path] == nil)
282 try type("x", at: 0)
283 #expect(session.save())
284 #expect(written == [path.path])
285 let disk = try Data(contentsOf: path)
286 #expect(!OpenPGP.isArmored(disk))
287 #expect(disk.range(of: Data(Self.secret.utf8)) == nil)
288 #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
289 // Recovery keeps the version replaced, encrypted, and shows it decrypted.
290 #expect(!recoveryFiles.isEmpty && recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
291 let version = try #require(session.recoveryVersions().first)
292 #expect(session.recoveryText(version.url) == Self.gpgText)
293 // A passphrase forgotten while the file is open must be the file's when given again.
294 session.crypt.forgetPassphrase(for: path.path)
295 try type("y", at: 0)
296 #expect(!session.save())
297 #expect(session.held[path.path] == .file)
298 #expect(session.unlock("typo", for: path.path) == "Wrong passphrase")
299 #expect(session.unlock("pw", for: path.path) == nil && !session.isDirty)
300 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("yx" + Self.gpgText).utf8))
301 // Closing forgets the passphrase.
302 session.kill(path.path)
303 session.open(path.path)
304 #expect(session.unlockRequest == path.path)
305 }
306
307 @Test func armoredFilesStayArmored() throws {
308 let armored = try OpenPGP.encrypt(Data(Self.gpgText.utf8), passphrase: "pw")
309 let path = try notes.write("diary.org.gpg", armored)
310 session.open(path.path)
311 #expect(session.unlock("pw", for: path.path) == nil)
312 try type("x", at: 0)
313 #expect(session.save())
314 let disk = try Data(contentsOf: path)
315 #expect(OpenPGP.isArmored(disk))
316 #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
317 }
318
319 @Test func aNewEncryptedFileWaitsForItsPassphrase() throws {
320 let path = try notes.write("new.org.gpg", "")
321 session.open(path.path)
322 #expect(session.unlockRequest == nil && session.path == path.path)
323 try type(Self.gpgText, at: 0)
324 #expect(!session.save())
325 #expect(session.held[path.path] == .file)
326 #expect(try Data(contentsOf: path).isEmpty)
327 #expect(recoveryFiles.isEmpty)
328 #expect(session.unlock("new", for: path.path) == nil)
329 #expect(!session.isDirty && session.held.isEmpty)
330 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "new") == Data(Self.gpgText.utf8))
331 }
332
333 @Test func anEncryptedFileChangedOnDiskMergesInMemory() throws {
334 let path = notes.url.appendingPathComponent("diary.org.gpg")
335 try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw").write(to: path)
336 session.open(path.path)
337 #expect(session.unlock("pw", for: path.path) == nil)
338 try type("x", at: 0)
339 try OpenPGP.encryptedMessage(Data((Self.gpgText + "* Added elsewhere\n").utf8), passphrase: "pw").write(to: path)
340 session.fileChanged(path.path)
341 #expect(session.document?.text == "x" + Self.gpgText + "* Added elsewhere\n")
342 #expect(session.save())
343 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("x" + Self.gpgText + "* Added elsewhere\n").utf8))
344 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) && !$0.contains("Added elsewhere") })
345 }
346}
Tests/OrgCoreTests/CryptFileTests.swift added +163 · view
@@ -0,0 +1,163 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// Encrypting tagged entries on save (`OrgCrypt.seal`) and whole encrypted files, against
6/// gpg and Emacs's EasyPG.
7struct CryptFileTests {
8 static var oracle: Bool { ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
9 static var gpg: Bool { OpenPGPTests.gpg != nil }
10 static var emacs: Bool { gpg && oracle && EmacsOracle.isAvailable }
11
12 @Test func sealEncryptsTaggedEntriesFromTheTop() throws {
13 let (sealed, messages) = try OrgCrypt.seal(OrgCryptTests.file, passphrase: "pw")
14 // Bank's tagged child goes inside Bank's message; the empty entry gets one too.
15 #expect(messages.map(\.plaintext) == ["Account 12345, ünïcödé.\n** Child\nChild text.\n", "Dear diary.\n", ""])
16 let (all, count) = try OrgCrypt.encryptAll(OrgCryptTests.file, passphrase: "pw")
17 #expect(count == 3)
18 #expect(OrgCryptTests.masked(sealed) == OrgCryptTests.masked(all))
19 for (message, plaintext) in messages {
20 #expect(sealed.contains(message))
21 #expect(try String(decoding: OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: "pw"), as: UTF8.self) == plaintext)
22 }
23 // Sealing again changes nothing: every entry is encrypted.
24 #expect(try OrgCrypt.seal(sealed, passphrase: "pw").text == sealed)
25 // Entries known by their text get their message back.
26 let known = Dictionary(uniqueKeysWithValues: messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) })
27 #expect(try OrgCrypt.seal(OrgCryptTests.file, passphrase: "pw", reuse: { known[$0] }).text == sealed)
28 // Without the tag, the text is as it was.
29 #expect(try OrgCrypt.seal("* A\ntext\n", passphrase: "pw").text == "* A\ntext\n")
30 }
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
58 @Test func unencryptedEntriesWithText() throws {
59 #expect(OrgCrypt.unencrypted(OrgCryptTests.file).count == 2)
60 let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location
61 let one = try #require(try OrgCrypt.encrypt(OrgCryptTests.file, at: bank, passphrase: "pw"))
62 #expect(OrgCrypt.unencrypted(one).count == 1)
63 #expect(OrgCrypt.firstMessage(one).map { OrgCrypt.opens($0, passphrase: "pw") } == true)
64 #expect(OrgCrypt.firstMessage(one).map { OrgCrypt.opens($0, passphrase: "other") } == false)
65 #expect(OrgCrypt.firstMessage(OrgCryptTests.file) == nil)
66 #expect(OrgCrypt.unencrypted("* Empty :crypt:\n\n* B\n").isEmpty)
67 #expect(OrgCrypt.unencrypted("#+FILETAGS: :crypt:\n* A\nsecret\n").count == 1)
68 }
69
70 @Test func encryptedFilesRoundTrip() throws {
71 let text = Data("* Diary\nDear diary, ünïcödé.\n".utf8)
72 let binary = try OpenPGP.encryptedMessage(text, passphrase: "pw")
73 #expect(!OpenPGP.isArmored(binary))
74 #expect(try OpenPGP.decryptFile(binary, passphrase: "pw") == text)
75 let armored = Data(try OpenPGP.encrypt(text, passphrase: "pw").utf8)
76 #expect(OpenPGP.isArmored(armored))
77 #expect(try OpenPGP.decryptFile(armored, passphrase: "pw") == text)
78 #expect(throws: OpenPGP.wrongPassphrase) { try OpenPGP.decryptFile(binary, passphrase: "wrong") }
79 #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(Data("* plain text\n".utf8), passphrase: "pw") }
80 }
81
82 @Test(.enabled(if: gpg && oracle))
83 func gpgReadsAndWritesEncryptedFiles() throws {
84 let text = Data("* Diary\nDear diary, ünïcödé.\n".utf8)
85 // `gpg --decrypt` reads orgstar's file, binary as orgstar writes it by default.
86 let ours = try OpenPGP.encryptedMessage(text, passphrase: "pass phrase")
87 #expect(try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--decrypt"], input: ours) == text)
88 // orgstar reads `gpg --symmetric`, binary and armored.
89 let theirs = try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--symmetric"], input: text)
90 #expect(!OpenPGP.isArmored(theirs))
91 #expect(try OpenPGP.decryptFile(theirs, passphrase: "pass phrase") == text)
92 let armored = try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--symmetric", "--armor"], input: text)
93 #expect(try OpenPGP.decryptFile(armored, passphrase: "pass phrase") == text)
94 #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(theirs, passphrase: "wrong") }
95 }
96
97 /// Emacs with EasyPG (`epa-file`), symmetric, the passphrase given without asking, run on
98 /// `file` in a fresh GnuPG home: `form` runs with `file` as the variable `file`.
99 static func emacs(_ form: String, in folder: URL) throws -> String {
100 let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
101 try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
102 defer {
103 let kill = Process()
104 kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
105 kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
106 try? kill.run()
107 kill.waitUntilExit()
108 try? FileManager.default.removeItem(atPath: home)
109 }
110 let elisp = """
111 (progn
112 (require 'org) (require 'epa-file) (epa-file-enable)
113 (setq epg-pinentry-mode 'loopback epa-pinentry-mode 'loopback epa-file-select-keys 'silent epa-file-encrypt-to nil
114 epg-gpg-program \(OrgCryptTests.lisp(OpenPGPTests.gpg!)) default-directory \(OrgCryptTests.lisp(folder.path + "/")))
115 (cl-letf (((symbol-function 'epa-file-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one")))
116 ((symbol-function 'epa-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one"))))
117 \(form)))
118 """
119 return try EmacsOracle.run(["-Q", "--batch", "--eval", elisp], environment: ["GNUPGHOME": home, "TZ": "UTC"])
120 }
121
122 @Test(.enabled(if: emacs))
123 func emacsOpensWhatOrgstarWritesAndTheReverse() throws {
124 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-gpg-\(UUID().uuidString)")
125 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
126 defer { try? FileManager.default.removeItem(at: folder) }
127 let text = "* Diary :private:\nDear diary, ünïcödé.\n** Child\nMore.\n"
128 // orgstar's file, binary and armored, opened by `find-file` in Emacs.
129 for (name, data) in [("ours.org.gpg", try OpenPGP.encryptedMessage(Data(text.utf8), passphrase: "pw one")),
130 ("armored.org.gpg", Data(try OpenPGP.encrypt(Data(text.utf8), passphrase: "pw one").utf8))] {
131 try data.write(to: folder.appendingPathComponent(name))
132 let log = try Self.emacs("""
133 (with-current-buffer (find-file-noselect \(OrgCryptTests.lisp(name)))
134 (let ((coding-system-for-write 'utf-8-unix)) (write-region (point-min) (point-max) "out.txt")))
135 """, in: folder)
136 let read = try? String(contentsOf: folder.appendingPathComponent("out.txt"), encoding: .utf8)
137 #expect(read == text, "\(log)")
138 try? FileManager.default.removeItem(at: folder.appendingPathComponent("out.txt"))
139 }
140 // Emacs's file, saved through EasyPG, opened by orgstar.
141 let log = try Self.emacs("""
142 (with-current-buffer (find-file-noselect "theirs.org.gpg")
143 (insert \(OrgCryptTests.lisp(text)))
144 (let ((coding-system-for-write 'utf-8-unix)) (save-buffer)))
145 """, in: folder)
146 let theirs = try Data(contentsOf: folder.appendingPathComponent("theirs.org.gpg"))
147 #expect(theirs.range(of: Data("Dear diary".utf8)) == nil, "\(log)")
148 #expect(String(decoding: try OpenPGP.decryptFile(theirs, passphrase: "pw one"), as: UTF8.self) == text)
149 #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(theirs, passphrase: "wrong") }
150 }
151
152 @Test(.enabled(if: emacs))
153 func orgCryptKeepsAnUnchangedEntrysMessageAsOrgstarDoes() throws {
154 // Emacs: an entry decrypted and encrypted again, unchanged, gets its own message back.
155 // An entry with no text has none to carry the old message, and gets a new one.
156 let file = OrgCryptTests.file.replacingOccurrences(of: "* Empty :crypt:\n", with: "")
157 let (sealed, _) = try OrgCrypt.seal(file, passphrase: "pw one")
158 let again = try OrgCryptTests.emacs(sealed, "(org-decrypt-entries) (org-encrypt-entries)")
159 #expect(again == sealed)
160 // And reads what orgstar sealed.
161 #expect(try OrgCryptTests.emacs(sealed, "(org-decrypt-entries)") == file)
162 }
163}
Tests/OrgDocumentTests/CryptSaverTests.swift added +62 · view
@@ -0,0 +1,62 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgDocument
5
6/// A version another writer puts on disk just before ours, with crypt-tagged entries in
7/// plaintext and no passphrase known: recovery can't keep it, and it must not be lost.
8struct CryptSaverTests {
9 static let theirs = "a\nb\nc\n* Theirs :crypt:\ntheir secret\n"
10
11 func saver(_ files: FaultyFileSystem, _ recovery: MemoryRecovery) -> (Saver, CryptVault) {
12 let vault = CryptVault()
13 vault.encryptsTaggedEntries = true
14 return (Saver(fileSystem: CryptFileSystem(base: files, vault: vault), recovery: CryptRecoveryStore(base: recovery, vault: vault)), vault)
15 }
16
17 @Test func anOverwrittenVersionMergesIntoTheBuffer() throws {
18 let files = FaultyFileSystem("a\nb\nc\n")
19 files.beforeReplace = Array(Self.theirs.utf8)
20 let recovery = MemoryRecovery()
21 var doc = try editedState()
22 let outcome = try saver(files, recovery).0.save(&doc, to: url)
23 guard case .overwroteExternalChange(.merged) = outcome else { Issue.record("\(outcome)"); return }
24 #expect(doc.text.contains("their secret"))
25 #expect(recovery.kept.allSatisfy { !$0.text.contains("their secret") })
26 }
27
28 @Test func aConflictingOverwrittenVersionGoesIntoTheBufferWithMarkers() throws {
29 let files = FaultyFileSystem("a\nb\nc\n")
30 files.beforeReplace = Array("Z\nb\nc\n* Theirs :crypt:\ntheir secret\n".utf8)
31 let recovery = MemoryRecovery()
32 var doc = try editedState()
33 _ = try saver(files, recovery).0.save(&doc, to: url)
34 #expect(doc.text.contains("their secret") && doc.text.contains("Z") && doc.text.contains("A"))
35 #expect(recovery.kept.allSatisfy { !$0.text.contains("their secret") })
36 }
37
38 @Test func keepMineDoesntReplaceAVersionItCantKeep() throws {
39 let files = FaultyFileSystem(Self.theirs)
40 let recovery = MemoryRecovery()
41 var doc = try editedState()
42 #expect(throws: CryptHold.self) { try saver(files, recovery).0.overwrite(&doc, to: url) }
43 #expect(files.text == Self.theirs)
44 }
45
46 @Test func closedFilesKeepNothingAfterTheirWrite() async throws {
47 let files = FaultyFileSystem("a\n")
48 let recovery = MemoryRecovery()
49 let (saver, vault) = saver(files, recovery)
50 vault.unlock("pw", for: url.path)
51 var doc = state("a\n")
52 try doc.apply([TextEdit(range: 2..<2, replacement: "* S :crypt:\nsecret\n")], baseRevision: 0)
53 #expect(try saver.save(&doc, to: url) == .saved)
54 #expect(files.text?.contains("secret") == false)
55 await MainActor.run {}
56 try await Task.sleep(for: .milliseconds(50))
57 #expect(!vault.keepsAnything(for: url.path))
58 // Only open files keep sealing after the setting goes off.
59 vault.encryptsTaggedEntries = false
60 #expect(!vault.sealsEntries(for: url.path))
61 }
62}
docs/manual/guide/04-outlines.org +34 −1 · view
@@ -953,7 +953,40 @@ The commands have no keys, as in Org; run them from the command palette, or bind
953 953
954Remember in the Keychain stores the passphrase for the file. The next command on that file uses it after Touch ID, Face ID or the device password, without asking. =org-crypt-tag-matcher= in =config.toml= sets the tag; it must be a single tag, not a match expression. 954Remember in the Keychain stores the passphrase for the file. The next command on that file uses it after Touch ID, Face ID or the device password, without asking. =org-crypt-tag-matcher= in =config.toml= sets the tag; it must be a single tag, not a match expression.
955 955
956Messages are written with AES-256 and an iterated and salted SHA-256 key, which GnuPG and Emacs read. Messages using AES-128, AES-192 or AES-256 are read, compressed or not. Messages encrypted to a public key, other ciphers, and AEAD (OpenPGP version 5 and 6) packets are not supported. Saving doesn't encrypt tagged entries, as =org-crypt-use-before-save-magic= does in Emacs; run Encrypt Tagged Entries…. 956Messages are written with AES-256 and an iterated and salted SHA-256 key, which GnuPG and Emacs read. Messages using AES-128, AES-192 or AES-256 are read, compressed or not. Messages encrypted to a public key, other ciphers, and AEAD (OpenPGP version 5 and 6) packets are not supported.
957
958** Encrypting on save
959
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
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, 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.
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 for each file while it's open, at the first save that needs it; another file asks again, and so does the same file after it was closed. A passphrase typed for an org-crypt command on the file is used too. Closing the file or Forget Encryption Passphrase forgets it.
967- Without the passphrase, or when Touch ID is declined, the file isn't saved at all, and no recovery version or snapshot of it is kept, until the entries can be encrypted. A notice above the mode line (on iOS, at the top of the editor) says how many tagged entries aren't encrypted, and stays while that's so; its Encrypt… button asks for the passphrase and saves. Other edits to the file wait meanwhile. An entry with no text doesn't keep the file from being saved.
968- When the file has encrypted entries already, the passphrase must open them. A first passphrase is asked twice. Entries encrypted to a public key (=org-crypt-key=) are left as they are and aren't checked; text typed below one can't be encrypted, and saving says so.
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.
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, between conflict markers if it conflicts, when no copy of it can be kept.
972- An entry that the passphrase can't encrypt (text typed below a message encrypted with another passphrase, or to a public key) holds the file too; the notice says why, without an Encrypt… button.
973- Closing the file, its window, or quitting while it's held asks for the passphrase, or whether to leave without saving; any other save that fails then offers Don't Save. On iOS, the edits stay in memory while orgstar is in the background, and the notice is there on return; if iOS ends orgstar meanwhile, the edits are lost, and orgstar says so when it next opens.
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, not at all.
975
976* Encrypted files
977
978orgstar opens and saves files encrypted with a passphrase as GnuPG (=gpg --symmetric=) and Emacs's EasyPG (=epa-file=) write them, named =NAME.org.gpg=. They show in the sidebar and the file list by name.
979
980Opening one asks for its passphrase, or takes it from the Keychain after Touch ID, Face ID or the device password; Remember in the Keychain keeps it for the file. A wrong passphrase leaves the file closed and as it was. While the file is open, saves encrypt it with that passphrase; closing it forgets the passphrase. A new file named =NAME.org.gpg= is empty: it isn't saved until Set Passphrase… in its notice gives it a passphrase, typed twice.
981
982The decrypted text is kept in memory only:
983- Files are written with AES-256 and an iterated and salted SHA-256 key, binary, or armored when the file was armored.
984- 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.
985- 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. Handoff doesn't offer the file, and Share Subtree… refuses its entries.
986- 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.
987- 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. The version of orgstar downloaded from the website can't make such items (it has no Keychain entitlement): it keeps remembered passphrases in the login keychain, not limited to this Mac, still asking for Touch ID or the password before one is used, and says so the first time.
988
989=age= files (=.age=) aren't supported.
957 990
958* The outline pane 991* The outline pane
959 992
docs/manual/guide/13-configuration.org +2 −1 · view
@@ -218,7 +218,7 @@ These settings have no control in the Settings window. Some are in the View menu
218| =notes-package=, =denote-directory=, =denote-prompts=, =denote-silo-directories=, =denote-sequence-scheme=, =denote-journal-directory=, =denote-journal-keyword=, =denote-journal-interval=, =denote-journal-title-format= | | 218| =notes-package=, =denote-directory=, =denote-prompts=, =denote-silo-directories=, =denote-sequence-scheme=, =denote-journal-directory=, =denote-journal-keyword=, =denote-journal-interval=, =denote-journal-title-format= | |
219| =org-attach-id-dir=, =org-attach-use-inheritance= | | 219| =org-attach-id-dir=, =org-attach-use-inheritance= | |
220| =org-yank-image-save-method=, =org-yank-dnd-method= | | 220| =org-yank-image-save-method=, =org-yank-dnd-method= | |
221| =org-crypt-tag-matcher= | | 221| =org-crypt-tag-matcher=, =org-crypt-use-before-save-magic= | |
222| =org-agenda-start-on-weekday= | | 222| =org-agenda-start-on-weekday= | |
223| =org-deadline-warning-days= | | 223| =org-deadline-warning-days= | |
224| =org-agenda-skip-scheduled-if-done= | | 224| =org-agenda-skip-scheduled-if-done= | |
@@ -291,6 +291,7 @@ A key you remove from the file goes back to its default. A key that isn't in the
291| =org-yank-image-save-method= | string | ="attach"= | Where a pasted image goes: =attach= for the entry's attachment folder, or a folder, relative to the org file's folder unless absolute. See [[file:09-links.org][Links]]. Mirrors =org-yank-image-save-method=. | 291| =org-yank-image-save-method= | string | ="attach"= | Where a pasted image goes: =attach= for the entry's attachment folder, or a folder, relative to the org file's folder unless absolute. See [[file:09-links.org][Links]]. Mirrors =org-yank-image-save-method=. |
292| =org-yank-dnd-method= | string | ="ask"= | What dropping files on the editor does: =ask=, =attach=, =open= or =file-link=. See [[file:09-links.org][Links]]. Mirrors =org-yank-dnd-method=. | 292| =org-yank-dnd-method= | string | ="ask"= | What dropping files on the editor does: =ask=, =attach=, =open= or =file-link=. See [[file:09-links.org][Links]]. Mirrors =org-yank-dnd-method=. |
293| =org-crypt-tag-matcher= | string | ="crypt"= | The tag Encrypt Tagged Entries… encrypts. A single tag. See [[file:04-outlines.org][Outlines]]. Mirrors =org-crypt-tag-matcher=. | 293| =org-crypt-tag-matcher= | string | ="crypt"= | The tag Encrypt Tagged Entries… encrypts. A single tag. See [[file:04-outlines.org][Outlines]]. Mirrors =org-crypt-tag-matcher=. |
294| =org-crypt-use-before-save-magic= | boolean | =false= | Encrypt the entries with =org-crypt-tag-matcher='s tag on every save. Without their passphrase the file isn't saved until it's given. See [[file:04-outlines.org][Outlines]]. Mirrors =org-crypt-use-before-save-magic=. |
294| =org-startup-indented= | boolean | =true= | Indent bodies under their headings, as =org-indent-mode=. =#+STARTUP: indent= / =noindent= override it. Mirrors =org-startup-indented=. | 295| =org-startup-indented= | boolean | =true= | Indent bodies under their headings, as =org-indent-mode=. =#+STARTUP: indent= / =noindent= override it. Mirrors =org-startup-indented=. |
295| =org-hide-leading-stars= | boolean | =false= | Show only a heading's last star, without indentation. =#+STARTUP: hidestars= / =showstars= override it. Mirrors =org-hide-leading-stars=. | 296| =org-hide-leading-stars= | boolean | =false= | Show only a heading's last star, without indentation. =#+STARTUP: hidestars= / =showstars= override it. Mirrors =org-hide-leading-stars=. |
296| =org-startup-align-all-tables= | boolean | =false= | Align every table when a file opens. =#+STARTUP: align= / =noalign= override it. Mirrors =org-startup-align-all-tables=. | 297| =org-startup-align-all-tables= | boolean | =false= | Align every table when a file opens. =#+STARTUP: align= / =noalign= override it. Mirrors =org-startup-align-all-tables=. |
docs/manual/guide/14-ios.org +3 −1 · view
@@ -208,6 +208,8 @@ Commands has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A r
208 208
209Rename Tag… and Rename TODO Keyword… in the editor's Commands, under TODO and Tags, rename a tag or a keyword in every org file of one folder or all folders, as on the Mac: a sheet asks for the old and new name (the menu beside the first field lists the tags of your folders, or the keywords), the folder, and whether to change =config.toml= too; Find lists each line that changes, with a switch to leave it out, and Rename applies them. A change to =config.toml= goes into the synced folder's file. See [[file:05-todos-and-tags.org][TODOs and tags]]. 209Rename Tag… and Rename TODO Keyword… in the editor's Commands, under TODO and Tags, rename a tag or a keyword in every org file of one folder or all folders, as on the Mac: a sheet asks for the old and new name (the menu beside the first field lists the tags of your folders, or the keywords), the folder, and whether to change =config.toml= too; Find lists each line that changes, with a switch to leave it out, and Rename applies them. A change to =config.toml= goes into the synced folder's file. See [[file:05-todos-and-tags.org][TODOs and tags]].
210 210
211With =org-crypt-use-before-save-magic=, a file whose tagged entries can't be encrypted isn't saved; a notice at the top of the editor says so, with Encrypt…. Going to the background saves every other file; the held file's edits stay in memory and the notice is there on return. iOS can end orgstar in the background without asking: the held edits are then lost, and the next launch names the files. Files named =NAME.org.gpg= are listed with the org files and open after their passphrase; see [[file:04-outlines.org][Outlines]].
212
211** The menu bar on iPad 213** The menu bar on iPad
212 214
213The iPad's menu bar, and the list of keys shown while =⌘= is held on a hardware keyboard, have these menus, after the Mac's and with the Mac's keys: 215The iPad's menu bar, and the list of keys shown while =⌘= is held on a hardware keyboard, have these menus, after the Mac's and with the Mac's keys:
@@ -525,7 +527,7 @@ These settings from =config.toml= apply on iOS:
525- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer= 527- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=
526- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks= 528- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks=
527- =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry= 529- =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry=
528- =org-crypt-tag-matcher=, =org-attach-id-dir=, =org-attach-use-inheritance=, =org-yank-image-save-method=, =org-timer-format=, =org-timer-default-timer= 530- =org-crypt-tag-matcher=, =org-crypt-use-before-save-magic=, =org-attach-id-dir=, =org-attach-use-inheritance=, =org-yank-image-save-method=, =org-timer-format=, =org-timer-default-timer=
529- =org-archive-location=, =[org-structure-template-alist]= 531- =org-archive-location=, =[org-structure-template-alist]=
530- =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist= 532- =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist=
531- =org-use-speed-commands=, with a hardware keyboard 533- =org-use-speed-commands=, with a hardware keyboard
docs/manual/guide/15-alongside-emacs.org +2 −1 · view
@@ -296,5 +296,6 @@ Other:
296- org-timer: =org-timer-display= is always the mode line. The timer's =C-u= forms are separate commands bound to =C-u C-c C-x 0=, =C-u C-u C-c C-x 0= and =C-u C-c C-x ,=; Set Countdown Timer… has no prefix-argument forms. 296- org-timer: =org-timer-display= is always the mode line. The timer's =C-u= forms are separate commands bound to =C-u C-c C-x 0=, =C-u C-u C-c C-x 0= and =C-u C-c C-x ,=; Set Countdown Timer… has no prefix-argument forms.
297- Radio lists are Org 9.8's =#+ATTR_ORG: :radio= checkbox lists. The =#+ORGLST= radio lists of Org 9.1 and earlier, removed in Org 9.2, aren't supported, nor is =org-list-checkbox-radio-mode=. 297- Radio lists are Org 9.8's =#+ATTR_ORG: :radio= checkbox lists. The =#+ORGLST= radio lists of Org 9.1 and earlier, removed in Org 9.2, aren't supported, nor is =org-list-checkbox-radio-mode=.
298- org-attach: =org-attach-method= is always =cp= for Attach File… (the other methods have their own commands), =org-attach-auto-tag= is always =ATTACH=, =org-attach-preferred-new-method= is always =id=, and =org-attach-id-to-path-function-list= is Org's default. The dispatcher's =b=, =O= and =F= keys and =org-attach-archive-delete= aren't supported. Delete All Attachments… asks once and deletes the folder with what's in it. 298- org-attach: =org-attach-method= is always =cp= for Attach File… (the other methods have their own commands), =org-attach-auto-tag= is always =ATTACH=, =org-attach-preferred-new-method= is always =id=, and =org-attach-id-to-path-function-list= is Org's default. The dispatcher's =b=, =O= and =F= keys and =org-attach-archive-delete= aren't supported. Delete All Attachments… asks once and deletes the folder with what's in it.
299- org-crypt works with symmetric encryption only (=org-crypt-key= nil); public keys and =org-crypt-use-before-save-magic= aren't supported. =org-crypt-tag-matcher= is a single tag. 299- org-crypt works with symmetric encryption only (=org-crypt-key= nil); public keys aren't supported. =org-crypt-tag-matcher= is a single tag. =org-crypt-use-before-save-magic= is a setting in =config.toml= rather than a function to call; with it, entries stay decrypted in the editor after a save, where Emacs's buffer holds the messages, and a file whose entries can't be encrypted isn't saved, where Emacs asks for the passphrase. Emacs Import doesn't read the call. =org-crypt-disable-auto-save= has no counterpart: orgstar keeps no auto-save files.
300- EasyPG's =.gpg= files are read and written with a passphrase only (symmetric); files encrypted to public keys aren't supported. orgstar keeps no passphrase cache beyond the open file; =epa-file-cache-passphrase-for-symmetric-encryption= has no counterpart.
300- When TODO dependencies refuse a change on a =COMMENT= heading, the heading keeps =COMMENT=. Org removes it before the check and doesn't put it back. 301- When TODO dependencies refuse a change on a =COMMENT= heading, the heading keeps =COMMENT=. Org removes it before the check and doesn't put it back.
l10n/Localizable.xcstrings +1327 · view
@@ -471,6 +471,74 @@
471 } 471 }
472 } 472 }
473 }, 473 },
474 "%@ has another passphrase; open it first.": {
475 "localizations": {
476 "de": {
477 "stringUnit": {
478 "state": "translated",
479 "value": "„%@“ hat ein anderes Passwort; öffne die Datei zuerst."
480 }
481 },
482 "es": {
483 "stringUnit": {
484 "state": "translated",
485 "value": "«%@» tiene otra frase de contraseña; ábrelo primero."
486 }
487 },
488 "fr": {
489 "stringUnit": {
490 "state": "translated",
491 "value": "« %@ » a une autre phrase secrète ; ouvrez-le d'abord."
492 }
493 },
494 "ja": {
495 "stringUnit": {
496 "state": "translated",
497 "value": "“%@”のパスフレーズは異なります。先に開いてください。"
498 }
499 },
500 "pt-BR": {
501 "stringUnit": {
502 "state": "translated",
503 "value": "\"%@\" tem outra senha; abra-o primeiro."
504 }
505 }
506 }
507 },
508 "%@ has decrypted entries that are encrypted on disk, so Emacs isn't given a copy of it.": {
509 "localizations": {
510 "de": {
511 "stringUnit": {
512 "state": "translated",
513 "value": "„%@“ hat entschlüsselte Einträge, die auf dem Datenträger verschlüsselt sind, daher erhält Emacs keine Kopie davon."
514 }
515 },
516 "es": {
517 "stringUnit": {
518 "state": "translated",
519 "value": "«%@» tiene entradas descifradas que están cifradas en el disco, así que Emacs no recibe una copia."
520 }
521 },
522 "fr": {
523 "stringUnit": {
524 "state": "translated",
525 "value": "« %@ » contient des entrées déchiffrées qui sont chiffrées sur le disque, donc Emacs n'en reçoit pas de copie."
526 }
527 },
528 "ja": {
529 "stringUnit": {
530 "state": "translated",
531 "value": "“%@”にはディスク上で暗号化されている復号済みエントリがあるため、Emacsにはコピーを渡しません。"
532 }
533 },
534 "pt-BR": {
535 "stringUnit": {
536 "state": "translated",
537 "value": "\"%@\" tem entradas descriptografadas que estão criptografadas no disco, então o Emacs não recebe uma cópia."
538 }
539 }
540 }
541 },
474 "%@ in a buffer": { 542 "%@ in a buffer": {
475 "localizations": { 543 "localizations": {
476 "de": { 544 "de": {
@@ -505,6 +573,244 @@
505 } 573 }
506 } 574 }
507 }, 575 },
576 "%@ is encrypted": {
577 "localizations": {
578 "de": {
579 "stringUnit": {
580 "state": "translated",
581 "value": "„%@“ ist verschlüsselt"
582 }
583 },
584 "es": {
585 "stringUnit": {
586 "state": "translated",
587 "value": "«%@» está cifrado"
588 }
589 },
590 "fr": {
591 "stringUnit": {
592 "state": "translated",
593 "value": "« %@ » est chiffré"
594 }
595 },
596 "ja": {
597 "stringUnit": {
598 "state": "translated",
599 "value": "“%@”は暗号化されています"
600 }
601 },
602 "pt-BR": {
603 "stringUnit": {
604 "state": "translated",
605 "value": "\"%@\" está criptografado"
606 }
607 }
608 }
609 },
610 "%@ is encrypted, and %@ isn't; the entry wasn't moved.": {
611 "localizations": {
612 "de": {
613 "stringUnit": {
614 "state": "translated",
615 "value": "„%1$@“ ist verschlüsselt, „%2$@“ nicht; der Eintrag wurde nicht verschoben."
616 }
617 },
618 "es": {
619 "stringUnit": {
620 "state": "translated",
621 "value": "«%1$@» está cifrado y «%2$@» no; la entrada no se movió."
622 }
623 },
624 "fr": {
625 "stringUnit": {
626 "state": "translated",
627 "value": "« %1$@ » est chiffré, « %2$@ » ne l'est pas ; l'entrée n'a pas été déplacée."
628 }
629 },
630 "ja": {
631 "stringUnit": {
632 "state": "translated",
633 "value": "“%1$@”は暗号化されていますが“%2$@”はされていないため、エントリは移動しませんでした。"
634 }
635 },
636 "pt-BR": {
637 "stringUnit": {
638 "state": "translated",
639 "value": "\"%1$@\" está criptografado e \"%2$@\" não; a entrada não foi movida."
640 }
641 }
642 }
643 },
644 "%@ is encrypted, so Emacs isn't given a copy of it.": {
645 "localizations": {
646 "de": {
647 "stringUnit": {
648 "state": "translated",
649 "value": "„%@“ ist verschlüsselt, daher erhält Emacs keine Kopie davon."
650 }
651 },
652 "es": {
653 "stringUnit": {
654 "state": "translated",
655 "value": "«%@» está cifrado, así que Emacs no recibe una copia."
656 }
657 },
658 "fr": {
659 "stringUnit": {
660 "state": "translated",
661 "value": "« %@ » est chiffré, donc Emacs n'en reçoit pas de copie."
662 }
663 },
664 "ja": {
665 "stringUnit": {
666 "state": "translated",
667 "value": "“%@”は暗号化されているため、Emacsにはコピーを渡しません。"
668 }
669 },
670 "pt-BR": {
671 "stringUnit": {
672 "state": "translated",
673 "value": "\"%@\" está criptografado, então o Emacs não recebe uma cópia."
674 }
675 }
676 }
677 },
678 "%@ is encrypted.": {
679 "localizations": {
680 "de": {
681 "stringUnit": {
682 "state": "translated",
683 "value": "„%@“ ist verschlüsselt."
684 }
685 },
686 "es": {
687 "stringUnit": {
688 "state": "translated",
689 "value": "«%@» está cifrado."
690 }
691 },
692 "fr": {
693 "stringUnit": {
694 "state": "translated",
695 "value": "« %@ » est chiffré."
696 }
697 },
698 "ja": {
699 "stringUnit": {
700 "state": "translated",
701 "value": "“%@”は暗号化されています。"
702 }
703 },
704 "pt-BR": {
705 "stringUnit": {
706 "state": "translated",
707 "value": "\"%@\" está criptografado."
708 }
709 }
710 }
711 },
712 "%@ is encrypted; its entries aren't shared.": {
713 "localizations": {
714 "de": {
715 "stringUnit": {
716 "state": "translated",
717 "value": "„%@“ ist verschlüsselt; seine Einträge werden nicht geteilt."
718 }
719 },
720 "es": {
721 "stringUnit": {
722 "state": "translated",
723 "value": "«%@» está cifrado; sus entradas no se comparten."
724 }
725 },
726 "fr": {
727 "stringUnit": {
728 "state": "translated",
729 "value": "« %@ » est chiffré ; ses entrées ne sont pas partagées."
730 }
731 },
732 "ja": {
733 "stringUnit": {
734 "state": "translated",
735 "value": "“%@”は暗号化されているため、エントリは共有されません。"
736 }
737 },
738 "pt-BR": {
739 "stringUnit": {
740 "state": "translated",
741 "value": "\"%@\" está criptografado; suas entradas não são compartilhadas."
742 }
743 }
744 }
745 },
746 "%@ is saved encrypted with this passphrase.": {
747 "localizations": {
748 "de": {
749 "stringUnit": {
750 "state": "translated",
751 "value": "„%@“ wird mit diesem Passwort verschlüsselt gesichert."
752 }
753 },
754 "es": {
755 "stringUnit": {
756 "state": "translated",
757 "value": "«%@» se guarda cifrado con esta frase de contraseña."
758 }
759 },
760 "fr": {
761 "stringUnit": {
762 "state": "translated",
763 "value": "« %@ » est enregistré chiffré avec cette phrase secrète."
764 }
765 },
766 "ja": {
767 "stringUnit": {
768 "state": "translated",
769 "value": "“%@”はこのパスフレーズで暗号化して保存されます。"
770 }
771 },
772 "pt-BR": {
773 "stringUnit": {
774 "state": "translated",
775 "value": "\"%@\" é salvo criptografado com esta senha."
776 }
777 }
778 }
779 },
780 "%@ is saved with its tagged entries encrypted.": {
781 "localizations": {
782 "de": {
783 "stringUnit": {
784 "state": "translated",
785 "value": "„%@“ wird mit verschlüsselten markierten Einträgen gesichert."
786 }
787 },
788 "es": {
789 "stringUnit": {
790 "state": "translated",
791 "value": "«%@» se guarda con sus entradas etiquetadas cifradas."
792 }
793 },
794 "fr": {
795 "stringUnit": {
796 "state": "translated",
797 "value": "« %@ » est enregistré avec ses entrées taguées chiffrées."
798 }
799 },
800 "ja": {
801 "stringUnit": {
802 "state": "translated",
803 "value": "“%@”はタグ付きエントリを暗号化して保存されます。"
804 }
805 },
806 "pt-BR": {
807 "stringUnit": {
808 "state": "translated",
809 "value": "\"%@\" é salvo com as entradas etiquetadas criptografadas."
810 }
811 }
812 }
813 },
508 "%@ isn't available on iPhone and iPad. It runs on the Mac.": { 814 "%@ isn't available on iPhone and iPad. It runs on the Mac.": {
509 "comment": "A command that runs only on the Mac", 815 "comment": "A command that runs only on the Mac",
510 "localizations": { 816 "localizations": {
@@ -610,6 +916,40 @@
610 } 916 }
611 } 917 }
612 }, 918 },
919 "%@ isn't saved until it has a passphrase.": {
920 "localizations": {
921 "de": {
922 "stringUnit": {
923 "state": "translated",
924 "value": "„%@“ wird erst gesichert, wenn es ein Passwort hat."
925 }
926 },
927 "es": {
928 "stringUnit": {
929 "state": "translated",
930 "value": "«%@» no se guarda hasta que tenga una frase de contraseña."
931 }
932 },
933 "fr": {
934 "stringUnit": {
935 "state": "translated",
936 "value": "« %@ » n'est pas enregistré tant qu'il n'a pas de phrase secrète."
937 }
938 },
939 "ja": {
940 "stringUnit": {
941 "state": "translated",
942 "value": "パスフレーズが設定されるまで“%@”は保存されません。"
943 }
944 },
945 "pt-BR": {
946 "stringUnit": {
947 "state": "translated",
948 "value": "\"%@\" só é salvo quando tiver uma senha."
949 }
950 }
951 }
952 },
613 "%@ late": { 953 "%@ late": {
614 "localizations": { 954 "localizations": {
615 "de": { 955 "de": {
@@ -2949,6 +3289,74 @@
2949 } 3289 }
2950 } 3290 }
2951 }, 3291 },
3292 "%lld tagged entries aren't encrypted": {
3293 "localizations": {
3294 "de": {
3295 "stringUnit": {
3296 "state": "translated",
3297 "value": "%lld markierte Einträge sind nicht verschlüsselt"
3298 }
3299 },
3300 "es": {
3301 "stringUnit": {
3302 "state": "translated",
3303 "value": "%lld entradas etiquetadas no están cifradas"
3304 }
3305 },
3306 "fr": {
3307 "stringUnit": {
3308 "state": "translated",
3309 "value": "%lld entrées taguées ne sont pas chiffrées"
3310 }
3311 },
3312 "ja": {
3313 "stringUnit": {
3314 "state": "translated",
3315 "value": "%lld件のタグ付きエントリが暗号化されていません"
3316 }
3317 },
3318 "pt-BR": {
3319 "stringUnit": {
3320 "state": "translated",
3321 "value": "%lld entradas etiquetadas não estão criptografadas"
3322 }
3323 }
3324 }
3325 },
3326 "%lld tagged entries aren't encrypted. Changes to %@ aren't saved until they are.": {
3327 "localizations": {
3328 "de": {
3329 "stringUnit": {
3330 "state": "translated",
3331 "value": "%lld markierte Einträge sind nicht verschlüsselt. Änderungen an „%@“ werden erst gesichert, wenn sie es sind."
3332 }
3333 },
3334 "es": {
3335 "stringUnit": {
3336 "state": "translated",
3337 "value": "%lld entradas etiquetadas no están cifradas. Los cambios en «%@» no se guardan hasta que lo estén."
3338 }
3339 },
3340 "fr": {
3341 "stringUnit": {
3342 "state": "translated",
3343 "value": "%lld entrées taguées ne sont pas chiffrées. Les modifications de « %@ » ne sont pas enregistrées tant qu'elles ne le sont pas."
3344 }
3345 },
3346 "ja": {
3347 "stringUnit": {
3348 "state": "translated",
3349 "value": "%lld件のタグ付きエントリが暗号化されていません。暗号化されるまで“%@”への変更は保存されません。"
3350 }
3351 },
3352 "pt-BR": {
3353 "stringUnit": {
3354 "state": "translated",
3355 "value": "%lld entradas etiquetadas não estão criptografadas. As alterações em \"%@\" só são salvas quando elas estiverem."
3356 }
3357 }
3358 }
3359 },
2952 "%lld words": { 3360 "%lld words": {
2953 "comment": "Modeline: words in the file", 3361 "comment": "Modeline: words in the file",
2954 "localizations": { 3362 "localizations": {
@@ -3246,6 +3654,74 @@
3246 } 3654 }
3247 } 3655 }
3248 }, 3656 },
3657 "1 tagged entry isn't encrypted": {
3658 "localizations": {
3659 "de": {
3660 "stringUnit": {
3661 "state": "translated",
3662 "value": "1 markierter Eintrag ist nicht verschlüsselt"
3663 }
3664 },
3665 "es": {
3666 "stringUnit": {
3667 "state": "translated",
3668 "value": "1 entrada etiquetada no está cifrada"
3669 }
3670 },
3671 "fr": {
3672 "stringUnit": {
3673 "state": "translated",
3674 "value": "1 entrée taguée n'est pas chiffrée"
3675 }
3676 },
3677 "ja": {
3678 "stringUnit": {
3679 "state": "translated",
3680 "value": "1件のタグ付きエントリが暗号化されていません"
3681 }
3682 },
3683 "pt-BR": {
3684 "stringUnit": {
3685 "state": "translated",
3686 "value": "1 entrada etiquetada não está criptografada"
3687 }
3688 }
3689 }
3690 },
3691 "1 tagged entry isn't encrypted. Changes to %@ aren't saved until it is.": {
3692 "localizations": {
3693 "de": {
3694 "stringUnit": {
3695 "state": "translated",
3696 "value": "1 markierter Eintrag ist nicht verschlüsselt. Änderungen an „%@“ werden erst gesichert, wenn er es ist."
3697 }
3698 },
3699 "es": {
3700 "stringUnit": {
3701 "state": "translated",
3702 "value": "1 entrada etiquetada no está cifrada. Los cambios en «%@» no se guardan hasta que lo esté."
3703 }
3704 },
3705 "fr": {
3706 "stringUnit": {
3707 "state": "translated",
3708 "value": "1 entrée taguée n'est pas chiffrée. Les modifications de « %@ » ne sont pas enregistrées tant qu'elle ne l'est pas."
3709 }
3710 },
3711 "ja": {
3712 "stringUnit": {
3713 "state": "translated",
3714 "value": "1件のタグ付きエントリが暗号化されていません。暗号化されるまで“%@”への変更は保存されません。"
3715 }
3716 },
3717 "pt-BR": {
3718 "stringUnit": {
3719 "state": "translated",
3720 "value": "1 entrada etiquetada não está criptografada. As alterações em \"%@\" só são salvas quando ela estiver."
3721 }
3722 }
3723 }
3724 },
3249 ":echo with a result that isn't text": { 3725 ":echo with a result that isn't text": {
3250 "comment": "Why an sqlite block can't run here", 3726 "comment": "Why an sqlite block can't run here",
3251 "localizations": { 3727 "localizations": {
@@ -8702,6 +9178,74 @@
8702 } 9178 }
8703 } 9179 }
8704 }, 9180 },
9181 "Changes to %@ aren't saved": {
9182 "localizations": {
9183 "de": {
9184 "stringUnit": {
9185 "state": "translated",
9186 "value": "Änderungen an „%@“ sind nicht gesichert"
9187 }
9188 },
9189 "es": {
9190 "stringUnit": {
9191 "state": "translated",
9192 "value": "Los cambios en «%@» no están guardados"
9193 }
9194 },
9195 "fr": {
9196 "stringUnit": {
9197 "state": "translated",
9198 "value": "Les modifications de « %@ » ne sont pas enregistrées"
9199 }
9200 },
9201 "ja": {
9202 "stringUnit": {
9203 "state": "translated",
9204 "value": "“%@”への変更は保存されていません"
9205 }
9206 },
9207 "pt-BR": {
9208 "stringUnit": {
9209 "state": "translated",
9210 "value": "As alterações em \"%@\" não estão salvas"
9211 }
9212 }
9213 }
9214 },
9215 "Changes to %@ aren't saved until that's fixed.": {
9216 "localizations": {
9217 "de": {
9218 "stringUnit": {
9219 "state": "translated",
9220 "value": "Änderungen an „%@“ werden erst gesichert, wenn das behoben ist."
9221 }
9222 },
9223 "es": {
9224 "stringUnit": {
9225 "state": "translated",
9226 "value": "Los cambios en «%@» no se guardan hasta que se corrija."
9227 }
9228 },
9229 "fr": {
9230 "stringUnit": {
9231 "state": "translated",
9232 "value": "Les modifications de « %@ » ne sont pas enregistrées tant que ce n'est pas corrigé."
9233 }
9234 },
9235 "ja": {
9236 "stringUnit": {
9237 "state": "translated",
9238 "value": "これが解決されるまで“%@”への変更は保存されません。"
9239 }
9240 },
9241 "pt-BR": {
9242 "stringUnit": {
9243 "state": "translated",
9244 "value": "As alterações em \"%@\" só são salvas quando isso for corrigido."
9245 }
9246 }
9247 }
9248 },
8705 "Check Spelling While Typing": { 9249 "Check Spelling While Typing": {
8706 "comment": "Command title", 9250 "comment": "Command title",
8707 "localizations": { 9251 "localizations": {
@@ -12051,6 +12595,41 @@
12051 } 12595 }
12052 } 12596 }
12053 }, 12597 },
12598 "Couldn't Keep a Copy": {
12599 "comment": "Error alert title",
12600 "localizations": {
12601 "de": {
12602 "stringUnit": {
12603 "state": "translated",
12604 "value": "Kopie nicht behalten"
12605 }
12606 },
12607 "es": {
12608 "stringUnit": {
12609 "state": "translated",
12610 "value": "No se pudo guardar una copia"
12611 }
12612 },
12613 "fr": {
12614 "stringUnit": {
12615 "state": "translated",
12616 "value": "Impossible de garder une copie"
12617 }
12618 },
12619 "ja": {
12620 "stringUnit": {
12621 "state": "translated",
12622 "value": "コピーを保持できません"
12623 }
12624 },
12625 "pt-BR": {
12626 "stringUnit": {
12627 "state": "translated",
12628 "value": "Não Foi Possível Manter uma Cópia"
12629 }
12630 }
12631 }
12632 },
12054 "Couldn't Merge": { 12633 "Couldn't Merge": {
12055 "comment": "Error alert title", 12634 "comment": "Error alert title",
12056 "localizations": { 12635 "localizations": {
@@ -13189,6 +13768,40 @@
13189 } 13768 }
13190 } 13769 }
13191 }, 13770 },
13771 "Decrypt File": {
13772 "localizations": {
13773 "de": {
13774 "stringUnit": {
13775 "state": "translated",
13776 "value": "Datei entschlüsseln"
13777 }
13778 },
13779 "es": {
13780 "stringUnit": {
13781 "state": "translated",
13782 "value": "Descifrar archivo"
13783 }
13784 },
13785 "fr": {
13786 "stringUnit": {
13787 "state": "translated",
13788 "value": "Déchiffrer le fichier"
13789 }
13790 },
13791 "ja": {
13792 "stringUnit": {
13793 "state": "translated",
13794 "value": "ファイルを復号"
13795 }
13796 },
13797 "pt-BR": {
13798 "stringUnit": {
13799 "state": "translated",
13800 "value": "Descriptografar Arquivo"
13801 }
13802 }
13803 }
13804 },
13192 "Decrypt in File": { 13805 "Decrypt in File": {
13193 "localizations": { 13806 "localizations": {
13194 "de": { 13807 "de": {
@@ -13223,6 +13836,40 @@
13223 } 13836 }
13224 } 13837 }
13225 }, 13838 },
13839 "Decrypt…": {
13840 "localizations": {
13841 "de": {
13842 "stringUnit": {
13843 "state": "translated",
13844 "value": "Entschlüsseln …"
13845 }
13846 },
13847 "es": {
13848 "stringUnit": {
13849 "state": "translated",
13850 "value": "Descifrar…"
13851 }
13852 },
13853 "fr": {
13854 "stringUnit": {
13855 "state": "translated",
13856 "value": "Déchiffrer…"
13857 }
13858 },
13859 "ja": {
13860 "stringUnit": {
13861 "state": "translated",
13862 "value": "復号…"
13863 }
13864 },
13865 "pt-BR": {
13866 "stringUnit": {
13867 "state": "translated",
13868 "value": "Descriptografar…"
13869 }
13870 }
13871 }
13872 },
13226 "Default": { 13873 "Default": {
13227 "localizations": { 13874 "localizations": {
13228 "de": { 13875 "de": {
@@ -15053,6 +15700,40 @@
15053 } 15700 }
15054 } 15701 }
15055 }, 15702 },
15703 "Edits to %@ weren't saved: they were waiting for a passphrase when orgstar was closed.": {
15704 "localizations": {
15705 "de": {
15706 "stringUnit": {
15707 "state": "translated",
15708 "value": "Änderungen an %@ wurden nicht gesichert: Sie warteten auf ein Passwort, als orgstar beendet wurde."
15709 }
15710 },
15711 "es": {
15712 "stringUnit": {
15713 "state": "translated",
15714 "value": "Los cambios en %@ no se guardaron: esperaban una frase de contraseña cuando orgstar se cerró."
15715 }
15716 },
15717 "fr": {
15718 "stringUnit": {
15719 "state": "translated",
15720 "value": "Les modifications de %@ n'ont pas été enregistrées : elles attendaient une phrase secrète quand orgstar a été fermé."
15721 }
15722 },
15723 "ja": {
15724 "stringUnit": {
15725 "state": "translated",
15726 "value": "%@への編集は保存されませんでした。orgstarが終了したとき、パスフレーズの入力を待っていました。"
15727 }
15728 },
15729 "pt-BR": {
15730 "stringUnit": {
15731 "state": "translated",
15732 "value": "As alterações em %@ não foram salvas: aguardavam uma senha quando o orgstar foi fechado."
15733 }
15734 }
15735 }
15736 },
15056 "Effort filter (<0:30, >1:00, =1:00):": { 15737 "Effort filter (<0:30, >1:00, =1:00):": {
15057 "localizations": { 15738 "localizations": {
15058 "de": { 15739 "de": {
@@ -15364,6 +16045,40 @@
15364 } 16045 }
15365 } 16046 }
15366 }, 16047 },
16048 "Encrypt Tagged Entries": {
16049 "localizations": {
16050 "de": {
16051 "stringUnit": {
16052 "state": "translated",
16053 "value": "Markierte Einträge verschlüsseln"
16054 }
16055 },
16056 "es": {
16057 "stringUnit": {
16058 "state": "translated",
16059 "value": "Cifrar entradas etiquetadas"
16060 }
16061 },
16062 "fr": {
16063 "stringUnit": {
16064 "state": "translated",
16065 "value": "Chiffrer les entrées taguées"
16066 }
16067 },
16068 "ja": {
16069 "stringUnit": {
16070 "state": "translated",
16071 "value": "タグ付きエントリを暗号化"
16072 }
16073 },
16074 "pt-BR": {
16075 "stringUnit": {
16076 "state": "translated",
16077 "value": "Criptografar Entradas Etiquetadas"
16078 }
16079 }
16080 }
16081 },
15367 "Encrypt Tagged Entries…": { 16082 "Encrypt Tagged Entries…": {
15368 "comment": "Command title", 16083 "comment": "Command title",
15369 "localizations": { 16084 "localizations": {
@@ -15399,6 +16114,40 @@
15399 } 16114 }
15400 } 16115 }
15401 }, 16116 },
16117 "Encrypt and Save": {
16118 "localizations": {
16119 "de": {
16120 "stringUnit": {
16121 "state": "translated",
16122 "value": "Verschlüsseln und sichern"
16123 }
16124 },
16125 "es": {
16126 "stringUnit": {
16127 "state": "translated",
16128 "value": "Cifrar y guardar"
16129 }
16130 },
16131 "fr": {
16132 "stringUnit": {
16133 "state": "translated",
16134 "value": "Chiffrer et enregistrer"
16135 }
16136 },
16137 "ja": {
16138 "stringUnit": {
16139 "state": "translated",
16140 "value": "暗号化して保存"
16141 }
16142 },
16143 "pt-BR": {
16144 "stringUnit": {
16145 "state": "translated",
16146 "value": "Criptografar e Salvar"
16147 }
16148 }
16149 }
16150 },
15402 "Encrypted Entry": { 16151 "Encrypted Entry": {
15403 "localizations": { 16152 "localizations": {
15404 "de": { 16153 "de": {
@@ -15433,6 +16182,74 @@
15433 } 16182 }
15434 } 16183 }
15435 }, 16184 },
16185 "Encrypted entry": {
16186 "localizations": {
16187 "de": {
16188 "stringUnit": {
16189 "state": "translated",
16190 "value": "Verschlüsselter Eintrag"
16191 }
16192 },
16193 "es": {
16194 "stringUnit": {
16195 "state": "translated",
16196 "value": "Entrada cifrada"
16197 }
16198 },
16199 "fr": {
16200 "stringUnit": {
16201 "state": "translated",
16202 "value": "Entrée chiffrée"
16203 }
16204 },
16205 "ja": {
16206 "stringUnit": {
16207 "state": "translated",
16208 "value": "暗号化されたエントリ"
16209 }
16210 },
16211 "pt-BR": {
16212 "stringUnit": {
16213 "state": "translated",
16214 "value": "Entrada criptografada"
16215 }
16216 }
16217 }
16218 },
16219 "Encrypted files were left out, and encrypted entries were exported as they are on disk.": {
16220 "localizations": {
16221 "de": {
16222 "stringUnit": {
16223 "state": "translated",
16224 "value": "Verschlüsselte Dateien wurden ausgelassen, und verschlüsselte Einträge wurden so exportiert, wie sie auf dem Datenträger stehen."
16225 }
16226 },
16227 "es": {
16228 "stringUnit": {
16229 "state": "translated",
16230 "value": "Se omitieron los archivos cifrados, y las entradas cifradas se exportaron tal como están en el disco."
16231 }
16232 },
16233 "fr": {
16234 "stringUnit": {
16235 "state": "translated",
16236 "value": "Les fichiers chiffrés ont été omis, et les entrées chiffrées ont été exportées telles qu'elles sont sur le disque."
16237 }
16238 },
16239 "ja": {
16240 "stringUnit": {
16241 "state": "translated",
16242 "value": "暗号化されたファイルは除外され、暗号化されたエントリはディスク上のまま書き出されました。"
16243 }
16244 },
16245 "pt-BR": {
16246 "stringUnit": {
16247 "state": "translated",
16248 "value": "Arquivos criptografados foram deixados de fora, e entradas criptografadas foram exportadas como estão no disco."
16249 }
16250 }
16251 }
16252 },
15436 "Encryption": { 16253 "Encryption": {
15437 "localizations": { 16254 "localizations": {
15438 "de": { 16255 "de": {
@@ -15467,6 +16284,40 @@
15467 } 16284 }
15468 } 16285 }
15469 }, 16286 },
16287 "Encrypt…": {
16288 "localizations": {
16289 "de": {
16290 "stringUnit": {
16291 "state": "translated",
16292 "value": "Verschlüsseln …"
16293 }
16294 },
16295 "es": {
16296 "stringUnit": {
16297 "state": "translated",
16298 "value": "Cifrar…"
16299 }
16300 },
16301 "fr": {
16302 "stringUnit": {
16303 "state": "translated",
16304 "value": "Chiffrer…"
16305 }
16306 },
16307 "ja": {
16308 "stringUnit": {
16309 "state": "translated",
16310 "value": "暗号化…"
16311 }
16312 },
16313 "pt-BR": {
16314 "stringUnit": {
16315 "state": "translated",
16316 "value": "Criptografar…"
16317 }
16318 }
16319 }
16320 },
15470 "End of Buffer": { 16321 "End of Buffer": {
15471 "comment": "Command title", 16322 "comment": "Command title",
15472 "localizations": { 16323 "localizations": {
@@ -15571,6 +16422,74 @@
15571 } 16422 }
15572 } 16423 }
15573 }, 16424 },
16425 "Enter a passphrase.": {
16426 "localizations": {
16427 "de": {
16428 "stringUnit": {
16429 "state": "translated",
16430 "value": "Gib ein Passwort ein."
16431 }
16432 },
16433 "es": {
16434 "stringUnit": {
16435 "state": "translated",
16436 "value": "Introduce una frase de contraseña."
16437 }
16438 },
16439 "fr": {
16440 "stringUnit": {
16441 "state": "translated",
16442 "value": "Saisissez une phrase secrète."
16443 }
16444 },
16445 "ja": {
16446 "stringUnit": {
16447 "state": "translated",
16448 "value": "パスフレーズを入力してください。"
16449 }
16450 },
16451 "pt-BR": {
16452 "stringUnit": {
16453 "state": "translated",
16454 "value": "Digite uma senha."
16455 }
16456 }
16457 }
16458 },
16459 "Enter the passphrase to encrypt and save them, or leave without saving.": {
16460 "localizations": {
16461 "de": {
16462 "stringUnit": {
16463 "state": "translated",
16464 "value": "Gib das Passwort ein, um sie zu verschlüsseln und zu sichern, oder verlasse die Datei ohne Sichern."
16465 }
16466 },
16467 "es": {
16468 "stringUnit": {
16469 "state": "translated",
16470 "value": "Introduce la frase de contraseña para cifrarlos y guardarlos, o sal sin guardar."
16471 }
16472 },
16473 "fr": {
16474 "stringUnit": {
16475 "state": "translated",
16476 "value": "Saisissez la phrase secrète pour les chiffrer et les enregistrer, ou quittez sans enregistrer."
16477 }
16478 },
16479 "ja": {
16480 "stringUnit": {
16481 "state": "translated",
16482 "value": "パスフレーズを入力して暗号化して保存するか、保存せずに閉じてください。"
16483 }
16484 },
16485 "pt-BR": {
16486 "stringUnit": {
16487 "state": "translated",
16488 "value": "Digite a senha para criptografá-las e salvá-las, ou saia sem salvar."
16489 }
16490 }
16491 }
16492 },
15574 "Entries can't be done before their TODO children": { 16493 "Entries can't be done before their TODO children": {
15575 "localizations": { 16494 "localizations": {
15576 "de": { 16495 "de": {
@@ -18771,6 +19690,40 @@
18771 } 19690 }
18772 } 19691 }
18773 }, 19692 },
19693 "Give the passphrase with Encrypt… first, so that a copy of your edits can be kept encrypted.": {
19694 "localizations": {
19695 "de": {
19696 "stringUnit": {
19697 "state": "translated",
19698 "value": "Gib zuerst mit „Verschlüsseln …“ das Passwort ein, damit eine Kopie deiner Änderungen verschlüsselt behalten werden kann."
19699 }
19700 },
19701 "es": {
19702 "stringUnit": {
19703 "state": "translated",
19704 "value": "Introduce primero la frase de contraseña con Cifrar… para que se pueda guardar cifrada una copia de tus cambios."
19705 }
19706 },
19707 "fr": {
19708 "stringUnit": {
19709 "state": "translated",
19710 "value": "Saisissez d'abord la phrase secrète avec Chiffrer… pour qu'une copie de vos modifications puisse être gardée chiffrée."
19711 }
19712 },
19713 "ja": {
19714 "stringUnit": {
19715 "state": "translated",
19716 "value": "編集内容のコピーを暗号化して保持できるよう、まず「暗号化…」でパスフレーズを入力してください。"
19717 }
19718 },
19719 "pt-BR": {
19720 "stringUnit": {
19721 "state": "translated",
19722 "value": "Informe primeiro a senha em Criptografar… para que uma cópia das suas alterações possa ser mantida criptografada."
19723 }
19724 }
19725 }
19726 },
18774 "Go": { 19727 "Go": {
18775 "comment": "The iPad menu bar's Go menu", 19728 "comment": "The iPad menu bar's Go menu",
18776 "localizations": { 19729 "localizations": {
@@ -36643,6 +37596,40 @@
36643 } 37596 }
36644 } 37597 }
36645 }, 37598 },
37599 "Saved encrypted": {
37600 "localizations": {
37601 "de": {
37602 "stringUnit": {
37603 "state": "translated",
37604 "value": "Verschlüsselt gesichert"
37605 }
37606 },
37607 "es": {
37608 "stringUnit": {
37609 "state": "translated",
37610 "value": "Guardado cifrado"
37611 }
37612 },
37613 "fr": {
37614 "stringUnit": {
37615 "state": "translated",
37616 "value": "Enregistré chiffré"
37617 }
37618 },
37619 "ja": {
37620 "stringUnit": {
37621 "state": "translated",
37622 "value": "暗号化して保存しました"
37623 }
37624 },
37625 "pt-BR": {
37626 "stringUnit": {
37627 "state": "translated",
37628 "value": "Salvo criptografado"
37629 }
37630 }
37631 }
37632 },
36646 "Save…": { 37633 "Save…": {
36647 "localizations": { 37634 "localizations": {
36648 "de": { 37635 "de": {
@@ -37780,6 +38767,74 @@
37780 } 38767 }
37781 } 38768 }
37782 }, 38769 },
38770 "Set Passphrase": {
38771 "localizations": {
38772 "de": {
38773 "stringUnit": {
38774 "state": "translated",
38775 "value": "Passwort festlegen"
38776 }
38777 },
38778 "es": {
38779 "stringUnit": {
38780 "state": "translated",
38781 "value": "Definir frase de contraseña"
38782 }
38783 },
38784 "fr": {
38785 "stringUnit": {
38786 "state": "translated",
38787 "value": "Définir la phrase secrète"
38788 }
38789 },
38790 "ja": {
38791 "stringUnit": {
38792 "state": "translated",
38793 "value": "パスフレーズを設定"
38794 }
38795 },
38796 "pt-BR": {
38797 "stringUnit": {
38798 "state": "translated",
38799 "value": "Definir Senha"
38800 }
38801 }
38802 }
38803 },
38804 "Set Passphrase…": {
38805 "localizations": {
38806 "de": {
38807 "stringUnit": {
38808 "state": "translated",
38809 "value": "Passwort festlegen …"
38810 }
38811 },
38812 "es": {
38813 "stringUnit": {
38814 "state": "translated",
38815 "value": "Definir frase de contraseña…"
38816 }
38817 },
38818 "fr": {
38819 "stringUnit": {
38820 "state": "translated",
38821 "value": "Définir la phrase secrète…"
38822 }
38823 },
38824 "ja": {
38825 "stringUnit": {
38826 "state": "translated",
38827 "value": "パスフレーズを設定…"
38828 }
38829 },
38830 "pt-BR": {
38831 "stringUnit": {
38832 "state": "translated",
38833 "value": "Definir Senha…"
38834 }
38835 }
38836 }
38837 },
37783 "Set Priority A": { 38838 "Set Priority A": {
37784 "comment": "Command title", 38839 "comment": "Command title",
37785 "localizations": { 38840 "localizations": {
@@ -42261,6 +43316,74 @@
42261 } 43316 }
42262 } 43317 }
42263 }, 43318 },
43319 "Tagged entries encrypted and saved": {
43320 "localizations": {
43321 "de": {
43322 "stringUnit": {
43323 "state": "translated",
43324 "value": "Markierte Einträge verschlüsselt und gesichert"
43325 }
43326 },
43327 "es": {
43328 "stringUnit": {
43329 "state": "translated",
43330 "value": "Entradas etiquetadas cifradas y guardadas"
43331 }
43332 },
43333 "fr": {
43334 "stringUnit": {
43335 "state": "translated",
43336 "value": "Entrées taguées chiffrées et enregistrées"
43337 }
43338 },
43339 "ja": {
43340 "stringUnit": {
43341 "state": "translated",
43342 "value": "タグ付きエントリを暗号化して保存しました"
43343 }
43344 },
43345 "pt-BR": {
43346 "stringUnit": {
43347 "state": "translated",
43348 "value": "Entradas etiquetadas criptografadas e salvas"
43349 }
43350 }
43351 }
43352 },
43353 "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first.": {
43354 "localizations": {
43355 "de": {
43356 "stringUnit": {
43357 "state": "translated",
43358 "value": "Markierte Einträge im Teilbaum sind nicht verschlüsselt; gib zuerst mit „Verschlüsseln …“ das Passwort ein."
43359 }
43360 },
43361 "es": {
43362 "stringUnit": {
43363 "state": "translated",
43364 "value": "Hay entradas etiquetadas sin cifrar en el subárbol; introduce primero la frase de contraseña con Cifrar…."
43365 }
43366 },
43367 "fr": {
43368 "stringUnit": {
43369 "state": "translated",
43370 "value": "Des entrées taguées du sous-arbre ne sont pas chiffrées ; saisissez d'abord la phrase secrète avec Chiffrer…."
43371 }
43372 },
43373 "ja": {
43374 "stringUnit": {
43375 "state": "translated",
43376 "value": "サブツリー内のタグ付きエントリが暗号化されていません。まず「暗号化…」でパスフレーズを入力してください。"
43377 }
43378 },
43379 "pt-BR": {
43380 "stringUnit": {
43381 "state": "translated",
43382 "value": "Há entradas etiquetadas não criptografadas na subárvore; informe primeiro a senha em Criptografar…."
43383 }
43384 }
43385 }
43386 },
42264 "Tags": { 43387 "Tags": {
42265 "comment": "Key bar button", 43388 "comment": "Key bar button",
42266 "localizations": { 43389 "localizations": {
@@ -43354,6 +44477,74 @@
43354 } 44477 }
43355 } 44478 }
43356 }, 44479 },
44480 "The file has no passphrase yet": {
44481 "localizations": {
44482 "de": {
44483 "stringUnit": {
44484 "state": "translated",
44485 "value": "Die Datei hat noch kein Passwort"
44486 }
44487 },
44488 "es": {
44489 "stringUnit": {
44490 "state": "translated",
44491 "value": "El archivo aún no tiene frase de contraseña"
44492 }
44493 },
44494 "fr": {
44495 "stringUnit": {
44496 "state": "translated",
44497 "value": "Le fichier n'a pas encore de phrase secrète"
44498 }
44499 },
44500 "ja": {
44501 "stringUnit": {
44502 "state": "translated",
44503 "value": "このファイルにはまだパスフレーズがありません"
44504 }
44505 },
44506 "pt-BR": {
44507 "stringUnit": {
44508 "state": "translated",
44509 "value": "O arquivo ainda não tem senha"
44510 }
44511 }
44512 }
44513 },
44514 "The file is encrypted, and its passphrase isn't known": {
44515 "localizations": {
44516 "de": {
44517 "stringUnit": {
44518 "state": "translated",
44519 "value": "Die Datei ist verschlüsselt, und ihr Passwort ist nicht bekannt"
44520 }
44521 },
44522 "es": {
44523 "stringUnit": {
44524 "state": "translated",
44525 "value": "El archivo está cifrado y no se conoce su frase de contraseña"
44526 }
44527 },
44528 "fr": {
44529 "stringUnit": {
44530 "state": "translated",
44531 "value": "Le fichier est chiffré et sa phrase secrète n'est pas connue"
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 está criptografado e sua senha não é conhecida"
44544 }
44545 }
44546 }
44547 },
43357 "The folder and its files stay on disk.": { 44548 "The folder and its files stay on disk.": {
43358 "localizations": { 44549 "localizations": {
43359 "de": { 44550 "de": {
@@ -43661,6 +44852,74 @@
43661 } 44852 }
43662 } 44853 }
43663 }, 44854 },
44855 "The passphrase wasn't remembered: the Keychain refused it.": {
44856 "localizations": {
44857 "de": {
44858 "stringUnit": {
44859 "state": "translated",
44860 "value": "Das Passwort wurde nicht gemerkt: Der Schlüsselbund hat es abgelehnt."
44861 }
44862 },
44863 "es": {
44864 "stringUnit": {
44865 "state": "translated",
44866 "value": "No se recordó la frase de contraseña: el llavero la rechazó."
44867 }
44868 },
44869 "fr": {
44870 "stringUnit": {
44871 "state": "translated",
44872 "value": "La phrase secrète n'a pas été mémorisée : le trousseau l'a refusée."
44873 }
44874 },
44875 "ja": {
44876 "stringUnit": {
44877 "state": "translated",
44878 "value": "パスフレーズは保存されませんでした。キーチェーンが拒否しました。"
44879 }
44880 },
44881 "pt-BR": {
44882 "stringUnit": {
44883 "state": "translated",
44884 "value": "A senha não foi lembrada: as Chaves a recusaram."
44885 }
44886 }
44887 }
44888 },
44889 "The passphrases differ": {
44890 "localizations": {
44891 "de": {
44892 "stringUnit": {
44893 "state": "translated",
44894 "value": "Die Passwörter stimmen nicht überein"
44895 }
44896 },
44897 "es": {
44898 "stringUnit": {
44899 "state": "translated",
44900 "value": "Las frases de contraseña no coinciden"
44901 }
44902 },
44903 "fr": {
44904 "stringUnit": {
44905 "state": "translated",
44906 "value": "Les phrases secrètes diffèrent"
44907 }
44908 },
44909 "ja": {
44910 "stringUnit": {
44911 "state": "translated",
44912 "value": "パスフレーズが一致しません"
44913 }
44914 },
44915 "pt-BR": {
44916 "stringUnit": {
44917 "state": "translated",
44918 "value": "As senhas não coincidem"
44919 }
44920 }
44921 }
44922 },
43664 "The purchase didn't go through. %@": { 44923 "The purchase didn't go through. %@": {
43665 "localizations": { 44924 "localizations": {
43666 "de": { 44925 "de": {
@@ -44456,6 +45715,40 @@
44456 } 45715 }
44457 } 45716 }
44458 }, 45717 },
45718 "This version of orgstar keeps remembered passphrases in your login keychain without limiting them to this Mac; Touch ID or your password is still asked before one is used.": {
45719 "localizations": {
45720 "de": {
45721 "stringUnit": {
45722 "state": "translated",
45723 "value": "Diese Version von orgstar bewahrt gemerkte Passwörter im Anmeldeschlüsselbund auf, ohne sie auf diesen Mac zu beschränken; Touch ID oder dein Passwort wird trotzdem abgefragt, bevor eines verwendet wird."
45724 }
45725 },
45726 "es": {
45727 "stringUnit": {
45728 "state": "translated",
45729 "value": "Esta versión de orgstar guarda las frases de contraseña recordadas en tu llavero de inicio de sesión sin limitarlas a este Mac; aun así se pide Touch ID o tu contraseña antes de usar una."
45730 }
45731 },
45732 "fr": {
45733 "stringUnit": {
45734 "state": "translated",
45735 "value": "Cette version d'orgstar garde les phrases secrètes mémorisées dans votre trousseau de session sans les limiter à ce Mac ; Touch ID ou votre mot de passe est quand même demandé avant d'en utiliser une."
45736 }
45737 },
45738 "ja": {
45739 "stringUnit": {
45740 "state": "translated",
45741 "value": "このバージョンのorgstarは、保存したパスフレーズをこのMacに限定せずログインキーチェーンに保持します。使用する前にTouch IDまたはパスワードを求めます。"
45742 }
45743 },
45744 "pt-BR": {
45745 "stringUnit": {
45746 "state": "translated",
45747 "value": "Esta versão do orgstar guarda as senhas lembradas nas suas chaves de início de sessão sem limitá-las a este Mac; o Touch ID ou sua senha ainda são pedidos antes de usar uma."
45748 }
45749 }
45750 }
45751 },
44459 "This view can't be saved from here; write it in views.toml.": { 45752 "This view can't be saved from here; write it in views.toml.": {
44460 "localizations": { 45753 "localizations": {
44461 "de": { 45754 "de": {
@@ -47210,6 +48503,40 @@
47210 } 48503 }
47211 } 48504 }
47212 }, 48505 },
48506 "Wrong passphrase": {
48507 "localizations": {
48508 "de": {
48509 "stringUnit": {
48510 "state": "translated",
48511 "value": "Falsches Passwort"
48512 }
48513 },
48514 "es": {
48515 "stringUnit": {
48516 "state": "translated",
48517 "value": "Frase de contraseña incorrecta"
48518 }
48519 },
48520 "fr": {
48521 "stringUnit": {
48522 "state": "translated",
48523 "value": "Phrase secrète incorrecte"
48524 }
48525 },
48526 "ja": {
48527 "stringUnit": {
48528 "state": "translated",
48529 "value": "パスフレーズが違います"
48530 }
48531 },
48532 "pt-BR": {
48533 "stringUnit": {
48534 "state": "translated",
48535 "value": "Senha incorreta"
48536 }
48537 }
48538 }
48539 },
47213 "Yank": { 48540 "Yank": {
47214 "comment": "Command title", 48541 "comment": "Command title",
47215 "localizations": { 48542 "localizations": {
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