Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAPI/APIClient.swift10// Module : ClaudeRemoteAPI11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteModels89import Foundation9091/// Refreshes or invalidates the native session on behalf of `APIClient`. Implemented by92/// `AuthService` (ClaudeRemoteAuth).93public protocol SessionAuthority: AnyObject, Sendable {94 /// Performs the device-key refresh (`/native/auth/refresh/challenge` + `/refresh`), stores the95 /// rotated session, and returns it. Throws `APIError` (401 = the session is gone).96 func refreshSession() async throws -> NativeSession97 /// The server answered 401 `unauthenticated` to a request carrying this token: the session was98 /// revoked or expired. Wipe local state and return to sign-in.99 func sessionWasRejected(token: String) async100}101102public enum HTTPMethod: String, Sendable {103 case get = "GET", post = "POST", put = "PUT", patch = "PATCH", delete = "DELETE"104}105106/// Which credential a request carries.107public enum RequestAuth: Hashable, Sendable {108 /// No `Authorization` header (preauth endpoints, refresh).109 case none110 /// The stored session's bearer; refreshed on `token_expired`. Fails locally when signed out.111 case session112 /// The stored bearer if there is one, else none.113 case optionalSession114 /// An explicit token (restricted session during a second-factor step). No refresh, no retry.115 case token(String)116}117118/// Progress of an upload or a download. `fraction` is nil when the total is unknown.119public struct TransferProgress: Hashable, Sendable {120 public var completedBytes: Int64121 public var totalBytes: Int64?122 public var fraction: Double? {123 guard let totalBytes, totalBytes > 0 else { return nil }124 return min(1, Double(completedBytes) / Double(totalBytes))125 }126 public init(completedBytes: Int64, totalBytes: Int64?) {127 self.completedBytes = completedBytes128 self.totalBytes = totalBytes129 }130}131132public struct EmptyBody: Codable, Hashable, Sendable {133 public init() {}134}135136/// Typed client of one instance (`<origin>/api/v1`).137///138/// - Every request carries `X-CR-Client`; bearer requests carry `Authorization: Bearer crn_…`.139/// - A 401 `token_expired` — or `unauthenticated`, which a rotated-away token also gets — triggers140/// ONE refresh shared by all concurrent callers (single flight), then each request is retried141/// once. A token about to expire is refreshed before use.142/// - A 401 that survives the refresh (or a refused refresh) is reported to the `SessionAuthority`.143/// - TLS uses system validation; the base URL must be HTTPS (plain HTTP only for localhost).144public actor APIClient {145 public nonisolated let baseURL: URL146 public nonisolated let client: ClientInfo147 private let session: URLSession148 private nonisolated let sockets: any WebSocketTransport149 private weak var authority: (any SessionAuthority)?150 private var token: String?151 private var tokenExpiresAt: Date?152 private var refreshTask: Task<NativeSession, Error>?153 private let now: @Sendable () -> Date154 /// A token expiring within this margin is refreshed before the request is sent.155 public static let refreshMargin: TimeInterval = 30156157 /// - Throws: `APIError` (`insecure_url`) when `baseURL` is not HTTPS and not a loopback host.158 public init(baseURL: URL, client: ClientInfo, configuration: URLSessionConfiguration = .crAPI,159 webSocketTransport: (any WebSocketTransport)? = nil, now: @escaping @Sendable () -> Date = { Date() }) throws {160 try Self.validate(baseURL)161 var normalized = baseURL162 if normalized.path().hasSuffix("/") { normalized = URL(string: String(normalized.absoluteString.dropLast()))! }163 self.baseURL = normalized164 self.client = client165 session = URLSession(configuration: configuration)166 sockets = webSocketTransport ?? URLSessionWebSocketTransport(configuration: configuration)167 self.now = now168 }169170 /// HTTPS only; `http://` is accepted for `localhost`, `127.0.0.1` and `::1` (dev stack, tests).171 public static func validate(_ url: URL) throws {172 let scheme = url.scheme?.lowercased()173 let host = url.host()?.lowercased() ?? ""174 if scheme == "https", !host.isEmpty { return }175 if scheme == "http", ["localhost", "127.0.0.1", "::1", "[::1]"].contains(host) { return }176 throw APIError.client("insecure_url", "Only HTTPS servers are accepted.")177 }178179 // MARK: Credential180181 public func setAuthority(_ authority: (any SessionAuthority)?) { self.authority = authority }182183 /// Installs (or clears) the bearer of the current session.184 public func setCredential(token: String?, expiresAt: Date?) {185 self.token = token186 tokenExpiresAt = token == nil ? nil : expiresAt187 }188189 public func setCredential(_ session: NativeSession?) {190 setCredential(token: session?.token, expiresAt: session?.tokenExpiresAt)191 }192193 public var hasCredential: Bool { token != nil }194195 // MARK: Requests196197 /// Sends a JSON request and decodes the answer.198 public func send<T: Decodable & Sendable>(199 _ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: (any Encodable & Sendable)? = nil,200 auth: RequestAuth = .session, timeout: TimeInterval? = nil, as type: T.Type = T.self201 ) async throws -> T {202 let (data, _) = try await sendRaw(method, path, query: query, body: body, auth: auth, timeout: timeout)203 if T.self == EmptyBody.self { return EmptyBody() as! T }204 do {205 return try CRJSON.decoder().decode(T.self, from: data)206 } catch {207 CRLog.api.error("decoding failed for \(method.rawValue, privacy: .public) \(path, privacy: .private): \(String(describing: type), privacy: .public)")208 throw APIError(status: 0, code: "decoding", message: "The server answered with an unexpected format.")209 }210 }211212 /// Sends a request whose answer body is ignored.213 public func perform(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: (any Encodable & Sendable)? = nil,214 auth: RequestAuth = .session) async throws {215 _ = try await sendRaw(method, path, query: query, body: body, auth: auth)216 }217218 /// Sends a request and returns the raw body (2xx only; errors are thrown as `APIError`).219 public func sendRaw(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: (any Encodable & Sendable)? = nil,220 auth: RequestAuth = .session, timeout: TimeInterval? = nil) async throws -> (Data, HTTPURLResponse) {221 let bodyData: Data?222 if let body {223 bodyData = try CRJSON.encoder().encode(body)224 } else if method == .post || method == .put || method == .patch {225 bodyData = Data("{}".utf8) // Fastify refuses an empty body with a JSON content type226 } else {227 bodyData = nil228 }229 return try await execute(auth: auth) { [baseURL, client] token in230 var request = URLRequest(url: Self.url(baseURL, path, query))231 request.httpMethod = method.rawValue232 if let timeout { request.timeoutInterval = timeout }233 Self.decorate(&request, client: client, token: token)234 if let bodyData {235 request.httpBody = bodyData236 request.setValue("application/json", forHTTPHeaderField: "Content-Type")237 }238 return request239 } run: { [session] request in240 let (data, response) = try await session.data(for: request)241 return (data, response)242 }243 }244245 /// Uploads a file as a raw body stream (`POST …/upload`), reporting progress.246 public func uploadFile(_ path: String, query: [String: String?], from fileURL: URL,247 progress: (@Sendable (TransferProgress) -> Void)? = nil) async throws -> Data {248 let size = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init)249 let (data, _) = try await execute(auth: .session) { [baseURL, client] token in250 var request = URLRequest(url: Self.url(baseURL, path, query))251 request.httpMethod = "POST"252 request.timeoutInterval = 10 * 60253 Self.decorate(&request, client: client, token: token)254 request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")255 return request256 } run: { [session] request in257 let delegate = ProgressDelegate(total: size, progress: progress)258 let (data, response) = try await session.upload(for: request, fromFile: fileURL, delegate: delegate)259 return (data, response)260 }261 return data262 }263264 /// Streams a download to `destination` (replaced atomically), reporting progress.265 public func downloadFile(_ path: String, query: [String: String?] = [:], to destination: URL,266 progress: (@Sendable (TransferProgress) -> Void)? = nil) async throws {267 _ = try await execute(auth: .session) { [baseURL, client] token in268 var request = URLRequest(url: Self.url(baseURL, path, query))269 request.timeoutInterval = 10 * 60270 Self.decorate(&request, client: client, token: token)271 return request272 } run: { [session] request in273 let delegate = ProgressDelegate(total: nil, progress: progress)274 let (temp, response) = try await session.download(for: request, delegate: delegate)275 guard let http = response as? HTTPURLResponse else { throw APIError.network() }276 if !(200..<300).contains(http.statusCode) {277 let data = (try? Data(contentsOf: temp)) ?? Data()278 try? FileManager.default.removeItem(at: temp)279 return (data, response)280 }281 let fm = FileManager.default282 try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)283 if fm.fileExists(atPath: destination.path) { _ = try fm.replaceItemAt(destination, withItemAt: temp) }284 else { try fm.moveItem(at: temp, to: destination) }285 return (Data(), response)286 }287 }288289 // MARK: WebSockets290291 /// Opens an authenticated WebSocket on `/api/v1<path>`. A refused upgrade is thrown as292 /// `APIError` with the HTTP status (401, 403, 404, 410, 503…); a 401 triggers one refresh.293 public func openWebSocket(_ path: String, query: [String: String?] = [:]) async throws -> any WebSocketConnection {294 var attempt = 0295 while true {296 let token = try await currentToken(refreshIfExpiring: true)297 var components = URLComponents(url: Self.url(baseURL, path, query), resolvingAgainstBaseURL: false)!298 components.scheme = components.scheme == "http" ? "ws" : "wss"299 var request = URLRequest(url: components.url!)300 request.timeoutInterval = 20301 Self.decorate(&request, client: client, token: token)302 do {303 return try await sockets.connect(request)304 } catch WebSocketConnectError.upgradeRefused(let status) {305 if status == 401, attempt == 0 {306 attempt += 1307 _ = try await refresh(rejecting: token)308 continue309 }310 if status == 401 { await authority?.sessionWasRejected(token: token) }311 throw APIError.from(status: status, data: Data())312 } catch WebSocketConnectError.unreachable(let message) {313 throw APIError.network(message)314 } catch {315 throw APIError.wrap(error)316 }317 }318 }319320 // MARK: Internals321322 private func currentToken(refreshIfExpiring: Bool) async throws -> String {323 guard let token else { throw APIError.notSignedIn }324 if refreshIfExpiring, let exp = tokenExpiresAt, exp.timeIntervalSince(now()) < Self.refreshMargin {325 return try await refresh(rejecting: token)326 }327 return token328 }329330 /// Single-flight refresh: concurrent callers rejected with the same token share one refresh.331 private func refresh(rejecting old: String) async throws -> String {332 if let token, token != old { return token } // already rotated by another caller333 if let refreshTask {334 // Waiters can be resumed before the caller that started the refresh: install the335 // rotated token here too, so the retry never reads the stale one.336 let fresh: NativeSession337 do { fresh = try await refreshTask.value } catch { throw APIError.wrap(error) }338 if token == old { setCredential(fresh) }339 return fresh.token340 }341 guard let authority else { throw APIError.notSignedIn }342 let task = Task { try await authority.refreshSession() }343 refreshTask = task344 defer { refreshTask = nil }345 do {346 let fresh = try await task.value347 setCredential(fresh)348 return fresh.token349 } catch {350 throw APIError.wrap(error)351 }352 }353354 private func execute(355 auth: RequestAuth, build: @Sendable (String?) -> URLRequest,356 run: @Sendable (URLRequest) async throws -> (Data, URLResponse)357 ) async throws -> (Data, HTTPURLResponse) {358 var retried = false359 while true {360 let bearer: String?361 switch auth {362 case .none: bearer = nil363 case .token(let explicit): bearer = explicit364 case .session: bearer = try await currentToken(refreshIfExpiring: true)365 case .optionalSession: bearer = token == nil ? nil : try await currentToken(refreshIfExpiring: true)366 }367 let request = build(bearer)368 let started = ContinuousClock.now369 let data: Data, response: URLResponse370 do {371 (data, response) = try await run(request)372 } catch {373 let mapped = APIError.wrap(error)374 if mapped.kind != .cancelled {375 CRLog.api.error("\(request.httpMethod ?? "GET", privacy: .public) \(request.url?.path() ?? "", privacy: .private) failed: \(mapped.code, privacy: .public)")376 }377 throw mapped378 }379 guard let http = response as? HTTPURLResponse else { throw APIError.network() }380 let ms = (ContinuousClock.now - started).components381 CRLog.api.debug("\(request.httpMethod ?? "GET", privacy: .public) \(request.url?.path() ?? "", privacy: .private) → \(http.statusCode, privacy: .public) in \(ms.seconds * 1000 + ms.attoseconds / 1_000_000_000_000_000, privacy: .public) ms")382 if (200..<300).contains(http.statusCode) { return (data, http) }383 let error = APIError.from(status: http.statusCode, data: data, headers: http.allHeaderFields)384 let usesSession = auth == .session || (auth == .optionalSession && bearer != nil)385 if usesSession, let bearer {386 // `token_expired`: the session is alive. `unauthenticated`: usually revoked, but also387 // what a rotated-away token gets when the answer of a refresh was lost in transit —388 // so ONE refresh is attempted before concluding (it only needs the device key).389 if error.kind == .tokenExpired || error.kind == .unauthenticated, !retried {390 retried = true391 _ = try await refresh(rejecting: bearer)392 continue393 }394 if error.kind == .unauthenticated || error.kind == .tokenExpired {395 if token == bearer { setCredential(token: nil, expiresAt: nil) }396 await authority?.sessionWasRejected(token: bearer)397 }398 }399 throw error400 }401 }402403 static func url(_ base: URL, _ path: String, _ query: [String: String?]) -> URL {404 var components = URLComponents(url: base, resolvingAgainstBaseURL: false)!405 components.path = (components.path.hasSuffix("/") ? String(components.path.dropLast()) : components.path) + "/api/v1" + path406 let items = query.compactMap { key, value in value.map { URLQueryItem(name: key, value: $0) } }.sorted { $0.name < $1.name }407 if !items.isEmpty {408 components.queryItems = items409 // URLComponents leaves "+" as is; the server would read it as a space.410 components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")411 }412 return components.url!413 }414415 static func decorate(_ request: inout URLRequest, client: ClientInfo, token: String?) {416 request.setValue(client.headerValue, forHTTPHeaderField: "X-CR-Client")417 request.setValue("application/json", forHTTPHeaderField: "Accept")418 request.setValue("ClaudeRemoteKit/\(client.appVersion) (\(client.platform.rawValue))", forHTTPHeaderField: "User-Agent")419 if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }420 }421422 /// Percent-encodes one path segment (ids, MCP names, node aliases).423 public static func segment(_ value: String) -> String {424 var allowed = CharacterSet.urlPathAllowed425 allowed.remove(charactersIn: "/?#%")426 return value.addingPercentEncoding(withAllowedCharacters: allowed) ?? value427 }428}429430private final class ProgressDelegate: NSObject, URLSessionTaskDelegate, URLSessionDownloadDelegate, Sendable {431 let total: Int64?432 let progress: (@Sendable (TransferProgress) -> Void)?433434 init(total: Int64?, progress: (@Sendable (TransferProgress) -> Void)?) {435 self.total = total436 self.progress = progress437 }438439 func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {440 progress?(TransferProgress(completedBytes: totalBytesSent, totalBytes: totalBytesExpectedToSend > 0 ? totalBytesExpectedToSend : total))441 }442443 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {444 progress?(TransferProgress(completedBytes: totalBytesWritten, totalBytes: totalBytesExpectedToWrite > 0 ? totalBytesExpectedToWrite : nil))445 }446447 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}448}449