Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Networking/HTTPClient.swift4// Description: URLSession transport for the SP Chat backend — session cookie kept in the Keychain, Origin header, rotation, 401/403 handling.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112/// Where the opaque session token lives. Production: Keychain. Tests: memory.13protocol SessionTokenStore: Sendable {14 func load() -> String?15 func save(_ token: String)16 func clear()17}1819struct HTTPRequest: Sendable {20 enum Body: Sendable {21 case none22 case json(Data)23 case multipart(data: Data, boundary: String)24 }25 var method: String = "GET"26 var path: String27 var query: [URLQueryItem] = []28 var body: Body = .none29 var accept: String = "application/json"30 var timeout: TimeInterval = 3031 /// Sensitive operations: when the server answers 403 `reauth_required`, run a passkey verification once and replay.32 var allowReauth: Bool = true3334 static func get(_ path: String, query: [URLQueryItem] = []) -> HTTPRequest { HTTPRequest(path: path, query: query) }35 static func json<T: Encodable>(_ method: String, _ path: String, _ value: T) throws -> HTTPRequest {36 HTTPRequest(method: method, path: path, body: .json(try JSONEncoder().encode(value)))37 }38 static func json(_ method: String, _ path: String, object: [String: JSONValue] = [:]) -> HTTPRequest {39 HTTPRequest(method: method, path: path, body: .json((try? JSONEncoder().encode(JSONValue.object(object))) ?? Data("{}".utf8)))40 }41}4243/// The single entry point to the network. An actor: cookie state is mutated from concurrent requests.44///45/// The backend authenticates with an HttpOnly cookie (`__Host-csa_session`) that it rotates after every passkey46/// verification. The app does not use `HTTPCookieStorage` (cookies would sit unprotected in the app container):47/// the token is read from `Set-Cookie`, kept in the Keychain and sent back explicitly. Short-lived ceremony cookies48/// (WebAuthn challenge id, enrolment window) stay in memory only.49actor HTTPClient {50 let configuration: AppConfiguration51 private let session: URLSession52 private let tokens: SessionTokenStore53 private var sessionToken: String?54 private var transientCookies: [String: String] = [:]55 private var reauthHandler: (@Sendable () async throws -> Void)?56 private var sessionLostHandler: (@Sendable () async -> Void)?57 private var offlineProbe: @Sendable () -> Bool = { false }5859 init(configuration: AppConfiguration, tokens: SessionTokenStore, protocolClasses: [AnyClass]? = nil) {60 self.configuration = configuration61 self.tokens = tokens62 self.sessionToken = tokens.load()63 let c = URLSessionConfiguration.ephemeral64 c.httpCookieStorage = nil65 c.httpShouldSetCookies = false66 c.httpCookieAcceptPolicy = .never67 c.urlCache = nil68 c.requestCachePolicy = .reloadIgnoringLocalCacheData69 c.waitsForConnectivity = false70 c.timeoutIntervalForRequest = 6071 c.timeoutIntervalForResource = 20 * 60 // a generation may stream for a long time72 c.tlsMinimumSupportedProtocolVersion = .TLSv1273 c.httpAdditionalHeaders = ["User-Agent": configuration.userAgent, "Accept-Language": Locale.preferredLanguages.prefix(2).joined(separator: ", ")]74 if let protocolClasses { c.protocolClasses = protocolClasses }75 self.session = URLSession(configuration: c)76 }7778 // MARK: session state7980 var hasSession: Bool { sessionToken != nil }81 func setReauthHandler(_ h: (@Sendable () async throws -> Void)?) { reauthHandler = h }82 func setSessionLostHandler(_ h: (@Sendable () async -> Void)?) { sessionLostHandler = h }83 func setOfflineProbe(_ p: @escaping @Sendable () -> Bool) { offlineProbe = p }8485 /// Forgets the local session (sign-out, revoked session, wipe). Does not call the server.86 func clearSession() {87 sessionToken = nil; transientCookies.removeAll(); tokens.clear()88 }89 #if DEBUG90 /// Test hook: installs a session token minted for the development database (never compiled in release builds).91 func installDebugSession(_ token: String) { sessionToken = token; tokens.save(token) }92 #endif9394 // MARK: requests9596 func data(_ request: HTTPRequest) async throws -> Data {97 try await perform(request).098 }99100 func decode<T: Decodable>(_ type: T.Type = T.self, _ request: HTTPRequest) async throws -> T {101 let data = try await perform(request).0102 do { return try JSONDecoder().decode(T.self, from: data) }103 catch { throw APIError.decoding(String(describing: error)) }104 }105106 func perform(_ request: HTTPRequest) async throws -> (Data, HTTPURLResponse) {107 do {108 return try await once(request)109 } catch let e as APIError where e.kind == .reauthRequired && request.allowReauth {110 guard let reauthHandler else { throw e }111 try await reauthHandler()112 var replay = request; replay.allowReauth = false113 return try await once(replay)114 }115 }116117 private func once(_ request: HTTPRequest) async throws -> (Data, HTTPURLResponse) {118 let urlRequest = try build(request)119 let data: Data, response: URLResponse120 do { (data, response) = try await session.data(for: urlRequest) }121 catch { throw APIError.from(error, offline: offlineProbe()) }122 guard let http = response as? HTTPURLResponse else { throw APIError.network(offline: false) }123 absorbCookies(from: http)124 guard (200..<300).contains(http.statusCode) else {125 let err = APIError.from(status: http.statusCode, data: data, lockedHeader: http.value(forHTTPHeaderField: "x-csa-locked") != nil)126 if err.kind == .locked { await sessionLost() }127 throw err128 }129 return (data, http)130 }131132 /// Opens a streaming response (Server-Sent Events). Non-2xx answers are read fully and thrown as `APIError`;133 /// a JSON 2xx answer (idempotent replay: `{deduplicated}`) is returned as `.json`.134 enum StreamOpening: Sendable {135 case events(URLSession.AsyncBytes)136 case json(Data)137 }138 func openStream(_ request: HTTPRequest) async throws -> StreamOpening {139 var r = request; r.accept = "text/event-stream"140 let urlRequest = try build(r)141 let bytes: URLSession.AsyncBytes, response: URLResponse142 do { (bytes, response) = try await session.bytes(for: urlRequest) }143 catch { throw APIError.from(error, offline: offlineProbe()) }144 guard let http = response as? HTTPURLResponse else { throw APIError.network(offline: false) }145 absorbCookies(from: http)146 let isJSON = (http.value(forHTTPHeaderField: "Content-Type") ?? "").contains("application/json")147 if (200..<300).contains(http.statusCode) && !isJSON { return .events(bytes) }148 var data = Data()149 do { for try await b in bytes { data.append(b); if data.count > 1_000_000 { break } } }150 catch { throw APIError.from(error, offline: offlineProbe()) }151 if (200..<300).contains(http.statusCode) { return .json(data) }152 let err = APIError.from(status: http.statusCode, data: data, lockedHeader: http.value(forHTTPHeaderField: "x-csa-locked") != nil)153 if err.kind == .locked { await sessionLost() }154 throw err155 }156157 /// Multipart upload with byte-level progress.158 func upload(_ request: HTTPRequest, progress: @escaping @Sendable (Double) -> Void) async throws -> Data {159 guard case .multipart(let body, _) = request.body else { return try await data(request) }160 var urlRequest = try build(request)161 urlRequest.httpBody = nil162 let delegate = UploadProgressDelegate(progress)163 let data: Data, response: URLResponse164 do { (data, response) = try await session.upload(for: urlRequest, from: body, delegate: delegate) }165 catch { throw APIError.from(error, offline: offlineProbe()) }166 guard let http = response as? HTTPURLResponse else { throw APIError.network(offline: false) }167 absorbCookies(from: http)168 guard (200..<300).contains(http.statusCode) else {169 let err = APIError.from(status: http.statusCode, data: data, lockedHeader: http.value(forHTTPHeaderField: "x-csa-locked") != nil)170 if err.kind == .locked { await sessionLost() }171 throw err172 }173 return data174 }175176 // MARK: plumbing177178 private func build(_ r: HTTPRequest) throws -> URLRequest {179 guard var comps = URLComponents(url: configuration.baseURL.appendingPathComponent(r.path), resolvingAgainstBaseURL: false) else { throw APIError.network(offline: false) }180 if !r.query.isEmpty { comps.queryItems = r.query }181 guard let url = comps.url else { throw APIError.network(offline: false) }182 var req = URLRequest(url: url, timeoutInterval: r.timeout)183 req.httpMethod = r.method184 req.setValue(r.accept, forHTTPHeaderField: "Accept")185 // The server refuses every mutation whose Origin is not its own public origin (CSRF defence designed for186 // browsers). A native client is not subject to CSRF; it states the origin it talks to.187 req.setValue(configuration.origin, forHTTPHeaderField: "Origin")188 var cookies = transientCookies189 if let sessionToken { cookies[configuration.sessionCookieName] = sessionToken }190 if !cookies.isEmpty { req.setValue(cookies.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: "; "), forHTTPHeaderField: "Cookie") }191 switch r.body {192 case .none: break193 case .json(let d): req.httpBody = d; req.setValue("application/json", forHTTPHeaderField: "Content-Type")194 case .multipart(let d, let boundary): req.httpBody = d; req.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")195 }196 return req197 }198199 private func absorbCookies(from http: HTTPURLResponse) {200 guard let url = http.url else { return }201 var fields: [String: String] = [:]202 for (k, v) in http.allHeaderFields { if let k = k as? String, let v = v as? String { fields[k] = v } }203 for cookie in HTTPCookie.cookies(withResponseHeaderFields: fields, for: url) {204 let expired = cookie.value.isEmpty || (cookie.expiresDate.map { $0 <= Date() } ?? false)205 if cookie.name == configuration.sessionCookieName {206 if expired { sessionToken = nil; tokens.clear() }207 else if cookie.value != sessionToken { sessionToken = cookie.value; tokens.save(cookie.value) }208 } else if configuration.transientCookieNames.contains(cookie.name) {209 transientCookies[cookie.name] = expired ? nil : cookie.value210 }211 }212 }213214 private func sessionLost() async {215 guard sessionToken != nil else { return }216 clearSession()217 await sessionLostHandler?()218 }219}220221private final class UploadProgressDelegate: NSObject, URLSessionTaskDelegate, Sendable {222 private let progress: @Sendable (Double) -> Void223 init(_ progress: @escaping @Sendable (Double) -> Void) { self.progress = progress }224 func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {225 guard totalBytesExpectedToSend > 0 else { return }226 progress(min(0.99, Double(totalBytesSent) / Double(totalBytesExpectedToSend)))227 }228}229230/// multipart/form-data builder.231struct MultipartForm: Sendable {232 let boundary = "spchat-" + UUID().uuidString233 private(set) var data = Data()234 mutating func addField(_ name: String, _ value: String) {235 data.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".utf8))236 }237 mutating func addFile(_ name: String, filename: String, mime: String, content: Data) {238 let safe = filename.replacingOccurrences(of: "\"", with: "_").replacingOccurrences(of: "\r", with: " ").replacingOccurrences(of: "\n", with: " ")239 data.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"; filename=\"\(safe)\"\r\nContent-Type: \(mime)\r\n\r\n".utf8))240 data.append(content); data.append(Data("\r\n".utf8))241 }242 func finalized() -> Data { var d = data; d.append(Data("--\(boundary)--\r\n".utf8)); return d }243}244