Sources/OrgCore/Crypto/OrgCrypt.swift

9945f06859a5feee9b6af3496e944cb6b395715b
orgstar/Sources/OrgCore/Crypto/OrgCrypt.swift

243 lines · 13694 bytes

  1import CryptoKit
  2import Foundation
  3
  4/// org-crypt (org-crypt.el, Org 9.8.7) with symmetric encryption, as with `org-crypt-key`
  5/// nil: an entry's text after its planning, properties and logbook, through the end of its
  6/// subtree, replaced by an armored OpenPGP message under the heading.
  7public enum OrgCrypt {
  8    public struct Failure: Error, Equatable, CustomStringConvertible {
  9        public let description: String
 10        public init(_ description: String) { self.description = description }
 11    }
 12
 13    /// `org-end-of-meta-data 'standard`: past planning, the property drawer, clock lines,
 14    /// blank lines and logbook drawers.
 15    static func metaDataEnd(_ buffer: EmacsBuffer) {
 16        buffer.endOfMetaData()
 17        guard !buffer.atHeading else { return }
 18        let end = buffer.saveExcursion { () -> Int in buffer.outlineNextHeading(); return buffer.point }
 19        while !buffer.eobp {
 20            if buffer.lookingAt("[ \\t]*$|^[ \\t]*CLOCK:") != nil {
 21                buffer.forwardLine(1)
 22            } else if buffer.lookingAt("[ \\t]*:LOGBOOK:[ \\t]*$") != nil {
 23                guard buffer.searchForward("^[ \\t]*:END:[ \\t]*$", bound: end, caseInsensitive: true) != nil else { return }
 24                buffer.forwardLine(1)
 25            } else {
 26                return
 27            }
 28        }
 29    }
 30
 31    /// The heading the entry at `offset` is under, or nil before the first.
 32    public static func heading(_ text: String, at offset: Int) -> Int? {
 33        let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
 34        return try? buffer.backToHeading()
 35    }
 36
 37    /// `org-at-encrypted-entry-p`: the message's lines, from its begin line through the line
 38    /// after its end line.
 39    public static func encryptedRange(_ text: String, at offset: Int) -> Range<Int>? {
 40        let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
 41        guard (try? buffer.backToHeading()) != nil else { return nil }
 42        metaDataEnd(buffer)
 43        guard buffer.lookingAt("[ \\t]*-----BEGIN PGP MESSAGE-----[ \\t]*$") != nil else { return nil }
 44        let start = buffer.point
 45        guard let match = buffer.searchForward("^(?:([ \\t]*-----END PGP MESSAGE-----)[ \\t]*$|\\*+ )", caseInsensitive: false),
 46              match[1] != nil else { return nil }
 47        let line = buffer.lineEnd(match[0]!.lowerBound)
 48        return start..<min(line + 1, buffer.length)
 49    }
 50
 51    /// What `org-encrypt-entry` encrypts: after the meta-data through the subtree's end, less
 52    /// the blank lines before the next heading.
 53    public static func bodyRange(_ text: String, at offset: Int) -> Range<Int>? {
 54        let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
 55        guard let heading = try? buffer.backToHeading() else { return nil }
 56        metaDataEnd(buffer)
 57        let start = buffer.point
 58        buffer.point = heading
 59        buffer.endOfSubtree(toHeading: true)
 60        buffer.backOverEmptyLines()
 61        return start..<max(start, buffer.point)
 62    }
 63
 64    /// `org-encrypt-entry`: the text with the entry at `offset` encrypted, or nil when it's
 65    /// encrypted already.
 66    public static func encrypt(_ text: String, at offset: Int, passphrase: String, now: Date = Date()) throws -> String? {
 67        guard heading(text, at: offset) != nil else { throw Failure("Before first headline") }
 68        guard encryptedRange(text, at: offset) == nil, let range = bodyRange(text, at: offset) else { return nil }
 69        let ns = text as NSString
 70        let contents = ns.substring(with: NSRange(range))
 71        let message = try OpenPGP.encrypt(Data(contents.utf8), passphrase: passphrase, now: now)
 72        return ns.replacingCharacters(in: NSRange(range), with: message)
 73    }
 74
 75    /// The decrypted text of the entry at `offset` and where its message is.
 76    public static func decrypt(_ text: String, at offset: Int, passphrase: String) throws -> (plaintext: String, range: Range<Int>) {
 77        guard let range = encryptedRange(text, at: offset) else { throw Failure("Not an encrypted entry") }
 78        let message = (text as NSString).substring(with: NSRange(range))
 79        let data: Data
 80        do {
 81            data = try OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)
 82        } catch let failure as OpenPGP.Failure {
 83            throw Failure(failure == OpenPGP.wrongPassphrase ? "Wrong passphrase" : failure.description)
 84        }
 85        var plain = String(decoding: data, as: UTF8.self)
 86        // epg encrypts in text mode, with CRLF line ends, and `decode-coding-string` with
 87        // `utf-8` takes them back to LF.
 88        if plain.contains("\r\n"), !plain.replacingOccurrences(of: "\r\n", with: "").contains("\n") {
 89            plain = plain.replacingOccurrences(of: "\r\n", with: "\n")
 90        }
 91        return (plain, range)
 92    }
 93
 94    /// `org-decrypt-entry`: the text with the entry's message replaced by what it holds, its
 95    /// headings moved below the entry's level when they aren't.
 96    public static func decryptInPlace(_ text: String, at offset: Int, passphrase: String) throws -> String {
 97        var (plain, range) = try decrypt(text, at: offset, passphrase: passphrase)
 98        let ns = text as NSString
 99        let headingStart = heading(text, at: offset)!
100        let level = ns.substring(from: headingStart).prefix { $0 == "*" }.count
101        let pattern = "(?m)^\\*{1,\(level)} "
102        if plain.range(of: pattern, options: .regularExpression) != nil {
103            let minLevel = plain.matches(of: try! Regex(pattern)).map { plain[$0.range].count - 1 }.min() ?? level
104            let prefix = String(repeating: "*", count: 1 + level - minLevel)
105            plain = plain.replacing(#/(?m)^\*+ /#) { prefix + $0.output }
106        }
107        return ns.replacingCharacters(in: NSRange((range.lowerBound - 1)..<range.upperBound), with: "\n" + plain)
108    }
109
110    /// The entry's message replaced by `plaintext` encrypted again.
111    public static func replacing(_ text: String, at offset: Int, with plaintext: String, passphrase: String, now: Date = Date()) throws -> String {
112        guard let range = encryptedRange(text, at: offset) else { throw Failure("Not an encrypted entry") }
113        let message = try OpenPGP.encrypt(Data(plaintext.utf8), passphrase: passphrase, now: now)
114        return (text as NSString).replacingCharacters(in: NSRange(range), with: message)
115    }
116
117    /// The headings with `tag` (`org-crypt-tag-matcher`), inherited or their own, in order.
118    public static func taggedHeadings(_ text: String, tag: String = "crypt", settings: OrgSettings = .default) -> [Int] {
119        let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings))
120        return model.headings.indices.filter { model.tags(of: $0).contains { $0.value == tag } }.map { model.headings[$0].headingRange.lowerBound }
121    }
122
123    /// `org-encrypt-entries`: every tagged entry not encrypted yet, from the top, so that an
124    /// entry's tagged children go inside its message. The text and how many were encrypted.
125    public static func encryptAll(_ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default, now: Date = Date()) throws -> (String, Int) {
126        var text = text
127        var count = 0
128        var from = 0
129        while let next = taggedHeadings(text, tag: tag, settings: settings).first(where: { $0 >= from }) {
130            if let encrypted = try encrypt(text, at: next, passphrase: passphrase, now: now) {
131                text = encrypted
132                count += 1
133            }
134            from = next + 1
135        }
136        return (text, count)
137    }
138
139    /// What saving does with the tagged entry at `heading`: nil when nothing (its text is a
140    /// message, or it has no text), else its text's range, the message at its start if any,
141    /// and whether it has text that isn't blank outside a message.
142    static func pending(_ text: String, at heading: Int) -> (body: Range<Int>, message: Range<Int>?, hasText: Bool)? {
143        guard let body = bodyRange(text, at: heading) else { return nil }
144        let ns = text as NSString
145        func blank(_ range: Range<Int>) -> Bool {
146            range.isEmpty || ns.substring(with: NSRange(range)).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
147        }
148        if let message = encryptedRange(text, at: heading) {
149            // Text typed below the message isn't encrypted.
150            let tail = min(message.upperBound, body.upperBound)..<max(message.upperBound, body.upperBound)
151            return blank(tail) ? nil : (body, message, true)
152        }
153        return (body, nil, !blank(body))
154    }
155
156    /// The tagged entries `seal` encrypts whose text isn't blank: those a save can't write
157    /// without the passphrase, text below a message included. Their headings' offsets.
158    public static func unencrypted(_ text: String, tag: String = "crypt", settings: OrgSettings = .default, within: Range<Int>? = nil) -> [Int] {
159        guard text.contains(tag) else { return [] }
160        var found: [Int] = []
161        var covered = 0
162        for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered && within?.contains(heading) ?? true {
163            guard let entry = pending(text, at: heading) else { continue }
164            // Tagged children go inside this entry's message.
165            covered = entry.body.upperBound
166            if entry.hasText { found.append(heading) }
167        }
168        return found
169    }
170
171    /// `org-encrypt-entries` as `org-crypt-use-before-save-magic` runs it before a save. An
172    /// entry whose text `reuse` knows by its `checksum` gets that message again, as org-crypt
173    /// keeps an entry decrypted and left unchanged byte for byte. Text below an entry's message
174    /// goes into one message with what the old one held. The text, and each message with the
175    /// text the entry had.
176    public static func seal(
177        _ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default,
178        reuse: (String) -> String? = { _ in nil }, within: Range<Int>? = nil, now: Date = Date()
179    ) throws -> (text: String, messages: [(message: String, plaintext: String)]) {
180        guard text.contains(tag) else { return (text, []) }
181        var result = text as NSString
182        var messages: [(String, String)] = []
183        var shift = 0
184        var covered = 0
185        for heading in taggedHeadings(text, tag: tag, settings: settings) where heading >= covered && within?.contains(heading) ?? true {
186            let current = result as String
187            guard let entry = pending(current, at: heading + shift) else { continue }
188            let range = entry.body
189            covered = range.upperBound - shift
190            let contents = result.substring(with: NSRange(range))
191            var plaintext = contents
192            if let old = entry.message {
193                let opened: String
194                do {
195                    opened = try decrypt(current, at: heading + shift, passphrase: passphrase).plaintext
196                } catch {
197                    throw Failure("An entry has text below a message that this passphrase doesn't open; entries encrypted to a public key aren't supported")
198                }
199                plaintext = opened + result.substring(with: NSRange(old.upperBound..<range.upperBound))
200            }
201            let message = try reuse(checksum(contents)) ?? OpenPGP.encrypt(Data(plaintext.utf8), passphrase: passphrase, now: now)
202            result = result.replacingCharacters(in: NSRange(range), with: message) as NSString
203            shift += (message as NSString).length - range.count
204            messages.append((message, contents))
205        }
206        return (result as String, messages)
207    }
208
209    /// Whether `offset` is in the text of an entry with `tag`, which a message holds on disk.
210    public static func isInTaggedText(_ text: String, at offset: Int, tag: String = "crypt", settings: OrgSettings = .default) -> Bool {
211        guard text.contains(tag) else { return false }
212        return taggedHeadings(text, tag: tag, settings: settings).contains { heading in
213            heading < offset && (bodyRange(text, at: heading)?.contains(offset) ?? false)
214        }
215    }
216
217    /// What an entry's text is known by, as `org-crypt-checksum` is.
218    public static func checksum(_ contents: String) -> String {
219        SHA256.hash(data: Data(contents.utf8)).map { String(format: "%02x", $0) }.joined()
220    }
221
222    /// The first entry's message in `text` encrypted with a passphrase; entries encrypted to a
223    /// public key are passed over.
224    public static func firstMessage(_ text: String) -> String? {
225        let ns = text as NSString
226        var search = NSRange(location: 0, length: ns.length)
227        while true {
228            let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", options: [], range: search)
229            guard begin.location != NSNotFound else { return nil }
230            let lineStart = ns.lineRange(for: NSRange(location: begin.location, length: 0)).location
231            if let range = encryptedRange(text, at: lineStart), range.lowerBound == lineStart {
232                let message = ns.substring(with: NSRange(range))
233                if let data = try? OpenPGP.dearmor(message), OpenPGP.isSymmetric(data) { return message }
234            }
235            search = NSRange(location: NSMaxRange(begin), length: ns.length - NSMaxRange(begin))
236        }
237    }
238
239    /// Whether `passphrase` opens `message`.
240    public static func opens(_ message: String, passphrase: String) -> Bool {
241        (try? OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)) != nil
242    }
243}
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