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(
5353 .target(name: "OrgCore"),
5454 .target(name: "OrgDocument", dependencies: ["OrgCore"]),
5555 .target(name: "OrgIndex", dependencies: ["OrgCore", .product(name: "GRDB", package: "GRDB.swift")]),
56 .target(name: "OrgWorkspace", dependencies: ["OrgIndex"]),
56 .target(name: "OrgWorkspace", dependencies: ["OrgCore", "OrgIndex"]),
5757 .target(name: "OrgPresentation", dependencies: ["OrgCore", .product(name: "SwiftMath", package: "SwiftMath")]),
5858 .target(name: "OrgEditorAppKit", dependencies: ["OrgDocument", "OrgPresentation"]),
5959 .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 {
204204
205205 // MARK: - The file
206206
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
207211 /// `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
209 /// reads by a sandbox exception, as an app group there needs a provisioning profile.
210 public static func file(group: String = CaptureInbox.group) -> URL? {
212 /// unless `useGroupContainer`, in `~/Library/Application Support/Orgstar/Widgets`, which the
213 /// sandboxed widget extension reads by a sandbox exception, as an app group there needs a
214 /// provisioning profile.
215 public static func file(group: String = CaptureInbox.group, inGroup: Bool = useGroupContainer) -> URL? {
211216 #if os(macOS)
212 return macWidgetsFolder.appendingPathComponent("agenda.json")
213 #else
214 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
215 .appendingPathComponent("Widgets").appendingPathComponent("agenda.json")
217 guard inGroup else { return macWidgetsFolder.appendingPathComponent("agenda.json") }
216218 #endif
219 return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
220 .appendingPathComponent("Widgets").appendingPathComponent("agenda.json")
217221 }
218222
219223 #if os(macOS)
Sources/OrgApp/PDFExport.swift +41 −3
@@ -1,5 +1,7 @@
11import Foundation
2import OrgCore
23import PDFKit
4import UniformTypeIdentifiers
35import WebKit
46#if os(macOS)
57import AppKit
@@ -39,6 +41,39 @@ public enum PDFExport {
3941 return printCSS.replacingOccurrences(of: "</style>", with: "body { font-family: \"\(family)\", -apple-system, sans-serif; }\n</style>")
4042 }
4143
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
4277 /// Each page's number, centred in its bottom margin, as an annotation: drawing it into the
4378 /// page would mean drawing the page again and losing WebKit's links.
4479 static func numberPages(_ data: Data, margin: Int) -> Data {
@@ -85,14 +120,17 @@ public enum PDFExport {
85120 webView.navigationDelegate = loader
86121 #if os(macOS)
87122 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
89126 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)")
90127 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
91128 defer { try? FileManager.default.removeItem(at: folder) }
92129 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
94132 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: "/"))
96134 #else
97135 webView.overrideUserInterfaceStyle = .light
98136 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 @@
11import CryptoKit
22import Foundation
3import OrgCore
34
45/// Reads and replaces files under `NSFileCoordinator`, so iCloud and other coordinating
56/// writers see a consistent file.
67public 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 }
815
916 public func read(_ url: URL) throws -> [UInt8]? {
1017 try coordinate(reading: url) { url in
@@ -17,7 +24,13 @@ public struct CoordinatedFileSystem: FileSystem {
1724 let manager = FileManager.default
1825 let folder = url.deletingLastPathComponent()
1926 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 }
2134 guard manager.fileExists(atPath: url.path) else {
2235 try manager.moveItem(at: temporary, to: url)
2336 return nil
@@ -32,6 +45,14 @@ public struct CoordinatedFileSystem: FileSystem {
3245 }
3346 }
3447
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
3556 private func coordinate<T>(reading url: URL, _ body: (URL) throws -> T) throws -> T {
3657 var coordinationError: NSError?
3758 var result: Result<T, Error>?
Sources/OrgWorkspace/Discovery.swift +8 −5
@@ -1,21 +1,24 @@
11import Foundation
2import OrgCore
23import OrgIndex
34
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.
57public struct WorkspaceRoot: Sendable, Equatable, Codable {
68 public let bookmark: Data
79 /// The path when the bookmark was made or last refreshed, for display.
810 public var path: String
911
10 public init(url: URL) throws {
11 bookmark = try url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)
12 public init(url: URL, sandboxed: Bool = Sandbox.isActive) throws {
13 bookmark = try url.bookmarkData(options: Sandbox.bookmarkCreationOptions(sandboxed: sandboxed), includingResourceValuesForKeys: nil, relativeTo: nil)
1214 path = url.standardizedFileURL.path
1315 }
1416
1517 /// 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) {
1719 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)
1922 _ = url.startAccessingSecurityScopedResource()
2023 return (url.standardizedFileURL, isStale)
2124 }
Tests/OrgAppTests/PDFExportTests.swift +17
@@ -31,4 +31,21 @@ struct PDFExportTests {
3131 #expect(css.contains("font-family: \"Georgia\""))
3232 #expect(!PDFExport.css(PDFExport.Options()).contains("font-family"))
3333 }
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 }
3451}
Tests/OrgAppTests/WidgetDataTests.swift +8
@@ -101,5 +101,13 @@ struct MacWidgetFolderTests {
101101 #expect(!agenda.path.contains("/Containers/"))
102102 #expect(HabitSnapshot.file()?.deletingLastPathComponent() == agenda.deletingLastPathComponent())
103103 }
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 }
104112}
105113#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 {
181181 #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path) == ["a.org"])
182182 }
183183
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
184210 @Test func savesThroughTheRealFileSystem() throws {
185211 let folder = try temporaryFolder()
186212 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}