Sources/OrgApp/CryptSheet.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgApp/CryptSheet.swift

331 lines · 14785 bytes

12 symbols in this file
  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import SwiftUI
  5
  6/// What an org-crypt command does with the entry at `offset` in the file at `path`.
  7public struct CryptRequest: Identifiable, Sendable {
  8    public enum Mode: Sendable {
  9        /// `org-encrypt-entry`.
 10        case encrypt
 11        /// `org-encrypt-entries`, with `org-crypt-tag-matcher`'s tag.
 12        case encryptAll(tag: String)
 13        /// The decrypted text, to read and change; the file keeps it encrypted.
 14        case open
 15        /// `org-decrypt-entry`: the decrypted text in the file.
 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
 23    }
 24
 25    public let id = UUID()
 26    public let mode: Mode
 27    public let path: String
 28    public let offset: Int
 29
 30    public init(mode: Mode, path: String, offset: Int) {
 31        self.mode = mode
 32        self.path = path
 33        self.offset = offset
 34    }
 35
 36    var encrypting: Bool {
 37        switch mode {
 38        case .encrypt, .encryptAll, .encryptOnSave, .newFile: true
 39        default: false
 40        }
 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    }
 55}
 56
 57/// The passphrase for an org-crypt command, from the Keychain when one is saved and "Use Face ID
 58/// to Decrypt" is on, then for `open` the decrypted entry to edit. `text` is the file's text
 59/// now; `apply` puts a new text in its place; `done` closes the sheet with a message. `session`
 60/// learns the passphrase, so saves encrypt with it without asking again.
 61public struct CryptSheet: View {
 62    let request: CryptRequest
 63    let session: DocumentSession?
 64    let text: () -> String
 65    let apply: (String) -> Void
 66    let done: (String?) -> Void
 67    @State private var passphrase = ""
 68    @State private var repeated = ""
 69    /// What the Keychain said when the passphrase was saved, shown with the result.
 70    @State private var keychainNote: String?
 71    /// A typed passphrase that worked, the file's text with it, waiting for the answer to
 72    /// whether to use Face ID, and what follows.
 73    @State private var question: (passphrase: String, text: String, then: () -> Void)?
 74    @State private var problem: String?
 75    /// The decrypted entry being edited, and the passphrase it came with.
 76    @State private var editing: (original: String, passphrase: String)?
 77    @State private var plaintext = ""
 78
 79    public init(request: CryptRequest, session: DocumentSession? = nil, text: @escaping () -> String, apply: @escaping (String) -> Void, done: @escaping (String?) -> Void) {
 80        self.request = request
 81        self.session = session
 82        self.text = text
 83        self.apply = apply
 84        self.done = done
 85    }
 86
 87    #if os(macOS)
 88    private var layout: some View {
 89        VStack(alignment: .leading, spacing: 12) {
 90            if editing != nil {
 91                Text("Encrypted Entry").font(.headline)
 92                TextEditor(text: $plaintext)
 93                    .font(.body.monospaced())
 94                    .frame(minHeight: 220)
 95                if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
 96                HStack {
 97                    Button("Decrypt in File") { decryptEdited() }
 98                    Spacer()
 99                    Button("Cancel", role: .cancel) { done(nil) }.keyboardShortcut(.cancelAction)
100                    Button("Save") { save() }.keyboardShortcut(.defaultAction)
101                }
102            } else {
103                Text(title).font(.headline)
104                if let explanation { Text(explanation).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }
105                SecureField("Passphrase", text: $passphrase).onSubmit(submit)
106                if asksTwice { SecureField("Repeat passphrase", text: $repeated).onSubmit(submit) }
107                if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
108                HStack {
109                    Spacer()
110                    Button("Cancel", role: .cancel) { cancel() }.keyboardShortcut(.cancelAction)
111                    Button(request.encrypting ? "Encrypt" : "Decrypt") { submit() }
112                        .keyboardShortcut(.defaultAction)
113                        .disabled(passphrase.isEmpty)
114                }
115            }
116        }
117        .padding(20)
118        .frame(minWidth: 460)
119    }
120    #else
121    @FocusState private var fieldFocused: Bool
122
123    /// The editor's sheet: a navigation bar with Cancel and the action, the fields in a form.
124    private var layout: some View {
125        Form {
126            if editing != nil {
127                Section {
128                    TextEditor(text: $plaintext)
129                        .font(.body.monospaced())
130                        .frame(minHeight: 220)
131                } footer: {
132                    if let problem { Text(problem).foregroundStyle(.red) }
133                }
134                Section {
135                    Button("Decrypt in File") { decryptEdited() }
136                }
137            } else {
138                Section {
139                    SecureField("Passphrase", text: $passphrase)
140                        .focused($fieldFocused)
141                        .submitLabel(.go)
142                        .onSubmit(submit)
143                    if asksTwice { SecureField("Repeat passphrase", text: $repeated).submitLabel(.go).onSubmit(submit) }
144                } footer: {
145                    VStack(alignment: .leading, spacing: 6) {
146                        if let explanation { Text(explanation) }
147                        if let problem { Text(problem).foregroundStyle(.red) }
148                    }
149                }
150            }
151        }
152        .navigationTitle(editing != nil ? String(localized: "Encrypted Entry") : title)
153        .toolbar {
154            ToolbarItem(placement: .cancellationAction) {
155                Button("Cancel", role: .cancel) { if editing != nil { done(nil) } else { cancel() } }
156            }
157            ToolbarItem(placement: .confirmationAction) {
158                if editing != nil {
159                    Button("Save") { save() }
160                } else {
161                    Button(request.encrypting ? "Encrypt" : "Decrypt") { submit() }.disabled(passphrase.isEmpty)
162                }
163            }
164        }
165        .presentationDetents(editing != nil ? [.large] : [.medium, .large])
166        .onAppear { fieldFocused = true }
167        // A wrong passphrase: the field again, to type it over.
168        .onChange(of: problem) { if problem != nil, editing == nil { fieldFocused = true } }
169    }
170    #endif
171
172    public var body: some View {
173        layout
174        .task {
175            if let stored = await passphrases.stored(for: request.path) { run(stored, remembered: true) }
176        }
177        .alert(CryptPassphrases.question, isPresented: Binding(get: { question != nil }, set: { _ in })) {
178            Button("Not Now", role: .cancel) { answer(enable: false) }
179            Button("Enable") { answer(enable: true) }
180        } message: {
181            Text(CryptPassphrases.explanation)
182        }
183    }
184
185    private var passphrases: CryptPassphrases { session?.passphrases ?? .shared }
186
187    /// A typed passphrase worked, and the file's text is now `text`: saved while the setting is
188    /// on, after the question while it's undecided, then `then`. A nil `text` (nothing was
189    /// checked) saves nothing.
190    private func keep(_ passphrase: String, remembered: Bool, text: String?, then: @escaping () -> Void) {
191        guard !remembered, let text else { return then() }
192        if passphrases.typed(passphrase, for: request.path, text: text, note: &keychainNote) { return question = (passphrase, text, then) }
193        then()
194    }
195
196    private func answer(enable: Bool) {
197        guard let question else { return }
198        self.question = nil
199        keychainNote = passphrases.answer(enable: enable, passphrase: question.passphrase, for: request.path, text: question.text)
200        question.then()
201    }
202
203    /// The open file's text, after a passphrase opened or saved it.
204    private var unlockedText: String { session?.document(of: request.path)?.text ?? "" }
205
206    private var title: String {
207        switch request.mode {
208        case .encrypt: "Encrypt Entry"
209        case .encryptAll: "Encrypt Tagged Entries"
210        case .open, .decryptInPlace: "Decrypt Entry"
211        case .encryptOnSave: String(localized: "Encrypt Tagged Entries")
212        case .openFile: String(localized: "Decrypt File")
213        case .newFile: String(localized: "Set Passphrase")
214        }
215    }
216
217    private var name: String { (request.path as NSString).lastPathComponent }
218
219    private var explanation: String? {
220        switch request.mode {
221        case .encryptOnSave: String(localized: "\(name) is saved with its tagged entries encrypted.")
222        case .openFile: String(localized: "\(name) is encrypted.")
223        case .newFile: String(localized: "\(name) is saved encrypted with this passphrase.")
224        default: nil
225        }
226    }
227
228    /// A new passphrase is typed twice; one that must open what's encrypted already, once.
229    private var asksTwice: Bool {
230        switch request.mode {
231        case .encryptOnSave: OrgCrypt.firstMessage(text()) == nil
232        case .openFile: false
233        default: request.encrypting
234        }
235    }
236
237    private func submit() {
238        guard !passphrase.isEmpty else { return }
239        if asksTwice, passphrase != repeated { return problem = "The passphrases differ" }
240        run(passphrase, remembered: false)
241    }
242
243    private func cancel() {
244        if case .openFile = request.mode { session?.cancelUnlock() }
245        done(nil)
246    }
247
248    private func run(_ passphrase: String, remembered: Bool) {
249        if request.unlocks {
250            if let failure = session?.unlock(passphrase, for: request.path) { return problem = failure }
251            switch request.mode {
252            case .encryptOnSave: return finish(String(localized: "Tagged entries encrypted and saved"), passphrase: passphrase, remembered: remembered, text: unlockedText)
253            case .newFile: return finish(String(localized: "Saved encrypted"), passphrase: passphrase, remembered: remembered, text: unlockedText)
254            default: return finish(nil, passphrase: passphrase, remembered: remembered, text: unlockedText)
255            }
256        }
257        let current = text()
258        do {
259            switch request.mode {
260            case .encrypt:
261                guard let encrypted = try OrgCrypt.encrypt(current, at: request.offset, passphrase: passphrase) else {
262                    return finish("The entry is encrypted already", passphrase: passphrase, remembered: remembered, text: nil)
263                }
264                apply(encrypted)
265                finish("Entry encrypted", passphrase: passphrase, remembered: remembered, text: encrypted)
266            case .encryptAll(let tag):
267                let (encrypted, count) = try OrgCrypt.encryptAll(current, passphrase: passphrase, tag: tag)
268                if count > 0 { apply(encrypted) }
269                finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered, text: count > 0 ? encrypted : nil)
270            case .open:
271                let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext
272                session?.cryptUsed(passphrase, for: request.path)
273                plaintext = plain
274                editing = (plain, passphrase)
275                problem = nil
276                keep(passphrase, remembered: remembered, text: current) {}
277            case .decryptInPlace:
278                let message = OrgCrypt.encryptedRange(current, at: request.offset).map { (current as NSString).substring(with: NSRange($0)) }
279                let decrypted = try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase)
280                // Saved unchanged with org-crypt-use-before-save-magic, the entry gets its message back.
281                if let message, let body = OrgCrypt.bodyRange(decrypted, at: request.offset) {
282                    session?.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: request.path)
283                }
284                apply(decrypted)
285                finish("Entry decrypted", passphrase: passphrase, remembered: remembered, text: decrypted)
286            case .encryptOnSave, .openFile, .newFile:
287                break
288            }
289        } catch {
290            problem = "\(error)"
291        }
292    }
293
294    /// Closes with `message`; `text` is the file's text the passphrase was checked against, nil
295    /// when it wasn't.
296    private func finish(_ message: String?, passphrase: String, remembered: Bool, text: String?) {
297        if !request.unlocks { session?.cryptUsed(passphrase, for: request.path) }
298        keep(passphrase, remembered: remembered, text: text) {
299            let text = [message, keychainNote].compactMap { $0 }.joined(separator: " ")
300            done(text.isEmpty ? nil : text)
301        }
302    }
303
304    /// The edited text encrypted again in the message's place; nothing changes if it wasn't edited.
305    private func save() {
306        guard let editing else { return }
307        guard plaintext != editing.original else { return done(nil) }
308        var plain = plaintext
309        if !plain.isEmpty, !plain.hasSuffix("\n") { plain += "\n" }
310        do {
311            apply(try OrgCrypt.replacing(text(), at: request.offset, with: plain, passphrase: editing.passphrase))
312            done("Entry encrypted again")
313        } catch {
314            problem = "\(error)"
315        }
316    }
317
318    /// `org-decrypt-entry` with the text as edited.
319    private func decryptEdited() {
320        guard let editing else { return }
321        var plain = plaintext
322        if !plain.isEmpty, !plain.hasSuffix("\n") { plain += "\n" }
323        do {
324            let replaced = try OrgCrypt.replacing(text(), at: request.offset, with: plain, passphrase: editing.passphrase)
325            apply(try OrgCrypt.decryptInPlace(replaced, at: request.offset, passphrase: editing.passphrase))
326            done("Entry decrypted")
327        } catch {
328            problem = "\(error)"
329        }
330    }
331}
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