SPB Git

Repository Public

APIClient.swift 17.3 KB 300 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Networking/APIClient.swift3// Description: Authenticated JSON / SSE / multipart client of the chat backend: session cookie from the Keychain, Origin header, error mapping, re-authentication retry.4import Foundation56// MARK: - Errors78public struct APIError: Error, Sendable, Equatable, CustomStringConvertible, LocalizedError {9    public enum Kind: Sendable, Equatable {10        case network(offline: Bool)   // nothing reached the server11        case locked                   // 401: no session, or session revoked / expired12        case reauthRequired           // 403: sensitive operation, passkey verification needed13        case rateLimited(retryAfter: Int?)14        case server(status: Int)      // any other HTTP error15        case decoding                 // the server answered something this client cannot read16        case insecure                 // refused locally: non-HTTPS server17        case cancelled18    }19    public let kind: Kind20    public let message: String21    public let code: String?22    public let requestId: String?2324    public init(_ kind: Kind, message: String, code: String? = nil, requestId: String? = nil) { self.kind = kind; self.message = message; self.code = code; self.requestId = requestId }25    public var description: String { message }26    public var errorDescription: String? { message }27    public var status: Int? { if case .server(let s) = kind { return s }; if case .locked = kind { return 401 }; if case .reauthRequired = kind { return 403 }; if case .rateLimited = kind { return 429 }; return nil }28    public var isNetwork: Bool { if case .network = kind { return true }; return false }2930    public static func from(_ error: Error) -> APIError {31        if let e = error as? APIError { return e }32        if error is CancellationError { return APIError(.cancelled, message: "Annulé") }33        if let u = error as? URLError {34            if u.code == .cancelled { return APIError(.cancelled, message: "Annulé") }35            let offline = [.notConnectedToInternet, .networkConnectionLost, .dataNotAllowed, .internationalRoamingOff].contains(u.code)36            if [.serverCertificateUntrusted, .serverCertificateHasBadDate, .serverCertificateHasUnknownRoot, .serverCertificateNotYetValid, .clientCertificateRejected, .secureConnectionFailed].contains(u.code) {37                return APIError(.network(offline: false), message: "Connexion sécurisée refusée : le certificat du serveur n'est pas valide.", code: "tls")38            }39            return APIError(.network(offline: offline), message: offline ? "Hors ligne : la requête n'a pas été envoyée." : "Réseau indisponible : la requête n'a pas abouti.", code: "network")40        }41        return APIError(.network(offline: false), message: "Réseau indisponible : la requête n'a pas abouti.", code: "network")42    }43}4445// MARK: - Configuration4647public struct ServerConfiguration: Sendable, Equatable {48    public let baseURL: URL49    /// Exact origin sent on every mutation (the server's CSRF check accepts only its own origin).50    public let origin: String51    public let host: String52    public var isSecure: Bool { baseURL.scheme == "https" }5354    public static let production = ServerConfiguration(url: URL(string: "https://chat.spboucher.ai")!)!5556    /// HTTPS is mandatory; plain HTTP is accepted for a loopback development server only.57    public init?(url: URL) {58        guard let scheme = url.scheme?.lowercased(), let host = url.host?.lowercased() else { return nil }59        let loopback = host == "localhost" || host == "127.0.0.1"60        guard scheme == "https" || (scheme == "http" && loopback) else { return nil }61        var origin = "\(scheme)://\(host)"62        if let port = url.port, !(scheme == "https" && port == 443), !(scheme == "http" && port == 80) { origin += ":\(port)" }63        self.baseURL = URL(string: origin)!; self.origin = origin; self.host = host64    }65}6667// MARK: - Cookies6869/// Minimal cookie handling for one origin. The session cookie is the only persistent secret: it is written to the70/// `SecretStore` (Keychain) and never to disk in clear. Ceremony / enrolment cookies live in memory only.71public final class CookieJar: @unchecked Sendable {72    private let lock = NSLock()73    private var cookies: [String: String] = [:]74    private let store: SecretStore75    private let storeKey: String76    private static let sessionNames: Set<String> = ["__Host-csa_session", "csa_session"]7778    public init(store: SecretStore, host: String) {79        self.store = store; self.storeKey = "session@\(host)"80        if let saved = store.read(storeKey), let i = saved.firstIndex(of: "=") {81            cookies[String(saved[..<i])] = String(saved[saved.index(after: i)...])82        }83    }8485    public var hasSession: Bool { lock.withLock { cookies.keys.contains(where: Self.sessionNames.contains) } }86    public var header: String? {87        lock.withLock { cookies.isEmpty ? nil : cookies.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: "; ") }88    }8990    /// Applies a (possibly comma-merged) `Set-Cookie` header value.91    public func ingest(setCookie header: String) {92        for item in Self.split(header) {93            let attrs = item.split(separator: ";").map { $0.trimmingCharacters(in: .whitespaces) }94            guard let first = attrs.first, let eq = first.firstIndex(of: "=") else { continue }95            let name = String(first[..<eq]); let value = String(first[first.index(after: eq)...])96            guard name.contains("csa_") else { continue } // only this application's cookies97            var expired = value.isEmpty98            for a in attrs.dropFirst() {99                let lower = a.lowercased()100                if lower.hasPrefix("max-age="), let n = Int(lower.dropFirst(8)), n <= 0 { expired = true }101            }102            lock.withLock {103                if expired { cookies[name] = nil } else { cookies[name] = value }104                if Self.sessionNames.contains(name) {105                    if expired { store.delete(storeKey) } else { try? store.write("\(name)=\(value)", for: storeKey) }106                }107            }108        }109    }110111    public func clear() { lock.withLock { cookies.removeAll(); store.delete(storeKey) } }112113    /// Splits `a=1; Expires=Wed, 18 Nov 2026 …, b=2; Path=/` on the commas that start a new cookie.114    static func split(_ header: String) -> [String] {115        var out: [String] = []; var current = ""116        let parts = header.components(separatedBy: ",")117        for (i, p) in parts.enumerated() {118            let startsCookie = p.range(of: #"^\s*[A-Za-z0-9_\-\.]+="#, options: .regularExpression) != nil119            if i > 0 && startsCookie && !Self.looksLikeAttribute(p) { out.append(current); current = p } else { current += (i > 0 ? "," : "") + p }120        }121        if !current.trimmingCharacters(in: .whitespaces).isEmpty { out.append(current) }122        return out.map { $0.trimmingCharacters(in: .whitespaces) }123    }124    private static func looksLikeAttribute(_ s: String) -> Bool {125        let l = s.trimmingCharacters(in: .whitespaces).lowercased()126        return ["expires=", "max-age=", "path=", "domain=", "samesite="].contains(where: l.hasPrefix)127    }128}129130// MARK: - Client131132public enum HTTPMethod: String, Sendable { case get = "GET", post = "POST", put = "PUT", patch = "PATCH", delete = "DELETE" }133134public struct DownloadedFile: Sendable {135    public let data: Data136    public let filename: String?137    public let mime: String138}139140public final class APIClient: @unchecked Sendable {141    public let server: ServerConfiguration142    public let cookies: CookieJar143    private let transport: HTTPTransport144    private let userAgent: String145    private let lock = NSLock()146    private var _reauthenticator: (@Sendable () async throws -> Void)?147    private var _onSessionEnded: (@Sendable () -> Void)?148149    public init(server: ServerConfiguration, transport: HTTPTransport, secrets: SecretStore, userAgent: String = "SPChat/1.0 (Macintosh; Mac OS X) native") {150        self.server = server; self.transport = transport; self.userAgent = userAgent151        self.cookies = CookieJar(store: secrets, host: server.host)152    }153154    /// Called once when a sensitive operation answers `reauth_required`; the request is then replayed.155    public var reauthenticator: (@Sendable () async throws -> Void)? {156        get { lock.withLock { _reauthenticator } } set { lock.withLock { _reauthenticator = newValue } }157    }158    /// Called when the server reports that the session no longer exists (revoked, expired, signed out elsewhere).159    public var onSessionEnded: (@Sendable () -> Void)? {160        get { lock.withLock { _onSessionEnded } } set { lock.withLock { _onSessionEnded = newValue } }161    }162    public var hasSession: Bool { cookies.hasSession }163164    // MARK: Request building165166    public func makeRequest(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], accept: String = "application/json", timeout: TimeInterval? = nil) -> URLRequest {167        var comps = URLComponents(url: server.baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!168        let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }169        if !items.isEmpty { comps.queryItems = items }170        var r = URLRequest(url: comps.url!)171        r.httpMethod = method.rawValue172        r.setValue(accept, forHTTPHeaderField: "Accept")173        r.setValue(userAgent, forHTTPHeaderField: "User-Agent")174        if method != .get { r.setValue(server.origin, forHTTPHeaderField: "Origin") }175        if let c = cookies.header { r.setValue(c, forHTTPHeaderField: "Cookie") }176        r.httpShouldHandleCookies = false177        if let timeout { r.timeoutInterval = timeout }178        return r179    }180181    private func absorb(_ response: HTTPResponse) {182        if let sc = response.header("set-cookie") { cookies.ingest(setCookie: sc) }183    }184185    /// Maps a non-2xx answer to an `APIError` (and reports a dead session).186    func failure(_ response: HTTPResponse, body: Data) -> APIError {187        let j = JSONValue.parse(body)188        let message = j?["error"]?.stringValue ?? j?["message"]?.stringValue ?? "HTTP \(response.status)"189        let code = j?["code"]?.stringValue190        let rid = response.header("x-request-id")191        switch response.status {192        case 401 where response.header("x-csa-locked") != nil || code == "locked":193            cookies.clear(); onSessionEnded?()194            return APIError(.locked, message: "Session terminée", code: "locked", requestId: rid)195        case 403 where code == "reauth_required": return APIError(.reauthRequired, message: message, code: code, requestId: rid)196        case 429: return APIError(.rateLimited(retryAfter: response.header("retry-after").flatMap(Int.init)), message: message == "HTTP 429" ? "Trop de tentatives. Réessaie plus tard." : message, code: code ?? "rate_limited", requestId: rid)197        default: return APIError(.server(status: response.status), message: message, code: code, requestId: rid)198        }199    }200201    // MARK: JSON202203    public func raw(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], json: JSONValue? = nil, allowReauth: Bool = true, timeout: TimeInterval? = nil) async throws -> (Data, HTTPResponse) {204        var r = makeRequest(method, path, query: query, timeout: timeout)205        if let json { r.setValue("application/json", forHTTPHeaderField: "Content-Type"); r.httpBody = Data(json.jsonString().utf8) }206        else if method != .get { r.setValue("application/json", forHTTPHeaderField: "Content-Type"); r.httpBody = Data("{}".utf8) }207        let data: Data; let resp: HTTPResponse208        do { (data, resp) = try await transport.send(r) } catch { throw APIError.from(error) }209        absorb(resp)210        guard (200..<300).contains(resp.status) else {211            let err = failure(resp, body: data)212            if err.kind == .reauthRequired, allowReauth, let reauth = reauthenticator {213                try await reauth()214                return try await raw(method, path, query: query, json: json, allowReauth: false, timeout: timeout)215            }216            throw err217        }218        return (data, resp)219    }220221    public func json(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil, allowReauth: Bool = true, timeout: TimeInterval? = nil) async throws -> JSONValue {222        let (data, _) = try await raw(method, path, query: query, json: body, allowReauth: allowReauth, timeout: timeout)223        guard let v = JSONValue.parse(data) else { throw APIError(.decoding, message: "Réponse illisible du serveur.") }224        return v225    }226227    /// Decodes `T` from the response, or from one of its top-level keys (`{"conversations": [...]}` → `key: "conversations"`).228    public func decode<T: Decodable>(_ type: T.Type = T.self, _ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil, key: String? = nil, timeout: TimeInterval? = nil) async throws -> T {229        let (data, _) = try await raw(method, path, query: query, json: body, timeout: timeout)230        do {231            if let key { return try JSONDecoder.api().decode(Keyed<T>.self, from: data, configuration: key).value }232            return try JSONDecoder.api().decode(T.self, from: data)233        } catch { throw APIError(.decoding, message: "Réponse inattendue du serveur (\(path)).") }234    }235236    private struct Keyed<T: Decodable>: DecodableWithConfiguration {237        let value: T238        struct AnyKey: CodingKey { var stringValue: String; var intValue: Int? { nil }; init?(stringValue: String) { self.stringValue = stringValue }; init?(intValue: Int) { nil } }239        init(from decoder: Decoder, configuration: String) throws {240            value = try decoder.container(keyedBy: AnyKey.self).decode(T.self, forKey: AnyKey(stringValue: configuration)!)241        }242    }243244    // MARK: Streams, files245246    public enum StreamOpening: Sendable {247        case events(HTTPResponse, AsyncThrowingStream<Data, Error>)248        case json(HTTPResponse, JSONValue)249    }250251    /// Opens an SSE endpoint. A JSON answer (idempotent replay, or an error) is returned / thrown instead of a stream.252    public func openStream(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: Data? = nil, timeout: TimeInterval = 60) async throws -> StreamOpening {253        var r = makeRequest(method, path, query: query, accept: "text/event-stream", timeout: timeout)254        if let body { r.setValue("application/json", forHTTPHeaderField: "Content-Type"); r.httpBody = body }255        let head: HTTPResponse; let bytes: AsyncThrowingStream<Data, Error>256        do { (head, bytes) = try await transport.stream(r) } catch { throw APIError.from(error) }257        absorb(head)258        if head.contentType.contains("text/event-stream"), (200..<300).contains(head.status) { return .events(head, bytes) }259        var data = Data()260        do { for try await chunk in bytes { data.append(chunk); if data.count > 2_000_000 { break } } } catch { throw APIError.from(error) }261        guard (200..<300).contains(head.status) else { throw failure(head, body: data) }262        guard let j = JSONValue.parse(data) else { throw APIError(.decoding, message: "Réponse illisible du serveur.") }263        return .json(head, j)264    }265266    public func download(_ path: String, query: [String: String?] = [:], method: HTTPMethod = .get, body: JSONValue? = nil) async throws -> DownloadedFile {267        var r = makeRequest(method, path, query: query, accept: "*/*", timeout: 120)268        if let body { r.setValue("application/json", forHTTPHeaderField: "Content-Type"); r.httpBody = Data(body.jsonString().utf8) }269        let data: Data; let resp: HTTPResponse270        do { (data, resp) = try await transport.send(r) } catch { throw APIError.from(error) }271        absorb(resp)272        guard (200..<300).contains(resp.status) else { throw failure(resp, body: data) }273        return DownloadedFile(data: data, filename: Self.filename(fromContentDisposition: resp.header("content-disposition")), mime: resp.contentType.components(separatedBy: ";").first ?? "application/octet-stream")274    }275276    public func upload(_ path: String, form: MultipartForm, progress: @escaping @Sendable (Double) -> Void = { _ in }) async throws -> JSONValue {277        var r = makeRequest(.post, path, timeout: 180)278        r.setValue(form.contentType, forHTTPHeaderField: "Content-Type")279        let data: Data; let resp: HTTPResponse280        do { (data, resp) = try await transport.upload(r, body: form.data, progress: progress) } catch { throw APIError.from(error) }281        absorb(resp)282        guard (200..<300).contains(resp.status) else { throw failure(resp, body: data) }283        progress(1)284        guard let j = JSONValue.parse(data) else { throw APIError(.decoding, message: "Réponse illisible du serveur.") }285        return j286    }287288    static func filename(fromContentDisposition header: String?) -> String? {289        guard let header else { return nil }290        if let r = header.range(of: #"filename\*=UTF-8''([^;]+)"#, options: .regularExpression) {291            let enc = String(header[r]).replacingOccurrences(of: "filename*=UTF-8''", with: "")292            if let name = enc.removingPercentEncoding { return FileValidator.sanitizedName(name) }293        }294        if let r = header.range(of: #"filename="([^"]+)""#, options: .regularExpression) {295            return FileValidator.sanitizedName(String(header[r]).replacingOccurrences(of: "filename=", with: "").replacingOccurrences(of: "\"", with: ""))296        }297        return nil298    }299}300
Files main
Menu

Theme