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