Sources/OrgCore/Crypto/OrgCrypt.swift
137 lines · 7638 bytes
1import Foundation
2
3/// 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/// subtree, replaced by an armored OpenPGP message under the heading.
6public enum OrgCrypt {
7 public struct Failure: Error, Equatable, CustomStringConvertible {
8 public let description: String
9 public init(_ description: String) { self.description = description }
10 }
11
12 /// `org-end-of-meta-data 'standard`: past planning, the property drawer, clock lines,
13 /// blank lines and logbook drawers.
14 static func metaDataEnd(_ buffer: EmacsBuffer) {
15 buffer.endOfMetaData()
16 guard !buffer.atHeading else { return }
17 let end = buffer.saveExcursion { () -> Int in buffer.outlineNextHeading(); return buffer.point }
18 while !buffer.eobp {
19 if buffer.lookingAt("[ \\t]*$|^[ \\t]*CLOCK:") != nil {
20 buffer.forwardLine(1)
21 } else if buffer.lookingAt("[ \\t]*:LOGBOOK:[ \\t]*$") != nil {
22 guard buffer.searchForward("^[ \\t]*:END:[ \\t]*$", bound: end, caseInsensitive: true) != nil else { return }
23 buffer.forwardLine(1)
24 } else {
25 return
26 }
27 }
28 }
29
30 /// The heading the entry at `offset` is under, or nil before the first.
31 public static func heading(_ text: String, at offset: Int) -> Int? {
32 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
33 return try? buffer.backToHeading()
34 }
35
36 /// `org-at-encrypted-entry-p`: the message's lines, from its begin line through the line
37 /// after its end line.
38 public static func encryptedRange(_ text: String, at offset: Int) -> Range<Int>? {
39 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
40 guard (try? buffer.backToHeading()) != nil else { return nil }
41 metaDataEnd(buffer)
42 guard buffer.lookingAt("[ \\t]*-----BEGIN PGP MESSAGE-----[ \\t]*$") != nil else { return nil }
43 let start = buffer.point
44 guard let match = buffer.searchForward("^(?:([ \\t]*-----END PGP MESSAGE-----)[ \\t]*$|\\*+ )", caseInsensitive: false),
45 match[1] != nil else { return nil }
46 let line = buffer.lineEnd(match[0]!.lowerBound)
47 return start..<min(line + 1, buffer.length)
48 }
49
50 /// What `org-encrypt-entry` encrypts: after the meta-data through the subtree's end, less
51 /// the blank lines before the next heading.
52 public static func bodyRange(_ text: String, at offset: Int) -> Range<Int>? {
53 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
54 guard let heading = try? buffer.backToHeading() else { return nil }
55 metaDataEnd(buffer)
56 let start = buffer.point
57 buffer.point = heading
58 buffer.endOfSubtree(toHeading: true)
59 buffer.backOverEmptyLines()
60 return start..<max(start, buffer.point)
61 }
62
63 /// `org-encrypt-entry`: the text with the entry at `offset` encrypted, or nil when it's
64 /// encrypted already.
65 public static func encrypt(_ text: String, at offset: Int, passphrase: String, now: Date = Date()) throws -> String? {
66 guard heading(text, at: offset) != nil else { throw Failure("Before first headline") }
67 guard encryptedRange(text, at: offset) == nil, let range = bodyRange(text, at: offset) else { return nil }
68 let ns = text as NSString
69 let contents = ns.substring(with: NSRange(range))
70 let message = try OpenPGP.encrypt(Data(contents.utf8), passphrase: passphrase, now: now)
71 return ns.replacingCharacters(in: NSRange(range), with: message)
72 }
73
74 /// The decrypted text of the entry at `offset` and where its message is.
75 public static func decrypt(_ text: String, at offset: Int, passphrase: String) throws -> (plaintext: String, range: Range<Int>) {
76 guard let range = encryptedRange(text, at: offset) else { throw Failure("Not an encrypted entry") }
77 let message = (text as NSString).substring(with: NSRange(range))
78 let data: Data
79 do {
80 data = try OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)
81 } catch let failure as OpenPGP.Failure {
82 throw Failure(failure == OpenPGP.wrongPassphrase ? "Wrong passphrase" : failure.description)
83 }
84 var plain = String(decoding: data, as: UTF8.self)
85 // epg encrypts in text mode, with CRLF line ends, and `decode-coding-string` with
86 // `utf-8` takes them back to LF.
87 if plain.contains("\r\n"), !plain.replacingOccurrences(of: "\r\n", with: "").contains("\n") {
88 plain = plain.replacingOccurrences(of: "\r\n", with: "\n")
89 }
90 return (plain, range)
91 }
92
93 /// `org-decrypt-entry`: the text with the entry's message replaced by what it holds, its
94 /// headings moved below the entry's level when they aren't.
95 public static func decryptInPlace(_ text: String, at offset: Int, passphrase: String) throws -> String {
96 var (plain, range) = try decrypt(text, at: offset, passphrase: passphrase)
97 let ns = text as NSString
98 let headingStart = heading(text, at: offset)!
99 let level = ns.substring(from: headingStart).prefix { $0 == "*" }.count
100 let pattern = "(?m)^\\*{1,\(level)} "
101 if plain.range(of: pattern, options: .regularExpression) != nil {
102 let minLevel = plain.matches(of: try! Regex(pattern)).map { plain[$0.range].count - 1 }.min() ?? level
103 let prefix = String(repeating: "*", count: 1 + level - minLevel)
104 plain = plain.replacing(#/(?m)^\*+ /#) { prefix + $0.output }
105 }
106 return ns.replacingCharacters(in: NSRange((range.lowerBound - 1)..<range.upperBound), with: "\n" + plain)
107 }
108
109 /// The entry's message replaced by `plaintext` encrypted again.
110 public static func replacing(_ text: String, at offset: Int, with plaintext: String, passphrase: String, now: Date = Date()) throws -> String {
111 guard let range = encryptedRange(text, at: offset) else { throw Failure("Not an encrypted entry") }
112 let message = try OpenPGP.encrypt(Data(plaintext.utf8), passphrase: passphrase, now: now)
113 return (text as NSString).replacingCharacters(in: NSRange(range), with: message)
114 }
115
116 /// The headings with `tag` (`org-crypt-tag-matcher`), inherited or their own, in order.
117 public static func taggedHeadings(_ text: String, tag: String = "crypt", settings: OrgSettings = .default) -> [Int] {
118 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings))
119 return model.headings.indices.filter { model.tags(of: $0).contains { $0.value == tag } }.map { model.headings[$0].headingRange.lowerBound }
120 }
121
122 /// `org-encrypt-entries`: every tagged entry not encrypted yet, from the top, so that an
123 /// entry's tagged children go inside its message. The text and how many were encrypted.
124 public static func encryptAll(_ text: String, passphrase: String, tag: String = "crypt", settings: OrgSettings = .default, now: Date = Date()) throws -> (String, Int) {
125 var text = text
126 var count = 0
127 var from = 0
128 while let next = taggedHeadings(text, tag: tag, settings: settings).first(where: { $0 >= from }) {
129 if let encrypted = try encrypt(text, at: next, passphrase: passphrase, now: now) {
130 text = encrypted
131 count += 1
132 }
133 from = next + 1
134 }
135 return (text, count)
136 }
137}