Commit df309f690d

df309f690db3c0512f80b7d4c3d501d345692e13

parent: 511a22a63d

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 04:57 UTC

Add sandbox switches for roots, saves, PDFs and widgets

- Sandbox.isActive in OrgCore, from APP_SANDBOX_CONTAINER_ID on macOS, false on iOS
- Sandbox.bookmarkCreationOptions/bookmarkResolutionOptions: security-scoped in the Mac sandbox
- WorkspaceRoot creates and resolves bookmarks with those options
- CoordinatedFileSystem writes in place when the folder refuses the temporary file in the sandbox
- PDFExport inlines local images as data: URIs and limits WebKit's read access when sandboxed
- AgendaSnapshot.useGroupContainer selects the app group container on the Mac
- OrgWorkspace declares its OrgCore dependency
- Tests for each switch

Layout: unified · split

Package.swift +1 −1
@@ -53,7 +53,7 @@ let package = Package(
53 .target(name: "OrgCore"), 53 .target(name: "OrgCore"),
54 .target(name: "OrgDocument", dependencies: ["OrgCore"]), 54 .target(name: "OrgDocument", dependencies: ["OrgCore"]),
55 .target(name: "OrgIndex", dependencies: ["OrgCore", .product(name: "GRDB", package: "GRDB.swift")]), 55 .target(name: "OrgIndex", dependencies: ["OrgCore", .product(name: "GRDB", package: "GRDB.swift")]),
56 .target(name: "OrgWorkspace", dependencies: ["OrgIndex"]), 56 .target(name: "OrgWorkspace", dependencies: ["OrgCore", "OrgIndex"]),
57 .target(name: "OrgPresentation", dependencies: ["OrgCore", .product(name: "SwiftMath", package: "SwiftMath")]), 57 .target(name: "OrgPresentation", dependencies: ["OrgCore", .product(name: "SwiftMath", package: "SwiftMath")]),
58 .target(name: "OrgEditorAppKit", dependencies: ["OrgDocument", "OrgPresentation"]), 58 .target(name: "OrgEditorAppKit", dependencies: ["OrgDocument", "OrgPresentation"]),
59 .target(name: "TreeSitterElisp", path: "Sources/TreeSitterElisp", sources: ["src/parser.c"], cSettings: [.headerSearchPath("src")]), 59 .target(name: "TreeSitterElisp", path: "Sources/TreeSitterElisp", sources: ["src/parser.c"], cSettings: [.headerSearchPath("src")]),
Sources/OrgApp/AgendaSnapshot.swift +11 −7
@@ -204,16 +204,20 @@ public struct AgendaSnapshot: Codable, Equatable, Sendable {
204 204
205 // MARK: - The file 205 // MARK: - The file
206 206
207 /// Use the app group's container on the Mac too. The App Store build sets it at launch, in
208 /// the app and in the widget extension, as both have a provisioning profile there.
209 nonisolated(unsafe) public static var useGroupContainer = false
210
207 /// `Widgets/agenda.json` in the app group's container; nil without the group. On the Mac, 211 /// `Widgets/agenda.json` in the app group's container; nil without the group. On the Mac,
208 /// in `~/Library/Application Support/Orgstar/Widgets`, which the sandboxed widget extension 212 /// unless `useGroupContainer`, in `~/Library/Application Support/Orgstar/Widgets`, which the
209 /// reads by a sandbox exception, as an app group there needs a provisioning profile. 213 /// sandboxed widget extension reads by a sandbox exception, as an app group there needs a
210 public static func file(group: String = CaptureInbox.group) -> URL? { 214 /// provisioning profile.
215 public static func file(group: String = CaptureInbox.group, inGroup: Bool = useGroupContainer) -> URL? {
211 #if os(macOS) 216 #if os(macOS)
212 return macWidgetsFolder.appendingPathComponent("agenda.json") 217 guard inGroup else { return macWidgetsFolder.appendingPathComponent("agenda.json") }
213 #else
214 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
215 .appendingPathComponent("Widgets").appendingPathComponent("agenda.json")
216 #endif 218 #endif
219 return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
220 .appendingPathComponent("Widgets").appendingPathComponent("agenda.json")
217 } 221 }
218 222
219 #if os(macOS) 223 #if os(macOS)
Sources/OrgApp/PDFExport.swift +41 −3
@@ -1,5 +1,7 @@
1import Foundation 1import Foundation
2import OrgCore
2import PDFKit 3import PDFKit
4import UniformTypeIdentifiers
3import WebKit 5import WebKit
4#if os(macOS) 6#if os(macOS)
5import AppKit 7import AppKit
@@ -39,6 +41,39 @@ public enum PDFExport {
39 return printCSS.replacingOccurrences(of: "</style>", with: "body { font-family: \"\(family)\", -apple-system, sans-serif; }\n</style>") 41 return printCSS.replacingOccurrences(of: "</style>", with: "body { font-family: \"\(family)\", -apple-system, sans-serif; }\n</style>")
40 } 42 }
41 43
44 /// `html` with each `<img>` that names a local file given that file as a `data:` URI.
45 /// Relative paths are read from `directory`; files that can't be read keep their `src`.
46 nonisolated static func inliningImages(_ html: String, directory: URL?) -> String {
47 let pattern = /(<img\b[^>]*?\bsrc=")([^"]*)(")/
48 return html.replacing(pattern) { match in
49 let (_, before, src, after) = match.output
50 guard let uri = dataURI(String(src), directory: directory) else { return String(match.output.0) }
51 return before + uri + after
52 }
53 }
54
55 /// The file an `<img src>` names, as a `data:` URI; nil for remote or unreadable images.
56 nonisolated static func dataURI(_ src: String, directory: URL?) -> String? {
57 let path = src.replacingOccurrences(of: "&quot;", with: "\"").replacingOccurrences(of: "&lt;", with: "<")
58 .replacingOccurrences(of: "&gt;", with: ">").replacingOccurrences(of: "&amp;", with: "&")
59 let url: URL
60 if path.hasPrefix("file://") {
61 guard let parsed = URL(string: path) else { return nil }
62 url = parsed
63 } else if path.hasPrefix("/") {
64 url = URL(fileURLWithPath: path)
65 } else if path.hasPrefix("~/") {
66 url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath)
67 } else if !path.contains(":"), let directory {
68 url = directory.appendingPathComponent(path)
69 } else {
70 return nil
71 }
72 guard let data = try? Data(contentsOf: url) else { return nil }
73 let type = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
74 return "data:\(type);base64,\(data.base64EncodedString())"
75 }
76
42 /// Each page's number, centred in its bottom margin, as an annotation: drawing it into the 77 /// Each page's number, centred in its bottom margin, as an annotation: drawing it into the
43 /// page would mean drawing the page again and losing WebKit's links. 78 /// page would mean drawing the page again and losing WebKit's links.
44 static func numberPages(_ data: Data, margin: Int) -> Data { 79 static func numberPages(_ data: Data, margin: Int) -> Data {
@@ -85,14 +120,17 @@ public enum PDFExport {
85 webView.navigationDelegate = loader 120 webView.navigationDelegate = loader
86 #if os(macOS) 121 #if os(macOS)
87 webView.appearance = NSAppearance(named: .aqua) 122 webView.appearance = NSAppearance(named: .aqua)
88 // A file beside nothing the user owns, readable with the images it links to. 123 // A file beside nothing the user owns, readable with the images it links to. In the
124 // sandbox WebKit's own process can't read the user's folders, so the images go in the page.
125 let sandboxed = Sandbox.isActive
89 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)") 126 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)")
90 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 127 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
91 defer { try? FileManager.default.removeItem(at: folder) } 128 defer { try? FileManager.default.removeItem(at: folder) }
92 let file = folder.appendingPathComponent("page.html") 129 let file = folder.appendingPathComponent("page.html")
93 let based = directory.map { page.replacingOccurrences(of: "<head>", with: "<head>\n<base href=\"\($0.absoluteString)\">") } ?? page 130 let source = sandboxed ? inliningImages(page, directory: directory) : page
131 let based = directory.map { source.replacingOccurrences(of: "<head>", with: "<head>\n<base href=\"\($0.absoluteString)\">") } ?? source
94 try based.write(to: file, atomically: true, encoding: .utf8) 132 try based.write(to: file, atomically: true, encoding: .utf8)
95 webView.loadFileURL(file, allowingReadAccessTo: URL(fileURLWithPath: "/")) 133 webView.loadFileURL(file, allowingReadAccessTo: sandboxed ? folder : URL(fileURLWithPath: "/"))
96 #else 134 #else
97 webView.overrideUserInterfaceStyle = .light 135 webView.overrideUserInterfaceStyle = .light
98 webView.loadHTMLString(page, baseURL: directory) 136 webView.loadHTMLString(page, baseURL: directory)
Sources/OrgCore/Sandbox.swift added +36
@@ -0,0 +1,36 @@
1import Foundation
2
3/// Whether this process runs in the App Sandbox, as the Mac App Store build does, and the
4/// choices that follow from it.
5public enum Sandbox {
6 /// True for a sandboxed Mac process. Always false on iOS.
7 public static let isActive = isActive(environment: ProcessInfo.processInfo.environment)
8
9 /// The sandbox sets `APP_SANDBOX_CONTAINER_ID` for the processes it confines.
10 static func isActive(environment: [String: String]) -> Bool {
11 #if os(macOS)
12 environment["APP_SANDBOX_CONTAINER_ID"] != nil
13 #else
14 false
15 #endif
16 }
17
18 /// Options for a bookmark that should give access back after relaunch: security-scoped in
19 /// the Mac sandbox, plain elsewhere.
20 public static func bookmarkCreationOptions(sandboxed: Bool = isActive) -> URL.BookmarkCreationOptions {
21 #if os(macOS)
22 sandboxed ? .withSecurityScope : []
23 #else
24 []
25 #endif
26 }
27
28 /// The resolving side of `bookmarkCreationOptions`.
29 public static func bookmarkResolutionOptions(sandboxed: Bool = isActive) -> URL.BookmarkResolutionOptions {
30 #if os(macOS)
31 sandboxed ? .withSecurityScope : []
32 #else
33 []
34 #endif
35 }
36}
Sources/OrgDocument/FileStorage.swift +23 −2
@@ -1,10 +1,17 @@
1import CryptoKit 1import CryptoKit
2import Foundation 2import Foundation
3import OrgCore
3 4
4/// Reads and replaces files under `NSFileCoordinator`, so iCloud and other coordinating 5/// Reads and replaces files under `NSFileCoordinator`, so iCloud and other coordinating
5/// writers see a consistent file. 6/// writers see a consistent file.
6public struct CoordinatedFileSystem: FileSystem { 7public struct CoordinatedFileSystem: FileSystem {
7 public init() {} 8 /// Write in place when the folder refuses the temporary file, as the sandbox does for a
9 /// file it granted alone. Not atomic, so only where it is the one way to save.
10 public let writesInPlaceWhenDenied: Bool
11
12 public init(writesInPlaceWhenDenied: Bool = Sandbox.isActive) {
13 self.writesInPlaceWhenDenied = writesInPlaceWhenDenied
14 }
8 15
9 public func read(_ url: URL) throws -> [UInt8]? { 16 public func read(_ url: URL) throws -> [UInt8]? {
10 try coordinate(reading: url) { url in 17 try coordinate(reading: url) { url in
@@ -17,7 +24,13 @@ public struct CoordinatedFileSystem: FileSystem {
17 let manager = FileManager.default 24 let manager = FileManager.default
18 let folder = url.deletingLastPathComponent() 25 let folder = url.deletingLastPathComponent()
19 let temporary = folder.appendingPathComponent(".\(url.lastPathComponent).orgstar-\(UUID().uuidString)") 26 let temporary = folder.appendingPathComponent(".\(url.lastPathComponent).orgstar-\(UUID().uuidString)")
20 try Data(bytes).write(to: temporary) 27 do {
28 try Data(bytes).write(to: temporary)
29 } catch where writesInPlaceWhenDenied && Self.isPermissionDenied(error) {
30 let previous = manager.fileExists(atPath: url.path) ? [UInt8](try Data(contentsOf: url)) : nil
31 try Data(bytes).write(to: url)
32 return previous
33 }
21 guard manager.fileExists(atPath: url.path) else { 34 guard manager.fileExists(atPath: url.path) else {
22 try manager.moveItem(at: temporary, to: url) 35 try manager.moveItem(at: temporary, to: url)
23 return nil 36 return nil
@@ -32,6 +45,14 @@ public struct CoordinatedFileSystem: FileSystem {
32 } 45 }
33 } 46 }
34 47
48 /// Whether `error` is the file system refusing access.
49 static func isPermissionDenied(_ error: Error) -> Bool {
50 let error = error as NSError
51 if error.domain == NSCocoaErrorDomain, error.code == CocoaError.fileWriteNoPermission.rawValue { return true }
52 if error.domain == NSPOSIXErrorDomain, [Int(EACCES), Int(EPERM)].contains(error.code) { return true }
53 return (error.userInfo[NSUnderlyingErrorKey] as? Error).map(isPermissionDenied) ?? false
54 }
55
35 private func coordinate<T>(reading url: URL, _ body: (URL) throws -> T) throws -> T { 56 private func coordinate<T>(reading url: URL, _ body: (URL) throws -> T) throws -> T {
36 var coordinationError: NSError? 57 var coordinationError: NSError?
37 var result: Result<T, Error>? 58 var result: Result<T, Error>?
Sources/OrgWorkspace/Discovery.swift +8 −5
@@ -1,21 +1,24 @@
1import Foundation 1import Foundation
2import OrgCore
2import OrgIndex 3import OrgIndex
3 4
4/// A folder the user added. Identified by its bookmark, so a moved folder is followed. 5/// A folder the user added. Identified by its bookmark, so a moved folder is followed. In the
6/// Mac sandbox the bookmark is security-scoped, so access comes back after relaunch.
5public struct WorkspaceRoot: Sendable, Equatable, Codable { 7public struct WorkspaceRoot: Sendable, Equatable, Codable {
6 public let bookmark: Data 8 public let bookmark: Data
7 /// The path when the bookmark was made or last refreshed, for display. 9 /// The path when the bookmark was made or last refreshed, for display.
8 public var path: String 10 public var path: String
9 11
10 public init(url: URL) throws { 12 public init(url: URL, sandboxed: Bool = Sandbox.isActive) throws {
11 bookmark = try url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) 13 bookmark = try url.bookmarkData(options: Sandbox.bookmarkCreationOptions(sandboxed: sandboxed), includingResourceValuesForKeys: nil, relativeTo: nil)
12 path = url.standardizedFileURL.path 14 path = url.standardizedFileURL.path
13 } 15 }
14 16
15 /// The folder's current location. `isStale` means the bookmark should be made again. 17 /// The folder's current location. `isStale` means the bookmark should be made again.
16 public func resolve() throws -> (url: URL, isStale: Bool) { 18 public func resolve(sandboxed: Bool = Sandbox.isActive) throws -> (url: URL, isStale: Bool) {
17 var isStale = false 19 var isStale = false
18 let url = try URL(resolvingBookmarkData: bookmark, options: [], relativeTo: nil, bookmarkDataIsStale: &isStale) 20 let options = Sandbox.bookmarkResolutionOptions(sandboxed: sandboxed)
21 let url = try URL(resolvingBookmarkData: bookmark, options: options, relativeTo: nil, bookmarkDataIsStale: &isStale)
19 _ = url.startAccessingSecurityScopedResource() 22 _ = url.startAccessingSecurityScopedResource()
20 return (url.standardizedFileURL, isStale) 23 return (url.standardizedFileURL, isStale)
21 } 24 }
Tests/OrgAppTests/PDFExportTests.swift +17
@@ -31,4 +31,21 @@ struct PDFExportTests {
31 #expect(css.contains("font-family: \"Georgia\"")) 31 #expect(css.contains("font-family: \"Georgia\""))
32 #expect(!PDFExport.css(PDFExport.Options()).contains("font-family")) 32 #expect(!PDFExport.css(PDFExport.Options()).contains("font-family"))
33 } 33 }
34
35 /// In the sandbox WebKit can't read the user's folders, so local images go in the page.
36 @Test func inlinesLocalImages() throws {
37 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
38 try FileManager.default.createDirectory(at: folder.appendingPathComponent("img"), withIntermediateDirectories: true)
39 defer { try? FileManager.default.removeItem(at: folder) }
40 try Data([1, 2, 3]).write(to: folder.appendingPathComponent("img/a b.png"))
41 try Data([4]).write(to: folder.appendingPathComponent("c.svg"))
42 let absolute = folder.appendingPathComponent("c.svg").path
43 let html = #"<p><img src="img/a b.png" alt="a"> <img alt="c" src="\#(absolute)"> <img src="https://x.org/r.png"> <img src="gone.png"></p>"#
44 let inlined = PDFExport.inliningImages(html, directory: folder)
45 #expect(inlined.contains(#"<img src="data:image/png;base64,AQID" alt="a">"#))
46 #expect(inlined.contains(#"<img alt="c" src="data:image/svg+xml;base64,BA==">"#))
47 #expect(inlined.contains(#"<img src="https://x.org/r.png">"#))
48 #expect(inlined.contains(#"<img src="gone.png">"#))
49 #expect(PDFExport.inliningImages(#"<img src="img/a b.png">"#, directory: nil) == #"<img src="img/a b.png">"#)
50 }
34} 51}
Tests/OrgAppTests/WidgetDataTests.swift +8
@@ -101,5 +101,13 @@ struct MacWidgetFolderTests {
101 #expect(!agenda.path.contains("/Containers/")) 101 #expect(!agenda.path.contains("/Containers/"))
102 #expect(HabitSnapshot.file()?.deletingLastPathComponent() == agenda.deletingLastPathComponent()) 102 #expect(HabitSnapshot.file()?.deletingLastPathComponent() == agenda.deletingLastPathComponent())
103 } 103 }
104
105 /// The App Store build reads and writes the app group's container, as iOS does.
106 @Test func groupContainerWhenSwitchedOn() {
107 #expect(!AgendaSnapshot.useGroupContainer)
108 let agenda = AgendaSnapshot.file(inGroup: true)
109 #expect(agenda.map { !$0.path.contains("/Application Support/Orgstar/") } ?? true)
110 #expect(agenda.map { $0.path.hasSuffix("/\(CaptureInbox.group)/Widgets/agenda.json") } ?? true)
111 }
104} 112}
105#endif 113#endif
Tests/OrgCoreTests/SandboxTests.swift added +33
@@ -0,0 +1,33 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct SandboxTests {
6 /// Tests run unsandboxed, so every switch keeps the Developer ID build's behaviour.
7 @Test func inactiveInTests() {
8 #expect(!Sandbox.isActive)
9 #expect(Sandbox.bookmarkCreationOptions() == [])
10 #expect(Sandbox.bookmarkResolutionOptions() == [])
11 }
12
13 @Test func detectedFromTheContainerVariable() {
14 #expect(!Sandbox.isActive(environment: [:]))
15 #if os(macOS)
16 #expect(Sandbox.isActive(environment: ["APP_SANDBOX_CONTAINER_ID": "sh.krz.orgstar"]))
17 #else
18 #expect(!Sandbox.isActive(environment: ["APP_SANDBOX_CONTAINER_ID": "sh.krz.orgstar"]))
19 #endif
20 }
21
22 @Test func bookmarksAreSecurityScopedInTheMacSandbox() {
23 #if os(macOS)
24 #expect(Sandbox.bookmarkCreationOptions(sandboxed: true) == .withSecurityScope)
25 #expect(Sandbox.bookmarkResolutionOptions(sandboxed: true) == .withSecurityScope)
26 #else
27 #expect(Sandbox.bookmarkCreationOptions(sandboxed: true) == [])
28 #expect(Sandbox.bookmarkResolutionOptions(sandboxed: true) == [])
29 #endif
30 #expect(Sandbox.bookmarkCreationOptions(sandboxed: false) == [])
31 #expect(Sandbox.bookmarkResolutionOptions(sandboxed: false) == [])
32 }
33}
Tests/OrgDocumentTests/SaveTests.swift +26
@@ -181,6 +181,32 @@ struct FileStorageTests {
181 #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path) == ["a.org"]) 181 #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path) == ["a.org"])
182 } 182 }
183 183
184 /// A file the sandbox granted alone: its folder takes no temporary file, so the save writes
185 /// in place and the previous bytes still come back for recovery.
186 @Test func writesInPlaceWhenTheFolderRefusesTheTemporaryFile() throws {
187 let folder = try temporaryFolder()
188 let manager = FileManager.default
189 let file = folder.appendingPathComponent("a.org")
190 try Data("one\n".utf8).write(to: file)
191 try manager.setAttributes([.posixPermissions: 0o555], ofItemAtPath: folder.path)
192 defer {
193 try? manager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path)
194 try? manager.removeItem(at: folder)
195 }
196 #expect(throws: (any Error).self) { try CoordinatedFileSystem(writesInPlaceWhenDenied: false).replace(file, with: Array("two\n".utf8)) }
197 let files = CoordinatedFileSystem(writesInPlaceWhenDenied: true)
198 #expect(try files.replace(file, with: Array("two\n".utf8)) == Array("one\n".utf8))
199 #expect(try files.read(file) == Array("two\n".utf8))
200 #expect(try manager.contentsOfDirectory(atPath: folder.path) == ["a.org"])
201 }
202
203 @Test func outsideTheSandboxSavesReplaceTheFile() {
204 #expect(!CoordinatedFileSystem().writesInPlaceWhenDenied)
205 #expect(CoordinatedFileSystem.isPermissionDenied(CocoaError(.fileWriteNoPermission)))
206 #expect(CoordinatedFileSystem.isPermissionDenied(NSError(domain: NSPOSIXErrorDomain, code: Int(EACCES))))
207 #expect(!CoordinatedFileSystem.isPermissionDenied(CocoaError(.fileWriteOutOfSpace)))
208 }
209
184 @Test func savesThroughTheRealFileSystem() throws { 210 @Test func savesThroughTheRealFileSystem() throws {
185 let folder = try temporaryFolder() 211 let folder = try temporaryFolder()
186 defer { try? FileManager.default.removeItem(at: folder) } 212 defer { try? FileManager.default.removeItem(at: folder) }
Tests/OrgWorkspaceTests/WorkspaceRootTests.swift added +23
@@ -0,0 +1,23 @@
1import Foundation
2import Testing
3@testable import OrgWorkspace
4
5struct WorkspaceRootTests {
6 @Test func plainBookmarkResolves() throws {
7 let folder = try Folder()
8 let root = try WorkspaceRoot(url: folder.url)
9 let resolved = try root.resolve()
10 #expect(resolved.url.resolvingSymlinksInPath() == folder.url.resolvingSymlinksInPath())
11 #expect(root.path == folder.url.path)
12 }
13
14 #if os(macOS)
15 /// The sandboxed build's bookmarks carry their scope, and resolve with it.
16 @Test func securityScopedBookmarkResolves() throws {
17 let folder = try Folder()
18 let root = try WorkspaceRoot(url: folder.url, sandboxed: true)
19 #expect(try root.resolve(sandboxed: true).url.resolvingSymlinksInPath() == folder.url.resolvingSymlinksInPath())
20 #expect(root.bookmark != (try WorkspaceRoot(url: folder.url, sandboxed: false)).bookmark)
21 }
22 #endif
23}