Cotton code
299 lines · 12.9 KB · SwiftRaw
// A web page kept as a document — a saved Claude artifact, most often — opened// in a SEALED web view inside the viewer's chrome.//// The seal, all of it here and nowhere else:// - the page is the local file and only the local file: `loadFileURL` with read//   access to that one file, never bytes handed over, never an address;// - every network load is refused by a content rule list except the few CDN//   hosts a self-contained artifact draws its libraries and fonts from//   (`ViewerSeal.hosts`); the list is compiled BEFORE the page loads, and a//   list that will not compile means the page does not open;// - nothing is kept: a non-persistent data store, so no cookie, storage or//   cache is shared with any other page or with a later opening;// - a link to anywhere else leaves the app (Safari), and a window the page//   tries to open does the same; the pane itself never navigates away;// - a page bigger than the app will hold in memory as one answer//   (`ViewerSeal.ceilingBytes`) is not run at all: a big body is a file.//// The guard is `ViewerSealTests`: a host added here without its reason in the// test fails it.import SwiftUIimport WebKit#if canImport(UIKit)import UIKit#elseimport AppKit#endifenum ViewerSeal {    /// The only hosts a sealed page may load from, over https.    static let hosts: [String] = [        "cdnjs.cloudflare.com",        "cdn.jsdelivr.net",        "unpkg.com",        "cdn.tailwindcss.com",        "code.jquery.com",        "fonts.googleapis.com",        "fonts.gstatic.com",    ]    /// The most a page may weigh and still run: the core's ceiling for one    /// answer held in memory (`ANSWER_CEILING_BYTES`, 32 MB). Past it the    /// document is a file, shared from the acts menu, never rendered.    static let ceilingBytes: Int64 = 32 * 1024 * 1024    static let ruleListIdentifier = "cotton.viewer.seal.v1"    /// Whether a document is a web page by its declared type or its name.    static func isPage(contentType: String?, name: String?) -> Bool {        let type = (contentType ?? "").lowercased().split(separator: ";").first.map(String.init)?            .trimmingCharacters(in: .whitespaces) ?? ""        if type == "text/html" || type == "application/xhtml+xml" { return true }        let ext = ((name ?? "") as NSString).pathExtension.lowercased()        return ext == "html" || ext == "htm"    }    /// The content rule list: block every load, then let back in the page's    /// own file, inline `data:`/`blob:` URLs the page made itself, and https    /// to the hosts above. Later rules win in WebKit's rule order.    static var ruleList: String {        var rules: [[String: Any]] = [            ["trigger": ["url-filter": ".*"], "action": ["type": "block"]],            ["trigger": ["url-filter": "^file:"], "action": ["type": "ignore-previous-rules"]],            ["trigger": ["url-filter": "^data:"], "action": ["type": "ignore-previous-rules"]],            ["trigger": ["url-filter": "^blob:"], "action": ["type": "ignore-previous-rules"]],        ]        for host in hosts {            let escaped = host.replacingOccurrences(of: ".", with: "\\.")            rules.append(["trigger": ["url-filter": "^https://\(escaped)[:/]"], "action": ["type": "ignore-previous-rules"]])        }        let data = (try? JSONSerialization.data(withJSONObject: rules, options: [.sortedKeys])) ?? Data("[]".utf8)        return String(decoding: data, as: UTF8.self)    }    /// Whether a URL is one a sealed page may load.    static func allows(_ url: URL?) -> Bool {        guard let url, let scheme = url.scheme?.lowercased() else { return false }        if scheme == "file" || scheme == "data" || scheme == "blob" || scheme == "about" { return true }        guard scheme == "https", let host = url.host?.lowercased() else { return false }        return hosts.contains(host)    }    /// The compiled list, made once per launch.    @MainActor private static var compiled: WKContentRuleList?    @MainActor static func rules() async -> WKContentRuleList? {        if let compiled { return compiled }        guard let store = WKContentRuleListStore.default() else { return nil }        let source = ruleList        let list: WKContentRuleList? = await withCheckedContinuation { done in            store.compileContentRuleList(forIdentifier: ruleListIdentifier, encodedContentRuleList: source) { list, _ in                done.resume(returning: list)            }        }        compiled = list        return list    }    /// The file's size, read from the file system — never by reading it.    static func size(of file: URL) -> Int64? {        (try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init)    }}/// The page, once the seal is in place; nothing at all until then.struct ViewerWebPage: View {    let file: URL    let ground: ThemeColor    var onGround: (ThemeColor?) -> Void = { _ in }    /// nil until compiled, and for ever if it will not compile: the page    /// never loads without its seal.    @State private var rules: WKContentRuleList?    @State private var painted = false    var body: some View {        ZStack {            // Partial page paint blends over the original viewer colour,            // not over the already-composited colour sent to the head.            if painted { ground.color }            if let rules {                ViewerSealedWebView(file: file, rules: rules, onGround: {                    painted = $0 != nil                    onGround(ViewerWebGround.composite($0, over: ground))                })            }        }        .task {            rules = await ViewerSeal.rules()        }    }}struct ViewerSealedWebView: PlatformViewRepresentable {    let file: URL    let rules: WKContentRuleList    var onGround: (ThemeColor?) -> Void = { _ in }    func makeCoordinator() -> Coordinator { Coordinator(file: file, onGround: onGround) }    private func made(_ context: Context) -> WKWebView {        let configuration = WKWebViewConfiguration()        configuration.websiteDataStore = .nonPersistent()        configuration.userContentController.add(rules)        configuration.preferences.javaScriptCanOpenWindowsAutomatically = false        #if canImport(UIKit)        configuration.dataDetectorTypes = []        configuration.allowsInlineMediaPlayback = true        #endif        let view = WKWebView(frame: .zero, configuration: configuration)        view.navigationDelegate = context.coordinator        view.uiDelegate = context.coordinator        #if canImport(UIKit)        view.isOpaque = false        view.backgroundColor = .clear        view.scrollView.backgroundColor = .clear        #endif        view.loadFileURL(file, allowingReadAccessTo: file)        return view    }    #if canImport(UIKit)    func makeUIView(context: Context) -> WKWebView { made(context) }    func updateUIView(_ view: WKWebView, context: Context) { context.coordinator.onGround = onGround }    #else    func makeNSView(context: Context) -> WKWebView { made(context) }    func updateNSView(_ view: WKWebView, context: Context) { context.coordinator.onGround = onGround }    #endif    final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {        let file: URL        var onGround: (ThemeColor?) -> Void        init(file: URL, onGround: @escaping (ThemeColor?) -> Void = { _ in }) {            self.file = file            self.onGround = onGround        }        func webView(_ view: WKWebView, didFinish navigation: WKNavigation!) {            // WebKit derives this from the page's html/body canvas, including            // the colour exposed by overscroll. Do not override it ourselves.            if let ground = ViewerWebGround.read(view) {                onGround(ground)            } else {                // A transparent native canvas may still have a body paint on                // platforms where WebKit has not supplied the canvas colour.                // Read it once, after load; a page with no paint keeps paper.                view.evaluateJavaScript("""                    (() => {                      const canvas = document.createElement('canvas');                      canvas.width = canvas.height = 1;                      const context = canvas.getContext('2d');                      for (const element of [document.documentElement, document.body]) {                        if (element) {                          context.fillStyle = getComputedStyle(element).backgroundColor;                          context.fillRect(0, 0, 1, 1);                        }                      }                      return Array.from(context.getImageData(0, 0, 1, 1).data, x => x / 255);                    })()                    """) { [weak self] value, _ in                    guard let rgba = value as? [Double], rgba.count == 4 else { self?.onGround(nil); return }                    self?.onGround(rgba[3] > 0 ? ThemeColor(components: rgba) : nil)                }            }        }        /// The pane stays on its file. A frame inside the page may load what        /// the rule list lets through; the page's own window moves nowhere,        /// and a link a person followed opens outside the app.        func webView(            _ view: WKWebView,            decidePolicyFor action: WKNavigationAction,            decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void        ) {            let url = action.request.url            let mainFrame = action.targetFrame?.isMainFrame ?? true            if mainFrame {                // The file itself, and an anchor within it (same path, a                // fragment), are the same page.                if let url, url.isFileURL, url.standardizedFileURL.path == file.standardizedFileURL.path {                    decisionHandler(.allow)                    return                }                decisionHandler(.cancel)                if action.navigationType == .linkActivated { Self.openOutside(url) }                return            }            decisionHandler(ViewerSeal.allows(url) ? .allow : .cancel)        }        /// A window the page asks for opens outside the app, never as a second        /// web view.        func webView(            _ view: WKWebView,            createWebViewWith configuration: WKWebViewConfiguration,            for action: WKNavigationAction,            windowFeatures: WKWindowFeatures        ) -> WKWebView? {            Self.openOutside(action.request.url)            return nil        }        /// Only http and https leave the app; a page cannot hand the system a        /// mail, app or script link.        @MainActor static func openOutside(_ url: URL?) {            guard let url = TableDefinition.webLink(url) else { return }            #if canImport(UIKit)            UIApplication.shared.open(url)            #else            NSWorkspace.shared.open(url)            #endif        }    }}/// A page supplies colour, never a Cotton paper texture. Partial paint is/// composited over the viewer's own ground before the head chooses its ink.enum ViewerWebGround {    static func composite(_ paint: ThemeColor?, over ground: ThemeColor) -> ThemeColor? {        guard let paint, paint.alpha > 0 else { return nil }        return paint.composited(over: ground)    }    // The theme's existing light-fill/dark-fill rule (ThemeBrand.ink).    static func isDark(_ ground: ThemeColor) -> Bool {        0.2126 * ground.red + 0.7152 * ground.green + 0.0722 * ground.blue <= 0.55    }    static func ink(on ground: ThemeColor, theme: Theme) -> ThemeColor {        let palette = theme.palette.resolved(.light)        return isDark(ground) ? palette.paper : palette.ink    }    @MainActor static func read(_ view: WKWebView) -> ThemeColor? {        #if canImport(UIKit)        guard let color = view.underPageBackgroundColor else { return nil }        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0        guard color.getRed(&r, green: &g, blue: &b, alpha: &a), a > 0 else { return nil }        return ThemeColor(components: [Double(r), Double(g), Double(b), Double(a)])        #else        guard let color = view.underPageBackgroundColor?.usingColorSpace(.sRGB), color.alphaComponent > 0 else { return nil }        return ThemeColor(components: [color.redComponent, color.greenComponent, color.blueComponent, color.alphaComponent])        #endif    }}extension TableDefinition {    /// The address itself when it is one a web view may load or a browser    /// may be handed — http or https with a host — else nil. The live page    /// holds every address it is given to this, not only the saved one: a    /// popup, a link it follows, where it reports it has landed.    public static func webLink(_ url: URL?) -> URL? {        guard let url, let scheme = url.scheme?.lowercased(),            scheme == "http" || scheme == "https", url.host?.isEmpty == false        else { return nil }        return url    }}