SPB Git

Repository Public License

ScriptBridge.swift 21.0 KB 401 lines swift

1import Foundation2import NavigatorCore34// The bridge is one-way and typed: bundled scripts in isolated content worlds post `{ v, kind, payload }` to the5// `orixBridge` handler, which exists only in those worlds. Page JavaScript has no reference to it. Every message6// is nevertheless validated as if it were hostile: world, frame, origin, then schema.78/// The isolated JavaScript worlds of the browser. The page world is deliberately not a case: nothing in this9/// module evaluates caller-supplied script there.10public enum ScriptWorld: String, Sendable, CaseIterable {11    /// Built-in reporters (metadata, scroll, media, context element, activation).12    case bridge = "orix.bridge"13    case reader = "orix.reader"14    case lens = "orix.lens"15    case morph = "orix.morph"16    case dev = "orix.dev"17    /// Scripts run on behalf of the agent and other features through `WebEngine.evaluate`.18    case agent = "orix.agent"19    /// User scripts installed by the user or by other modules.20    case userScripts = "orix.userscripts"21}2223/// A validated message from a bundled script.24public enum BridgeMessage: Sendable, Hashable {25    case activation26    case metadata(PageMetadata)27    case scroll(ScrollMetrics)28    case media(frame: String, activity: MediaActivity, muted: Bool)29    case context(ContextMenuElement)30    case selection(TextSelection)31    case elementPicked(PickedElement?)32    case console(ConsoleEntry)3334    public var kind: String {35        switch self {36        case .activation: "activation"37        case .metadata: "metadata"38        case .scroll: "scroll"39        case .media: "media"40        case .context: "context"41        case .selection: "selection"42        case .elementPicked: "elementPicked"43        case .console: "console"44        }45    }46}4748public enum BridgeRejection: Error, Sendable, Hashable {49    case unknownHandler(String)50    /// The message came from a world that may not send this kind (or from the page world).51    case untrustedWorld(String?)52    case foreignWebView53    case subframeNotAllowed(kind: String)54    case originMismatch55    /// The payload describes another document than the one committed (a late message from the previous page).56    case staleDocument57    case malformed(String)58    case unknownKind(String)59    case unsupportedVersion60}6162/// Everything known about an incoming message, lifted out of `WKScriptMessage` so the validator is testable.63public struct BridgeEnvelope: Sendable {64    public var handlerName: String65    /// `WKContentWorld.name`; `nil` for the page world.66    public var worldName: String?67    /// The message was delivered by the web view that owns this bridge.68    public var isFromOwnWebView: Bool69    public var isMainFrame: Bool70    public var frameOrigin: WebOrigin?71    /// Origin of the document committed in the main frame.72    public var pageOrigin: WebOrigin?73    public var pageURL: URL?74    public var body: ScriptValue7576    public init(handlerName: String, worldName: String?, isFromOwnWebView: Bool = true, isMainFrame: Bool,77                frameOrigin: WebOrigin?, pageOrigin: WebOrigin?, pageURL: URL?, body: ScriptValue) {78        self.handlerName = handlerName; self.worldName = worldName; self.isFromOwnWebView = isFromOwnWebView79        self.isMainFrame = isMainFrame; self.frameOrigin = frameOrigin; self.pageOrigin = pageOrigin80        self.pageURL = pageURL; self.body = body81    }82}8384public enum BridgeValidator {85    /// Which kinds each world may send. Anything else is rejected, whatever the payload looks like.86    static let allowedKinds: [String: Set<String>] = [87        ScriptWorld.bridge.rawValue: ["activation", "metadata", "scroll", "media", "context"],88        ScriptWorld.lens.rawValue: ["selection", "elementPicked"],89        ScriptWorld.dev.rawValue: ["console"],90    ]91    /// Kinds that only the main frame may send, and whose frame origin must equal the page origin.92    static let mainFrameOnly: Set<String> = ["metadata", "scroll", "selection", "elementPicked", "console"]9394    public static func validate(_ envelope: BridgeEnvelope) throws(BridgeRejection) -> BridgeMessage {95        guard envelope.isFromOwnWebView else { throw .foreignWebView }96        guard case .object(let body) = envelope.body else { throw .malformed("body is not an object") }97        guard body["v"]?.intValue == 1 else { throw .unsupportedVersion }98        guard let kind = body["kind"]?.stringValue, kind.count <= 32 else { throw .malformed("kind") }99        guard case .object(let payload)? = body["payload"] else { throw .malformed("payload is not an object") }100101        switch envelope.handlerName {102        case WebRuntimeConstants.bridgeHandlerName:103            guard let world = envelope.worldName, let kinds = allowedKinds[world] else {104                throw .untrustedWorld(envelope.worldName)105            }106            guard kinds.contains(kind) else {107                if allowedKinds.values.contains(where: { $0.contains(kind) }) { throw BridgeRejection.untrustedWorld(world) }108                throw BridgeRejection.unknownKind(kind)109            }110        case WebRuntimeConstants.consoleHandlerName:111            // The console mirror lives in the page world and may only ever produce console text.112            guard envelope.worldName == nil else { throw .untrustedWorld(envelope.worldName) }113            guard kind == "console" else { throw .unknownKind(kind) }114        default:115            throw .unknownHandler(envelope.handlerName)116        }117118        if mainFrameOnly.contains(kind) {119            guard envelope.isMainFrame else { throw .subframeNotAllowed(kind: kind) }120            guard envelope.frameOrigin == envelope.pageOrigin else { throw .originMismatch }121        }122123        let trusted = envelope.handlerName == WebRuntimeConstants.bridgeHandlerName124        switch kind {125        case "activation":126            return .activation127        case "metadata":128            return .metadata(try metadata(payload, pageURL: envelope.pageURL))129        case "scroll":130            return .scroll(try scroll(payload))131        case "media":132            return try media(payload)133        case "context":134            return .context(try context(payload))135        case "selection":136            return .selection(try selection(payload, pageURL: envelope.pageURL))137        case "elementPicked":138            return .elementPicked(try pickedElement(payload))139        case "console":140            return .console(try console(payload, trusted: trusted))141        default:142            throw .unknownKind(kind)143        }144    }145146    // MARK: Field helpers147148    private static func string(_ payload: [String: ScriptValue], _ key: String, max: Int,149                               required: Bool = false) throws(BridgeRejection) -> String {150        switch payload[key] {151        case .string(let value):152            guard value.utf16.count <= max else { throw .malformed("\(key) too long") }153            return value154        case nil, .null?:155            if required { throw .malformed("\(key) missing") }156            return ""157        default:158            throw .malformed("\(key) is not a string")159        }160    }161162    private static func number(_ payload: [String: ScriptValue], _ key: String, min: Double = -1e7,163                               max: Double = 1e9) throws(BridgeRejection) -> Double {164        guard let value = payload[key]?.doubleValue, value.isFinite, value >= min, value <= max else {165            throw .malformed("\(key) is not a number in range")166        }167        return value168    }169170    private static func bool(_ payload: [String: ScriptValue], _ key: String) -> Bool { payload[key]?.boolValue ?? false }171172    /// http(s) URL or nil. Anything else (javascript:, file:, data:…) is dropped rather than passed on.173    static func webURL(_ text: String) -> URL? {174        guard !text.isEmpty, text.utf16.count <= 8192, let url = URL(string: text),175              let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",176              !(url.host() ?? "").isEmpty else { return nil }177        return url178    }179180    /// Any absolute URL, for display only (context menus on internal or local pages).181    static func anyURL(_ text: String) -> URL? {182        guard !text.isEmpty, text.utf16.count <= 8192, let url = URL(string: text), url.scheme != nil else { return nil }183        return url184    }185186    private static func rect(_ value: ScriptValue?) throws(BridgeRejection) -> CGRect {187        guard case .object(let object)? = value else { return .zero }188        return CGRect(x: try number(object, "x"), y: try number(object, "y"),189                      width: try number(object, "width", min: 0), height: try number(object, "height", min: 0))190    }191192    private static func sameDocument(_ reported: String, as pageURL: URL?) -> Bool {193        guard let pageURL, let url = URL(string: reported) else { return false }194        return NavigationPolicy.sameDocumentTarget(url, pageURL)195    }196197    // MARK: Payload parsers198199    static func metadata(_ payload: [String: ScriptValue], pageURL: URL?) throws(BridgeRejection) -> PageMetadata {200        let reportedURL = try string(payload, "url", max: 8192, required: true)201        guard sameDocument(reportedURL, as: pageURL), let pageURL else { throw .staleDocument }202        var icons: [PageIcon] = []203        if let list = payload["icons"]?.arrayValue {204            guard list.count <= 16 else { throw .malformed("too many icons") }205            for item in list {206                guard case .object(let icon) = item else { throw .malformed("icon") }207                guard let url = webURL(try string(icon, "href", max: 4096)) else { continue }208                let sizes = try string(icon, "sizes", max: 64)209                icons.append(PageIcon(url: url, rel: try string(icon, "rel", max: 64), declaredSize: declaredSize(sizes),210                                      mimeType: try string(icon, "type", max: 64)))211            }212        }213        var openGraph = OpenGraphData()214        if case .object(let og)? = payload["openGraph"] {215            openGraph.title = try string(og, "title", max: 2048)216            openGraph.description = try string(og, "description", max: 2048)217            openGraph.imageURL = webURL(try string(og, "image", max: 4096))218            openGraph.siteName = try string(og, "siteName", max: 2048)219            openGraph.type = try string(og, "type", max: 64)220            openGraph.url = webURL(try string(og, "url", max: 4096))221        }222        return PageMetadata(url: pageURL, title: try string(payload, "title", max: 1024),223                            description: try string(payload, "description", max: 2048),224                            language: try string(payload, "language", max: 35),225                            themeColor: try string(payload, "themeColor", max: 64),226                            canonicalURL: webURL(try string(payload, "canonical", max: 4096)),227                            icons: icons, openGraph: openGraph)228    }229230    /// Largest edge declared by an HTML `sizes` attribute ("16x16 32x32", "any").231    static func declaredSize(_ sizes: String) -> Int {232        if sizes.contains("any") { return Int.max }233        return sizes.split(separator: " ").compactMap { token -> Int? in234            let parts = token.split(separator: "x")235            guard parts.count == 2, let width = Int(parts[0]), let height = Int(parts[1]), width > 0, height > 0,236                  width <= 8192, height <= 8192 else { return nil }237            return max(width, height)238        }.max() ?? 0239    }240241    static func scroll(_ payload: [String: ScriptValue]) throws(BridgeRejection) -> ScrollMetrics {242        ScrollMetrics(x: try number(payload, "x"), y: try number(payload, "y"),243                      contentWidth: try number(payload, "contentWidth", min: 0),244                      contentHeight: try number(payload, "contentHeight", min: 0),245                      viewportWidth: try number(payload, "viewportWidth", min: 0),246                      viewportHeight: try number(payload, "viewportHeight", min: 0))247    }248249    static func media(_ payload: [String: ScriptValue]) throws(BridgeRejection) -> BridgeMessage {250        let frame = try string(payload, "frame", max: 64, required: true)251        guard !frame.isEmpty else { throw .malformed("frame") }252        let activity = MediaActivity(totalElements: Int(try number(payload, "total", min: 0, max: 100_000)),253                                     playingElements: Int(try number(payload, "playing", min: 0, max: 100_000)),254                                     audibleElements: Int(try number(payload, "audible", min: 0, max: 100_000)),255                                     isPictureInPictureActive: bool(payload, "pictureInPicture"))256        return .media(frame: frame, activity: activity, muted: bool(payload, "muted"))257    }258259    static func context(_ payload: [String: ScriptValue]) throws(BridgeRejection) -> ContextMenuElement {260        ContextMenuElement(pageURL: anyURL(try string(payload, "pageURL", max: 8192)),261                           linkURL: anyURL(try string(payload, "linkURL", max: 8192)),262                           linkText: try string(payload, "linkText", max: 512),263                           imageURL: anyURL(try string(payload, "imageURL", max: 8192)),264                           imageAlt: try string(payload, "imageAlt", max: 512),265                           mediaURL: anyURL(try string(payload, "mediaURL", max: 8192)),266                           selectionText: try string(payload, "selectionText", max: 4096),267                           isEditable: bool(payload, "isEditable"),268                           location: CGPoint(x: try number(payload, "x"), y: try number(payload, "y")))269    }270271    static func selection(_ payload: [String: ScriptValue], pageURL: URL?) throws(BridgeRejection) -> TextSelection {272        let reportedURL = try string(payload, "url", max: 8192, required: true)273        guard sameDocument(reportedURL, as: pageURL) else { throw .staleDocument }274        return TextSelection(url: pageURL, text: try string(payload, "text", max: 20_000),275                             isCollapsed: bool(payload, "isCollapsed"), rect: try rect(payload["rect"]))276    }277278    static func pickedElement(_ payload: [String: ScriptValue]) throws(BridgeRejection) -> PickedElement? {279        if bool(payload, "cancelled") { return nil }280        let tag = try string(payload, "tag", max: 32, required: true)281        guard !tag.isEmpty, tag.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-") }) else {282            throw .malformed("tag")283        }284        return PickedElement(url: anyURL(try string(payload, "url", max: 8192)), tag: tag,285                             selector: try string(payload, "selector", max: 1024),286                             text: try string(payload, "text", max: 20_000),287                             html: try string(payload, "html", max: 50_000),288                             linkURL: anyURL(try string(payload, "href", max: 8192)),289                             sourceURL: anyURL(try string(payload, "src", max: 8192)),290                             rect: try rect(payload["rect"]))291    }292293    static func console(_ payload: [String: ScriptValue], trusted: Bool) throws(BridgeRejection) -> ConsoleEntry {294        guard let level = ConsoleEntry.Level(rawValue: try string(payload, "level", max: 16, required: true)) else {295            throw .malformed("level")296        }297        guard let source = ConsoleEntry.Source(rawValue: try string(payload, "source", max: 16, required: true)) else {298            throw .malformed("source")299        }300        // The page-world mirror may only claim to be `console` output.301        if !trusted && source != .console { throw .malformed("source") }302        return ConsoleEntry(id: UUID(), level: level, source: source,303                            message: try string(payload, "message", max: 4000),304                            url: try string(payload, "url", max: 2048),305                            line: Int(try number(payload, "line", min: 0, max: 1e8)),306                            column: Int(try number(payload, "column", min: 0, max: 1e8)),307                            date: .now, isFromIsolatedWorld: trusted)308    }309}310311// MARK: - Reader article312313/// An article extracted by `reader.js`. `contentHTML` only contains the tags and attributes of314/// `ReaderHTMLPolicy`; it was re-validated natively after extraction.315public struct ReaderArticle: Sendable, Hashable {316    public var url: URL?317    public var title: String318    public var byline: String319    /// BCP 47 tag from the document, possibly empty.320    public var language: String321    public var publishedTime: String322    public var contentHTML: String323    public var textContent: String324    public var wordCount: Int325    /// The article was cut at the size limit.326    public var isTruncated: Bool327328    /// Reading time at 230 words per minute, at least one minute.329    public var estimatedReadingMinutes: Int { max(1, Int((Double(wordCount) / 230).rounded())) }330}331332/// The safe HTML subset a reader article may contain.333public enum ReaderHTMLPolicy {334    public static let allowedTags: Set<String> = [335        "p", "h2", "h3", "h4", "h5", "h6", "blockquote", "ul", "ol", "li", "pre", "code", "em", "strong", "u", "s",336        "sub", "sup", "a", "img", "figure", "figcaption", "br", "hr", "table", "thead", "tbody", "tr", "td", "th",337        "dl", "dt", "dd", "mark", "q", "cite", "kbd", "small",338    ]339    static let allowedAttributes: [String: Set<String>] = [340        "a": ["href"], "img": ["src", "alt"], "td": ["colspan", "rowspan"], "th": ["colspan", "rowspan"],341    ]342    static let urlAttributes: Set<String> = ["href", "src"]343344    /// Returns `nil` when `html` is inside the subset, else a description of the first violation.345    /// A strict scanner, not a parser: the serialiser in `reader.js` emits a canonical form (double-quoted346    /// attributes, escaped text), so anything else is by definition not ours.347    public static func firstViolation(in html: String) -> String? {348        var index = html.startIndex349        while let open = html[index...].firstIndex(of: "<") {350            guard let close = html[open...].firstIndex(of: ">") else { return "unterminated tag" }351            var inner = html[html.index(after: open)..<close]352            index = html.index(after: close)353            if inner.hasPrefix("/") {354                let name = String(inner.dropFirst())355                guard allowedTags.contains(name) else { return "closing tag </\(name.prefix(20))>" }356                continue357            }358            guard let first = inner.first, first.isASCII, first.isLetter else { return "markup <\(inner.prefix(20))" }359            let nameEnd = inner.firstIndex(where: { $0 == " " }) ?? inner.endIndex360            let name = String(inner[..<nameEnd])361            guard allowedTags.contains(name) else { return "tag <\(name.prefix(20))>" }362            inner = inner[nameEnd...]363            let permitted = allowedAttributes[name] ?? []364            while !inner.isEmpty {365                guard inner.hasPrefix(" ") else { return "attribute syntax in <\(name)>" }366                inner = inner.dropFirst()367                guard let equals = inner.firstIndex(of: "=") else { return "attribute without value in <\(name)>" }368                let attribute = String(inner[..<equals])369                guard permitted.contains(attribute) else { return "attribute \(attribute.prefix(20)) on <\(name)>" }370                inner = inner[inner.index(after: equals)...]371                guard inner.hasPrefix("\"") else { return "unquoted attribute in <\(name)>" }372                inner = inner.dropFirst()373                guard let quote = inner.firstIndex(of: "\"") else { return "unterminated attribute in <\(name)>" }374                let value = String(inner[..<quote])375                if urlAttributes.contains(attribute) {376                    let decoded = value.replacingOccurrences(of: "&amp;", with: "&")377                    guard BridgeValidator.webURL(decoded) != nil else { return "non-web URL in \(attribute)" }378                }379                inner = inner[inner.index(after: quote)...]380            }381        }382        return nil383    }384385    static func article(from value: ScriptValue) throws(WebEngineError) -> ReaderArticle {386        guard case .object(let object) = value else { throw .readerUnavailable("no result") }387        guard object["ok"]?.boolValue == true else {388            throw .readerUnavailable(object["reason"]?.stringValue ?? "not an article")389        }390        guard let html = object["contentHTML"]?.stringValue, let text = object["textContent"]?.stringValue,391              html.utf16.count <= 4_000_000 else { throw .readerUnavailable("malformed result") }392        if let violation = firstViolation(in: html) { throw .readerUnavailable("unsafe markup: \(violation)") }393        func capped(_ key: String, _ limit: Int) -> String { String((object[key]?.stringValue ?? "").prefix(limit)) }394        return ReaderArticle(url: (object["url"]?.stringValue).flatMap(BridgeValidator.anyURL),395                             title: capped("title", 500), byline: capped("byline", 120), language: capped("language", 35),396                             publishedTime: capped("publishedTime", 64), contentHTML: html, textContent: text,397                             wordCount: max(0, object["wordCount"]?.intValue ?? 0),398                             isTruncated: object["truncated"]?.boolValue ?? false)399    }400}401
Files main
Menu

Theme