Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/HTTPClient.swift3// Description: The transport of the native apps: one ephemeral URLSession without cookie storage, the session cookie4// sent by hand from the token store, ceremony cookie replay, Origin / request id / idempotency headers,5// file uploads and downloads, event streams, and the "signed out" signal.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011// MARK: - Request and response1213public enum HTTPMethod: String, Sendable, Equatable {14 case get = "GET"15 case post = "POST"16 case patch = "PATCH"17 case put = "PUT"18 case delete = "DELETE"1920 /// Mutating requests carry the `Origin` header (the server refuses them otherwise: `403 csrf`).21 public var isMutating: Bool { self != .get }22}2324/// One request to the backend, relative to the base URL of the configuration.25public struct HTTPRequest: Sendable, Equatable {26 /// Role of the request in a WebAuthn ceremony. The `options` call of a ceremony receives the `__Host-note_wa`27 /// cookie; only the matching `verify` call sends it back, once.28 public enum Ceremony: Sendable, Equatable {29 case none30 /// An `options` call: the ceremony cookie of the answer is kept under this key.31 case begin(String)32 /// A `verify` call: the ceremony cookie kept under this key is sent, then forgotten.33 case complete(String)34 }3536 public var method: HTTPMethod37 /// Absolute path on the server, already percent-encoded (`/api/pages/<id>`).38 public var path: String39 public var query: [URLQueryItem]40 /// Request body (JSON unless `contentType` says otherwise).41 public var body: Data?42 public var contentType: String?43 public var accept: String44 /// `Idempotency-Key` (`[A-Za-z0-9_-]{8,100}`): the server runs the request at most once per key.45 public var idempotencyKey: String?46 /// `x-request-id` (`[A-Za-z0-9_-]{8,64}`); generated when `nil`.47 public var requestID: String?48 /// Idle timeout in seconds; the configuration's default when `nil`.49 public var timeout: TimeInterval?50 public var ceremony: Ceremony51 /// Automatic retries of `HTTPClient.send` (2.0). `nil` (the default) = a single attempt, as before. A policy is52 /// only honoured when the request `isSafeToRetry`; on any other request it is ignored.53 public var retry: RetryPolicy?54 /// Additional request headers (3.0: `Range`, `If-Range`, `Accept-Encoding`). Never overrides the headers the55 /// transport owns (`Cookie`, `Origin`, `User-Agent`, `Accept`, `Content-Type`, `x-request-id`, `Idempotency-Key`).56 public var extraHeaders: [String: String] = [:]5758 public init(59 method: HTTPMethod = .get, path: String, query: [URLQueryItem] = [], body: Data? = nil, contentType: String? = nil,60 accept: String = "application/json", idempotencyKey: String? = nil, requestID: String? = nil, timeout: TimeInterval? = nil,61 ceremony: Ceremony = .none, retry: RetryPolicy? = nil62 ) {63 self.retry = retry64 self.method = method65 self.path = path66 self.query = query67 self.body = body68 self.contentType = contentType69 self.accept = accept70 self.idempotencyKey = idempotencyKey71 self.requestID = requestID72 self.timeout = timeout73 self.ceremony = ceremony74 }7576 public static func get(_ path: String, query: [URLQueryItem] = []) -> HTTPRequest {77 HTTPRequest(method: .get, path: path, query: query)78 }7980 /// A request with a JSON body encoded with the backend conventions (`APIJSON.encoder()`).81 public static func json<Body: Encodable>(_ method: HTTPMethod, _ path: String, query: [URLQueryItem] = [], body: Body, idempotencyKey: String? = nil) throws -> HTTPRequest {82 let data: Data83 do { data = try APIJSON.encoder().encode(body) } catch { throw APIError.decoding("request body: \(error)") }84 return HTTPRequest(method: method, path: path, query: query, body: data, contentType: "application/json", idempotencyKey: idempotencyKey)85 }8687 /// Whether sending the request twice cannot do the work twice: a GET, or any request carrying an88 /// `Idempotency-Key` (the server runs it at most once per key). WebAuthn ceremony calls never are (their cookie89 /// is single-use).90 public var isSafeToRetry: Bool {91 guard ceremony == .none else { return false }92 return method == .get || idempotencyKey != nil93 }9495 /// The same request with automatic retries. A mutating request without `Idempotency-Key` gets a fresh one when96 /// `addingKey` is true (pass false to leave it non-retryable); a ceremony call is returned unchanged.97 public func retrying(_ policy: RetryPolicy = .standard, addingKey: Bool = true) -> HTTPRequest {98 guard ceremony == .none else { return self }99 var copy = self100 if copy.method != .get, copy.idempotencyKey == nil, addingKey { copy.idempotencyKey = HTTPRequest.newIdempotencyKey() }101 copy.retry = policy102 return copy103 }104105 /// A fresh `Idempotency-Key`: 32 characters of `[0-9a-f]`.106 public static func newIdempotencyKey() -> String { UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() }107108 /// Percent-encodes one path segment (identifiers are UUIDs, but nothing is assumed).109 public static func segment(_ text: String) -> String {110 var allowed = CharacterSet.urlPathAllowed111 allowed.remove(charactersIn: "/?#%;")112 return text.addingPercentEncoding(withAllowedCharacters: allowed) ?? text113 }114}115116/// How `HTTPClient.send` retries a request that is safe to retry (2.0): exponential backoff with jitter, bounded by117/// `maxAttempts`, honouring `Retry-After`. Only failures for which `APIError.isRetryable` is true are retried118/// (offline, transport, timeout, 408, 429, 5xx, `409 in_progress`).119public struct RetryPolicy: Sendable, Equatable {120 /// Total number of attempts, the first included (1 = no retry).121 public var maxAttempts: Int122 /// Delay before the first retry, in seconds.123 public var baseDelay: TimeInterval124 public var multiplier: Double125 /// Upper bound of one delay (also caps `Retry-After`).126 public var maxDelay: TimeInterval127 /// 0…1: each delay is reduced by a random share of up to this fraction (0 = deterministic).128 public var jitter: Double129130 public init(maxAttempts: Int = 3, baseDelay: TimeInterval = 0.4, multiplier: Double = 2, maxDelay: TimeInterval = 8, jitter: Double = 0.25) {131 self.maxAttempts = max(1, maxAttempts)132 self.baseDelay = max(0, baseDelay)133 self.multiplier = max(1, multiplier)134 self.maxDelay = max(0, maxDelay)135 self.jitter = min(1, max(0, jitter))136 }137138 /// A single attempt.139 public static let none = RetryPolicy(maxAttempts: 1)140 /// 3 attempts, 0.4 s then 0.8 s (± jitter), at most 8 s.141 public static let standard = RetryPolicy()142 /// 5 attempts, for background work that can wait: 1 s, 2 s, 4 s, 8 s, at most 30 s.143 public static let patient = RetryPolicy(maxAttempts: 5, baseDelay: 1, multiplier: 2, maxDelay: 30, jitter: 0.25)144145 /// The wait before retry number `retry` (1-based). `retryAfter` (seconds, from the server) replaces the146 /// computed backoff when it is longer; `random` in 0…1 drives the jitter.147 public func delay(retry: Int, retryAfter: TimeInterval? = nil, random: Double = 0) -> TimeInterval {148 let exponent = Double(min(max(retry - 1, 0), 30))149 var delay = min(maxDelay, baseDelay * pow(multiplier, exponent))150 delay -= delay * jitter * min(1, max(0, random))151 if let retryAfter, retryAfter.isFinite, retryAfter > delay { delay = min(maxDelay, retryAfter) }152 return max(0, delay)153 }154}155156/// A received answer (2xx).157public struct HTTPResponse: Sendable, Equatable {158 public let status: Int159 /// Header fields, names lower-cased.160 public let headers: [String: String]161 public let data: Data162163 public init(status: Int, headers: [String: String], data: Data) {164 self.status = status165 self.headers = Dictionary(headers.map { ($0.key.lowercased(), $0.value) }, uniquingKeysWith: { a, _ in a })166 self.data = data167 }168169 public func header(_ name: String) -> String? { headers[name.lowercased()] }170171 /// The request id echoed by the server (present in its log).172 public var requestID: String? { header("x-request-id") }173 /// `x-existing: 1` — the client-chosen id already existed: the stored object was returned as it is.174 public var isExisting: Bool { header("x-existing") == "1" }175 /// `idempotent-replay: true` — the stored answer of an earlier request with the same idempotency key.176 public var isIdempotentReplay: Bool { header("idempotent-replay") == "true" }177 public var contentType: String? { header("content-type") }178179 /// Decodes the JSON body with the backend conventions.180 public func decode<T: Decodable>(_ type: T.Type = T.self) throws -> T {181 do { return try APIJSON.decoder().decode(T.self, from: data) } catch { throw APIError.decoding(HTTPResponse.describe(error)) }182 }183184 /// A short description of a decoding failure: the coding path and the reason, never the payload.185 static func describe(_ error: Error) -> String {186 func path(_ c: DecodingError.Context) -> String { c.codingPath.map { $0.intValue.map { "[\($0)]" } ?? $0.stringValue }.joined(separator: ".") }187 switch error {188 case DecodingError.keyNotFound(let key, let c): return "missing key \(key.stringValue) at \(path(c))"189 case DecodingError.typeMismatch(_, let c): return "type mismatch at \(path(c)): \(c.debugDescription)"190 case DecodingError.valueNotFound(_, let c): return "missing value at \(path(c))"191 case DecodingError.dataCorrupted(let c): return "corrupted data at \(path(c)): \(c.debugDescription)"192 default: return String(describing: type(of: error))193 }194 }195}196197/// Progress of an upload or a download.198public struct TransferProgress: Sendable, Equatable {199 public var completedBytes: Int64200 /// Total size when known.201 public var totalBytes: Int64?202203 public init(completedBytes: Int64, totalBytes: Int64?) {204 self.completedBytes = completedBytes205 self.totalBytes = totalBytes206 }207208 /// 0…1 when the total is known.209 public var fraction: Double? {210 guard let totalBytes, totalBytes > 0 else { return nil }211 return min(1, max(0, Double(completedBytes) / Double(totalBytes)))212 }213}214215public typealias TransferProgressHandler = @Sendable (TransferProgress) -> Void216217// MARK: - Session events218219public enum SignOutReason: Sendable, Equatable {220 /// The server answered 401 to a request that carried the current token (expired or revoked session).221 case unauthorized222 /// The server cleared the session cookie (logout, global revocation).223 case cookieCleared224 /// The app forgot the session itself (`clearSession()`).225 case local226}227228public enum SessionEvent: Sendable, Equatable {229 /// A session token was received while none was held (sign-in).230 case signedIn231 /// The token was replaced (step-up rotation).232 case tokenRotated233 /// The session ended. Emitted exactly once per session.234 case signedOut(SignOutReason)235}236237// MARK: - Client238239/// The single entry point to the network. An actor: the token and the ceremony cookies are mutated by concurrent240/// requests.241///242/// The backend authenticates with an HttpOnly cookie. The client keeps no cookie jar: the token is read from243/// `Set-Cookie`, stored in the `SessionTokenStore` (Keychain) and sent back explicitly in the `Cookie` header.244/// Redirects are not followed (a redirect would carry the cookie to another URL).245public actor HTTPClient {246 public nonisolated let configuration: APIConfiguration247 private nonisolated let session: URLSession248 private let tokenStore: any SessionTokenStore249 private var token: String?250 private var ceremonyCookies: [String: String] = [:]251 private var listeners: [UUID: AsyncStream<SessionEvent>.Continuation] = [:]252253 /// - Parameters:254 /// - tokenStore: where the session token is kept (`KeychainTokenStore` in the apps).255 /// - sessionConfiguration: base `URLSessionConfiguration`; tests inject one with a `URLProtocol` stub. Whatever256 /// is passed, cookie storage, cookie handling, credential storage and the URL cache are switched off.257 public init(configuration: APIConfiguration = .production, tokenStore: any SessionTokenStore, sessionConfiguration: URLSessionConfiguration = .ephemeral) {258 self.configuration = configuration259 self.tokenStore = tokenStore260 self.token = tokenStore.load()261 let c = sessionConfiguration262 c.httpCookieStorage = nil263 c.httpShouldSetCookies = false264 c.httpCookieAcceptPolicy = .never265 c.urlCredentialStorage = nil266 c.urlCache = nil267 c.requestCachePolicy = .reloadIgnoringLocalCacheData268 c.waitsForConnectivity = false269 c.timeoutIntervalForRequest = configuration.requestTimeout270 c.timeoutIntervalForResource = configuration.resourceTimeout271 c.tlsMinimumSupportedProtocolVersion = .TLSv12272 var headers = c.httpAdditionalHeaders ?? [:]273 headers["User-Agent"] = configuration.userAgent274 c.httpAdditionalHeaders = headers275 self.session = URLSession(configuration: c, delegate: RedirectRefuser(), delegateQueue: nil)276 }277278 deinit {279 session.finishTasksAndInvalidate()280 for listener in listeners.values { listener.finish() }281 }282283 // MARK: session state284285 /// Whether a session token is held (it may still be refused by the server).286 public var hasSession: Bool { token != nil }287288 /// Installs a token obtained elsewhere (development token of the test server, migration). Emits `.signedIn` or289 /// `.tokenRotated`.290 public func setSessionToken(_ newToken: String) {291 guard newToken != token else { return }292 let had = token != nil293 token = newToken294 try? tokenStore.save(newToken)295 emit(had ? .tokenRotated : .signedIn)296 }297298 /// Forgets the session locally (no server call). Emits `.signedOut(.local)` if a token was held.299 public func clearSession() {300 endSession(.local)301 }302303 /// A stream of session events. Each call returns an independent stream; it ends when the client is released.304 public func sessionEvents() -> AsyncStream<SessionEvent> {305 let id = UUID()306 let (stream, continuation) = AsyncStream<SessionEvent>.makeStream(bufferingPolicy: .bufferingNewest(32))307 listeners[id] = continuation308 continuation.onTermination = { [weak self] _ in309 Task { await self?.removeListener(id) }310 }311 return stream312 }313314 // MARK: requests315316 /// Sends a request and returns the 2xx answer; anything else is thrown as `APIError`.317 /// When the request carries a `RetryPolicy` and `isSafeToRetry`, a retryable failure is tried again after a318 /// backoff (same `Idempotency-Key`, new request id); otherwise there is exactly one attempt, as in 1.x.319 public func send(_ request: HTTPRequest) async throws -> HTTPResponse {320 let policy = request.retry.flatMap { $0.maxAttempts > 1 && request.isSafeToRetry ? $0 : nil } ?? .none321 var attempt = 1322 while true {323 let failure: AttemptFailure324 switch await sendOnce(request) {325 case .success(let response): return response326 case .failure(let failed): failure = failed327 }328 guard attempt < policy.maxAttempts, failure.error.isRetryable else { throw failure.error }329 let delay = policy.delay(retry: attempt, retryAfter: failure.retryAfter, random: Double.random(in: 0...1))330 do { try await sleeper(delay) } catch { throw APIError.cancelled }331 attempt += 1332 }333 }334335 /// A failed attempt with what the server said about when to come back.336 private struct AttemptFailure: Error {337 var error: APIError338 var retryAfter: TimeInterval?339 }340341 private func sendOnce(_ request: HTTPRequest) async -> Result<HTTPResponse, AttemptFailure> {342 do {343 let prepared = try prepare(request)344 let data: Data, response: URLResponse345 do { (data, response) = try await session.data(for: prepared.urlRequest) } catch { throw APIError.fromTransport(error) }346 let head = try absorb(response, prepared)347 guard (200..<300).contains(head.status) else {348 let after = head.headers["retry-after"].flatMap { TimeInterval($0.trimmingCharacters(in: .whitespaces)) }349 return .failure(AttemptFailure(error: APIError.fromResponse(status: head.status, body: data), retryAfter: after))350 }351 return .success(HTTPResponse(status: head.status, headers: head.headers, data: data))352 } catch let error as APIError {353 return .failure(AttemptFailure(error: error, retryAfter: nil))354 } catch {355 return .failure(AttemptFailure(error: APIError.fromTransport(error), retryAfter: nil))356 }357 }358359 /// The wait between two attempts (replaced in tests).360 private var sleeper: @Sendable (TimeInterval) async throws -> Void = { seconds in361 try await Task.sleep(nanoseconds: UInt64(max(0, seconds) * 1_000_000_000))362 }363364 /// Tests: replaces the wait between attempts.365 func setRetrySleeper(_ sleeper: @escaping @Sendable (TimeInterval) async throws -> Void) { self.sleeper = sleeper }366367 /// Sends a request and decodes the JSON body of the answer.368 public func decode<T: Decodable & Sendable>(_ type: T.Type = T.self, _ request: HTTPRequest) async throws -> T {369 try await send(request).decode(T.self)370 }371372 /// Sends a request whose body is a file on disk, streamed by `URLSession` (never loaded in memory).373 /// Cancelling the calling task cancels the transfer.374 /// - Parameter progress: called on a background queue as bytes leave.375 public func upload(_ request: HTTPRequest, fromFile file: URL, progress: TransferProgressHandler? = nil) async throws -> HTTPResponse {376 var request = request377 request.body = nil378 if request.timeout == nil { request.timeout = max(configuration.requestTimeout, 600) } // the server hashes and indexes after the last byte379 let prepared = try prepare(request)380 let delegate = TransferDelegate(kind: .upload, progress: progress)381 let data: Data, response: URLResponse382 do { (data, response) = try await session.upload(for: prepared.urlRequest, fromFile: file, delegate: delegate) } catch { throw APIError.fromTransport(error) }383 let head = try absorb(response, prepared)384 guard (200..<300).contains(head.status) else { throw APIError.fromResponse(status: head.status, body: data) }385 return HTTPResponse(status: head.status, headers: head.headers, data: data)386 }387388 /// Downloads the answer to `destination` (replaced if it exists) without holding it in memory.389 /// Cancelling the calling task cancels the transfer.390 /// - Returns: the answer without body (`data` is empty).391 public func download(_ request: HTTPRequest, to destination: URL, progress: TransferProgressHandler? = nil) async throws -> HTTPResponse {392 var request = request393 request.accept = "*/*"394 let prepared = try prepare(request)395 let delegate = TransferDelegate(kind: .download, progress: progress)396 let temporary: URL, response: URLResponse397 do { (temporary, response) = try await session.download(for: prepared.urlRequest, delegate: delegate) } catch { throw APIError.fromTransport(error) }398 let fm = FileManager.default399 let head: ResponseHead400 do { head = try absorb(response, prepared) } catch { try? fm.removeItem(at: temporary); throw error }401 guard (200..<300).contains(head.status) else {402 let body = (try? FileHandle(forReadingFrom: temporary)).flatMap { handle -> Data? in403 defer { try? handle.close() }404 return try? handle.read(upToCount: 1 << 20)405 } ?? Data()406 try? fm.removeItem(at: temporary)407 throw APIError.fromResponse(status: head.status, body: body)408 }409 do {410 try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)411 if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }412 try fm.moveItem(at: temporary, to: destination)413 } catch {414 try? fm.removeItem(at: temporary)415 throw APIError.file("cannot store the download: \(error.localizedDescription)")416 }417 return HTTPResponse(status: head.status, headers: head.headers, data: Data())418 }419420 /// Opens a `text/event-stream` answer. A non-2xx answer is read (up to 1 MB) and thrown as `APIError` before any421 /// byte is returned. The caller iterates the bytes; cancelling that task closes the connection.422 public func openStream(_ request: HTTPRequest) async throws -> (response: HTTPResponse, bytes: URLSession.AsyncBytes) {423 var request = request424 request.accept = "text/event-stream"425 if request.timeout == nil { request.timeout = configuration.streamIdleTimeout }426 let prepared = try prepare(request)427 let bytes: URLSession.AsyncBytes, response: URLResponse428 do { (bytes, response) = try await session.bytes(for: prepared.urlRequest) } catch { throw APIError.fromTransport(error) }429 let head = try absorb(response, prepared)430 guard (200..<300).contains(head.status) else {431 var body = Data()432 do { for try await byte in bytes { body.append(byte); if body.count >= 1 << 20 { break } } } catch { throw APIError.fromTransport(error) }433 throw APIError.fromResponse(status: head.status, body: body)434 }435 return (HTTPResponse(status: head.status, headers: head.headers, data: Data()), bytes)436 }437438 /// Opens any answer as a byte stream **without judging its status** (3.0, ranged downloads): the caller reads439 /// `response.status` (200, 206, 416, 404…) and the headers, then iterates the bytes. Session handling is the440 /// same as for every request (a 401 on the current token ends the session). `request.accept` is sent as it is.441 public func openBytes(_ request: HTTPRequest) async throws -> (response: HTTPResponse, bytes: URLSession.AsyncBytes) {442 let prepared = try prepare(request)443 let bytes: URLSession.AsyncBytes, response: URLResponse444 do { (bytes, response) = try await session.bytes(for: prepared.urlRequest) } catch { throw APIError.fromTransport(error) }445 let head = try absorb(response, prepared)446 return (HTTPResponse(status: head.status, headers: head.headers, data: Data()), bytes)447 }448449 /// Header names the transport sets itself: `HTTPRequest.extraHeaders` cannot replace them.450 private static let ownedHeaders: Set<String> = ["cookie", "origin", "user-agent", "accept", "content-type", "x-request-id", "idempotency-key", "host", "content-length"]451452 // MARK: plumbing453454 private struct Prepared {455 var urlRequest: URLRequest456 var tokenUsed: String?457 var ceremony: HTTPRequest.Ceremony458 }459460 private struct ResponseHead {461 var status: Int462 var headers: [String: String]463 }464465 /// Builds the `URLRequest` (internal so that tests can inspect the exact headers).466 func urlRequest(for request: HTTPRequest) throws -> URLRequest { try prepare(request, consumeCeremony: false).urlRequest }467468 private func prepare(_ r: HTTPRequest, consumeCeremony: Bool = true) throws -> Prepared {469 guard r.path.hasPrefix("/"), var components = URLComponents(url: configuration.baseURL, resolvingAgainstBaseURL: false) else { throw APIError.invalidResponse }470 components.percentEncodedPath += r.path471 if !r.query.isEmpty {472 components.queryItems = r.query473 // URLComponents leaves "+" as it is, and servers read it as a space.474 components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")475 }476 guard let url = components.url else { throw APIError.invalidResponse }477 var req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: r.timeout ?? configuration.requestTimeout)478 req.httpMethod = r.method.rawValue479 req.httpShouldHandleCookies = false480 for (name, value) in r.extraHeaders where !HTTPClient.ownedHeaders.contains(name.lowercased()) { req.setValue(value, forHTTPHeaderField: name) }481 req.setValue(r.accept, forHTTPHeaderField: "Accept")482 req.setValue(configuration.userAgent, forHTTPHeaderField: "User-Agent")483 req.setValue(r.requestID ?? UUID().uuidString.lowercased(), forHTTPHeaderField: "x-request-id")484 // The server refuses every mutation whose Origin is not its own (CSRF defence designed for browsers).485 if r.method.isMutating {486 req.setValue(configuration.origin, forHTTPHeaderField: "Origin")487 if let key = r.idempotencyKey { req.setValue(key, forHTTPHeaderField: "Idempotency-Key") }488 }489 var cookies: [String] = []490 if let token { cookies.append("\(configuration.sessionCookieName)=\(token)") }491 if case .complete(let key) = r.ceremony {492 let value = consumeCeremony ? ceremonyCookies.removeValue(forKey: key) : ceremonyCookies[key]493 if let value { cookies.append("\(configuration.ceremonyCookieName)=\(value)") }494 }495 if !cookies.isEmpty { req.setValue(cookies.joined(separator: "; "), forHTTPHeaderField: "Cookie") }496 if let body = r.body {497 req.httpBody = body498 req.setValue(r.contentType ?? "application/json", forHTTPHeaderField: "Content-Type")499 } else if let contentType = r.contentType {500 req.setValue(contentType, forHTTPHeaderField: "Content-Type")501 }502 return Prepared(urlRequest: req, tokenUsed: token, ceremony: r.ceremony)503 }504505 /// Reads the cookies and the status of an answer: token rotation, ceremony cookie capture, end of session.506 private func absorb(_ response: URLResponse, _ prepared: Prepared) throws -> ResponseHead {507 guard let http = response as? HTTPURLResponse else { throw APIError.invalidResponse }508 var headers: [String: String] = [:]509 for (key, value) in http.allHeaderFields {510 if let key = key as? String, let value = value as? String { headers[key.lowercased()] = value }511 }512 for cookie in SetCookie.parse(headers["set-cookie"] ?? "") {513 if cookie.name == configuration.sessionCookieName {514 if cookie.isCleared {515 endSession(.cookieCleared)516 } else if cookie.value != token {517 let had = token != nil518 token = cookie.value519 try? tokenStore.save(cookie.value)520 emit(had ? .tokenRotated : .signedIn)521 }522 } else if cookie.name == configuration.ceremonyCookieName, case .begin(let key) = prepared.ceremony {523 ceremonyCookies[key] = cookie.isCleared ? nil : cookie.value524 }525 }526 headers["set-cookie"] = nil // never handed to callers527 // A 401 only ends the session if the refused request carried the token that is still current: an answer to a528 // request sent before a rotation must not sign the user out.529 if http.statusCode == 401, let used = prepared.tokenUsed, used == token {530 endSession(.unauthorized)531 }532 return ResponseHead(status: http.statusCode, headers: headers)533 }534535 private func endSession(_ reason: SignOutReason) {536 ceremonyCookies.removeAll()537 guard token != nil else { return }538 token = nil539 try? tokenStore.clear()540 emit(.signedOut(reason))541 }542543 private func emit(_ event: SessionEvent) {544 for listener in listeners.values { listener.yield(event) }545 }546547 private func removeListener(_ id: UUID) {548 listeners[id] = nil549 }550551 /// Test hook: whether a ceremony cookie is held for this key.552 func holdsCeremonyCookie(_ key: String) -> Bool { ceremonyCookies[key] != nil }553}554555// MARK: - Set-Cookie556557/// One cookie of a `Set-Cookie` header (several cookies arrive joined by commas in `HTTPURLResponse`).558struct SetCookie: Equatable, Sendable {559 var name: String560 var value: String561 var maxAge: Int?562 var expires: Date?563564 /// The server deletes a cookie with an empty value, `Max-Age=0` or a date in the past.565 var isCleared: Bool {566 if value.isEmpty { return true }567 if let maxAge { return maxAge <= 0 }568 if let expires { return expires <= Date() }569 return false570 }571572 static func parse(_ header: String) -> [SetCookie] {573 guard !header.isEmpty else { return [] }574 // Split on the commas that start a new cookie ("name=…"), not on the comma of an Expires date.575 var parts: [String] = []576 for piece in header.components(separatedBy: ",") {577 let trimmed = piece.trimmingCharacters(in: .whitespaces)578 let startsCookie: Bool = {579 guard let stop = trimmed.firstIndex(where: { $0 == "=" || $0 == ";" }), trimmed[stop] == "=" else { return false }580 let name = trimmed[..<stop]581 return !name.isEmpty && !name.contains(" ")582 }()583 if startsCookie || parts.isEmpty { parts.append(trimmed) } else { parts[parts.count - 1] += "," + piece }584 }585 return parts.compactMap { part in586 let segments = part.components(separatedBy: ";")587 guard let first = segments.first, let eq = first.firstIndex(of: "=") else { return nil }588 let name = first[..<eq].trimmingCharacters(in: .whitespaces)589 var value = first[first.index(after: eq)...].trimmingCharacters(in: .whitespaces)590 if value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") { value = String(value.dropFirst().dropLast()) }591 guard !name.isEmpty else { return nil }592 var cookie = SetCookie(name: name, value: value)593 for attribute in segments.dropFirst() {594 let pair = attribute.split(separator: "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }595 guard let key = pair.first?.lowercased() else { continue }596 if key == "max-age", pair.count == 2 { cookie.maxAge = Int(pair[1]) }597 if key == "expires", pair.count == 2 { cookie.expires = httpDate(pair[1]) }598 }599 return cookie600 }601 }602603 /// `Thu, 01 Jan 1970 00:00:00 GMT` (and the dashed variant).604 static func httpDate(_ text: String) -> Date? {605 let tokens = text.split(whereSeparator: { $0 == " " || $0 == "-" || $0 == "," }).map(String.init)606 guard tokens.count >= 4 else { return nil }607 let months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]608 let t = tokens.first.map { Int($0) == nil } == true ? Array(tokens.dropFirst()) : tokens // drop the weekday609 guard t.count >= 4, let day = Int(t[0]), let monthIndex = months.firstIndex(of: String(t[1].lowercased().prefix(3))), var year = Int(t[2]) else { return nil }610 if year < 70 { year += 2000 } else if year < 100 { year += 1900 }611 let pad = { (v: Int) in v < 10 ? "0\(v)" : "\(v)" }612 return APIDate.parse("\(String(repeating: "0", count: max(0, 4 - String(year).count)))\(year)-\(pad(monthIndex + 1))-\(pad(day))T\(t[3])Z")613 }614}615616// MARK: - Delegates617618/// Session delegate: refuses redirects, so the session cookie never follows one.619private final class RedirectRefuser: NSObject, URLSessionTaskDelegate, Sendable {620 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {621 completionHandler(nil)622 }623}624625/// Per-task delegate reporting transfer progress.626private final class TransferDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {627 enum Kind { case upload, download }628 private let kind: Kind629 private let progress: TransferProgressHandler?630 private let lock = NSLock()631 private var observation: NSKeyValueObservation?632 private var last: Int64 = -1633634 init(kind: Kind, progress: TransferProgressHandler?) {635 self.kind = kind636 self.progress = progress637 }638639 private func report(_ completed: Int64, _ total: Int64) {640 guard let progress else { return }641 let fresh: Bool = lock.withLock {642 guard completed > last else { return false }643 last = completed644 return true645 }646 if fresh { progress(TransferProgress(completedBytes: completed, totalBytes: total > 0 ? total : nil)) }647 }648649 func urlSession(_ session: URLSession, didCreateTask task: URLSessionTask) {650 guard kind == .download, progress != nil else { return }651 let observation = task.observe(\.countOfBytesReceived, options: [.new]) { [weak self] task, _ in652 self?.report(task.countOfBytesReceived, task.countOfBytesExpectedToReceive)653 }654 lock.withLock { self.observation = observation }655 }656657 func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {658 guard kind == .upload else { return }659 report(totalBytesSent, totalBytesExpectedToSend)660 }661662 func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {663 if kind == .download, error == nil { report(task.countOfBytesReceived, task.countOfBytesExpectedToReceive) }664 let observation = lock.withLock { () -> NSKeyValueObservation? in665 defer { self.observation = nil }666 return self.observation667 }668 observation?.invalidate()669 }670}671