Commit ea98aa3032

ea98aa303287e7bc94425330f51d3c2dfd1ef77e

parent: 7afd4a4aa1

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 14:00 UTC

org-crypt

Symmetric OpenPGP encryption of entries: encrypt, decrypt to a sheet or in the file, encrypt tagged entries, Keychain passphrases, org-crypt-tag-matcher. Mac and iOS.

Closes #41

Layout: unified · split

Sources/OrgApp/CryptPassphrases.swift added +44
@@ -0,0 +1,44 @@
1import Foundation
2import LocalAuthentication
3import Security
4
5/// Passphrases for encrypted entries, kept in the Keychain by file when asked, and given back
6/// only after Touch ID, Face ID or the device's password.
7public enum CryptPassphrases {
8 static let service = "sh.krz.orgstar.crypt"
9
10 static func query(_ path: String) -> [String: Any] {
11 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
12 }
13
14 public static func store(_ passphrase: String, for path: String) {
15 forget(path)
16 var item = query(path)
17 item[kSecValueData as String] = Data(passphrase.utf8)
18 item[kSecAttrLabel as String] = "orgstar: encrypted entries in " + (path as NSString).lastPathComponent
19 SecItemAdd(item as CFDictionary, nil)
20 }
21
22 public static func forget(_ path: String) {
23 SecItemDelete(query(path) as CFDictionary)
24 }
25
26 public static func hasStored(_ path: String) -> Bool {
27 var q = query(path)
28 q[kSecReturnAttributes as String] = true
29 return SecItemCopyMatching(q as CFDictionary, nil) == errSecSuccess
30 }
31
32 /// The stored passphrase, once the person has proved who they are; nil otherwise.
33 public static func stored(for path: String) async -> String? {
34 guard hasStored(path) else { return nil }
35 let context = LAContext()
36 let reason = "unlock the passphrase for encrypted entries in " + (path as NSString).lastPathComponent
37 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
38 var q = query(path)
39 q[kSecReturnData as String] = true
40 var result: AnyObject?
41 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
42 return String(decoding: data, as: UTF8.self)
43 }
44}
Sources/OrgApp/CryptSheet.swift added +175
@@ -0,0 +1,175 @@
1import Foundation
2import OrgCore
3import SwiftUI
4
5/// What an org-crypt command does with the entry at `offset` in the file at `path`.
6public struct CryptRequest: Identifiable, Sendable {
7 public enum Mode: Sendable {
8 /// `org-encrypt-entry`.
9 case encrypt
10 /// `org-encrypt-entries`, with `org-crypt-tag-matcher`'s tag.
11 case encryptAll(tag: String)
12 /// The decrypted text, to read and change; the file keeps it encrypted.
13 case open
14 /// `org-decrypt-entry`: the decrypted text in the file.
15 case decryptInPlace
16 }
17
18 public let id = UUID()
19 public let mode: Mode
20 public let path: String
21 public let offset: Int
22
23 public init(mode: Mode, path: String, offset: Int) {
24 self.mode = mode
25 self.path = path
26 self.offset = offset
27 }
28
29 var encrypting: Bool {
30 switch mode {
31 case .encrypt, .encryptAll: true
32 default: false
33 }
34 }
35}
36
37/// 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
39/// in its place; `done` closes the sheet with a message.
40public struct CryptSheet: View {
41 let request: CryptRequest
42 let text: () -> String
43 let apply: (String) -> Void
44 let done: (String?) -> Void
45 @State private var passphrase = ""
46 @State private var repeated = ""
47 @State private var remember = false
48 @State private var problem: String?
49 /// The decrypted entry being edited, and the passphrase it came with.
50 @State private var editing: (original: String, passphrase: String)?
51 @State private var plaintext = ""
52
53 public init(request: CryptRequest, text: @escaping () -> String, apply: @escaping (String) -> Void, done: @escaping (String?) -> Void) {
54 self.request = request
55 self.text = text
56 self.apply = apply
57 self.done = done
58 }
59
60 public var body: some View {
61 VStack(alignment: .leading, spacing: 12) {
62 if editing != nil {
63 Text("Encrypted Entry").font(.headline)
64 TextEditor(text: $plaintext)
65 .font(.body.monospaced())
66 .frame(minHeight: 220)
67 if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
68 HStack {
69 Button("Decrypt in File") { decryptEdited() }
70 Spacer()
71 Button("Cancel", role: .cancel) { done(nil) }.keyboardShortcut(.cancelAction)
72 Button("Save") { save() }.keyboardShortcut(.defaultAction)
73 }
74 } else {
75 Text(title).font(.headline)
76 SecureField("Passphrase", text: $passphrase).onSubmit(submit)
77 if request.encrypting { SecureField("Repeat passphrase", text: $repeated).onSubmit(submit) }
78 Toggle("Remember in the Keychain", isOn: $remember)
79 if let problem { Text(problem).foregroundStyle(.red).font(.callout) }
80 HStack {
81 Spacer()
82 Button("Cancel", role: .cancel) { done(nil) }.keyboardShortcut(.cancelAction)
83 Button(request.encrypting ? "Encrypt" : "Decrypt") { submit() }
84 .keyboardShortcut(.defaultAction)
85 .disabled(passphrase.isEmpty)
86 }
87 }
88 }
89 .padding(20)
90 #if os(macOS)
91 .frame(minWidth: 460)
92 #else
93 .frame(maxHeight: .infinity, alignment: .top)
94 #endif
95 .task {
96 if let stored = await CryptPassphrases.stored(for: request.path) { run(stored, remembered: true) }
97 }
98 }
99
100 private var title: String {
101 switch request.mode {
102 case .encrypt: "Encrypt Entry"
103 case .encryptAll: "Encrypt Tagged Entries"
104 case .open, .decryptInPlace: "Decrypt Entry"
105 }
106 }
107
108 private func submit() {
109 guard !passphrase.isEmpty else { return }
110 if request.encrypting, passphrase != repeated { return problem = "The passphrases differ" }
111 run(passphrase, remembered: false)
112 }
113
114 private func run(_ passphrase: String, remembered: Bool) {
115 let current = text()
116 do {
117 switch request.mode {
118 case .encrypt:
119 guard let encrypted = try OrgCrypt.encrypt(current, at: request.offset, passphrase: passphrase) else {
120 return finish("The entry is encrypted already", passphrase: passphrase, remembered: remembered)
121 }
122 apply(encrypted)
123 finish("Entry encrypted", passphrase: passphrase, remembered: remembered)
124 case .encryptAll(let tag):
125 let (encrypted, count) = try OrgCrypt.encryptAll(current, passphrase: passphrase, tag: tag)
126 if count > 0 { apply(encrypted) }
127 finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered)
128 case .open:
129 let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext
130 if remember, !remembered { CryptPassphrases.store(passphrase, for: request.path) }
131 plaintext = plain
132 editing = (plain, passphrase)
133 problem = nil
134 case .decryptInPlace:
135 apply(try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase))
136 finish("Entry decrypted", passphrase: passphrase, remembered: remembered)
137 }
138 } catch {
139 problem = "\(error)"
140 }
141 }
142
143 private func finish(_ message: String, passphrase: String, remembered: Bool) {
144 if remember, !remembered { CryptPassphrases.store(passphrase, for: request.path) }
145 done(message)
146 }
147
148 /// The edited text encrypted again in the message's place; nothing changes if it wasn't edited.
149 private func save() {
150 guard let editing else { return }
151 guard plaintext != editing.original else { return done(nil) }
152 var plain = plaintext
153 if !plain.isEmpty, !plain.hasSuffix("\n") { plain += "\n" }
154 do {
155 apply(try OrgCrypt.replacing(text(), at: request.offset, with: plain, passphrase: editing.passphrase))
156 done("Entry encrypted again")
157 } catch {
158 problem = "\(error)"
159 }
160 }
161
162 /// `org-decrypt-entry` with the text as edited.
163 private func decryptEdited() {
164 guard let editing else { return }
165 var plain = plaintext
166 if !plain.isEmpty, !plain.hasSuffix("\n") { plain += "\n" }
167 do {
168 let replaced = try OrgCrypt.replacing(text(), at: request.offset, with: plain, passphrase: editing.passphrase)
169 apply(try OrgCrypt.decryptInPlace(replaced, at: request.offset, passphrase: editing.passphrase))
170 done("Entry decrypted")
171 } catch {
172 problem = "\(error)"
173 }
174 }
175}
Sources/OrgApp/EmacsImport.swift +3
@@ -543,6 +543,9 @@ public struct EmacsImport: Sendable {
543543 else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count {
544544 add(name, .string(keywords.joined(separator: " ")))
545545 } else { note("unexpected value \(value.description)") }
546 case "org-crypt-tag-matcher":
547 guard let tag = value.string, tag.range(of: "^[\\w@#%]+$", options: .regularExpression) != nil else { return note("not a single tag") }
548 add(name, .string(tag))
546549 case "org-display-remote-inline-images":
547550 guard let mode = value.symbol, ["skip", "download", "cache"].contains(mode) else { return note("not skip, download or cache") }
548551 add(name, .string(mode))
Sources/OrgApp/OrgPreferences.swift +5
@@ -145,6 +145,11 @@ public enum OrgPreferences {
145145 options.userFullName = NSFullUserName()
146146 return options
147147 }
148 /// `org-crypt-tag-matcher`, a tag.
149 public static func cryptTag(_ defaults: UserDefaults = .standard) -> String {
150 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces)
151 return tag.isEmpty ? "crypt" : tag
152 }
148153 /// `org-icalendar-combined-agenda-file`, `~` expanded.
149154 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String {
150155 (string("icalendarCombinedAgendaFile", defaults) as NSString).expandingTildeInPath
Sources/OrgApp/UserConfig.swift +2
@@ -147,6 +147,8 @@ public enum UserConfig {
147147 comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""),
148148 Setting(section: "", key: "org-startup-with-latex-preview", defaultsKey: "startupWithLatexPreview", kind: .bool, fallback: .bool(false),
149149 comment: "show LaTeX fragments as typeset math when a file opens; #+STARTUP: (no)latexpreview overrides", legacy: ""),
150 Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"),
151 comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""),
150152 Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages",
151153 kind: .choice([("skip", "skip"), ("download", "download"), ("cache", "cache")]), fallback: .string("skip"),
152154 comment: "images at http(s) links: skip, download (each run) or cache (kept on disk)", legacy: ""),
Sources/OrgCore/Crypto/OpenPGP.swift added +345
@@ -0,0 +1,345 @@
1import CommonCrypto
2import CryptoKit
3import Foundation
4
5/// Passphrase-encrypted OpenPGP messages (RFC 4880), as `gpg --symmetric --armor` writes and
6/// reads them: a symmetric-key session packet with a string-to-key specifier, an integrity
7/// protected data packet (MDC), and inside it literal data, compressed or not. AES ciphers
8/// only; no public keys, no AEAD packets.
9public enum OpenPGP {
10 public struct Failure: Error, Equatable, CustomStringConvertible {
11 public let description: String
12 init(_ description: String) { self.description = description }
13 }
14
15 // MARK: - Armor
16
17 /// `-----BEGIN PGP MESSAGE-----`, base64 in lines of 64, the CRC-24 checksum, the end
18 /// line, and a final newline.
19 public static func armor(_ data: Data) -> String {
20 let base64 = data.base64EncodedString()
21 var lines: [String] = []
22 var index = base64.startIndex
23 while index < base64.endIndex {
24 let end = base64.index(index, offsetBy: 64, limitedBy: base64.endIndex) ?? base64.endIndex
25 lines.append(String(base64[index..<end]))
26 index = end
27 }
28 var crc = crc24(data).bigEndian
29 let checksum = withUnsafeBytes(of: &crc) { Data($0.dropFirst()) }.base64EncodedString()
30 return "-----BEGIN PGP MESSAGE-----\n\n" + lines.joined(separator: "\n") + "\n=" + checksum + "\n-----END PGP MESSAGE-----\n"
31 }
32
33 /// The bytes of an armored message, its checksum checked when it has one.
34 public static func dearmor(_ text: String) throws -> Data {
35 var lines = text.components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }
36 guard let begin = lines.firstIndex(where: { $0.hasPrefix("-----BEGIN PGP MESSAGE") }) else { throw Failure("Not a PGP message") }
37 lines = Array(lines[(begin + 1)...])
38 // Header lines such as `Version:`, up to a blank line.
39 if let blank = lines.firstIndex(of: ""), lines[..<blank].allSatisfy({ $0.contains(":") }) { lines = Array(lines[(blank + 1)...]) }
40 var body = ""
41 var checksum: String?
42 for line in lines {
43 if line.hasPrefix("-----END") { break }
44 if line.hasPrefix("=") { checksum = String(line.dropFirst()); continue }
45 body += line
46 }
47 guard let data = Data(base64Encoded: body) else { throw Failure("The PGP message is damaged") }
48 if let checksum, let sum = Data(base64Encoded: checksum), sum.count == 3 {
49 let crc = crc24(data)
50 guard [UInt8((crc >> 16) & 0xff), UInt8((crc >> 8) & 0xff), UInt8(crc & 0xff)] == Array(sum) else { throw Failure("The PGP message's checksum is wrong") }
51 }
52 return data
53 }
54
55 static func crc24(_ data: Data) -> UInt32 {
56 var crc: UInt32 = 0xB704CE
57 for byte in data {
58 crc ^= UInt32(byte) << 16
59 for _ in 0..<8 {
60 crc <<= 1
61 if crc & 0x1000000 != 0 { crc ^= 0x1864CFB }
62 }
63 }
64 return crc & 0xFFFFFF
65 }
66
67 // MARK: - Packets
68
69 struct Packet {
70 let tag: Int
71 let body: Data
72 }
73
74 /// The packets in `data`, partial lengths joined.
75 static func packets(_ data: Data) throws -> [Packet] {
76 let bytes = [UInt8](data)
77 var i = 0
78 var out: [Packet] = []
79 func need(_ n: Int) throws { guard i + n <= bytes.count else { throw Failure("The PGP message is cut short") } }
80 while i < bytes.count {
81 let ctb = bytes[i]
82 guard ctb & 0x80 != 0 else { throw Failure("The PGP message is damaged") }
83 i += 1
84 var body = Data()
85 let tag: Int
86 if ctb & 0x40 != 0 {
87 tag = Int(ctb & 0x3f)
88 while true {
89 try need(1)
90 let first = Int(bytes[i])
91 i += 1
92 var length: Int
93 var partial = false
94 switch first {
95 case 0..<192: length = first
96 case 192..<224:
97 try need(1)
98 length = ((first - 192) << 8) + Int(bytes[i]) + 192
99 i += 1
100 case 255:
101 try need(4)
102 length = bytes[i..<(i + 4)].reduce(0) { $0 << 8 | Int($1) }
103 i += 4
104 default:
105 length = 1 << (first & 0x1f)
106 partial = true
107 }
108 try need(length)
109 body.append(contentsOf: bytes[i..<(i + length)])
110 i += length
111 if !partial { break }
112 }
113 } else {
114 tag = Int((ctb >> 2) & 0x0f)
115 let length: Int
116 switch ctb & 3 {
117 case 0:
118 try need(1)
119 length = Int(bytes[i]); i += 1
120 case 1:
121 try need(2)
122 length = Int(bytes[i]) << 8 | Int(bytes[i + 1]); i += 2
123 case 2:
124 try need(4)
125 length = bytes[i..<(i + 4)].reduce(0) { $0 << 8 | Int($1) }; i += 4
126 default:
127 length = bytes.count - i
128 }
129 try need(length)
130 body.append(contentsOf: bytes[i..<(i + length)])
131 i += length
132 }
133 out.append(Packet(tag: tag, body: body))
134 }
135 return out
136 }
137
138 /// A new-format packet with a definite length.
139 static func packet(_ tag: Int, _ body: Data) -> Data {
140 var out = Data([0xC0 | UInt8(tag)])
141 switch body.count {
142 case 0..<192: out.append(UInt8(body.count))
143 case 192..<8384:
144 let n = body.count - 192
145 out.append(contentsOf: [UInt8(n >> 8 + 192), UInt8(n & 0xff)])
146 default:
147 out.append(255)
148 out.append(contentsOf: (0..<4).reversed().map { UInt8((body.count >> ($0 * 8)) & 0xff) })
149 }
150 return out + body
151 }
152
153 // MARK: - Keys from passphrases
154
155 /// AES's key sizes by OpenPGP's cipher numbers.
156 static let keySizes = [7: 16, 8: 24, 9: 32]
157
158 static func hash(_ algorithm: Int, _ data: Data) throws -> Data {
159 switch algorithm {
160 case 1: return Data(Insecure.MD5.hash(data: data))
161 case 2: return Data(Insecure.SHA1.hash(data: data))
162 case 8: return Data(SHA256.hash(data: data))
163 case 9: return Data(SHA384.hash(data: data))
164 case 10: return Data(SHA512.hash(data: data))
165 case 11:
166 var digest = [UInt8](repeating: 0, count: Int(CC_SHA224_DIGEST_LENGTH))
167 data.withUnsafeBytes { _ = CC_SHA224($0.baseAddress, CC_LONG(data.count), &digest) }
168 return Data(digest)
169 default: throw Failure("Hash algorithm \(algorithm) isn't supported")
170 }
171 }
172
173 /// The string-to-key specifier: its type, hash, salt and count, and how long it is.
174 struct S2K {
175 let type: Int
176 let hash: Int
177 let salt: Data
178 let count: Int
179
180 static func parse(_ bytes: [UInt8], at i: Int) throws -> (S2K, Int) {
181 guard i + 2 <= bytes.count else { throw Failure("The PGP message is damaged") }
182 let type = Int(bytes[i]), hash = Int(bytes[i + 1])
183 switch type {
184 case 0: return (S2K(type: 0, hash: hash, salt: Data(), count: 0), 2)
185 case 1:
186 guard i + 10 <= bytes.count else { throw Failure("The PGP message is damaged") }
187 return (S2K(type: 1, hash: hash, salt: Data(bytes[(i + 2)..<(i + 10)]), count: 0), 10)
188 case 3:
189 guard i + 11 <= bytes.count else { throw Failure("The PGP message is damaged") }
190 let c = Int(bytes[i + 10])
191 return (S2K(type: 3, hash: hash, salt: Data(bytes[(i + 2)..<(i + 10)]), count: (16 + (c & 15)) << ((c >> 4) + 6)), 11)
192 default: throw Failure("String-to-key type \(type) isn't supported")
193 }
194 }
195
196 /// RFC 4880 3.7.1: as many hashes as the key needs, each preloaded with one more zero.
197 func key(_ passphrase: String, size: Int) throws -> Data {
198 let material = salt + Data(passphrase.utf8)
199 var key = Data()
200 var round = 0
201 while key.count < size {
202 var input = Data(repeating: 0, count: round)
203 if type == 3 {
204 let total = max(count, material.count)
205 var stream = Data(capacity: total)
206 while stream.count < total { stream.append(material.prefix(total - stream.count)) }
207 input.append(stream)
208 } else {
209 input.append(material)
210 }
211 key.append(try OpenPGP.hash(hash, input))
212 round += 1
213 }
214 return key.prefix(size)
215 }
216 }
217
218 // MARK: - AES in CFB
219
220 static func cfb(_ data: Data, key: Data, iv: Data = Data(repeating: 0, count: 16), encrypt: Bool) throws -> Data {
221 var cryptor: CCCryptorRef?
222 let status = key.withUnsafeBytes { k in
223 iv.withUnsafeBytes { v in
224 CCCryptorCreateWithMode(CCOperation(encrypt ? kCCEncrypt : kCCDecrypt), CCMode(kCCModeCFB), CCAlgorithm(kCCAlgorithmAES),
225 CCPadding(ccNoPadding), v.baseAddress, k.baseAddress, key.count, nil, 0, 0, CCModeOptions(0), &cryptor)
226 }
227 }
228 guard status == kCCSuccess, let cryptor else { throw Failure("The cipher couldn't start") }
229 defer { CCCryptorRelease(cryptor) }
230 var out = [UInt8](repeating: 0, count: data.count)
231 var moved = 0
232 let result = data.withUnsafeBytes { d in CCCryptorUpdate(cryptor, d.baseAddress, data.count, &out, out.count, &moved) }
233 guard result == kCCSuccess else { throw Failure("The cipher failed") }
234 return Data(out.prefix(moved))
235 }
236
237 static func random(_ count: Int) -> Data {
238 var bytes = [UInt8](repeating: 0, count: count)
239 _ = SecRandomCopyBytes(kSecRandomDefault, count, &bytes)
240 return Data(bytes)
241 }
242
243 // MARK: - Messages
244
245 public static let wrongPassphrase = Failure("Bad session key")
246
247 /// The literal data of a passphrase-encrypted message.
248 public static func decrypt(_ message: Data, passphrase: String) throws -> Data {
249 var sessionKey: (cipher: Int, key: Data)?
250 for packet in try packets(message) {
251 switch packet.tag {
252 case 3:
253 let b = [UInt8](packet.body)
254 guard b.count >= 2, b[0] == 4 else { throw Failure("Only version 4 passphrase packets are supported") }
255 let cipher = Int(b[1])
256 guard let size = keySizes[cipher] else { throw Failure("Cipher \(cipher) isn't supported; orgstar reads AES") }
257 let (s2k, length) = try S2K.parse(b, at: 2)
258 let key = try s2k.key(passphrase, size: size)
259 if b.count > 2 + length {
260 // An encrypted session key.
261 let esk = try cfb(Data(b[(2 + length)...]), key: key, encrypt: false)
262 guard let algorithm = esk.first, let eskSize = keySizes[Int(algorithm)], esk.count == eskSize + 1 else { throw wrongPassphrase }
263 sessionKey = (Int(algorithm), esk.dropFirst())
264 } else {
265 sessionKey = (cipher, key)
266 }
267 case 18:
268 guard let sessionKey else { throw Failure("The PGP message has no passphrase packet") }
269 guard packet.body.first == 1 else { throw Failure("Only version 1 integrity protected packets are supported") }
270 let plain = try cfb(packet.body.dropFirst(), key: sessionKey.key, encrypt: false)
271 let block = 16
272 guard plain.count >= block + 2 + 22 else { throw Failure("The PGP message is cut short") }
273 let p = [UInt8](plain)
274 guard p[block - 2] == p[block], p[block - 1] == p[block + 1] else { throw wrongPassphrase }
275 let mdc = plain.suffix(20)
276 guard p[p.count - 22] == 0xD3, p[p.count - 21] == 0x14,
277 Data(Insecure.SHA1.hash(data: plain.prefix(plain.count - 20))) == mdc else {
278 throw Failure("The PGP message was modified")
279 }
280 return try literal(Data(p[(block + 2)..<(p.count - 22)]))
281 case 9:
282 throw Failure("The message has no integrity protection, which orgstar doesn't read")
283 case 20:
284 throw Failure("AEAD encrypted messages aren't supported")
285 case 10:
286 continue
287 default:
288 throw Failure("PGP packet \(packet.tag) isn't supported")
289 }
290 }
291 throw Failure("The PGP message has no encrypted data")
292 }
293
294 /// The data of the literal packet in `data`, decompressing on the way.
295 static func literal(_ data: Data) throws -> Data {
296 for packet in try packets(data) {
297 switch packet.tag {
298 case 11:
299 let b = [UInt8](packet.body)
300 guard b.count >= 6 else { throw Failure("The PGP message is damaged") }
301 let nameLength = Int(b[1])
302 guard b.count >= 2 + nameLength + 4 else { throw Failure("The PGP message is damaged") }
303 return Data(b[(2 + nameLength + 4)...])
304 case 8:
305 guard let algorithm = packet.body.first else { throw Failure("The PGP message is damaged") }
306 let compressed = packet.body.dropFirst()
307 switch algorithm {
308 case 0: return try literal(Data(compressed))
309 case 1: return try literal(try inflate(Data(compressed)))
310 case 2: return try literal(try inflate(Data(compressed.dropFirst(2))))
311 default: throw Failure("BZip2 compressed messages aren't supported")
312 }
313 default:
314 continue
315 }
316 }
317 throw Failure("The PGP message has no literal data")
318 }
319
320 /// Raw deflate, as ZIP and ZLIB packets hold it.
321 static func inflate(_ data: Data) throws -> Data {
322 do {
323 return try (data as NSData).decompressed(using: .zlib) as Data
324 } catch {
325 throw Failure("The PGP message's compressed data is damaged")
326 }
327 }
328
329 /// `gpg --symmetric --armor`: AES-256, an iterated and salted SHA-256 key, integrity
330 /// protection, binary literal data without a name.
331 public static func encrypt(_ data: Data, passphrase: String, now: Date = Date()) throws -> String {
332 let salt = random(8)
333 let s2k = S2K(type: 3, hash: 8, salt: salt, count: (16 + (96 & 15)) << ((96 >> 4) + 6))
334 let key = try s2k.key(passphrase, size: 32)
335 let skesk = packet(3, Data([4, 9, 3, 8]) + salt + Data([96]))
336 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)
338 var prefix = random(16)
339 prefix.append(prefix.suffix(2))
340 var plain = prefix + literal + Data([0xD3, 0x14])
341 plain.append(Data(Insecure.SHA1.hash(data: plain)))
342 let seipd = packet(18, Data([1]) + (try cfb(plain, key: key, encrypt: true)))
343 return armor(skesk + seipd)
344 }
345}
Sources/OrgCore/Crypto/OrgCrypt.swift added +137
@@ -0,0 +1,137 @@
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}
Sources/OrgEditorAppKit/EditorCommands.swift +5
@@ -108,6 +108,11 @@ public enum EditorCommands {
108108 EditorCommand(id: "app.table-import", title: "Import Table from File…", action: .app),
109109 EditorCommand(id: "app.table-export", title: "Export Table to File…", action: .app),
110110 EditorCommand(id: "app.plot", title: "Plot Table", action: .app),
111 EditorCommand(id: "app.crypt.encrypt-entry", title: "Encrypt Entry…", action: .app),
112 EditorCommand(id: "app.crypt.open-entry", title: "Decrypt Entry…", action: .app),
113 EditorCommand(id: "app.crypt.decrypt-entry", title: "Decrypt Entry in File…", action: .app),
114 EditorCommand(id: "app.crypt.encrypt-entries", title: "Encrypt Tagged Entries…", action: .app),
115 EditorCommand(id: "app.crypt.forget-passphrase", title: "Forget Encryption Passphrase", action: .app),
111116 EditorCommand(id: "app.export-dialog", title: "Export…", action: .app),
112117 EditorCommand(id: "app.sync-conflicts", title: "Resolve Sync Conflicts…", action: .app),
113118 EditorCommand(id: "app.revert", title: "Revert to File on Disk", action: .app),
Sources/Orgstar/ContentView.swift +64 −22
@@ -327,28 +327,7 @@ struct ContentView: View {
327327 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
328328 .onChange(of: preset, initial: true) { loadKeymap() }
329329 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
330 .sheet(item: $panel) { panel in
331 switch panel {
332 case .columns(_, let view):
333 ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
334 commands.editor?.reveal(offset)
335 }
336 case .export(_, let source):
337 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
338 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
339 }
340 case .plot(_, let plot):
341 PlotSheet(content: .chart(plot))
342 case .plotImage(_, let url):
343 PlotSheet(content: .image(url))
344 case .conflict:
345 ConflictSheet(session: session)
346 case .syncCopies:
347 SyncConflictSheet(session: session) { commands.show($0) }
348 case .recovery:
349 RecoverySheet(session: session) { commands.show($0) }
350 }
351 }
330 .sheet(item: $panel) { panel in panelView(panel) }
352331 .sheet(item: $blockEdit) { request in
353332 BlockEditorView(edit: request.edit) { content in
354333 blockEdit = nil
@@ -668,6 +647,67 @@ struct ContentView: View {
668647 }
669648 }
670649
650 /// org-crypt's commands at the caret, through the passphrase sheet.
651 private func crypt(_ id: String) {
652 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
653 let caret = editor.context().caret
654 let text = editor.context().text
655 switch id {
656 case "app.crypt.forget-passphrase":
657 CryptPassphrases.forget(path)
658 commands.show("Passphrase forgotten for \((path as NSString).lastPathComponent)")
659 case "app.crypt.encrypt-entries":
660 panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
661 default:
662 guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show("Before first headline") }
663 if id == "app.crypt.encrypt-entry" {
664 guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show("The entry is encrypted already") }
665 panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
666 } else {
667 guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show("Not an encrypted entry") }
668 panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
669 }
670 }
671 }
672
673 /// The sheet a panel shows.
674 @ViewBuilder
675 private func panelView(_ panel: Panel) -> some View {
676 switch panel {
677 case .columns(_, let view):
678 ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
679 commands.editor?.reveal(offset)
680 }
681 case .export(_, let source):
682 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
683 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
684 }
685 case .plot(_, let plot):
686 PlotSheet(content: .chart(plot))
687 case .plotImage(_, let url):
688 PlotSheet(content: .image(url))
689 case .crypt(_, let request):
690 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: applyText) { message in
691 self.panel = nil
692 if let message { commands.show(message) }
693 }
694 case .conflict:
695 ConflictSheet(session: session)
696 case .syncCopies:
697 SyncConflictSheet(session: session) { commands.show($0) }
698 case .recovery:
699 RecoverySheet(session: session) { commands.show($0) }
700 }
701 }
702
703 /// `new` in place of the buffer's text, as one edit.
704 private func applyText(_ new: String) {
705 guard let editor = commands.editor else { return }
706 let context = editor.context()
707 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new),
708 selection: [min(context.caret, (new as NSString).length)..<min(context.caret, (new as NSString).length)])))
709 }
710
671711 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
672712 /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
673713 private func plotTable() {
@@ -1046,6 +1086,8 @@ struct ContentView: View {
10461086 publish(id)
10471087 case "app.plot":
10481088 plotTable()
1089 case let id where id.hasPrefix("app.crypt."):
1090 crypt(id)
10491091 default:
10501092 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
10511093 }
Sources/Orgstar/Panels.swift +3 −1
@@ -1,4 +1,5 @@
11import Foundation
2import OrgApp
23import OrgCore
34
45enum Panel: Identifiable {
@@ -10,10 +11,11 @@ enum Panel: Identifiable {
1011 /// A `#+PLOT` table drawn here, or gnuplot's image of it.
1112 case plot(UUID, TablePlot.Plot)
1213 case plotImage(UUID, URL)
14 case crypt(UUID, CryptRequest)
1315
1416 var id: UUID {
1517 switch self {
16 case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id), .plot(let id, _), .plotImage(let id, _): id
18 case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id), .plot(let id, _), .plotImage(let id, _), .crypt(let id, _): id
1719 }
1820 }
1921}
Sources/OrgstarMobile/EditorScreen.swift +63
@@ -52,6 +52,7 @@ struct EditorScreen: View {
5252 case block(BlockEdit)
5353 case columns(ColumnView.View)
5454 case plot(TablePlot.Plot)
55 case crypt(CryptRequest)
5556
5657 var id: String {
5758 switch self {
@@ -63,6 +64,7 @@ struct EditorScreen: View {
6364 case .block(let edit): "block \(edit.range)"
6465 case .columns: "columns"
6566 case .plot: "plot"
67 case .crypt(let request): request.id.uuidString
6668 }
6769 }
6870 }
@@ -100,6 +102,13 @@ struct EditorScreen: View {
100102 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
101103 }
102104 RecentClockMenu(clock: clock) { editor?.run($0) }
105 Menu("Encryption", systemImage: "lock") {
106 Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
107 Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
108 Button("Decrypt Entry in File…", systemImage: "lock.open.trianglebadge.exclamationmark") { crypt("app.crypt.decrypt-entry") }
109 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
110 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
111 }
103112 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
104113 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
105114 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
@@ -162,6 +171,8 @@ struct EditorScreen: View {
162171 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
163172 case .plot(let plot):
164173 PlotScreen(plot: plot)
174 case .crypt(let request):
175 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
165176 }
166177 }
167178 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
@@ -267,6 +278,8 @@ struct EditorScreen: View {
267278 exportTable(csv: true)
268279 } else if id == "app.plot" {
269280 plotTable()
281 } else if id.hasPrefix("app.crypt.") {
282 crypt(id)
270283 } else if id == "app.toggle-markup" {
271284 model.showMarkup.toggle()
272285 } else if MobileEditor.linkCommands.contains(id) {
@@ -297,6 +310,29 @@ extension EditorScreen {
297310 _ = editor.perform(ImportTable(contents: contents))
298311 }
299312
313 /// org-crypt's commands at the caret, through the passphrase sheet.
314 private func crypt(_ id: String) {
315 guard let editor else { return }
316 let context = editor.editContext()
317 switch id {
318 case "app.crypt.forget-passphrase":
319 CryptPassphrases.forget(path)
320 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
321 case "app.crypt.encrypt-entries":
322 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
323 default:
324 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
325 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
326 if id == "app.crypt.encrypt-entry" {
327 guard !encrypted else { return message = "The entry is encrypted already" }
328 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
329 } else {
330 guard encrypted else { return message = "Not an encrypted entry" }
331 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
332 }
333 }
334 }
335
300336 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
301337 /// one, else shown.
302338 private func plotTable() {
@@ -619,6 +655,8 @@ struct CommandPalette: View {
619655 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
620656 ("org.table.expand", "Expand Table Columns"),
621657 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
658 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
659 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
622660 ]
623661
624662 /// The commands that apply at the caret and their keys, worked out once when the palette
@@ -690,4 +728,29 @@ struct PlotScreen: View {
690728 }
691729 }
692730}
731/// The passphrase sheet for org-crypt, its new text applied in the editor.
732struct CryptScreen: View {
733 let request: CryptRequest
734 let session: DocumentSession
735 let editor: MobileEditor?
736 let report: (String) -> Void
737 @Environment(\.dismiss) private var dismiss
738
739 var body: some View {
740 NavigationStack {
741 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
742 dismiss()
743 if let message { report(message) }
744 }
745 .navigationBarTitleDisplayMode(.inline)
746 }
747 }
748
749 private func apply(_ new: String) {
750 guard let editor else { return }
751 let context = editor.editContext()
752 let caret = min(context.caret, (new as NSString).length)
753 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
754 }
755}
693756#endif
Sources/OrgstarMobile/MobileEditor.swift +3 −1
@@ -301,7 +301,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
301301 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.latex-preview", "editor.toggle-truncate-lines": return true
302302 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
303303 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
304 case "app.refile.goto", "app.table-import": return onAppCommand != nil
304 case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase": return onAppCommand != nil
305 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
306 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
305307 case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
306308 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
307309 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
Tests/OrgCoreTests/OpenPGPTests.swift added +80
@@ -0,0 +1,80 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct OpenPGPTests {
6 static var gpg: String? {
7 ["/opt/homebrew/bin/gpg", "/usr/local/bin/gpg", "/usr/bin/gpg"].first { FileManager.default.isExecutableFile(atPath: $0) }
8 }
9
10 /// gpg with its own short home (the agent's socket path has a length limit), the
11 /// passphrase given in loopback.
12 static func gpg(_ arguments: [String], input: Data) throws -> Data {
13 let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
14 try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
15 defer {
16 let kill = Process()
17 kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
18 kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
19 try? kill.run()
20 kill.waitUntilExit()
21 try? FileManager.default.removeItem(atPath: home)
22 }
23 let process = Process()
24 process.executableURL = URL(fileURLWithPath: gpg!)
25 process.arguments = ["--homedir", home, "--batch", "--yes", "--pinentry-mode", "loopback", "--quiet"] + arguments
26 let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
27 process.standardInput = stdin
28 process.standardOutput = stdout
29 process.standardError = stderr
30 try process.run()
31 stdin.fileHandleForWriting.write(input)
32 try stdin.fileHandleForWriting.close()
33 let out = stdout.fileHandleForReading.readDataToEndOfFile()
34 process.waitUntilExit()
35 guard process.terminationStatus == 0 else {
36 throw OpenPGP.Failure(String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self))
37 }
38 return out
39 }
40
41 static let text = Data("Secret notes: ünïcödé, and\n** a sub-heading\n".utf8) + Data(repeating: 65, count: 3000)
42
43 static let variants: [[String]] = [
44 [],
45 ["--compress-algo", "none"],
46 ["--compress-algo", "zlib", "--cipher-algo", "AES128"],
47 ["--cipher-algo", "AES192", "--s2k-digest-algo", "SHA1"],
48 ["--s2k-mode", "1", "--s2k-digest-algo", "SHA512"],
49 ["--s2k-mode", "0", "--s2k-digest-algo", "SHA224"],
50 ["--s2k-count", "65011712"],
51 ["--force-mdc", "--compress-algo", "zip"],
52 ]
53
54 @Test(.enabled(if: gpg != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: variants.indices)
55 func readsWhatGPGWrites(variant: Int) throws {
56 let armored = try Self.gpg(["--passphrase", "correct horse", "--symmetric", "--armor"] + Self.variants[variant], input: Self.text)
57 let message = try OpenPGP.dearmor(String(decoding: armored, as: UTF8.self))
58 #expect(try OpenPGP.decrypt(message, passphrase: "correct horse") == Self.text)
59 #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decrypt(message, passphrase: "wrong") }
60 }
61
62 @Test(.enabled(if: gpg != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
63 func gpgReadsWhatWeWrite() throws {
64 for plain in [Self.text, Data(), Data("short\n".utf8), Data(repeating: 7, count: 70_000)] {
65 let armored = try OpenPGP.encrypt(plain, passphrase: "pass phrase")
66 #expect(armored.hasPrefix("-----BEGIN PGP MESSAGE-----\n\n") && armored.hasSuffix("-----END PGP MESSAGE-----\n"))
67 let back = try Self.gpg(["--passphrase", "pass phrase", "--decrypt"], input: Data(armored.utf8))
68 #expect(back == plain)
69 #expect(try OpenPGP.decrypt(OpenPGP.dearmor(armored), passphrase: "pass phrase") == plain)
70 }
71 }
72
73 @Test func armorChecksum() throws {
74 let armored = OpenPGP.armor(Data([1, 2, 3]))
75 #expect(try OpenPGP.dearmor(armored) == Data([1, 2, 3]))
76 let damaged = armored.replacingOccurrences(of: "AQID", with: "AQIE")
77 #expect(throws: OpenPGP.Failure.self) { try OpenPGP.dearmor(damaged) }
78 #expect(OpenPGP.crc24(Data()) == 0xB704CE)
79 }
80}
Tests/OrgCoreTests/OrgCryptTests.swift added +110
@@ -0,0 +1,110 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct OrgCryptTests {
6 static let file = """
7 #+TITLE: Secrets
8 * Plain
9 Open text.
10 * TODO Bank :crypt:
11 SCHEDULED: <2026-10-20 Tue>
12 :PROPERTIES:
13 :ID: bank
14 :END:
15 :LOGBOOK:
16 CLOCK: [2026-10-01 Thu 09:00]--[2026-10-01 Thu 10:00] => 1:00
17 :END:
18 Account 12345, ünïcödé.
19 ** Child
20 Child text.
21
22 * Diary :crypt:
23 Dear diary.
24 * Empty :crypt:
25 * Last
26 """ + "\n"
27
28 static func lisp(_ s: String) -> String {
29 "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
30 }
31
32 /// `form` run in Emacs on `text` in an Org buffer, with symmetric org-crypt and the
33 /// passphrase given in loopback; the buffer's text afterwards.
34 static func emacs(_ text: String, _ form: String) throws -> String {
35 let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
36 try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
37 defer {
38 let kill = Process()
39 kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
40 kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
41 try? kill.run()
42 kill.waitUntilExit()
43 try? FileManager.default.removeItem(atPath: home)
44 }
45 let out = home + "/out.org"
46 let elisp = """
47 (progn
48 (require 'org) (require 'org-crypt) (require 'epg)
49 (setq org-crypt-key nil epg-pinentry-mode 'loopback org-crypt-disable-auto-save nil
50 epg-gpg-program "/opt/homebrew/bin/gpg")
51 (require 'epa)
52 (cl-letf (((symbol-function 'epa-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one")))
53 ((symbol-function 'epg-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one"))))
54 (with-temp-buffer
55 (insert \(lisp(text)))
56 (org-mode)
57 \(form)
58 (write-region (point-min) (point-max) \(lisp(out))))))
59 """
60 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", elisp], environment: ["GNUPGHOME": home, "TZ": "UTC"])
61 guard let result = try? String(contentsOfFile: out, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) }
62 return result
63 }
64
65 /// The text with each message's lines as one placeholder line.
66 static func masked(_ s: String) -> String {
67 s.replacing(#/(?s)-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----\n/#, with: "<MESSAGE>\n")
68 }
69
70 static var gpg: Bool { FileManager.default.isExecutableFile(atPath: "/opt/homebrew/bin/gpg") }
71
72 @Test(.enabled(if: gpg && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
73 func encryptsAndDecryptsAsOrg() throws {
74 // Emacs encrypts every tagged entry; ours does the same around the same text.
75 let theirs = try Self.emacs(Self.file, "(org-encrypt-entries)")
76 let (ours, count) = try OrgCrypt.encryptAll(Self.file, passphrase: "pw one")
77 #expect(count == 3)
78 #expect(Self.masked(ours) == Self.masked(theirs), "ours:\n\(Self.masked(ours))\nemacs:\n\(Self.masked(theirs))")
79 // Each side reads the other's.
80 var back = theirs
81 for heading in OrgCrypt.taggedHeadings(back).reversed() { back = try OrgCrypt.decryptInPlace(back, at: heading, passphrase: "pw one") }
82 #expect(back == Self.file, "\(back.debugDescription)\n\(Self.file.debugDescription)")
83 let decrypted = try Self.emacs(ours, "(org-decrypt-entries)")
84 #expect(decrypted == Self.file, "\(decrypted)")
85 let bank = (ours as NSString).range(of: "* TODO Bank").location
86 #expect(try OrgCrypt.decrypt(ours, at: bank, passphrase: "pw one").plaintext == "Account 12345, ünïcödé.\n** Child\nChild text.\n")
87 #expect(throws: OrgCrypt.Failure("Wrong passphrase")) { try OrgCrypt.decrypt(ours, at: bank, passphrase: "nope") }
88 // Edited and encrypted again, Emacs reads it.
89 let edited = try OrgCrypt.replacing(ours, at: bank, with: "New text.\n", passphrase: "pw one")
90 let read = try Self.emacs(edited, "(goto-char (point-min)) (re-search-forward \"Bank\") (org-decrypt-entry)")
91 #expect(read.contains("* TODO Bank :crypt:\nSCHEDULED: <2026-10-20 Tue>\n:PROPERTIES:\n:ID: bank\n:END:\n:LOGBOOK:\nCLOCK: [2026-10-01 Thu 09:00]--[2026-10-01 Thu 10:00] => 1:00\n:END:\nNew text.\n\n* Diary"), "\(read)")
92 }
93
94 @Test func regions() throws {
95 let file = Self.file
96 let bank = (file as NSString).range(of: "* TODO Bank").location
97 let body = try #require(OrgCrypt.bodyRange(file, at: bank + 3))
98 #expect((file as NSString).substring(with: NSRange(body)) == "Account 12345, ünïcödé.\n** Child\nChild text.\n")
99 #expect(OrgCrypt.encryptedRange(file, at: bank) == nil)
100 // The child inherits the tag.
101 #expect(OrgCrypt.taggedHeadings(file).count == 4)
102 let encrypted = try #require(try OrgCrypt.encrypt(file, at: bank, passphrase: "x"))
103 #expect(try OrgCrypt.encrypt(encrypted, at: bank, passphrase: "x") == nil)
104 #expect(throws: OrgCrypt.Failure.self) { try OrgCrypt.encrypt("text\n", at: 0, passphrase: "x") }
105 // A decrypted heading above the entry's level goes below it.
106 let shallow = try OrgCrypt.replacing(encrypted, at: bank, with: "* Top\ntext\n", passphrase: "x")
107 let placed = try OrgCrypt.decryptInPlace(shallow, at: bank, passphrase: "x")
108 #expect(placed.contains(":END:\n** Top\ntext\n\n* Diary"), "\(placed)")
109 }
110}
docs/manual/guide/04-outlines.org +26
@@ -883,6 +883,32 @@ subtree at the caret under a sibling heading named =Archive= with the =ARCHIVE=
883883creating it at the end of the parent's children if needed. The moved entry gets an
884884=ARCHIVE_TIME= property, and the =Archive= sibling is folded.
885885
886* Encrypted entries
887
888orgstar reads and writes entries encrypted by org-crypt with a passphrase (=org-crypt-key= nil, symmetric encryption). The text after the entry's planning line, property drawer and logbook, through the end of its subtree, is replaced by an OpenPGP message under the heading:
889
890#+begin_example
891,* Secret :crypt:
892-----BEGIN PGP MESSAGE-----
893
894ww0ECQMI…
895-----END PGP MESSAGE-----
896#+end_example
897
898| Command | What it does |
899|-+-|
900| Encrypt Entry… (=app.crypt.encrypt-entry=) | Asks for a passphrase twice and encrypts the entry at the caret (=org-encrypt-entry=). |
901| Decrypt Entry… (=app.crypt.open-entry=) | Asks for the passphrase and shows the decrypted text in a sheet. Save encrypts the edited text again in the message's place; the file never holds the plaintext. Decrypt in File puts the text in the file instead. |
902| Decrypt Entry in File… (=app.crypt.decrypt-entry=) | Replaces the message with the decrypted text (=org-decrypt-entry=). Headings in it are moved below the entry's level when they aren't. |
903| Encrypt Tagged Entries… (=app.crypt.encrypt-entries=) | Encrypts every entry with the =crypt= tag, its own or inherited, that isn't encrypted yet (=org-encrypt-entries=). A tagged entry's tagged children go inside its message. |
904| Forget Encryption Passphrase (=app.crypt.forget-passphrase=) | Removes the current file's passphrase from the Keychain. |
905
906The commands have no keys, as in Org; run them from the Org menu or the palette, or bind them in =keymap.toml=. On iOS they are under More ▸ Encryption.
907
908Remember 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.
909
910Messages 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….
911
886912* The outline pane
887913
888914The outline pane, to the left of the editor, lists the headings of the open org file,
docs/manual/guide/13-configuration.org +3
@@ -160,6 +160,7 @@ These settings have no control in the Settings window. Some are in the View menu
160160| =org-archive-location= | |
161161| =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist= | |
162162| =org-track-ordered-property-with-tag= | |
163| =org-crypt-tag-matcher= | |
163164| =org-agenda-start-on-weekday= | |
164165| =org-deadline-warning-days= | |
165166| =org-agenda-skip-scheduled-if-done= | |
@@ -208,6 +209,7 @@ A key you remove from the file goes back to its default. A key that isn't in the
208209| =org-tags-exclude-from-inheritance= | string | =""= | Tags that never inherit, separated by spaces. Read at launch. Mirrors =org-tags-exclude-from-inheritance=. |
209210| =org-tag-alist= | string | =""= | The tags Set Tags offers in files without =#+TAGS=, in =#+TAGS= syntax with keys and groups, rows separated by =\n=. Mirrors =org-tag-alist=. |
210211| =org-track-ordered-property-with-tag= | string | ="nil"= | A tag that Toggle ORDERED Property adds and removes with the property: ="t"= for the tag =ORDERED=, or a tag name. Mirrors =org-track-ordered-property-with-tag=. |
212| =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=. |
211213| =org-startup-indented= | boolean | =true= | Indent bodies under their headings, as =org-indent-mode=. =#+STARTUP: indent= / =noindent= override it. Mirrors =org-startup-indented=. |
212214| =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=. |
213215| =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=. |
@@ -565,6 +567,7 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
565567| =org-agenda-log-mode-items= | The symbols =closed=, =clock= and =state= of the list, separated by spaces |
566568| =org-agenda-todo-ignore-scheduled=, =-deadlines=, =-timestamp= | The symbol or number as a string; =org-agenda-todo-ignore-with-date= and =org-agenda-tags-todo-honor-ignore-options= as booleans |
567569| =org-track-ordered-property-with-tag= | A tag name as given; =t= becomes ="t"=, =nil= ="nil"= |
570| =org-crypt-tag-matcher= | The same key, when the value is a single tag |
568571| =org-archive-location= | The same key, when the value is a =file::heading= string |
569572| =org-structure-template-alist= | =[org-structure-template-alist]=: each =("key" . "type")= entry that isn't one of Org's, from =setq= or =(add-to-list 'org-structure-template-alist …)= |
570573| =org-todo-keywords= | =org-todo-keywords=, one line per sequence. Keywords with spaces are left out; =type= sequences are read as sequences. |
docs/manual/guide/14-ios.org +3
@@ -133,6 +133,8 @@ Cancel answers nothing, as =C-g= does.
133133
134134=C-c '= on a block, and =C-c `= on a table field, open the text in a sheet of its own; Save puts it back. A src block's code is colored as its language, as in the editor.
135135
136More ▸ Encryption has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A remembered passphrase is used after Face ID, Touch ID or the device passcode.
137
136138** Hardware keyboard
137139
138140With a hardware keyboard, the editor uses the preset =keymap= sets in the folder's =config.toml= (=emacs=, =mac= or =doom=), with the folder's =keymap.toml= on it. The Doom preset brings Vim keys; see [[file:03-keys.org][Keys]]. Bindings with =⌘= stay with iOS, so the Mac preset adds little.
@@ -349,6 +351,7 @@ These settings from =config.toml= apply on iOS:
349351- =[theme]= (=font=, =font-size=, =line-spacing=, =heading-size-step=, =theme-file= and colours), =[theme.light]=, =[theme.dark]=, =[theme.todo]=, =[theme.category]=
350352- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=
351353- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks=
354- =org-crypt-tag-matcher=
352355- =org-archive-location=, =[org-structure-template-alist]=
353356- =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist=
354357- =org-use-speed-commands=, with a hardware keyboard
docs/manual/guide/15-alongside-emacs.org +1
@@ -248,5 +248,6 @@ Other:
248248- =display-line-numbers-type= has no relative or visual mode.
249249- The agenda's text search (see [[file:07-agenda.org][The agenda]]) covers the agenda files only: =org-agenda-text-search-extra-files= and =org-agenda-search-view-max-outline-level= aren't supported. It runs from the view menu rather than the dispatcher's =s= and =S=, and the search view's =[=, =]=, ={= and =}= keys, which add words and regexps to the search, aren't supported.
250250- In regexps, =\<=, =\>= and =\b= use Org's word syntax but don't find a word boundary where the script changes between two word characters, as Emacs does (for example between an emoji and a letter).
251- 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.
251252- =org-track-ordered-property-with-tag= isn't supported; Toggle ORDERED Property sets only the property.
252253- 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.
ios/Orgstar/Info.plist +2
@@ -37,6 +37,8 @@
3737 <string>$(CURRENT_PROJECT_VERSION)</string>
3838 <key>LSApplicationCategoryType</key>
3939 <string>public.app-category.productivity</string>
40 <key>NSFaceIDUsageDescription</key>
41 <string>Face ID unlocks the passphrase of encrypted entries you asked orgstar to remember.</string>
4042 <key>NSCalendarsFullAccessUsageDescription</key>
4143 <string>The agenda shows your calendar events alongside your Org entries. orgstar only reads them.</string>
4244 <key>NSSupportsLiveActivities</key>
scripts/build-ios-app.sh +2
@@ -49,6 +49,8 @@ cat > "$app/Info.plist" <<PLIST
4949 <array><string>iPhoneSimulator</string></array>
5050 <key>MinimumOSVersion</key>
5151 <string>26.0</string>
52 <key>NSFaceIDUsageDescription</key>
53 <string>Face ID unlocks the passphrase of encrypted entries you asked orgstar to remember.</string>
5254 <key>NSCalendarsFullAccessUsageDescription</key>
5355 <string>The agenda shows your calendar events alongside your Org entries. orgstar only reads them.</string>
5456 <key>UIDeviceFamily</key>