SPB Git

Repository Public

EngineHost.swift 7.1 KB 121 lines swift

1import Foundation2import WebKit34/// Runs the SP Message client engine (the same code as the web application: MLS, identity, sync,5/// attachments) from the app bundle, in an isolated script context that loads nothing from the6/// network. Networking and storage are provided by Swift; the interface is entirely SwiftUI.7@MainActor8final class EngineHost: NSObject, WKScriptMessageHandlerWithReply, WKNavigationDelegate {9    let webView: WKWebView10    let net = Net()11    private let kv: KV?12    /// Set when the local encrypted store could not be opened; the app then shows the reason instead of starting.13    private(set) var storeError: String?14    private var loaded: CheckedContinuation<Void, Never>?15    private var isLoaded = false16    var onChanged: (() -> Void)?17    var onNotify: ((String, String) -> Void)?1819    override init() {20        do { kv = try KV() } catch {21            kv = nil22            storeError = "The encrypted local store could not be opened (\((error as NSError).domain) \((error as NSError).code))."23        }24        let cfg = WKWebViewConfiguration()25        cfg.websiteDataStore = .nonPersistent()26        cfg.defaultWebpagePreferences.allowsContentJavaScript = true27        webView = WKWebView(frame: .init(x: 0, y: 0, width: 1, height: 1), configuration: cfg)28        super.init()29        cfg.userContentController.addScriptMessageHandler(self, contentWorld: .page, name: "spm")30        // script errors of the engine are reported to the system log (never message content)31        cfg.userContentController.addUserScript(WKUserScript(source: """32            addEventListener('error', e => webkit.messageHandlers.spm.postMessage({op:'log', text:'error: ' + e.message + ' @' + e.lineno + ':' + e.colno}));33            addEventListener('unhandledrejection', e => webkit.messageHandlers.spm.postMessage({op:'log', text:'rejection: ' + (e.reason && e.reason.message || e.reason)}));34            """, injectionTime: .atDocumentStart, forMainFrameOnly: true))35        webView.navigationDelegate = self36        net.onSocket = { [weak self] kind, data in37            Task { @MainActor in38                _ = try? await self?.webView.callAsyncJavaScript("__spmSocket(kind, data)", arguments: ["kind": kind, "data": data ?? NSNull()], in: nil, contentWorld: .page)39            }40        }41    }4243    func start() async {44        guard !isLoaded else { return }45        let js = (try? String(contentsOf: Bundle.main.url(forResource: "core", withExtension: "js")!, encoding: .utf8)) ?? ""46        // The document only contains the bundled engine. The content policy forbids every network load47        // and every script other than this one; the base URL gives it a secure context for WebCrypto.48        let html = """49        <!doctype html><meta charset="utf-8">50        <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; img-src data: blob:; media-src blob: data:; connect-src blob: data:">51        <script>\(js.replacingOccurrences(of: "</script", with: "<\\/script"))</script>52        """53        await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in54            loaded = c55            webView.loadHTMLString(html, baseURL: Config.base)56        }57    }5859    /// Calls a function of the engine API and awaits its result.60    @discardableResult61    func call(_ name: String, _ args: Any...) async throws -> Any? {62        do {63            return try await webView.callAsyncJavaScript("return await spm[name](...args)", arguments: ["name": name, "args": args], in: nil, contentWorld: .page)64        } catch {65            let ns = error as NSError66            let text = (ns.userInfo["WKJavaScriptExceptionMessage"] as? String) ?? ns.localizedDescription67            throw APIError(status: 0, code: "engine", message: text.replacingOccurrences(of: "Error: ", with: ""))68        }69    }7071    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { NSLog("SPMessage engine load failed: %@", error.localizedDescription) }72    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { NSLog("SPMessage engine load failed (provisional): %@", error.localizedDescription) }73    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { NSLog("SPMessage engine document finished, loaded=%d", isLoaded ? 1 : 0) }7475    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy {76        // only the initial bundled document is ever allowed77        navigationAction.navigationType == .other && !isLoaded ? .allow : .cancel78    }7980    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage, replyHandler: @escaping (Any?, String?) -> Void) {81        guard let m = message.body as? [String: Any], let op = m["op"] as? String else { return replyHandler(nil, "bad message") }82        Task { @MainActor in83            let (value, error) = await self.handle(op, m)84            replyHandler(value, error)85        }86    }8788    private func handle(_ op: String, _ m: [String: Any]) async -> (Any?, String?) {89        #if DEBUG90        if UserDefaults.standard.bool(forKey: "SPMTrace") { NSLog("SPMessage op %@ %@", op, (m["path"] as? String) ?? (m["key"] as? String) ?? "") }91        #endif92        switch op {93        case "loaded":94            isLoaded = true95            loaded?.resume(); loaded = nil96            if m["subtle"] as? Bool != true { NSLog("SPMessage: WebCrypto unavailable in the engine context") }97            return (true, nil)98        case "http":99            let bytes = (m["bytes"] as? String).flatMap { Data(base64Encoded: $0) }100            let (status, data) = await net.request(m["method"] as? String ?? "GET", m["path"] as? String ?? "/", json: m["json"] as? String, bytes: bytes)101            #if DEBUG102            if UserDefaults.standard.bool(forKey: "SPMTrace") { NSLog("SPMessage http done %d (%d bytes)", status, data.count) }103            #endif104            let body = (m["binary"] as? Bool == true) ? data.base64EncodedString() : (String(data: data, encoding: .utf8) ?? "")105            return (["status": status, "body": body], nil)106        case "ws-open": net.openSocket(); return (true, nil)107        case "ws-send": net.send(m["text"] as? String ?? ""); return (true, nil)108        case "ws-close": net.closeSocket(); return (true, nil)109        case "kv-get": return (kv?.get(m["key"] as? String ?? "") ?? NSNull(), nil)110        case "kv-set": kv?.set(m["key"] as? String ?? "", m["value"] as? String ?? ""); return (true, nil)111        case "kv-del": kv?.del(m["key"] as? String ?? ""); return (true, nil)112        case "kv-list": return (kv?.list(m["prefix"] as? String ?? "") ?? [], nil)113        case "kv-clear": kv?.clear(m["prefix"] as? String ?? ""); return (true, nil)114        case "log": NSLog("SPMessage engine: %@", m["text"] as? String ?? ""); return (true, nil)115        case "changed": onChanged?(); return (true, nil)116        case "notify": onNotify?(m["title"] as? String ?? "SP Message", m["conv"] as? String ?? ""); return (true, nil)117        default: return (nil, "unknown op")118        }119    }120}121
Files main
Menu

Theme