User command trust prompt: full path, imports and what it can do !529

merged merged by cmc on 2026-11-27 16:05 UTC · krz/orgstar:250-user-command-trust-prompt into main

8 files changed, +265 −30

One commit's changes, read-only. Review comments go on all commits.

Layout: unified · split

Changed files (8)
Sources/OrgApp/UserCommandFile.swift +71 −17 · view
@@ -58,10 +58,21 @@ public enum UserCommandFile {
5858 /// path order. Nil when `file` can't be read.
5959 @MainActor
6060 public static func trustedText(_ file: String, modules: URL) -> String? {
61 var seen: [String: String] = [:]
61 moduleTexts(file, modules: modules).map(trustedText)
62 }
63
64 static func trustedText(_ texts: [String: String?]) -> String {
65 texts.keys.sorted().map { "// \($0)\n\(texts[$0]! ?? "(missing)")" }.joined(separator: "\n")
66 }
67
68 /// `file` and every module it imports, directly or through another, by path in `modules`;
69 /// nil for an import that can't be read. Nil when `file` can't be read.
70 @MainActor
71 static func moduleTexts(_ file: String, modules: URL) -> [String: String?]? {
72 var seen: [String: String?] = [:]
6273 var pending = [file]
6374 while let path = pending.popLast() {
64 guard seen[path] == nil else { continue }
75 guard !seen.keys.contains(path) else { continue }
6576 #if canImport(WebKit)
6677 let data = CommandHost.Files.file(path, in: modules)
6778 #else
@@ -69,13 +80,13 @@ public enum UserCommandFile {
6980 #endif
7081 guard let data, let text = String(data: data, encoding: .utf8) else {
7182 if path == file { return nil }
72 seen[path] = "(missing)"
83 seen[path] = .some(nil)
7384 continue
7485 }
7586 seen[path] = text
7687 pending += imports(text, from: path)
7788 }
78 return seen.keys.sorted().map { "// \($0)\n\(seen[$0]!)" }.joined(separator: "\n")
89 return seen
7990 }
8091
8192 private static let importPatterns = [
@@ -113,32 +124,75 @@ public enum UserCommandFile {
113124/// The question before a command from a file this device hasn't trusted runs.
114125@MainActor
115126public enum UserCommandTrust {
116 static var runOnce: String { String(localized: "Run Once", comment: "Answer to the question before a user command runs") }
117 static var always: String { String(localized: "Always", comment: "Answer to the question before a user command runs") }
118 static var dontRun: String { String(localized: "Don't Run", comment: "Answer to the question before a user command runs") }
127 public enum Answer: CaseIterable, Sendable {
128 case runOnce, always, dontRun
129
130 public var title: String {
131 switch self {
132 case .runOnce: String(localized: "Run Once", comment: "Answer to the question before a user command runs")
133 case .always: String(localized: "Always", comment: "Answer to the question before a user command runs")
134 case .dontRun: String(localized: "Don't Run", comment: "Answer to the question before a user command runs")
135 }
136 }
137 }
138
139 public struct Question: Equatable, Sendable {
140 /// The command's file, as `commands/review.js`.
141 public let file: String
142 /// The modules it imports, directly or through another, as `commands/lib/dates.js`, in
143 /// path order. Trust covers them with the file.
144 public let imports: [String]
145 /// Its commands can also read every file in the folders and capture to them.
146 public let workspace: Bool
147
148 public init(file: String, imports: [String] = [], workspace: Bool = false) {
149 self.file = file
150 self.imports = imports
151 self.workspace = workspace
152 }
153
154 public var title: String {
155 String(localized: "Run commands from \(file)?", comment: "Asked before a user command from a file not yet trusted on this device runs")
156 }
157
158 /// The modules it imports, if any, and what its commands can do, a line each.
159 public var message: String {
160 var lines: [String] = []
161 if !imports.isEmpty {
162 let list = ListFormatter.localizedString(byJoining: imports)
163 lines.append(String(localized: "It imports \(list).", comment: "The modules a user command's file imports, in the question before it runs"))
164 }
165 lines.append(workspace
166 ? String(localized: "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network.",
167 comment: "What user commands with access to the folders can do, in the question before they run")
168 : String(localized: "They can read and change the file you run them in, and nothing else: no other files and no network.",
169 comment: "What user commands can do, in the question before they run"))
170 return lines.joined(separator: "\n")
171 }
172 }
119173
120174 /// Runs `run` at once when the command's file and its imports are trusted, else asks: Run
121175 /// Once runs it, Always trusts the files as they are now and runs it, anything else says
122176 /// why nothing ran through `refuse`.
123177 public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
124 ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
178 ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
125179 run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
126 guard let text = UserCommandFile.trustedText(command.file, modules: modules) else {
180 guard let texts = UserCommandFile.moduleTexts(command.file, modules: modules) else {
127181 return refuse("No file \(UserCommands.folderName)/\(command.file)")
128182 }
183 let text = UserCommandFile.trustedText(texts)
129184 let path = modules.appendingPathComponent(command.file).path
130185 if trust.isTrusted(path: path, content: text) { return run() }
131 let choices = [runOnce, always, dontRun]
132 let file = "\(UserCommands.folderName)/\(command.file)"
133 let message = String(localized: "Run commands from \(file)?",
134 comment: "Asked before a user command from a file not yet trusted on this device runs")
135 ask(Prompt(key: "confirm", message: message, choices: choices)) { answer in
186 let imports = texts.filter { $0.key != command.file && $0.value != nil }.keys.sorted()
187 let question = Question(file: "\(UserCommands.folderName)/\(command.file)",
188 imports: imports.map { "\(UserCommands.folderName)/\($0)" })
189 ask(question) { answer in
136190 switch answer {
137 case runOnce: run()
138 case always:
191 case .runOnce: run()
192 case .always:
139193 trust.trust(path: path, content: text)
140194 run()
141 default: refuse(String(localized: "Not run"))
195 case .dontRun, nil: refuse(String(localized: "Not run"))
142196 }
143197 }
144198 }
Sources/Orgstar/ContentView.swift +9 −1 · view
@@ -1299,7 +1299,15 @@ struct ContentView: View {
12991299 private func runUserCommand(_ request: UserCommandRequest) {
13001300 guard let path = session.path, let modules = session.userCommands.folder else { return }
13011301 if let refusal = session.refusesUserCommand(path) { return commands.show(refusal) }
1302 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: commands.ask, run: {
1302 let ask: @MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void = { question, reply in
1303 let answers = UserCommandTrust.Answer.allCases
1304 // The echo area's line can cut the path short, so the detail above it repeats it whole.
1305 commands.ask(Prompt(key: "confirm", message: question.title, choices: answers.map(\.title)),
1306 detail: question.title + "\n" + question.message) { answer in
1307 reply(answers.first { $0.title == answer })
1308 }
1309 }
1310 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: {
13031311 guard let context = commands.editor?.context() else { return }
13041312 commands.show(String(localized: "Running \(request.command.title)… (⌘. to cancel)", comment: "A user command started"))
13051313 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: commands.ask) { commands.show($0) }
Sources/Orgstar/Keys.swift +8 · view
@@ -136,6 +136,14 @@ struct PromptView: View {
136136 } else {
137137 let matches = filteredChoices(prompt.choices)
138138 let current = min(selected, matches.count - 1)
139 if let detail = request.detail {
140 Divider()
141 Text(detail)
142 .font(.system(.callout, design: .monospaced))
143 .frame(maxWidth: .infinity, alignment: .leading)
144 .padding(.horizontal, 10)
145 .padding(.vertical, 6)
146 }
139147 if !prompt.choices.isEmpty {
140148 Divider()
141149 ScrollViewReader { proxy in
Sources/Orgstar/OrgstarApp.swift +7 · view
@@ -99,6 +99,11 @@ final class AppCommands {
9999 self.prompt = PromptRequest(prompt: prompt, reply: reply)
100100 }
101101
102 /// Asks with `detail` shown in full above the question.
103 func ask(_ prompt: Prompt, detail: String, reply: @escaping (String?) -> Void) {
104 self.prompt = PromptRequest(prompt: prompt, detail: detail, reply: reply)
105 }
106
102107 /// Clock questions in the echo area.
103108 var askClock: ClockModel.Ask {
104109 { [self] prompt in
@@ -282,6 +287,8 @@ final class AppCommands {
282287struct PromptRequest: Identifiable {
283288 let id = UUID()
284289 let prompt: Prompt
290 /// Lines shown in full above the question.
291 var detail: String? = nil
285292 let reply: (String?) -> Void
286293}
287294
Sources/OrgstarMobile/EditorScreen.swift +24 −1 · view
@@ -59,6 +59,28 @@ struct EditorScreen: View {
5959 let reply: (String?) -> Void
6060 }
6161
62 /// The question before a user command from a file not yet trusted here runs, as an alert.
63 struct TrustRequest {
64 let question: UserCommandTrust.Question
65 let reply: (UserCommandTrust.Answer?) -> Void
66 }
67 @State private var trustRequest: TrustRequest?
68
69 struct TrustAlert: ViewModifier {
70 @Binding var request: TrustRequest?
71
72 func body(content: Content) -> some View {
73 content.alert(request?.question.title ?? "", isPresented: Binding(get: { request != nil }, set: { if !$0 { request = nil } }),
74 presenting: request) { request in
75 ForEach(UserCommandTrust.Answer.allCases, id: \.self) { answer in
76 Button(answer.title, role: answer == .dontRun ? .cancel : nil) { request.reply(answer) }
77 }
78 } message: { request in
79 Text(request.question.message)
80 }
81 }
82 }
83
6284 /// One sheet at a time: two presenters on this screen interfere.
6385 /// `org-table-import`'s file picker is up.
6486 @State private var importingTable = false
@@ -219,6 +241,7 @@ struct EditorScreen: View {
219241 request.reply(answer)
220242 }
221243 }
244 .modifier(TrustAlert(request: $trustRequest))
222245 .sheet(item: $sheet, onDismiss: {
223246 // An encrypted file opened with its passphrase.
224247 if editor == nil, session.isOpen(path) { start() }
@@ -425,7 +448,7 @@ struct EditorScreen: View {
425448 guard let modules = session.userCommands.folder else { return }
426449 if let refusal = session.refusesUserCommand(path) { return message = refusal }
427450 let ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { prompt = PromptRequest(prompt: $0, reply: $1) }
428 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: {
451 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: { trustRequest = TrustRequest(question: $0, reply: $1) }, run: {
429452 guard let context = editor?.editContext() else { return }
430453 message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad")
431454 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: ask) { message = $0 }
Tests/OrgAppTests/UserCommandRunTests.swift +38 −10 · view
@@ -233,26 +233,26 @@ struct UserCommandFileTests {
233233 let modules = config.url.appendingPathComponent("commands")
234234 let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
235235 let command = UserCommand(name: "go", title: "Go", file: "main.js", function: "go")
236 var asked: [String] = []
236 var asked: [UserCommandTrust.Question] = []
237237 var runs = 0
238238 var refusals: [String] = []
239 func check(_ answer: String?) {
240 UserCommandTrust.check(command, modules: modules, trust: trust, ask: { prompt, reply in
241 asked.append(prompt.message)
239 func check(_ answer: UserCommandTrust.Answer?) {
240 UserCommandTrust.check(command, modules: modules, trust: trust, ask: { question, reply in
241 asked.append(question)
242242 reply(answer)
243243 }, run: { runs += 1 }, refuse: { refusals.append($0) })
244244 }
245 check(UserCommandTrust.dontRun)
245 check(.dontRun)
246246 #expect(runs == 0 && refusals == ["Not run"])
247 #expect(asked == ["Run commands from commands/main.js?"])
248 check(UserCommandTrust.runOnce)
249 check(UserCommandTrust.runOnce)
247 #expect(asked == [UserCommandTrust.Question(file: "commands/main.js", imports: ["commands/lib.js"])])
248 check(.runOnce)
249 check(.runOnce)
250250 #expect(runs == 2 && asked.count == 3)
251 check(UserCommandTrust.always)
251 check(.always)
252252 check(nil)
253253 #expect(runs == 4 && asked.count == 4)
254254 try config.write("commands/lib.js", "export const x = 1;\n")
255 check(UserCommandTrust.always)
255 check(.always)
256256 #expect(runs == 5 && asked.count == 5)
257257 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return 2; }\n")
258258 check(nil)
@@ -262,6 +262,34 @@ struct UserCommandFileTests {
262262 check(nil)
263263 #expect(runs == 6)
264264 #expect(UserCommandFile.trustedText("gone.js", modules: modules) == nil)
265 #expect(UserCommandFile.trustedText("main.js", modules: modules)
266 == "// lib.js\nexport const x = 1;\n\n// main.js\nimport { x } from \"./lib.js\";\nexport function go() { return x; }\n")
267 }
268
269 /// The question names the file and every module it imports, through other modules too;
270 /// one that can't be read isn't listed.
271 @Test func theTrustQuestionListsTheImportedModules() throws {
272 let config = try Folder()
273 try config.write("commands/tools/main.js", "import { a } from \"../lib/a.js\";\nimport \"./gone.js\";\nexport function go() {}\n")
274 try config.write("commands/lib/a.js", "export { b } from \"./b.js\";\nexport const a = 1;\n")
275 try config.write("commands/lib/b.js", "export const b = 2;\n")
276 let modules = config.url.appendingPathComponent("commands")
277 let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
278 var asked: [UserCommandTrust.Question] = []
279 UserCommandTrust.check(UserCommand(name: "go", title: "Go", file: "tools/main.js", function: "go"), modules: modules, trust: trust,
280 ask: { question, _ in asked.append(question) }, run: {}, refuse: { _ in })
281 #expect(asked == [UserCommandTrust.Question(file: "commands/tools/main.js", imports: ["commands/lib/a.js", "commands/lib/b.js"])])
282 #expect(asked.first?.title == "Run commands from commands/tools/main.js?")
283
284 let question = UserCommandTrust.Question(file: "commands/review.js", imports: ["commands/lib/dates.js"])
285 #expect(question.message == """
286 It imports commands/lib/dates.js.
287 They can read and change the file you run them in, and nothing else: no other files and no network.
288 """)
289 #expect(UserCommandTrust.Question(file: "commands/review.js").message
290 == "They can read and change the file you run them in, and nothing else: no other files and no network.")
291 #expect(UserCommandTrust.Question(file: "commands/review.js", workspace: true).message
292 == "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network.")
265293 }
266294
267295 @Test func emacsImportNotesBindingsToTheUsersFunctions() throws {
docs/manual/guide/18-user-commands.org +3 −1 · view
@@ -175,9 +175,11 @@ The first time you run a command from a file, orgstar asks:
175175
176176#+BEGIN_EXAMPLE
177177Run commands from commands/review.js?
178It imports commands/lib/dates.js.
179They can read and change the file you run them in, and nothing else: no other files and no network.
178180#+END_EXAMPLE
179181
180A command can read and change the file you run it in, and nothing else (see [[*Limits][Limits]]). The answers are Run Once, Always and Don't Run:
182The question names the file's full path under =commands/= and every module it imports, directly or through another module; the line about imports is left out when there are none. On the Mac the question is in the echo area, with the answers listed above it; on iPhone and iPad it is an alert. [[*Limits][Limits]] has the details of what a command can't reach. The answers are Run Once, Always and Don't Run:
181183
182184- Run Once runs it this time and asks again next time.
183185- Always runs it and doesn't ask again while the file and every module it imports stay as they are.
l10n/Localizable.xcstrings +105 · view
@@ -25378,6 +25378,41 @@
2537825378 }
2537925379 }
2538025380 },
25381 "It imports %@.": {
25382 "comment": "The modules a user command's file imports, in the question before it runs",
25383 "localizations": {
25384 "de": {
25385 "stringUnit": {
25386 "state": "translated",
25387 "value": "Die Datei importiert %@."
25388 }
25389 },
25390 "es": {
25391 "stringUnit": {
25392 "state": "translated",
25393 "value": "El archivo importa %@."
25394 }
25395 },
25396 "fr": {
25397 "stringUnit": {
25398 "state": "translated",
25399 "value": "Le fichier importe %@."
25400 }
25401 },
25402 "ja": {
25403 "stringUnit": {
25404 "state": "translated",
25405 "value": "%@ をインポートしています。"
25406 }
25407 },
25408 "pt-BR": {
25409 "stringUnit": {
25410 "state": "translated",
25411 "value": "O arquivo importa %@."
25412 }
25413 }
25414 }
25415 },
2538125416 "It isn't in one of your folders. Grant access to it to continue.": {
2538225417 "comment": "Alert for a folder outside the sidebar's folders",
2538325418 "localizations": {
@@ -51045,6 +51080,76 @@
5104551080 }
5104651081 }
5104751082 },
51083 "They can read and change the file you run them in, and nothing else: no other files and no network.": {
51084 "comment": "What user commands can do, in the question before they run",
51085 "localizations": {
51086 "de": {
51087 "stringUnit": {
51088 "state": "translated",
51089 "value": "Die Befehle können die Datei lesen und ändern, in der du sie ausführst, und sonst nichts: keine anderen Dateien und kein Netzwerk."
51090 }
51091 },
51092 "es": {
51093 "stringUnit": {
51094 "state": "translated",
51095 "value": "Pueden leer y modificar el archivo en el que los ejecutas, y nada más: ni otros archivos ni la red."
51096 }
51097 },
51098 "fr": {
51099 "stringUnit": {
51100 "state": "translated",
51101 "value": "Elles peuvent lire et modifier le fichier dans lequel vous les exécutez, et rien d'autre : ni autres fichiers, ni réseau."
51102 }
51103 },
51104 "ja": {
51105 "stringUnit": {
51106 "state": "translated",
51107 "value": "コマンドは実行したファイルを読み取って変更できますが、それ以外はできません。ほかのファイルやネットワークは使えません。"
51108 }
51109 },
51110 "pt-BR": {
51111 "stringUnit": {
51112 "state": "translated",
51113 "value": "Eles podem ler e alterar o arquivo em que você os executa, e nada mais: nenhum outro arquivo e nenhuma rede."
51114 }
51115 }
51116 }
51117 },
51118 "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network.": {
51119 "comment": "What user commands with access to the folders can do, in the question before they run",
51120 "localizations": {
51121 "de": {
51122 "stringUnit": {
51123 "state": "translated",
51124 "value": "Die Befehle können die Datei lesen und ändern, in der du sie ausführst, jede Datei in deinen Ordnern lesen und darin erfassen, aber nicht das Netzwerk nutzen."
51125 }
51126 },
51127 "es": {
51128 "stringUnit": {
51129 "state": "translated",
51130 "value": "Pueden leer y modificar el archivo en el que los ejecutas, leer todos los archivos de tus carpetas y capturar en ellos, pero no usar la red."
51131 }
51132 },
51133 "fr": {
51134 "stringUnit": {
51135 "state": "translated",
51136 "value": "Elles peuvent lire et modifier le fichier dans lequel vous les exécutez, lire tous les fichiers de vos dossiers et y capturer, mais pas utiliser le réseau."
51137 }
51138 },
51139 "ja": {
51140 "stringUnit": {
51141 "state": "translated",
51142 "value": "コマンドは実行したファイルの読み取りと変更、フォルダ内のすべてのファイルの読み取りとキャプチャができますが、ネットワークは使えません。"
51143 }
51144 },
51145 "pt-BR": {
51146 "stringUnit": {
51147 "state": "translated",
51148 "value": "Eles podem ler e alterar o arquivo em que você os executa, ler todos os arquivos das suas pastas e capturar neles, mas não usar a rede."
51149 }
51150 }
51151 }
51152 },
5104851153 "Third-Party Notices": {
5104951154 "localizations": {
5105051155 "de": {
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form