SPB Git

Repository Public

URLPolicy.swift 3.6 KB 61 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatNetworking/Sources/URLPolicy.swift3// Description: Transport rule for remote nodes: HTTPS anywhere, plain HTTP only towards loopback / private / link-local / .local hosts unless the user opts in.4import Foundation56public enum URLPolicy {7    public enum HostClass: String, Sendable { case loopback, privateNetwork, linkLocal, localName, overlay, publicHost }89    public enum Violation: LocalizedError, Sendable, Equatable {10        case invalidURL(String)11        case unsupportedScheme(String)12        case insecurePublicHost(String)13        public var errorDescription: String? {14            switch self {15            case .invalidURL(let u): "“\(u)” is not a valid URL."16            case .unsupportedScheme(let s): "Unsupported scheme “\(s)”. Use https:// (or http:// on your own network)."17            case .insecurePublicHost(let h): "Plain HTTP to “\(h)” would send your conversations unencrypted over the Internet. Use https://, or explicitly allow insecure HTTP for this node."18            }19        }20    }2122    public static func classify(host raw: String) -> HostClass {23        var host = raw.lowercased()24        if host.hasPrefix("["), host.hasSuffix("]") { host = String(host.dropFirst().dropLast()) }25        if let zone = host.firstIndex(of: "%") { host = String(host[..<zone]) }26        if host == "localhost" || host.hasSuffix(".localhost") || host == "::1" { return .loopback }27        let parts = host.split(separator: ".", omittingEmptySubsequences: false).map { Int($0) }28        if parts.count == 4, let a = parts[0], let b = parts[1], parts[2] != nil, parts[3] != nil, parts.allSatisfy({ ($0 ?? -1) >= 0 && ($0 ?? 256) <= 255 }) {29            if a == 127 { return .loopback }30            if a == 10 || (a == 172 && (16...31).contains(b)) || (a == 192 && b == 168) { return .privateNetwork }31            if a == 169 && b == 254 { return .linkLocal }32            if a == 100 && (64...127).contains(b) { return .overlay }   // CGNAT range used by Tailscale / WireGuard overlays33            return .publicHost34        }35        if host.contains(":") {   // IPv6 literal36            if host.hasPrefix("fe8") || host.hasPrefix("fe9") || host.hasPrefix("fea") || host.hasPrefix("feb") { return .linkLocal }37            if host.hasPrefix("fc") || host.hasPrefix("fd") { return .privateNetwork }38            if host.hasPrefix("::ffff:") { return classify(host: String(host.dropFirst(7))) }39            return .publicHost40        }41        if host.hasSuffix(".local") || host.hasSuffix(".lan") || host.hasSuffix(".home.arpa") || host.hasSuffix(".internal") || !host.contains(".") { return .localName }42        return .publicHost43    }4445    /// Returns the validated URL or throws the reason it is refused.46    @discardableResult47    public static func validate(_ string: String, allowInsecureHTTP: Bool = false) throws -> URL {48        let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)49        guard let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else { throw Violation.invalidURL(string) }50        switch scheme {51        case "https": return url52        case "http":53            if allowInsecureHTTP || classify(host: host) != .publicHost { return url }54            throw Violation.insecurePublicHost(host)55        default: throw Violation.unsupportedScheme(scheme)56        }57    }5859    public static func isAllowed(_ string: String, allowInsecureHTTP: Bool = false) -> Bool { (try? validate(string, allowInsecureHTTP: allowInsecureHTTP)) != nil }60}61
Files main
Menu

Theme