Command host: user commands in a sandboxed web worker !526

merged merged by cmc on 2026-11-27 08:01 UTC · krz/orgstar:issue-244-command-host into main

2 files changed, +712 −0

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

Layout: unified · split

Changed files (2)
Sources/OrgApp/CommandHost.swift added +430 · view
@@ -0,0 +1,430 @@
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
Tests/OrgAppTests/CommandHostTests.swift added +282 · view
@@ -0,0 +1,282 @@
1import Foundation
2import Network
3import Testing
4import WebKit
5@testable import OrgApp
6
7/// A local port that counts the connections made to it, to show a load never left the web view.
8final class Listener: @unchecked Sendable {
9 private let listener: NWListener
10 private let counter = Counter()
11 let port: UInt16
12 var connections: Int { counter.value }
13 var url: String { "http://127.0.0.1:\(port)/" }
14
15 final class Counter: @unchecked Sendable {
16 private let lock = NSLock()
17 private var count = 0
18 var value: Int { lock.withLock { count } }
19 func add() { lock.withLock { count += 1 } }
20 }
21
22 init() async throws {
23 let parameters = NWParameters.tcp
24 parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any)
25 let listener = try NWListener(using: parameters)
26 let counter = counter
27 listener.newConnectionHandler = { connection in
28 counter.add()
29 connection.cancel()
30 }
31 let ready = AsyncStream<UInt16> { continuation in
32 listener.stateUpdateHandler = { state in
33 if case .ready = state { continuation.yield(listener.port?.rawValue ?? 0); continuation.finish() }
34 }
35 }
36 listener.start(queue: .global())
37 var port: UInt16 = 0
38 for await value in ready { port = value }
39 self.listener = listener
40 self.port = port
41 }
42
43 deinit { listener.cancel() }
44}
45
46@MainActor
47@Suite(.serialized)
48struct CommandHostTests {
49 let folder: Folder
50 let host: CommandHost
51
52 init() throws {
53 folder = try Folder()
54 host = CommandHost(folder: folder.url.appendingPathComponent("commands"))
55 try folder.write("commands/util.js", "export const twice = s => s + s;\n")
56 try folder.write("commands/main.js", """
57 import { twice } from "./util.js";
58 export function echo(context) { return context; }
59 export async function double(context) { return { text: twice(context.text) }; }
60 export function nothing() {}
61 export function fails() { throw new Error("no heading here"); }
62 export function loop() { for (;;) {} }
63 export function counter() { globalThis.count = (globalThis.count ?? 0) + 1; return globalThis.count; }
64 export async function ask(context, call) { return [await call("prompt", context), await call("message", "hi")]; }
65 export async function refused(context, call) {
66 try { await call("nope", null); } catch (e) { return "caught " + e.message; }
67 }
68 export async function waits(context, call) { await call("wait", null); return "done"; }
69 """)
70 }
71
72 @Test func runsAnExportedFunction() async throws {
73 #expect(try await host.run(module: "main.js", function: "double", context: #"{"text": "ab"}"#) == #"{"text":"abab"}"#)
74 #expect(try await host.run(module: "main.js", function: "echo", context: #"[1, "é", null]"#) == #"[1,"é",null]"#)
75 #expect(try await host.run(module: "main.js", function: "nothing", context: "{}") == "null")
76 await #expect(throws: CommandHost.Failure.script("no heading here")) {
77 _ = try await host.run(module: "main.js", function: "fails", context: "{}")
78 }
79 await #expect(throws: CommandHost.Failure.script("main.js exports no function absent.")) {
80 _ = try await host.run(module: "main.js", function: "absent", context: "{}")
81 }
82 await #expect(throws: CommandHost.Failure.script("No module ../main.js in commands/.")) {
83 _ = try await host.run(module: "../main.js", function: "echo", context: "{}")
84 }
85 }
86
87 /// Each run has a new worker: nothing a command leaves in the global scope reaches the next,
88 /// and a changed file is read again.
89 @Test func runsDontShareState() async throws {
90 #expect(try await host.run(module: "main.js", function: "counter", context: "{}") == "1")
91 #expect(try await host.run(module: "main.js", function: "counter", context: "{}") == "1")
92 try folder.write("commands/util.js", "export const twice = s => s + s + s;\n")
93 #expect(try await host.run(module: "main.js", function: "double", context: #"{"text": "a"}"#) == #"{"text":"aaa"}"#)
94 }
95
96 @Test func callsTheApp() async throws {
97 var seen: [String] = []
98 host.calls = { name, value in
99 seen.append(name)
100 switch name {
101 case "prompt": return "answer to \((value as? [String: Any])?["message"] ?? "")"
102 case "message": return NSNull()
103 default: throw CommandHost.Failure.script("No call \(name).")
104 }
105 }
106 #expect(try await host.run(module: "main.js", function: "ask", context: #"{"message": "Week"}"#) == #"["answer to Week",null]"#)
107 #expect(seen == ["prompt", "message"])
108 #expect(try await host.run(module: "main.js", function: "refused", context: "{}") == #""caught No call nope.""#)
109 }
110
111 /// Time the app spends answering a call, as in a prompt, isn't counted.
112 @Test func timeInACallDoesntCount() async throws {
113 host.calls = { _, _ in
114 try await Task.sleep(for: .milliseconds(1500))
115 return NSNull()
116 }
117 #expect(try await host.run(module: "main.js", function: "waits", context: "{}", timeout: .seconds(1)) == #""done""#)
118 }
119
120 @Test func stopsAnEndlessLoopAndRunsAgain() async throws {
121 let start = ContinuousClock.now
122 await #expect(throws: CommandHost.Failure.timedOut(.seconds(1))) {
123 _ = try await host.run(module: "main.js", function: "loop", context: "{}", timeout: .seconds(1))
124 }
125 #expect(try await host.run(module: "main.js", function: "echo", context: "7") == "7")
126 // The same web view: only the worker was ended.
127 #expect(host.engine != nil)
128 #expect(ContinuousClock.now - start < .seconds(10))
129 }
130
131 @Test func cancels() async throws {
132 let task = Task { try await host.run(module: "main.js", function: "loop", context: "{}", timeout: .seconds(30)) }
133 try await Task.sleep(for: .milliseconds(300))
134 task.cancel()
135 await #expect(throws: CancellationError.self) { _ = try await task.value }
136 #expect(try await host.run(module: "main.js", function: "echo", context: "8") == "8")
137 }
138
139 @Test func importsOnlyFromTheCommandsFolder() async throws {
140 try folder.write("outside.js", "export const secret = 1;\n")
141 try folder.write("commands/escape.js", """
142 export async function parent() { return (await import("../outside.js")).secret; }
143 export async function absolute() { return (await import("/outside.js")).secret; }
144 export async function file(path) { return (await import("file://" + path)).secret; }
145 export async function data() { return (await import("data:text/javascript,export const secret = 1")).secret; }
146 """)
147 for function in ["parent", "absolute", "data"] {
148 await #expect(throws: CommandHost.Failure.self, "\(function)") {
149 _ = try await host.run(module: "escape.js", function: function, context: "{}")
150 }
151 }
152 await #expect(throws: CommandHost.Failure.self) {
153 _ = try await host.run(module: "escape.js", function: "file", context: "\"\(folder.url.appendingPathComponent("outside.js").path)\"")
154 }
155 }
156
157 @Test func refusesSymlinksOutOfTheCommandsFolder() async throws {
158 try folder.write("secret.js", "export function echo(c) { return c; }\n")
159 try folder.write("lib/inner.js", "export function echo(c) { return c; }\n")
160 let commands = folder.url.appendingPathComponent("commands")
161 try FileManager.default.createSymbolicLink(atPath: commands.appendingPathComponent("link.js").path, withDestinationPath: "../secret.js")
162 try FileManager.default.createSymbolicLink(atPath: commands.appendingPathComponent("lib").path, withDestinationPath: folder.url.appendingPathComponent("lib").path)
163 try FileManager.default.createSymbolicLink(atPath: commands.appendingPathComponent("same.js").path, withDestinationPath: "main.js")
164 await #expect(throws: CommandHost.Failure.self) { _ = try await host.run(module: "link.js", function: "echo", context: "1") }
165 await #expect(throws: CommandHost.Failure.self) { _ = try await host.run(module: "lib/inner.js", function: "echo", context: "1") }
166 #expect(try await host.run(module: "same.js", function: "echo", context: "1") == "1")
167 #expect(CommandHost.Files.file("link.js", in: commands) == nil)
168 #expect(CommandHost.Files.file("lib/inner.js", in: commands) == nil)
169 #expect(CommandHost.Files.file("main.js", in: commands) != nil)
170 #expect(CommandHost.Files.file("../secret.js", in: commands) == nil)
171 #expect(CommandHost.Files.file("util.txt", in: commands) == nil)
172 }
173
174 /// The worker has none of the ways out, and nothing reaches a local port: not from a command,
175 /// not from a worker with its globals intact, not from the page.
176 @Test func reachesNoNetwork() async throws {
177 let listener = try await Listener()
178 try folder.write("commands/net.js", """
179 export function globals() {
180 return ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker"].filter(n => n in self);
181 }
182 export async function load(url) { return (await import(url)).x; }
183 export async function fetched(url) { return await fetch(url); }
184 export async function requested(url) { const r = new XMLHttpRequest(); r.open("GET", url, false); r.send(); }
185 export async function socket(url) { new WebSocket(url.replace("http", "ws")); }
186 """)
187 try folder.write("commands/probe.js", """
188 const url = "\(listener.url)";
189 const tries = [
190 () => fetch(url, { mode: "no-cors" }),
191 () => { const r = new XMLHttpRequest(); r.open("GET", url, false); r.send(); },
192 () => new WebSocket(url.replace("http", "ws")),
193 () => new EventSource(url),
194 () => import(url + "x.js"),
195 ];
196 Promise.allSettled(tries.map(t => { try { return Promise.resolve(t()); } catch (e) { return Promise.reject(e); } }))
197 .then(r => postMessage(r.map(x => x.status)));
198 """)
199 #expect(try await host.run(module: "net.js", function: "globals", context: "{}") == "[]")
200 for function in ["load", "fetched", "requested", "socket"] {
201 await #expect(throws: CommandHost.Failure.self, "\(function)") {
202 _ = try await host.run(module: "net.js", function: function, context: "\"\(listener.url)x.js\"")
203 }
204 }
205 let webView = try #require(host.engine?.webView)
206 let probed = try await webView.callAsyncJavaScript("""
207 const w = new Worker("commands/probe.js", { type: "module" });
208 return await new Promise(r => { w.onmessage = e => r(e.data); w.onerror = e => r(["error", e.message]); });
209 """, contentWorld: .page)
210 print("A worker with its globals: \(probed ?? "nothing")")
211 _ = try? await webView.callAsyncJavaScript("await fetch(url, { mode: 'no-cors' });", arguments: ["url": listener.url], contentWorld: .page)
212 _ = try? await webView.callAsyncJavaScript("await fetch(url, { mode: 'no-cors' });", arguments: ["url": listener.url], contentWorld: .defaultClient)
213 try await Task.sleep(for: .milliseconds(500))
214 #expect(listener.connections == 0)
215 }
216
217 /// The content rule list alone blocks a load the same web view makes without it.
218 @Test func ruleListBlocksOtherLoads() async throws {
219 let listener = try await Listener()
220 func connects(_ rules: WKContentRuleList?) async throws -> Bool {
221 let before = listener.connections
222 let configuration = WKWebViewConfiguration()
223 configuration.websiteDataStore = .nonPersistent()
224 if let rules { configuration.userContentController.add(rules) }
225 let webView = WKWebView(frame: .zero, configuration: configuration)
226 _ = try? await webView.callAsyncJavaScript("await fetch(url, { mode: 'no-cors' });", arguments: ["url": listener.url], contentWorld: .page)
227 try await Task.sleep(for: .milliseconds(300))
228 return listener.connections > before
229 }
230 #expect(try await connects(nil))
231 #expect(try await !connects(CommandHost.Engine.rules()))
232 }
233
234 @Test func recoversWhenTheContentProcessEnds() async throws {
235 #expect(try await host.run(module: "main.js", function: "echo", context: "1") == "1")
236 let webView = try #require(host.engine?.webView)
237 // Ended from outside, as the system ends a process that runs out of memory.
238 let pid = try #require(webView.value(forKey: "_webProcessIdentifier") as? Int32)
239 try #require(pid > 0)
240 let task = Task { try await host.run(module: "main.js", function: "loop", context: "{}", timeout: .seconds(10)) }
241 try await Task.sleep(for: .milliseconds(300))
242 kill(pid, SIGKILL)
243 await #expect(throws: CommandHost.Failure.stopped) { _ = try await task.value }
244 #expect(host.engine == nil)
245 #expect(try await host.run(module: "main.js", function: "echo", context: "2") == "2")
246 }
247
248 @Test func unloadsWhenIdle() async throws {
249 let host = CommandHost(folder: folder.url.appendingPathComponent("commands"), idle: .milliseconds(200))
250 #expect(try await host.run(module: "main.js", function: "echo", context: "1") == "1")
251 #expect(host.engine != nil)
252 try await Task.sleep(for: .seconds(1))
253 #expect(host.engine == nil)
254 }
255
256 /// Prints first start, a warm round trip and a round trip carrying 1 MB each way.
257 @Test func measures() async throws {
258 host.unload()
259 var start = ContinuousClock.now
260 _ = try await host.run(module: "main.js", function: "echo", context: "1")
261 let first = ContinuousClock.now - start
262 func median(_ times: Int, _ body: () async throws -> Void) async rethrows -> Duration {
263 var all: [Duration] = []
264 for _ in 0..<times {
265 start = .now
266 try await body()
267 all.append(ContinuousClock.now - start)
268 try? await Task.sleep(for: .milliseconds(50))
269 }
270 return all.sorted()[times / 2]
271 }
272 let warm = try await median(21) { _ = try await host.run(module: "main.js", function: "echo", context: "1") }
273 let megabyte = String(repeating: "* Heading\nSome text é\n", count: 1_048_576 / 23)
274 let context = String(data: try JSONSerialization.data(withJSONObject: ["text": megabyte]), encoding: .utf8)!
275 let large = try await median(9) {
276 let reply = try await host.run(module: "main.js", function: "echo", context: context)
277 #expect(reply.count == context.count)
278 }
279 print("Command host: first start \(first), warm round trip \(warm), 1 MB round trip \(large)")
280 }
281}
282
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