Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraCore/Sources/Transport.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation8990/// The only door to the network. Adapters never touch URLSession directly, so every provider parser is testable from fixtures.91public protocol HTTPTransport: Sendable {92 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)93 /// Opens a streaming response. On a non-2xx status the lines are the error body.94 func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>)95}9697/// Redirect rule for provider API calls. URLSession re-sends custom headers (`x-api-key`, `x-goog-api-key`, a custom endpoint's98/// extra headers) to wherever a redirect points, so a redirect is followed only when it stays on the same host and does not99/// leave https. Anything else ends the request with the 3xx response, which adapters report as an error.100public final class SameOriginRedirectPolicy: NSObject, URLSessionTaskDelegate, Sendable {101 public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,102 newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {103 let from = response.url ?? task.originalRequest?.url104 guard let from, let to = request.url, let fromHost = from.host?.lowercased(), let toHost = to.host?.lowercased(), fromHost == toHost,105 (from.port ?? -1) == (to.port ?? -1) || from.scheme?.lowercased() != to.scheme?.lowercased(),106 !(from.scheme?.lowercased() == "https" && to.scheme?.lowercased() != "https") else {107 completionHandler(nil); return108 }109 completionHandler(request)110 }111}112113public struct URLSessionTransport: HTTPTransport {114 private let session: URLSession115116 public init(configuration: URLSessionConfiguration? = nil) {117 let c = configuration ?? {118 let c = URLSessionConfiguration.ephemeral119 c.timeoutIntervalForRequest = 90120 c.timeoutIntervalForResource = 900121 c.httpCookieStorage = nil122 c.urlCache = nil123 c.httpShouldSetCookies = false124 c.waitsForConnectivity = false125 return c126 }()127 session = URLSession(configuration: c, delegate: SameOriginRedirectPolicy(), delegateQueue: nil)128 }129130 public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {131 do {132 let (data, response) = try await session.data(for: request)133 guard let http = response as? HTTPURLResponse else { throw AstraError.network("The server did not answer over HTTP.") }134 return (data, http)135 } catch { throw AstraError.wrap(error) }136 }137138 public func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) {139 do {140 let (bytes, response) = try await session.bytes(for: request)141 guard let http = response as? HTTPURLResponse else { throw AstraError.network("The server did not answer over HTTP.") }142 // A bounded buffer gives backpressure: a slow consumer suspends the reader instead of growing memory.143 let (stream, continuation) = AsyncThrowingStream<String, Error>.makeStream(bufferingPolicy: .unbounded)144 let task = Task {145 do {146 // `bytes.lines` drops empty lines, which SSE needs as event separators: split manually.147 var buffer = [UInt8](); buffer.reserveCapacity(4096)148 for try await byte in bytes {149 if byte == 0x0A {150 if buffer.last == 0x0D { buffer.removeLast() }151 continuation.yield(String(decoding: buffer, as: UTF8.self))152 buffer.removeAll(keepingCapacity: true)153 } else {154 buffer.append(byte)155 if buffer.count > 8_000_000 { throw AstraError.protocolViolation("A single stream line exceeded 8 MB.") }156 }157 }158 if !buffer.isEmpty { continuation.yield(String(decoding: buffer, as: UTF8.self)) }159 continuation.finish()160 } catch { continuation.finish(throwing: AstraError.wrap(error)) }161 }162 continuation.onTermination = { _ in task.cancel() }163 return (http, stream)164 } catch { throw AstraError.wrap(error) }165 }166}167168// MARK: - Server-sent events169170public struct SSEEvent: Sendable, Hashable {171 public var event: String?172 public var data: String173 public init(event: String? = nil, data: String) { self.event = event; self.data = data }174}175176/// Incremental server-sent-events parser (WHATWG rules: `data:` lines joined by newlines, blank line dispatches, `:` lines are comments).177public struct SSEParser: Sendable {178 private var event: String?179 private var data: [String] = []180 public private(set) var comments = 0181 private var atStart = true182 public init() {}183184 /// Feeds one line (without its terminator); returns an event when a blank line completes one.185 public mutating func feed(_ line: String) -> SSEEvent? {186 var line = line187 // A byte-order mark is allowed before the first field only.188 if atStart { atStart = false; if line.unicodeScalars.first == "\u{FEFF}" { line = String(line.unicodeScalars.dropFirst()) } }189 if line.isEmpty {190 defer { event = nil; data.removeAll(keepingCapacity: true) }191 return data.isEmpty ? nil : SSEEvent(event: event, data: data.joined(separator: "\n"))192 }193 if line.hasPrefix(":") { comments += 1; return nil }194 let field: Substring, value: Substring195 if let colon = line.firstIndex(of: ":") {196 field = line[..<colon]197 var rest = line[line.index(after: colon)...]198 if rest.first == " " { rest = rest.dropFirst() }199 value = rest200 } else { field = Substring(line); value = "" }201 switch field {202 case "event": event = String(value)203 case "data": data.append(String(value))204 default: break205 }206 return nil207 }208209 /// Flushes an event left without its trailing blank line when the stream ends.210 public mutating func finish() -> SSEEvent? { feed("") }211}212213public extension HTTPURLResponse {214 func header(_ name: String) -> String? { value(forHTTPHeaderField: name) }215216 /// `Retry-After` in seconds (delta form or HTTP date), falling back to provider-specific reset headers.217 var retryAfter: TimeInterval? {218 if let raw = header("retry-after") {219 if let s = Double(raw) { return Self.saneDelay(s) }220 let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"221 if let d = f.date(from: raw) { return Self.saneDelay(d.timeIntervalSinceNow) }222 }223 if let ms = header("retry-after-ms").flatMap(Double.init) { return Self.saneDelay(ms / 1000) }224 return nil225 }226227 /// A server-supplied delay as a finite number of seconds between 0 and one day; nil when it is not a number at all.228 static func saneDelay(_ seconds: Double) -> TimeInterval? { RetryDelay.sane(seconds) }229}230231/// Normalises delays that come from a server (header or body) before anything sleeps on them or prints them.232public enum RetryDelay {233 /// Finite, never negative, at most one day. `nil` for NaN.234 public static func sane(_ seconds: Double) -> TimeInterval? {235 guard !seconds.isNaN else { return nil }236 return min(86_400, max(0, seconds))237 }238}239240/// Collects a streamed error body (bounded) so adapters can map it to a typed error.241public func collectBody(_ lines: AsyncThrowingStream<String, Error>, limit: Int = 64_000) async -> Data {242 var text = ""243 do { for try await line in lines { text += line + "\n"; if text.utf8.count > limit { break } } } catch {}244 return Data(text.utf8)245}246247// MARK: - Endpoint safety248249public enum EndpointPolicy {250 /// Validates a user-entered base URL. Plain HTTP is refused unless `allowInsecure` is set, and then only for hosts251 /// on the local network or loopback, which is what App Transport Security's local-networking exception permits.252 public static func validate(_ text: String, allowInsecure: Bool) throws -> URL {253 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)254 guard let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {255 throw AstraError.invalidRequest("Enter a full URL such as https://example.com/v1.")256 }257 guard url.user == nil, url.password == nil else {258 throw AstraError.invalidRequest("Do not put credentials in the URL; use the API key field.")259 }260 switch scheme {261 case "https": return url262 case "http":263 guard allowInsecure else {264 throw AstraError.insecureEndpoint("Plain HTTP sends your prompts and key unencrypted. Use https, or explicitly allow insecure HTTP for a server on your own network.")265 }266 guard isLocalHost(host) else {267 throw AstraError.insecureEndpoint("Plain HTTP is only allowed for servers on your local network. Use https for “\(host)”.")268 }269 return url270 default: throw AstraError.invalidRequest("Only https (or local http) endpoints are supported.")271 }272 }273274 public static func isLocalHost(_ host: String) -> Bool {275 let h = host.lowercased()276 if h == "localhost" || h.hasSuffix(".local") || h == "::1" || h == "[::1]" { return true }277 // Exactly four labels, each made of ASCII digits only: "10.0.0.1.evil.com" and "+10.0.0.1" are names, not addresses.278 let labels = h.split(separator: ".", omittingEmptySubsequences: false)279 guard labels.count == 4 else { return false }280 let parts = labels.compactMap { label -> Int? in281 guard (1...3).contains(label.utf8.count), label.utf8.allSatisfy({ (48...57).contains($0) }) else { return nil }282 return Int(label)283 }284 guard parts.count == 4, parts.allSatisfy({ (0...255).contains($0) }) else { return false }285 if parts[0] == 10 || parts[0] == 127 { return true }286 if parts[0] == 192 && parts[1] == 168 { return true }287 if parts[0] == 172 && (16...31).contains(parts[1]) { return true }288 if parts[0] == 169 && parts[1] == 254 { return true }289 if parts[0] == 100 && (64...127).contains(parts[1]) { return true } // CGNAT range used by private overlay networks290 return false291 }292}293