Sources/OrgApp/CommandHost.swift
461 lines · 21315 bytes
1#if canImport(WebKit)
2import Foundation
3import WebKit
4
5/// Runs user commands: ES modules in the configuration folder's `commands/`, each run in a new
6/// web worker of a hidden web view. Nothing else is reachable from a command. The page, the
7/// worker and the modules come from `Files`, which serves only files under `commands/`; every
8/// response carries a Content-Security-Policy allowing scripts from this scheme alone; a content
9/// rule list blocks every other load; and the worker deletes `fetch`, `XMLHttpRequest` and the
10/// other ways out before the command's module loads.
11///
12/// A worker is started ahead of each run, so a run waits only for its modules; the worker is
13/// ended after the run, so no state or module survives into the next. A run that passes its
14/// timeout or is canceled ends its worker, which stops it wherever it is. The web view goes after
15/// `idle` without a run or `prepare()`, and when its content process ends.
16@MainActor
17public final class CommandHost {
18 public enum Failure: Error, Equatable {
19 /// The run passed its time limit and was stopped.
20 case timedOut(Duration)
21 /// The command threw, or its module or function wasn't found.
22 case script(String)
23 /// The web view's content process ended, as when a command uses up its memory.
24 case stopped
25 }
26
27 public static let defaultTimeout: Duration = .seconds(2)
28 public static let maximumTimeout: Duration = .seconds(30)
29 static let scheme = "orgstar-commands"
30
31 /// The `commands` folder.
32 public let folder: URL
33 let idle: Duration
34 /// Answers a command's call to the app: a name and a JSON value, replying with a JSON value or
35 /// throwing to reject the call. Time spent here doesn't count against the run's timeout.
36 public var calls: @MainActor (String, Any) async throws -> Any = { name, _ in throw Failure.script("No call \(name).") }
37
38 var engine: Engine?
39 private var idleTask: Task<Void, Never>?
40 private var next = 0
41
42 public init(folder: URL, idle: Duration = .seconds(300)) {
43 self.folder = folder
44 self.idle = idle
45 }
46
47 isolated deinit {
48 idleTask?.cancel()
49 engine?.close()
50 }
51
52 /// Starts the web view and a worker, if they aren't running, so the next run needn't wait.
53 public func prepare() {
54 idleTask?.cancel()
55 let engine = started()
56 Task { [weak self] in
57 try? await engine.loaded.value
58 _ = try? await engine.webView?.callAsyncJavaScript("prepare();", contentWorld: .page)
59 if self?.engine === engine, engine.runs.isEmpty { self?.scheduleIdle() }
60 }
61 }
62
63 /// Ends the web view; a run in progress fails as `.stopped`.
64 public func unload() {
65 idleTask?.cancel()
66 guard let engine else { return }
67 self.engine = nil
68 engine.close()
69 }
70
71 /// Calls `function` exported by `module`, a path in `commands/`, with the JSON `context` and a
72 /// function the command calls the app with, and returns its result as JSON. With `api`, the
73 /// function gets that version's `org` object instead, whose calls reach `calls`, and then
74 /// `context` unless it is `null`. `timeout` is at most `maximumTimeout`. `answer`, when
75 /// given, answers this run's calls in place of `calls`.
76 public func run(module: String, function: String, context: String, timeout: Duration = defaultTimeout, api: Int? = nil,
77 answer: (@MainActor (String, Any) async throws -> Any)? = nil) async throws -> String {
78 guard Files.relative(module) != nil else { throw Failure.script("No module \(module) in commands/.") }
79 let limit = min(timeout, Self.maximumTimeout)
80 idleTask?.cancel()
81 let engine = started()
82 next += 1
83 let id = next
84 defer { if self.engine === engine, engine.runs.isEmpty { scheduleIdle() } }
85 do {
86 try await engine.loaded.value
87 } catch {
88 if self.engine === engine { unload() }
89 throw Failure.stopped
90 }
91 try Task.checkCancellation()
92 let run = Run(limit: limit, answer: answer)
93 engine.runs[id] = run
94 defer { engine.runs[id] = nil }
95 let reply: String
96 do {
97 reply = try await withTaskCancellationHandler {
98 try await withCheckedThrowingContinuation { continuation in
99 run.start(continuation)
100 Task { @MainActor in
101 do {
102 let reply = try await engine.webView?.callAsyncJavaScript(
103 "return await run(id, module, name, context, api);",
104 arguments: ["id": id, "module": module, "name": function, "context": context, "api": api ?? 0],
105 contentWorld: .page
106 )
107 run.end(.success(reply as? String ?? ""))
108 } catch {
109 run.end(.failure(Failure.stopped))
110 }
111 }
112 }
113 } onCancel: {
114 Task { @MainActor in run.end(.failure(CancellationError())) }
115 }
116 } catch {
117 // Not awaited: a page whose process has stopped answering would never reply.
118 engine.webView?.callAsyncJavaScript("stop(id);", arguments: ["id": id], in: nil, in: .page)
119 throw error
120 }
121 guard let object = try? JSONSerialization.jsonObject(with: Data(reply.utf8)) as? [String: Any] else { throw Failure.stopped }
122 if let result = object["result"] as? String { return result }
123 if let message = object["error"] as? String { throw Failure.script(message) }
124 throw Failure.stopped
125 }
126
127 private func started() -> Engine {
128 if let engine { return engine }
129 let engine = Engine(folder: folder, host: self)
130 self.engine = engine
131 return engine
132 }
133
134 private func scheduleIdle() {
135 idleTask?.cancel()
136 idleTask = Task { [weak self, idle] in
137 guard (try? await Task.sleep(for: idle)) != nil, let self, self.engine?.runs.isEmpty != false else { return }
138 self.unload()
139 }
140 }
141
142 func terminated(_ engine: Engine) {
143 if self.engine === engine { unload() } else { engine.close() }
144 }
145
146 func call(_ name: String, _ value: Any, run: Run) async throws -> Any {
147 try await (run.answer ?? calls)(name, value)
148 }
149
150 /// A run, which ends once: with the worker's reply, a cancel, the timeout or the end of the
151 /// web view. The time limit stands still while the app answers a call.
152 @MainActor
153 final class Run {
154 let limit: Duration
155 /// Answers this run's calls in place of the host's `calls`.
156 let answer: (@MainActor (String, Any) async throws -> Any)?
157 private var remaining: Duration
158 private var since = ContinuousClock.now
159 private var timer: Task<Void, Never>?
160 private var calls = 0
161 private(set) var ended = false
162 private var continuation: CheckedContinuation<String, Error>?
163
164 init(limit: Duration, answer: (@MainActor (String, Any) async throws -> Any)? = nil) {
165 self.limit = limit
166 self.answer = answer
167 remaining = limit
168 }
169
170 func start(_ continuation: CheckedContinuation<String, Error>) {
171 self.continuation = continuation
172 startTimer()
173 }
174
175 func end(_ outcome: Result<String, Error>) {
176 guard !ended else { return }
177 ended = true
178 timer?.cancel()
179 continuation?.resume(with: outcome)
180 continuation = nil
181 }
182
183 func pause() {
184 calls += 1
185 guard calls == 1 else { return }
186 timer?.cancel()
187 remaining -= ContinuousClock.now - since
188 }
189
190 func resume() {
191 calls -= 1
192 if calls == 0, !ended { startTimer() }
193 }
194
195 private func startTimer() {
196 since = .now
197 timer = Task { [weak self, remaining, limit] in
198 guard (try? await Task.sleep(for: remaining)) != nil else { return }
199 self?.end(.failure(Failure.timedOut(limit)))
200 }
201 }
202 }
203
204 /// The hidden web view and its page, which keeps one worker ready.
205 @MainActor
206 final class Engine: NSObject, WKNavigationDelegate, WKScriptMessageHandlerWithReply {
207 weak var host: CommandHost?
208 private(set) var webView: WKWebView?
209 var runs: [Int: Run] = [:]
210 private(set) var loaded: Task<Void, Error>!
211 private var loading: CheckedContinuation<Void, Error>?
212 private var closed = false
213
214 init(folder: URL, host: CommandHost) {
215 self.host = host
216 super.init()
217 loaded = Task { try await start(folder) }
218 }
219
220 private func start(_ folder: URL) async throws {
221 let rules = try await Engine.rules()
222 guard !closed else { throw CancellationError() }
223 let configuration = WKWebViewConfiguration()
224 configuration.setURLSchemeHandler(Files(folder: folder), forURLScheme: CommandHost.scheme)
225 configuration.websiteDataStore = .nonPersistent()
226 configuration.userContentController.add(rules)
227 configuration.userContentController.addScriptMessageHandler(self, contentWorld: .page, name: "commands")
228 let webView = WKWebView(frame: .zero, configuration: configuration)
229 webView.navigationDelegate = self
230 self.webView = webView
231 try await withCheckedThrowingContinuation { continuation in
232 loading = continuation
233 webView.load(URLRequest(url: URL(string: "\(CommandHost.scheme)://host/index.html")!))
234 }
235 }
236
237 func close() {
238 closed = true
239 for run in runs.values { run.end(.failure(Failure.stopped)) }
240 runs = [:]
241 finishLoading(.failure(CancellationError()))
242 webView?.stopLoading()
243 webView?.navigationDelegate = nil
244 webView?.configuration.userContentController.removeAllScriptMessageHandlers()
245 webView = nil
246 }
247
248 private func finishLoading(_ result: Result<Void, Error>) {
249 loading?.resume(with: result)
250 loading = nil
251 }
252
253 /// Blocks every load but this scheme's, as a second layer under the page's policy.
254 static let ruleList = """
255 [{"trigger": {"url-filter": ".*"}, "action": {"type": "block"}},
256 {"trigger": {"url-filter": "^orgstar-commands://host/"}, "action": {"type": "ignore-previous-rules"}}]
257 """
258 private static var compiling: Task<WKContentRuleList, Error>?
259
260 static func rules() async throws -> WKContentRuleList {
261 let task = compiling ?? Task {
262 guard let list = try await WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "orgstar-commands", encodedContentRuleList: ruleList)
263 else { throw Failure.stopped }
264 return list
265 }
266 compiling = task
267 do {
268 return try await task.value
269 } catch {
270 compiling = nil
271 throw error
272 }
273 }
274
275 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void) {
276 decisionHandler(navigationAction.request.url?.scheme == CommandHost.scheme ? .allow : .cancel)
277 }
278
279 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finishLoading(.success(())) }
280 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finishLoading(.failure(error)) }
281 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finishLoading(.failure(error)) }
282 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
283 host?.terminated(self)
284 }
285
286 /// A call from a command, which the page passes on with its run's id.
287 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) async -> (Any?, String?) {
288 guard let body = message.body as? [String: Any], let id = body["run"] as? Int, let name = body["name"] as? String,
289 let run = runs[id], !run.ended, let host
290 else { return (nil, "The command was stopped.") }
291 run.pause()
292 defer { run.resume() }
293 do {
294 return (try await host.call(name, body["value"] ?? NSNull(), run: run), nil)
295 } catch let Failure.script(message) {
296 return (nil, message)
297 } catch {
298 return (nil, error.localizedDescription)
299 }
300 }
301 }
302
303 /// Serves the page and the worker, and the modules in `commands/`, and nothing else.
304 @MainActor
305 final class Files: NSObject, WKURLSchemeHandler {
306 let folder: URL
307 static let policy = "default-src 'none'; script-src orgstar-commands:"
308
309 init(folder: URL) { self.folder = folder }
310
311 /// The parts of a path in `commands/`, or nil when it isn't one: a part that is empty, `.`
312 /// or `..`, or a file that isn't `.js` or `.mjs`.
313 static func relative(_ path: String) -> [Substring]? {
314 let parts = path.split(separator: "/", omittingEmptySubsequences: false)
315 guard parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains(where: { "?#%\\".contains($0) }) }),
316 let last = parts.last, last.hasSuffix(".js") || last.hasSuffix(".mjs")
317 else { return nil }
318 return parts
319 }
320
321 /// The file at `path` in `folder`, once symlinks are resolved, when it is still in `folder`.
322 static func file(_ path: String, in folder: URL) -> Data? {
323 guard let parts = relative(path),
324 let root = realpath(folder.path, nil).map({ defer { free($0) }; return String(cString: $0) }),
325 let file = realpath(parts.reduce(folder) { $0.appendingPathComponent(String($1)) }.path, nil)
326 .map({ defer { free($0) }; return String(cString: $0) }),
327 file.hasPrefix(root.hasSuffix("/") ? root : root + "/")
328 else { return nil }
329 var directory: ObjCBool = false
330 guard FileManager.default.fileExists(atPath: file, isDirectory: &directory), !directory.boolValue else { return nil }
331 return FileManager.default.contents(atPath: file)
332 }
333
334 func webView(_ webView: WKWebView, start task: any WKURLSchemeTask) {
335 guard let url = task.request.url, url.host == "host" else { return task.didFailWithError(URLError(.fileDoesNotExist)) }
336 let path = url.path
337 let file: (Data, String)?
338 switch path {
339 case "/index.html": file = (Data(Self.page.utf8), "text/html")
340 case "/host.js": file = (Data(Self.host.utf8), "text/javascript")
341 case "/worker.js": file = (Data(Self.worker.utf8), "text/javascript")
342 default:
343 file = path.hasPrefix("/commands/") ? Self.file(String(path.dropFirst("/commands/".count)), in: folder).map { ($0, "text/javascript") } : nil
344 }
345 guard let (data, type) = file else { return task.didFailWithError(URLError(.fileDoesNotExist)) }
346 task.didReceive(HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [
347 "Content-Type": type, "Content-Length": String(data.count),
348 "Content-Security-Policy": Self.policy, "Cache-Control": "no-store",
349 ])!)
350 task.didReceive(data)
351 task.didFinish()
352 }
353
354 func webView(_ webView: WKWebView, stop task: any WKURLSchemeTask) {}
355
356 static let page = "<!doctype html><meta charset=\"utf-8\"><script src=\"host.js\"></script>"
357
358 /// `run` gives the ready worker a command and starts the next; the run's result, error or
359 /// stop ends its worker. Calls from the worker go to the app with the run's id.
360 static let host = """
361 "use strict";
362 let ready = null;
363 const runs = new Map();
364 function prepare() {
365 if (!ready) ready = new Worker("worker.js", { type: "module" });
366 }
367 function finish(id, reply) {
368 const run = runs.get(id);
369 if (!run) return;
370 runs.delete(id);
371 run.worker.terminate();
372 run.resolve(JSON.stringify(reply));
373 }
374 function run(id, module, name, context, api) {
375 prepare();
376 const worker = ready;
377 ready = null;
378 prepare();
379 return new Promise(resolve => {
380 runs.set(id, { worker, resolve });
381 worker.onmessage = async e => {
382 const m = e.data;
383 if (m.kind !== "call") return finish(id, { result: m.result, error: m.error });
384 let reply;
385 try {
386 reply = { seq: m.seq, value: await window.webkit.messageHandlers.commands.postMessage({ run: id, name: m.name, value: m.value }) };
387 } catch (error) {
388 reply = { seq: m.seq, error: String(error && error.message || error) };
389 }
390 if (runs.has(id)) worker.postMessage(reply);
391 };
392 worker.onerror = e => { e.preventDefault(); finish(id, { error: e.message || "The command didn't start." }); };
393 worker.postMessage({ module, name, context, api });
394 });
395 }
396 function stop(id) { finish(id, {}); }
397 """
398
399 /// Removes the ways out of the worker, then waits for a command: imports its module, calls
400 /// the function with the context and `call`, or for API version 1 with `org` and the
401 /// context unless it is null, and posts the result as JSON.
402 static let worker = """
403 const post = self.postMessage.bind(self);
404 for (const name of ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker", "SharedWorker"]) {
405 for (let o = self; o; o = Object.getPrototypeOf(o)) delete o[name];
406 }
407 let calls = 0;
408 const waiting = new Map();
409 function call(name, value) {
410 const seq = calls++;
411 return new Promise((resolve, reject) => {
412 waiting.set(seq, { resolve, reject });
413 post({ kind: "call", seq, name, value });
414 });
415 }
416 function api1() {
417 const fail = async text => {
418 await call("fail", String(text));
419 throw new Error(String(text));
420 };
421 return Object.freeze({
422 version: 1,
423 text: () => call("text", null),
424 selection: () => call("selection", null),
425 heading: at => call("heading", at ?? null),
426 outline: () => call("outline", null),
427 file: () => call("file", null),
428 settings: () => call("settings", null),
429 prompt: options => call("prompt", typeof options === "string" ? { message: options } : options ?? {}),
430 message: text => call("message", String(text)),
431 run: id => call("run", String(id)),
432 search: query => call("search", String(query)),
433 outlineOf: path => call("outlineOf", String(path)),
434 agenda: span => call("agenda", span ?? {}),
435 capture: (template, text, fields) => call("capture", { template: String(template), text: text ?? null, fields: fields ?? null }),
436 fail,
437 });
438 }
439 self.onmessage = async e => {
440 const m = e.data;
441 if (m.seq !== undefined) {
442 const w = waiting.get(m.seq);
443 waiting.delete(m.seq);
444 if (w) m.error !== undefined ? w.reject(new Error(m.error)) : w.resolve(m.value);
445 return;
446 }
447 try {
448 const module = await import("./commands/" + m.module);
449 if (typeof module[m.name] !== "function") throw new Error(`${m.module} exports no function ${m.name}.`);
450 const context = JSON.parse(m.context);
451 const value = await module[m.name](...(m.api === 1 ? [api1(), ...(context === null ? [] : [context])] : [context, call]));
452 post({ result: JSON.stringify(value) ?? "null" });
453 } catch (error) {
454 post({ error: String(error && error.message || error) });
455 }
456 };
457 """
458 }
459}
460#endif
461