// 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.importSwiftUIimportWebKit#if canImport(UIKit)import UIKit#elseimportAppKit#endifenumViewerSeal {/// The only hosts a sealed page may load from, over https.staticlet 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.staticlet ceilingBytes: Int64 = 32 * 1024 * 1024staticlet ruleListIdentifier = "cotton.viewer.seal.v1"/// Whether a document is a web page by its declared type or its name.staticfunc 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" { returntrue }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.staticvar 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)returnString(decoding: data, as: UTF8.self) }/// Whether a URL is one a sealed page may load.staticfunc allows(_ url: URL?) -> Bool {guardlet url, let scheme = url.scheme?.lowercased() else { returnfalse }if scheme == "file" || scheme == "data" || scheme == "blob" || scheme == "about" { returntrue }guard scheme == "https", let host = url.host?.lowercased() else { returnfalse }return hosts.contains(host) }/// The compiled list, made once per launch. @MainActor privatestaticvar compiled: WKContentRuleList? @MainActor staticfunc rules() async -> WKContentRuleList? {iflet compiled { return compiled }guardlet store = WKContentRuleListStore.default() else { returnnil }let source = ruleListlet list: WKContentRuleList? = await withCheckedContinuation { done in store.compileContentRuleList(forIdentifier: ruleListIdentifier, encodedContentRuleList: source) { list, _ in done.resume(returning: list) } } compiled = listreturn list }/// The file's size, read from the file system — never by reading it.staticfunc 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.structViewerWebPage: View {let file: URLlet ground: ThemeColorvar onGround: (ThemeColor?) -> Void = { _ in }/// nil until compiled, and for ever if it will not compile: the page/// never loads without its seal. @State privatevar rules: WKContentRuleList? @State privatevar painted = falsevar body: someView { ZStack {// Partial page paint blends over the original viewer colour,// not over the already-composited colour sent to the head.if painted { ground.color }iflet rules {ViewerSealedWebView(file: file, rules: rules, onGround: { painted = $0 != nil onGround(ViewerWebGround.composite($0, over: ground)) }) } } .task { rules = awaitViewerSeal.rules() } }}structViewerSealedWebView: PlatformViewRepresentable {let file: URLlet rules: WKContentRuleListvar onGround: (ThemeColor?) -> Void = { _ in }func makeCoordinator() -> Coordinator { Coordinator(file: file, onGround: onGround) }privatefunc 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 #endiflet 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 } #elsefunc makeNSView(context: Context) -> WKWebView { made(context) }func updateNSView(_ view: WKWebView, context: Context) { context.coordinator.onGround = onGround } #endiffinalclassCoordinator: NSObject, WKNavigationDelegate, WKUIDelegate {let file: URLvar onGround: (ThemeColor?) -> Voidinit(file: URL, onGround: @escaping (ThemeColor?) -> Void = { _ in }) {self.file = fileself.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.iflet 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); })() """) { [weakself] value, _ inguardlet rgba = value as? [Double], rgba.count == 4else { 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.urllet mainFrame = action.targetFrame?.isMainFrame ?? trueif mainFrame {// The file itself, and an anchor within it (same path, a// fragment), are the same page.iflet 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)returnnil }/// Only http and https leave the app; a page cannot hand the system a/// mail, app or script link. @MainActor staticfunc openOutside(_ url: URL?) {guardlet 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.enumViewerWebGround {staticfunc composite(_ paint: ThemeColor?, over ground: ThemeColor) -> ThemeColor? {guardlet paint, paint.alpha > 0else { returnnil }return paint.composited(over: ground) }// The theme's existing light-fill/dark-fill rule (ThemeBrand.ink).staticfunc isDark(_ ground: ThemeColor) -> Bool {0.2126 * ground.red + 0.7152 * ground.green + 0.0722 * ground.blue <= 0.55 }staticfunc ink(on ground: ThemeColor, theme: Theme) -> ThemeColor {let palette = theme.palette.resolved(.light)return isDark(ground) ? palette.paper : palette.ink } @MainActor staticfunc read(_ view: WKWebView) -> ThemeColor? { #if canImport(UIKit)guardlet color = view.underPageBackgroundColor else { returnnil }var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0guard color.getRed(&r, green: &g, blue: &b, alpha: &a), a > 0else { returnnil }returnThemeColor(components: [Double(r), Double(g), Double(b), Double(a)]) #elseguardlet color = view.underPageBackgroundColor?.usingColorSpace(.sRGB), color.alphaComponent > 0else { returnnil }returnThemeColor(components: [color.redComponent, color.greenComponent, color.blueComponent, color.alphaComponent]) #endif }}extensionTableDefinition {/// 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.publicstaticfunc webLink(_ url: URL?) -> URL? {guardlet url, let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", url.host?.isEmpty == falseelse { returnnil }return url }}