Sources/OrgApp/CommandHost.swift

61025559a3989ea7536dda296a9e27ddc7909aac
orgstar/Sources/OrgApp/CommandHost.swift

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