Repository Public
1import Foundation23/// Where the SP Browser backend lives. Overridable for tests and development (`-SPBBackendURL http://127.0.0.1:8710`).4struct BackendConfiguration: Equatable, Sendable {5 var baseURL: URL6 /// WebAuthn relying-party identifier: the domain passkeys are bound to.7 var relyingParty: String89 static let production = BackendConfiguration(baseURL: URL(string: "https://browser.spboucher.ai")!, relyingParty: "browser.spboucher.ai")1011 static func current(defaults: UserDefaults = .standard) -> BackendConfiguration {12 if let override = defaults.string(forKey: "SPBBackendURL"), let url = URL(string: override), url.host != nil {13 return BackendConfiguration(baseURL: url, relyingParty: defaults.string(forKey: "SPBRelyingParty") ?? production.relyingParty)14 }15 return .production16 }17}1819/// A failure reported by the backend (stable `code`) or by the transport.20struct BackendError: Error, Equatable, Sendable, LocalizedError {21 enum Kind: Equatable, Sendable { case offline, timeout, server, unauthenticated, rateLimited, invalidResponse }22 var kind: Kind23 var code: String24 var message: String25 var status: Int26 var retryAfter: TimeInterval?2728 var errorDescription: String? { message }29 var isTransient: Bool { kind == .offline || kind == .timeout || kind == .rateLimited || status >= 500 }3031 static func transport(_ error: Error) -> BackendError {32 let ns = error as NSError33 if ns.domain == NSURLErrorDomain {34 switch ns.code {35 case NSURLErrorNotConnectedToInternet, NSURLErrorNetworkConnectionLost, NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost,36 NSURLErrorDNSLookupFailed, NSURLErrorInternationalRoamingOff, NSURLErrorDataNotAllowed, NSURLErrorSecureConnectionFailed:37 return BackendError(kind: .offline, code: "offline", message: L("The server cannot be reached. Check the internet connection."), status: 0)38 case NSURLErrorTimedOut:39 return BackendError(kind: .timeout, code: "timeout", message: L("The server took too long to answer."), status: 0)40 default: break41 }42 }43 return BackendError(kind: .offline, code: "network", message: L("The server cannot be reached. Check the internet connection."), status: 0)44 }45}4647/// Minimal JSON-over-HTTPS client shared by SP Search, SP Identity and SP Sync.48/// The session token is supplied by a closure so the client never stores it.49final class BackendClient: Sendable {50 let configuration: BackendConfiguration51 private let session: URLSession52 private let token: @Sendable () -> String?5354 init(configuration: BackendConfiguration = .current(), session: URLSession? = nil, token: @escaping @Sendable () -> String? = { nil }) {55 self.configuration = configuration56 self.token = token57 if let session {58 self.session = session59 } else {60 let config = URLSessionConfiguration.ephemeral61 config.timeoutIntervalForRequest = 2062 config.timeoutIntervalForResource = 4063 config.httpCookieStorage = nil64 config.urlCache = nil65 config.waitsForConnectivity = false66 self.session = URLSession(configuration: config)67 }68 }6970 struct Empty: Codable, Sendable { init() {} }7172 func send<Body: Encodable & Sendable, Response: Decodable & Sendable>(73 _ method: String, _ path: String, body: Body? = Optional<Empty>.none, headers: [String: String] = [:],74 authenticated: Bool = true, as type: Response.Type = Response.self75 ) async throws -> Response {76 guard let url = URL(string: path, relativeTo: configuration.baseURL) else {77 throw BackendError(kind: .invalidResponse, code: "bad_url", message: L("The request could not be built."), status: 0)78 }79 var request = URLRequest(url: url)80 request.httpMethod = method81 request.setValue("application/json", forHTTPHeaderField: "Accept")82 if authenticated, let token = token() { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }83 for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }84 if let body {85 request.setValue("application/json", forHTTPHeaderField: "Content-Type")86 request.httpBody = try JSONEncoder().encode(body)87 }88 let data: Data, response: URLResponse89 do { (data, response) = try await session.data(for: request) } catch let error as CancellationError { throw error } catch {90 if (error as NSError).code == NSURLErrorCancelled { throw CancellationError() }91 throw BackendError.transport(error)92 }93 guard let http = response as? HTTPURLResponse else {94 throw BackendError(kind: .invalidResponse, code: "invalid_response", message: L("The server sent an unreadable answer."), status: 0)95 }96 guard (200..<300).contains(http.statusCode) else { throw Self.error(status: http.statusCode, data: data, response: http) }97 do { return try JSONDecoder().decode(Response.self, from: data) } catch {98 throw BackendError(kind: .invalidResponse, code: "invalid_response", message: L("The server sent an unreadable answer."), status: http.statusCode)99 }100 }101102 private struct ErrorEnvelope: Decodable { struct Detail: Decodable { var code: String; var message: String; var retryAfter: Double? }; var error: Detail }103104 private static func error(status: Int, data: Data, response: HTTPURLResponse) -> BackendError {105 let detail = (try? JSONDecoder().decode(ErrorEnvelope.self, from: data))?.error106 let retry = detail?.retryAfter ?? response.value(forHTTPHeaderField: "Retry-After").flatMap(Double.init)107 let kind: BackendError.Kind = status == 401 ? .unauthenticated : status == 429 ? .rateLimited : .server108 return BackendError(kind: kind, code: detail?.code ?? "http_\(status)", message: detail?.message ?? L("The server answered with an error (%d).", status),109 status: status, retryAfter: retry)110 }111}112