SPB Git

Repository Public

PageScripts.swift 11.4 KB 248 lines swift

1import AppKit2import Security3import WebKit45/// JavaScript run by the browser itself. Everything executes in an isolated content world, so page scripts6/// can neither observe nor tamper with it, and results are plain JSON values.7@MainActor8enum PageScripts {9    static let world = WKContentWorld.world(name: "SPBrowserInternal")1011    static let faviconURL = """12    (function () {13      const links = Array.from(document.querySelectorAll("link[rel~='icon'], link[rel='apple-touch-icon'], link[rel='shortcut icon']"));14      const best = links.find(l => /apple-touch-icon/i.test(l.rel)) || links.find(l => (l.sizes && l.sizes.value || '').match(/(32|48|64|96|128|180|192)/)) || links[0];15      return best && best.href ? best.href : new URL('/favicon.ico', location.href).href;16    })()17    """1819    static let pageText = "(document.body ? document.body.innerText : '') || ''"2021    static let pageSource = "document.documentElement ? document.documentElement.outerHTML : ''"2223    /// Title, description, canonical, robots, Open Graph, headings, links and resource timings as one JSON string.24    static let metadata = """25    (function () {26      const meta = (sel) => { const e = document.querySelector(sel); return e ? (e.content || e.getAttribute('href') || '') : ''; };27      const og = {};28      document.querySelectorAll("meta[property^='og:'], meta[name^='twitter:']").forEach(m => {29        og[m.getAttribute('property') || m.getAttribute('name')] = (m.content || '').slice(0, 500);30      });31      const links = Array.from(document.querySelectorAll('a[href]')).slice(0, 500).map(a => ({32        text: (a.innerText || a.getAttribute('aria-label') || '').trim().slice(0, 120), href: a.href,33        rel: a.rel || '', external: a.hostname !== location.hostname }));34      const resources = performance.getEntriesByType('resource').slice(0, 500).map(r => ({35        name: r.name, type: r.initiatorType, duration: Math.round(r.duration), start: Math.round(r.startTime),36        size: r.transferSize || 0, protocol: r.nextHopProtocol || '' }));37      const nav = performance.getEntriesByType('navigation')[0];38      return JSON.stringify({39        title: document.title, lang: document.documentElement.lang || '', charset: document.characterSet,40        description: meta("meta[name='description']"), canonical: meta("link[rel='canonical']"),41        robots: meta("meta[name='robots']"), viewport: meta("meta[name='viewport']"), generator: meta("meta[name='generator']"),42        social: og,43        headings: Array.from(document.querySelectorAll('h1, h2')).slice(0, 60).map(h => ({ level: h.tagName, text: h.innerText.trim().slice(0, 160) })),44        images: document.images.length, imagesWithoutAlt: Array.from(document.images).filter(i => !i.alt).length,45        links: links, resources: resources,46        timing: nav ? { domContentLoaded: Math.round(nav.domContentLoadedEventEnd), load: Math.round(nav.loadEventEnd),47                        ttfb: Math.round(nav.responseStart), transfer: nav.transferSize || 0 } : null48      });49    })()50    """5152    /// The reader extraction is shared with iOS: see `ReadingScripts` in Core/Aura.53    static let reader = ReadingScripts.reader54}5556struct PageMetadata: Decodable, Equatable {57    struct Heading: Decodable, Equatable, Identifiable { var level: String; var text: String; var id: String { level + text } }58    struct Link: Decodable, Equatable { var text: String; var href: String; var rel: String; var external: Bool }59    struct Resource: Decodable, Equatable { var name: String; var type: String; var duration: Int; var start: Int; var size: Int; var `protocol`: String }60    struct Timing: Decodable, Equatable { var domContentLoaded: Int; var load: Int; var ttfb: Int; var transfer: Int }61    var title: String62    var lang: String63    var charset: String64    var description: String65    var canonical: String66    var robots: String67    var viewport: String68    var generator: String69    var social: [String: String]70    var headings: [Heading]71    var images: Int72    var imagesWithoutAlt: Int73    var links: [Link]74    var resources: [Resource]75    var timing: Timing?76}7778/// What the address bar shows about the connection.79enum SecurityState: Equatable {80    case none        // start page, about:blank81    case secure      // HTTPS, all content secure82    case mixed       // HTTPS page that loaded insecure sub-resources83    case insecure    // plain HTTP to a remote host84    case local       // localhost, private network literal or file8586    var symbol: String {87        switch self {88        case .none: return "magnifyingglass"89        case .secure: return "lock.fill"90        case .mixed: return "lock.trianglebadge.exclamationmark"91        case .insecure: return "exclamationmark.triangle.fill"92        case .local: return "desktopcomputer"93        }94    }9596    var title: String {97        switch self {98        case .none: return ""99        case .secure: return L("Secure connection")100        case .mixed: return L("Connection partly insecure")101        case .insecure: return L("Connection not secure")102        case .local: return L("Local page")103        }104    }105106    static func evaluate(url: URL?, hasOnlySecureContent: Bool) -> SecurityState {107        guard let url, let scheme = url.scheme?.lowercased() else { return .none }108        switch scheme {109        case "https": return hasOnlySecureContent ? .secure : .mixed110        case "http": return AddressResolver.classify(host: url.host ?? "") == .local ? .local : .insecure111        case "file": return .local112        default: return .none113        }114    }115}116117/// The parts of a TLS certificate that public Security APIs expose.118struct CertificateSummary: Equatable {119    var subject: String120    var issuer: String121    var expires: Date?122    var chainLength: Int123124    init?(trust: SecTrust?) {125        guard let trust, let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], let leaf = chain.first else { return nil }126        subject = (SecCertificateCopySubjectSummary(leaf) as String?) ?? ""127        issuer = chain.count > 1 ? ((SecCertificateCopySubjectSummary(chain[1]) as String?) ?? "") : L("Self-signed or unknown")128        chainLength = chain.count129        expires = nil130        let key = kSecOIDX509V1ValidityNotAfter131        if let values = SecCertificateCopyValues(leaf, [key] as CFArray, nil) as? [CFString: Any],132           let entry = values[key] as? [CFString: Any], let number = entry[kSecPropertyKeyValue] as? NSNumber {133            expires = Date(timeIntervalSinceReferenceDate: number.doubleValue)134        }135    }136}137138/// A failed navigation, classified so the error page can say something useful.139struct PageError: Equatable {140    enum Kind { case offline, hostNotFound, timeout, tls, connection, blocked, other }141    var url: URL?142    var kind: Kind143    var code: Int144    var domain: String145    var detail: String146147    init(error: Error, url: URL?) {148        let ns = error as NSError149        self.url = url ?? (ns.userInfo[NSURLErrorFailingURLErrorKey] as? URL)150        code = ns.code151        domain = ns.domain152        detail = ns.localizedDescription153        switch (ns.domain, ns.code) {154        case (NSURLErrorDomain, NSURLErrorNotConnectedToInternet), (NSURLErrorDomain, NSURLErrorNetworkConnectionLost),155             (NSURLErrorDomain, NSURLErrorDataNotAllowed), (NSURLErrorDomain, NSURLErrorInternationalRoamingOff):156            kind = .offline157        case (NSURLErrorDomain, NSURLErrorCannotFindHost), (NSURLErrorDomain, NSURLErrorDNSLookupFailed):158            kind = .hostNotFound159        case (NSURLErrorDomain, NSURLErrorTimedOut):160            kind = .timeout161        case (NSURLErrorDomain, let c) where (NSURLErrorClientCertificateRequired...NSURLErrorSecureConnectionFailed).contains(c):162            kind = .tls163        case (NSURLErrorDomain, NSURLErrorCannotConnectToHost), (NSURLErrorDomain, NSURLErrorResourceUnavailable),164             (NSURLErrorDomain, NSURLErrorBadServerResponse):165            kind = .connection166        default:167            kind = .other168        }169    }170171    init(blocked url: URL?, reason: String) {172        self.url = url; kind = .blocked; code = 0; domain = "SPBrowser"; detail = reason173    }174175    /// Cancelled loads and policy interruptions (downloads, redirects to apps) are not errors.176    static func isBenign(_ error: Error) -> Bool {177        let ns = error as NSError178        return (ns.domain == NSURLErrorDomain && ns.code == NSURLErrorCancelled) || (ns.domain == "WebKitErrorDomain" && [102, 204].contains(ns.code))179    }180181    var title: String {182        switch kind {183        case .offline: return L("You are offline")184        case .hostNotFound: return L("This site can’t be found")185        case .timeout: return L("The site took too long to respond")186        case .tls: return L("A secure connection could not be established")187        case .connection: return L("The site refused the connection")188        case .blocked: return L("Navigation blocked")189        case .other: return L("This page could not be loaded")190        }191    }192193    var advice: String {194        switch kind {195        case .offline: return L("Check your network connection, then try again.")196        case .hostNotFound: return L("Check the address for typing mistakes. The site may also be temporarily unavailable.")197        case .timeout: return L("The server may be busy or unreachable. Try again in a moment.")198        case .tls: return L("The site’s certificate or encryption is not valid. SP Browser does not offer a way to bypass this check, because doing so would expose what you send to the site.")199        case .connection: return L("The server is not accepting connections at this address or port.")200        case .blocked: return L("SP Browser stopped this navigation to protect you.")201        case .other: return L("Try reloading the page.")202        }203    }204205    var symbol: String {206        switch kind {207        case .offline: return "wifi.slash"208        case .hostNotFound: return "questionmark.circle"209        case .timeout: return "clock.badge.exclamationmark"210        case .tls: return "lock.slash"211        case .connection: return "xmark.octagon"212        case .blocked: return "hand.raised"213        case .other: return "exclamationmark.triangle"214        }215    }216}217218/// In-memory favicon cache shared by all tabs. Icons are fetched with an ephemeral, cookie-less session.219@MainActor220final class FaviconLoader {221    static let shared = FaviconLoader()222    private var cache: [String: NSImage] = [:]223    private var inFlight: Set<String> = []224    private let session: URLSession = {225        let config = URLSessionConfiguration.ephemeral226        config.httpShouldSetCookies = false227        config.httpCookieAcceptPolicy = .never228        config.timeoutIntervalForRequest = 10229        return URLSession(configuration: config)230    }()231232    func cached(forHost host: String?) -> NSImage? { host.flatMap { cache[$0.lowercased()] } }233234    func load(from iconURL: URL, host: String) async -> NSImage? {235        let key = host.lowercased()236        if let image = cache[key] { return image }237        guard let scheme = iconURL.scheme?.lowercased(), scheme == "https" || scheme == "http", !inFlight.contains(key) else { return nil }238        inFlight.insert(key)239        defer { inFlight.remove(key) }240        guard let (data, response) = try? await session.data(from: iconURL), (response as? HTTPURLResponse)?.statusCode == 200,241              data.count < 1_000_000, let image = NSImage(data: data), image.isValid, image.size.width > 0 else { return nil }242        image.size = NSSize(width: 16, height: 16)243        if cache.count > 500 { cache.removeAll() }244        cache[key] = image245        return image246    }247}248
Files main
Menu

Theme