Sources/OrgApp/CryptSheet.swift

c2d503b97e80b560fda12d61ecc99864f2a18a25
orgstar/Sources/OrgApp/CryptSheet.swift

279 lines · 12618 bytes

  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    public var body: some View {
 88        VStack(alignment: .leading, spacing: 12) {
 89            if editing != nil {
 90                Text("Encrypted Entry").font(.headline)
 91                TextEditor(text: $plaintext)
 92                    .font(.body.monospaced())
 93                    .frame(minHeight: 220)
 94                if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
 95                HStack {
 96                    Button("Decrypt in File") { decryptEdited() }
 97                    Spacer()
 98                    Button("Cancel", role: .cancel) { done(nil) }.keyboardShortcut(.cancelAction)
 99                    Button("Save") { save() }.keyboardShortcut(.defaultAction)
100                }
101            } else {
102                Text(title).font(.headline)
103                if let explanation { Text(explanation).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }
104                SecureField("Passphrase", text: $passphrase).onSubmit(submit)
105                if asksTwice { SecureField("Repeat passphrase", text: $repeated).onSubmit(submit) }
106                if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
107                HStack {
108                    Spacer()
109                    Button("Cancel", role: .cancel) { cancel() }.keyboardShortcut(.cancelAction)
110                    Button(request.encrypting ? "Encrypt" : "Decrypt") { submit() }
111                        .keyboardShortcut(.defaultAction)
112                        .disabled(passphrase.isEmpty)
113                }
114            }
115        }
116        .padding(20)
117        #if os(macOS)
118        .frame(minWidth: 460)
119        #else
120        .frame(maxHeight: .infinity, alignment: .top)
121        #endif
122        .task {
123            if let stored = await passphrases.stored(for: request.path) { run(stored, remembered: true) }
124        }
125        .alert(CryptPassphrases.question, isPresented: Binding(get: { question != nil }, set: { _ in })) {
126            Button("Not Now", role: .cancel) { answer(enable: false) }
127            Button("Enable") { answer(enable: true) }
128        } message: {
129            Text(CryptPassphrases.explanation)
130        }
131    }
132
133    private var passphrases: CryptPassphrases { session?.passphrases ?? .shared }
134
135    /// A typed passphrase worked, and the file's text is now `text`: saved while the setting is
136    /// on, after the question while it's undecided, then `then`. A nil `text` (nothing was
137    /// checked) saves nothing.
138    private func keep(_ passphrase: String, remembered: Bool, text: String?, then: @escaping () -> Void) {
139        guard !remembered, let text else { return then() }
140        if passphrases.typed(passphrase, for: request.path, text: text, note: &keychainNote) { return question = (passphrase, text, then) }
141        then()
142    }
143
144    private func answer(enable: Bool) {
145        guard let question else { return }
146        self.question = nil
147        keychainNote = passphrases.answer(enable: enable, passphrase: question.passphrase, for: request.path, text: question.text)
148        question.then()
149    }
150
151    /// The open file's text, after a passphrase opened or saved it.
152    private var unlockedText: String { session?.document(of: request.path)?.text ?? "" }
153
154    private var title: String {
155        switch request.mode {
156        case .encrypt: "Encrypt Entry"
157        case .encryptAll: "Encrypt Tagged Entries"
158        case .open, .decryptInPlace: "Decrypt Entry"
159        case .encryptOnSave: String(localized: "Encrypt Tagged Entries")
160        case .openFile: String(localized: "Decrypt File")
161        case .newFile: String(localized: "Set Passphrase")
162        }
163    }
164
165    private var name: String { (request.path as NSString).lastPathComponent }
166
167    private var explanation: String? {
168        switch request.mode {
169        case .encryptOnSave: String(localized: "\(name) is saved with its tagged entries encrypted.")
170        case .openFile: String(localized: "\(name) is encrypted.")
171        case .newFile: String(localized: "\(name) is saved encrypted with this passphrase.")
172        default: nil
173        }
174    }
175
176    /// A new passphrase is typed twice; one that must open what's encrypted already, once.
177    private var asksTwice: Bool {
178        switch request.mode {
179        case .encryptOnSave: OrgCrypt.firstMessage(text()) == nil
180        case .openFile: false
181        default: request.encrypting
182        }
183    }
184
185    private func submit() {
186        guard !passphrase.isEmpty else { return }
187        if asksTwice, passphrase != repeated { return problem = "The passphrases differ" }
188        run(passphrase, remembered: false)
189    }
190
191    private func cancel() {
192        if case .openFile = request.mode { session?.cancelUnlock() }
193        done(nil)
194    }
195
196    private func run(_ passphrase: String, remembered: Bool) {
197        if request.unlocks {
198            if let failure = session?.unlock(passphrase, for: request.path) { return problem = failure }
199            switch request.mode {
200            case .encryptOnSave: return finish(String(localized: "Tagged entries encrypted and saved"), passphrase: passphrase, remembered: remembered, text: unlockedText)
201            case .newFile: return finish(String(localized: "Saved encrypted"), passphrase: passphrase, remembered: remembered, text: unlockedText)
202            default: return finish(nil, passphrase: passphrase, remembered: remembered, text: unlockedText)
203            }
204        }
205        let current = text()
206        do {
207            switch request.mode {
208            case .encrypt:
209                guard let encrypted = try OrgCrypt.encrypt(current, at: request.offset, passphrase: passphrase) else {
210                    return finish("The entry is encrypted already", passphrase: passphrase, remembered: remembered, text: nil)
211                }
212                apply(encrypted)
213                finish("Entry encrypted", passphrase: passphrase, remembered: remembered, text: encrypted)
214            case .encryptAll(let tag):
215                let (encrypted, count) = try OrgCrypt.encryptAll(current, passphrase: passphrase, tag: tag)
216                if count > 0 { apply(encrypted) }
217                finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered, text: count > 0 ? encrypted : nil)
218            case .open:
219                let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext
220                session?.cryptUsed(passphrase, for: request.path)
221                plaintext = plain
222                editing = (plain, passphrase)
223                problem = nil
224                keep(passphrase, remembered: remembered, text: current) {}
225            case .decryptInPlace:
226                let message = OrgCrypt.encryptedRange(current, at: request.offset).map { (current as NSString).substring(with: NSRange($0)) }
227                let decrypted = try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase)
228                // Saved unchanged with org-crypt-use-before-save-magic, the entry gets its message back.
229                if let message, let body = OrgCrypt.bodyRange(decrypted, at: request.offset) {
230                    session?.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: request.path)
231                }
232                apply(decrypted)
233                finish("Entry decrypted", passphrase: passphrase, remembered: remembered, text: decrypted)
234            case .encryptOnSave, .openFile, .newFile:
235                break
236            }
237        } catch {
238            problem = "\(error)"
239        }
240    }
241
242    /// Closes with `message`; `text` is the file's text the passphrase was checked against, nil
243    /// when it wasn't.
244    private func finish(_ message: String?, passphrase: String, remembered: Bool, text: String?) {
245        if !request.unlocks { session?.cryptUsed(passphrase, for: request.path) }
246        keep(passphrase, remembered: remembered, text: text) {
247            let text = [message, keychainNote].compactMap { $0 }.joined(separator: " ")
248            done(text.isEmpty ? nil : text)
249        }
250    }
251
252    /// The edited text encrypted again in the message's place; nothing changes if it wasn't edited.
253    private func save() {
254        guard let editing else { return }
255        guard plaintext != editing.original else { return done(nil) }
256        var plain = plaintext
257        if !plain.isEmpty, !plain.hasSuffix("\n") { plain += "\n" }
258        do {
259            apply(try OrgCrypt.replacing(text(), at: request.offset, with: plain, passphrase: editing.passphrase))
260            done("Entry encrypted again")
261        } catch {
262            problem = "\(error)"
263        }
264    }
265
266    /// `org-decrypt-entry` with the text as edited.
267    private func decryptEdited() {
268        guard let editing else { return }
269        var plain = plaintext
270        if !plain.isEmpty, !plain.hasSuffix("\n") { plain += "\n" }
271        do {
272            let replaced = try OrgCrypt.replacing(text(), at: request.offset, with: plain, passphrase: editing.passphrase)
273            apply(try OrgCrypt.decryptInPlace(replaced, at: request.offset, passphrase: editing.passphrase))
274            done("Entry decrypted")
275        } catch {
276            problem = "\(error)"
277        }
278    }
279}
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