Repository Public License
1import Foundation23/// The transport rule for user-supplied endpoints.4///5/// HTTPS is always accepted. Plain HTTP sends prompts, page content and the key unencrypted, so it is accepted6/// without further consent only for a host on this machine or a private network (Ollama, LM Studio, a home server);7/// for any other host the user must explicitly opt in.8public enum EndpointPolicy {9 /// Validates a base URL typed by the user.10 /// - Parameter allowInsecureHTTP: the user's explicit opt-in to plain HTTP for a host that is not local or private.11 public static func validate(_ text: String, allowInsecureHTTP: Bool = false) throws -> URL {12 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)13 guard let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {14 throw ProviderError.configuration("Enter a full URL such as https://example.com/v1.")15 }16 guard url.user == nil, url.password == nil else {17 throw ProviderError.configuration("Do not put credentials in the URL; use the API key field.")18 }19 guard url.query == nil, url.fragment == nil else {20 throw ProviderError.configuration("The base URL cannot contain a query or a fragment.")21 }22 switch scheme {23 case "https": return url24 case "http":25 guard isLocalOrPrivateHost(host) || allowInsecureHTTP else {26 throw ProviderError.insecureEndpoint("Plain HTTP would send your prompts and key unencrypted to “\(host)”. Use https, or explicitly allow insecure HTTP for this endpoint.")27 }28 return url29 default:30 throw ProviderError.configuration("Only https (or http on your own network) endpoints are supported.")31 }32 }3334 /// Whether `host` names this machine or an address in a private range. Decided from the spelling alone: no DNS35 /// lookup is made, so a public name that resolves to a private address is not "local".36 public static func isLocalOrPrivateHost(_ host: String) -> Bool {37 var name = host.lowercased()38 if name.hasPrefix("["), name.hasSuffix("]") { name = String(name.dropFirst().dropLast()) }39 if name == "localhost" || name.hasSuffix(".localhost") || name.hasSuffix(".local") { return true }40 if name.contains(":") { // IPv6 literal41 if name == "::1" { return true }42 // fc00::/7 unique local, fe80::/10 link local.43 return name.hasPrefix("fc") || name.hasPrefix("fd") || name.hasPrefix("fe8") || name.hasPrefix("fe9") || name.hasPrefix("fea") || name.hasPrefix("feb")44 }45 // Exactly four labels of ASCII digits: "10.0.0.1.evil.com" and "+10.0.0.1" are names, not addresses.46 let labels = name.split(separator: ".", omittingEmptySubsequences: false)47 guard labels.count == 4 else { return false }48 let parts = labels.compactMap { label -> Int? in49 guard (1...3).contains(label.utf8.count), label.utf8.allSatisfy({ (48...57).contains($0) }) else { return nil }50 // The system resolver reads a label with a leading zero as octal ("010" is 8): what this function would51 // call 10.0.0.1 could be dialled as 8.0.0.1. Such a spelling is refused rather than interpreted.52 guard label.utf8.count == 1 || label.utf8.first != 48 else { return nil }53 return Int(label)54 }55 guard parts.count == 4, parts.allSatisfy({ (0...255).contains($0) }) else { return false }56 if parts[0] == 10 || parts[0] == 127 { return true }57 if parts[0] == 192, parts[1] == 168 { return true }58 if parts[0] == 172, (16...31).contains(parts[1]) { return true }59 if parts[0] == 169, parts[1] == 254 { return true }60 if parts[0] == 100, (64...127).contains(parts[1]) { return true } // CGNAT range used by private overlay networks61 return false62 }6364 /// Headers a user may add to a compatible endpoint. Credentials belong in the key field (and so in the Keychain),65 /// not in the non-secret configuration.66 public static func validate(headers: [String: String]) throws {67 let reserved: Set<String> = ["authorization", "proxy-authorization", "x-api-key", "api-key", "cookie", "set-cookie", "host", "content-length", "content-type"]68 for (name, value) in headers {69 let lower = name.lowercased().trimmingCharacters(in: .whitespaces)70 guard !lower.isEmpty, lower.range(of: #"^[a-z0-9\-_]+$"#, options: .regularExpression) != nil else {71 throw ProviderError.configuration("“\(name)” is not a valid header name.")72 }73 guard !reserved.contains(lower) else {74 throw ProviderError.configuration("The “\(name)” header cannot be set here. Put credentials in the API key field.")75 }76 // Scalar check: "\r\n" is a single Character in Swift, so a Character-level search would miss it.77 guard !value.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7F }) else {78 throw ProviderError.configuration("Header values cannot contain line breaks or control characters.")79 }80 }81 }82}83