SPB Git

Repository Public License

InternalSchemeHandler.swift 5.7 KB 126 lines swift

1import Foundation2import NavigatorCore3import WebKit45/// Content of an internal `orix://` page or resource.6public struct InternalResource: Sendable, Hashable {7    public var data: Data8    public var mimeType: String9    public var textEncodingName: String?10    /// Overrides the default policy of internal pages. Keep it as strict as the page allows.11    public var contentSecurityPolicy: String?1213    public init(data: Data, mimeType: String, textEncodingName: String? = "utf-8", contentSecurityPolicy: String? = nil) {14        self.data = data; self.mimeType = mimeType; self.textEncodingName = textEncodingName15        self.contentSecurityPolicy = contentSecurityPolicy16    }1718    public static func html(_ html: String) -> InternalResource {19        InternalResource(data: Data(html.utf8), mimeType: "text/html")20    }21}2223/// Supplies the pages behind `orix://` (new tab, error pages, offline archive reader). Implemented by the app.24/// Only content the app owns may be returned: never proxy a remote URL through this scheme.25@MainActor26public protocol InternalContentProvider: AnyObject {27    func internalResource(for url: URL, profile: Profile) async -> InternalResource?28}2930/// Well-known internal addresses.31public enum InternalPage {32    public static let scheme = WebRuntimeConstants.internalScheme33    public static let newTab = URL(string: "orix://newtab/")!3435    public static func url(host: String, path: String = "/", query: [URLQueryItem] = []) -> URL? {36        var components = URLComponents()37        components.scheme = scheme38        components.host = host39        components.path = path.hasPrefix("/") ? path : "/" + path40        if !query.isEmpty { components.queryItems = query }41        return components.url42    }4344    public static func isInternal(_ url: URL?) -> Bool { url?.scheme?.lowercased() == scheme }45}4647/// `WKURLSchemeHandler` for `orix://`.48///49/// Two independent gates keep the web away from internal pages: the navigation policy refuses any `orix:`50/// navigation started by web content, and this handler refuses any request whose main document is not itself51/// an internal page (sub-resources never pass through the navigation policy).52@MainActor53final class InternalSchemeHandler: NSObject, WKURLSchemeHandler {54    static let defaultContentSecurityPolicy =55        "default-src 'none'; img-src orix: data:; style-src orix: 'unsafe-inline'; script-src orix:; font-src orix:; "56        + "media-src orix:; connect-src orix:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"5758    private let profile: Profile59    weak var provider: (any InternalContentProvider)?60    private var activeTasks: Set<ObjectIdentifier> = []61    /// Requests refused because they came from a document that is not internal.62    private(set) var refusedRequestCount = 06364    init(profile: Profile) { self.profile = profile }6566    func webView(_ webView: WKWebView, start urlSchemeTask: any WKURLSchemeTask) {67        let request = urlSchemeTask.request68        guard let url = request.url, InternalPage.isInternal(url) else {69            urlSchemeTask.didFailWithError(URLError(.unsupportedURL))70            return71        }72        let mainDocument = request.mainDocumentURL73        let embedderIsInternal = mainDocument.map { InternalPage.isInternal($0) } ?? InternalPage.isInternal(webView.url)74        guard embedderIsInternal else {75            refusedRequestCount += 176            urlSchemeTask.didFailWithError(URLError(.noPermissionsToReadFile))77            return78        }79        guard request.httpMethod == nil || request.httpMethod == "GET" else {80            urlSchemeTask.didFailWithError(URLError(.badServerResponse))81            return82        }8384        let key = ObjectIdentifier(urlSchemeTask)85        activeTasks.insert(key)86        Task { @MainActor [weak self] in87            guard let self else { return }88            let resource = await self.provider?.internalResource(for: url, profile: self.profile)89                ?? Self.builtInResource(for: url)90            // WebKit raises an exception when a stopped task is messaged.91            guard self.activeTasks.remove(key) != nil else { return }92            guard let resource else {93                urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist))94                return95            }96            var contentType = resource.mimeType97            if let encoding = resource.textEncodingName { contentType += "; charset=\(encoding)" }98            let headers = [99                "Content-Type": contentType,100                "Content-Length": "\(resource.data.count)",101                "Content-Security-Policy": resource.contentSecurityPolicy ?? Self.defaultContentSecurityPolicy,102                "X-Content-Type-Options": "nosniff",103                "Cache-Control": "no-store",104                "Referrer-Policy": "no-referrer",105            ]106            guard let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers) else {107                urlSchemeTask.didFailWithError(URLError(.badServerResponse))108                return109            }110            urlSchemeTask.didReceive(response)111            urlSchemeTask.didReceive(resource.data)112            urlSchemeTask.didFinish()113        }114    }115116    func webView(_ webView: WKWebView, stop urlSchemeTask: any WKURLSchemeTask) {117        activeTasks.remove(ObjectIdentifier(urlSchemeTask))118    }119120    /// Used when the app supplies nothing: an empty new-tab document, so a fresh tab has a real, inert page.121    static func builtInResource(for url: URL) -> InternalResource? {122        guard url.host()?.lowercased() == "newtab", url.path.isEmpty || url.path == "/" else { return nil }123        return .html("<!doctype html><html><head><meta charset=\"utf-8\"><title></title></head><body></body></html>")124    }125}126
Files main
Menu

Theme