Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/API/APIClient.swift3// Description: The one HTTP client of the native apps. Same contract as the web client (apps/web/src/api.ts): JSON under /api/v1,4// the owner session as an HttpOnly cookie, `Origin` + `X-SPW-CSRF` on every state-changing request. The cookie is5// handled by hand (never by a shared cookie jar) and only ever sent to the configured origin.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011public struct APIConfiguration: Sendable, Equatable {12 /** Scheme + host (+ port) of the wallet, e.g. https://wallet.spboucher.ai. No path. */13 public let origin: URL14 /** WebAuthn relying-party id the passkeys belong to. */15 public let rpId: String16 /** `__Host-spw` behind TLS; `spw` on a plain-HTTP development stack. */17 public let cookieName: String18 public let userAgent: String1920 public init(origin: URL, rpId: String, userAgent: String) {21 self.origin = origin; self.rpId = rpId; self.userAgent = userAgent22 self.cookieName = origin.scheme == "https" ? "__Host-spw" : "spw"23 }2425 public static func production(userAgent: String) -> APIConfiguration {26 APIConfiguration(origin: URL(string: "https://wallet.spboucher.ai")!, rpId: "wallet.spboucher.ai", userAgent: userAgent)27 }2829 /** The exact string the server compares the `Origin` header with. */30 public var originHeader: String {31 var s = "\(origin.scheme ?? "https")://\(origin.host ?? "")"32 if let p = origin.port { s += ":\(p)" }33 return s34 }35 public var webSocketOrigin: URL { URL(string: originHeader.replacingOccurrences(of: "http", with: "ws", options: .anchored))! }36}3738public enum HTTPMethod: String, Sendable { case get = "GET", post = "POST", put = "PUT", patch = "PATCH", delete = "DELETE" }3940public enum SessionEvent: Sendable, Equatable {41 /** The server refused the session (expired, idle for 30 minutes, revoked). The token has been erased. */42 case unauthenticated43 case signedIn44 case signedOut45}4647/** What performs the request. `URLSession` in the apps; a scripted transport in tests. */48public protocol HTTPTransport: Sendable {49 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)50}5152public struct EmptyBody: Codable, Sendable { public init() {} }53public struct OKResponse: Codable, Sendable { public let ok: Bool }5455public actor APIClient {56 public nonisolated let configuration: APIConfiguration57 private let transport: HTTPTransport58 private let tokens: SessionTokenStoring59 private var continuations: [UUID: AsyncStream<SessionEvent>.Continuation] = [:]6061 public init(configuration: APIConfiguration, tokens: SessionTokenStoring, transport: HTTPTransport? = nil) {62 self.configuration = configuration63 self.tokens = tokens64 self.transport = transport ?? URLSessionTransport()65 }6667 /** True when a session token is stored. It may still be refused by the server (idle or expired): `auth.state()` tells. */68 public var hasToken: Bool { tokens.load() != nil }6970 public func events() -> AsyncStream<SessionEvent> {71 let id = UUID()72 return AsyncStream { c in73 continuations[id] = c74 c.onTermination = { [weak self] _ in Task { await self?.drop(id) } }75 }76 }77 private func drop(_ id: UUID) { continuations[id] = nil }78 private func emit(_ e: SessionEvent) { for c in continuations.values { c.yield(e) } }7980 /** Erase the local session without calling the server (lock, or after the server refused it). */81 public func forgetSession() { tokens.save(nil); emit(.signedOut) }8283 // MARK: requests8485 public func get<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {86 try await send(.get, path, query: query, body: Optional<EmptyBody>.none)87 }88 public func post<T: Decodable & Sendable>(_ path: String, body: (any Encodable & Sendable)? = nil, idempotencyKey: String? = nil, as type: T.Type = T.self) async throws -> T {89 try await send(.post, path, body: body, idempotencyKey: idempotencyKey)90 }91 public func put<T: Decodable & Sendable>(_ path: String, body: (any Encodable & Sendable)? = nil, as type: T.Type = T.self) async throws -> T {92 try await send(.put, path, body: body)93 }94 public func delete<T: Decodable & Sendable>(_ path: String, body: (any Encodable & Sendable)? = nil, as type: T.Type = T.self) async throws -> T {95 try await send(.delete, path, body: body)96 }9798 public func send<T: Decodable & Sendable>(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:],99 body: (any Encodable & Sendable)? = nil, idempotencyKey: String? = nil,100 headers: [String: String] = [:]) async throws -> T {101 let (data, _) = try await raw(method, path, query: query, body: body, idempotencyKey: idempotencyKey, headers: headers)102 do { return try APICoding.decoder().decode(T.self, from: data) }103 catch { throw APIError(status: 200, code: "decoding", message: "unexpected answer from the server for \(path): \(Self.describe(error))") }104 }105106 /** The undecoded answer (CSV export, media). Errors are mapped exactly as for JSON calls. */107 public func raw(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: (any Encodable & Sendable)? = nil,108 idempotencyKey: String? = nil, headers: [String: String] = [:]) async throws -> (Data, HTTPURLResponse) {109 var req = URLRequest(url: try url(path, query: query))110 req.httpMethod = method.rawValue111 req.httpShouldHandleCookies = false112 req.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData113 req.timeoutInterval = 30114 req.setValue(configuration.userAgent, forHTTPHeaderField: "User-Agent")115 req.setValue("application/json", forHTTPHeaderField: "Accept")116 if let t = tokens.load() { req.setValue("\(configuration.cookieName)=\(t)", forHTTPHeaderField: "Cookie") }117 if method != .get {118 // the server's CSRF rule: strict same origin + a custom header. A native client carries no ambient credential; it states its origin.119 req.setValue(configuration.originHeader, forHTTPHeaderField: "Origin")120 req.setValue("1", forHTTPHeaderField: "X-SPW-CSRF")121 req.setValue("application/json", forHTTPHeaderField: "Content-Type")122 req.httpBody = try body.map { try APICoding.encoder().encode($0) } ?? Data("{}".utf8)123 }124 if let idempotencyKey { req.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") }125 for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) }126127 let data: Data, http: HTTPURLResponse128 do { (data, http) = try await transport.send(req) }129 catch let e as APIError { throw e }130 catch is CancellationError { throw CancellationError() }131 catch let e as URLError where e.code == .cancelled { throw CancellationError() }132 catch { throw APIError.offline(error.localizedDescription) }133134 absorbCookie(http)135 guard (200..<300).contains(http.statusCode) else {136 let j = try? APICoding.decoder().decode(JSONValue.self, from: data)137 let err = APIError(status: http.statusCode, code: j?["error"]?.stringValue ?? "error", message: j?["message"]?.stringValue ?? "error", data: j?["data"], body: j)138 if err.isUnauthenticated { tokens.save(nil); emit(.unauthenticated) }139 throw err140 }141 return (data, http)142 }143144 private func url(_ path: String, query: [String: String?]) throws -> URL {145 precondition(path.hasPrefix("/"), "API paths are absolute below /api/v1")146 guard var c = URLComponents(url: configuration.origin, resolvingAgainstBaseURL: false) else { throw APIError(status: 0, code: "bad_url", message: "bad origin") }147 // `path` may carry its own percent-encoding (ids in path segments are encoded by the callers through `APIClient.segment`)148 c.percentEncodedPath = "/api/v1" + path149 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }150 if !items.isEmpty { c.queryItems = items }151 guard let u = c.url else { throw APIError(status: 0, code: "bad_url", message: "bad path \(path)") }152 return u153 }154155 /** Percent-encode one path segment (an id, a symbol) so that it cannot change the route. */156 public nonisolated static func segment(_ s: String) -> String {157 var allowed = CharacterSet.urlPathAllowed158 allowed.remove(charactersIn: "/?#%")159 return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s160 }161162 /** Session cookie set or cleared by the server (login, logout, revoke-all). Only the configured cookie name is read. */163 private func absorbCookie(_ http: HTTPURLResponse) {164 guard let fields = http.allHeaderFields as? [String: String], let u = http.url else { return }165 for c in HTTPCookie.cookies(withResponseHeaderFields: fields, for: u) where c.name == configuration.cookieName {166 if c.value.isEmpty || (c.expiresDate.map { $0 < Date() } ?? false) { tokens.save(nil); emit(.signedOut) }167 else { tokens.save(c.value); emit(.signedIn) }168 }169 }170171 /** The `Cookie` header of an authenticated side channel (the quote websocket). Nil when signed out. */172 public func cookieHeader() -> String? { tokens.load().map { "\(configuration.cookieName)=\($0)" } }173174 private static func describe(_ e: Error) -> String {175 switch e {176 case DecodingError.keyNotFound(let k, let c): return "missing \(c.codingPath.map(\.stringValue).joined(separator: ".")).\(k.stringValue)"177 case DecodingError.typeMismatch(_, let c), DecodingError.valueNotFound(_, let c), DecodingError.dataCorrupted(let c):178 return "\(c.codingPath.map(\.stringValue).joined(separator: ".")): \(c.debugDescription)"179 default: return String(describing: e)180 }181 }182183 /** A fresh Idempotency-Key in the form the server requires (16–64 characters of [A-Za-z0-9-]). */184 public nonisolated static func newIdempotencyKey() -> String { UUID().uuidString.lowercased() }185}186187/** URLSession without a cookie jar, without a cache, and that never follows a redirect (a redirect could carry the session elsewhere). */188public final class URLSessionTransport: NSObject, HTTPTransport, URLSessionTaskDelegate, @unchecked Sendable {189 private var session: URLSession!190191 public override init() {192 super.init()193 let c = URLSessionConfiguration.ephemeral194 c.httpCookieStorage = nil195 c.httpShouldSetCookies = false196 c.httpCookieAcceptPolicy = .never197 c.urlCache = nil198 c.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData199 c.urlCredentialStorage = nil200 c.tlsMinimumSupportedProtocolVersion = .TLSv12201 c.waitsForConnectivity = false202 c.timeoutIntervalForRequest = 30203 c.timeoutIntervalForResource = 120204 session = URLSession(configuration: c, delegate: self, delegateQueue: nil)205 }206207 public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {208 let (d, r) = try await session.data(for: request)209 guard let h = r as? HTTPURLResponse else { throw APIError.offline("no HTTP answer") }210 if (300..<400).contains(h.statusCode) { throw APIError(status: h.statusCode, code: "refused_redirect", message: "the server answered with a redirect; it was not followed") }211 return (d, h)212 }213214 public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,215 newRequest request: URLRequest) async -> URLRequest? { nil }216}217