Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraCore/Sources/Errors.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/// Every failure the app can show. Messages are written for the person using the app and never contain secrets.91public enum AstraError: Error, Sendable, Hashable, Codable, LocalizedError {92 case missingCredential(ProviderKind)93 case unauthorized(String?)94 case forbidden(String?)95 case rateLimited(retryAfter: TimeInterval?, message: String?)96 case quotaExceeded(String?)97 case modelNotFound(String)98 case contextTooLong(String?)99 case contentFiltered(String?)100 case invalidRequest(String)101 case overloaded(String?)102 case server(status: Int, message: String?)103 case network(String)104 case timeout105 case insecureEndpoint(String)106 case decoding(String)107 case protocolViolation(String)108 case unsupported(String)109 case local(String)110 /// A failure inside the app itself (database, Keychain, an unexpected error). Never transient, never blamed on the network.111 case internalFailure(String)112 case cancelled113114 public var errorDescription: String? { message }115116 public var title: String {117 switch self {118 case .missingCredential: "No API key"119 case .unauthorized: "Key rejected"120 case .forbidden: "Not allowed"121 case .rateLimited: "Rate limited"122 case .quotaExceeded: "Out of credit"123 case .modelNotFound: "Model unavailable"124 case .contextTooLong: "Conversation too long"125 case .contentFiltered: "Blocked by the provider"126 case .invalidRequest: "Request rejected"127 case .overloaded: "Provider overloaded"128 case .server: "Provider error"129 case .network: "Network problem"130 case .timeout: "Timed out"131 case .insecureEndpoint: "Insecure endpoint"132 case .decoding, .protocolViolation: "Unexpected response"133 case .unsupported: "Not supported"134 case .local: "On-device model"135 case .internalFailure: "Something went wrong"136 case .cancelled: "Stopped"137 }138 }139140 public var message: String {141 switch self {142 case .missingCredential(let p): "Add your \(p.displayName) API key in Models to use this model."143 case .unauthorized(let m): m ?? "The provider rejected this API key. Check it or replace it."144 case .forbidden(let m): m ?? "This key is not allowed to use that model or feature."145 case .rateLimited(let after, let m):146 if let after, after.isFinite, after > 0 { "The provider is rate limiting this key. Try again in \(Int(min(after, 86_400).rounded(.up))) s." }147 else { m ?? "The provider is rate limiting this key. Try again shortly." }148 case .quotaExceeded(let m): m ?? "This account has no remaining credit or quota."149 case .modelNotFound(let id): "The provider does not offer “\(id)” to this key."150 case .contextTooLong(let m): m ?? "The conversation no longer fits in this model's context window. Shorten it or lower the context budget."151 case .contentFiltered(let m): m ?? "The provider declined to answer this request."152 case .invalidRequest(let m): m153 case .overloaded(let m): m ?? "The provider is overloaded right now. Try again in a moment."154 case .server(let status, let m): m ?? "The provider returned an error (HTTP \(status))."155 case .network(let m): m156 case .timeout: "The provider took too long to answer."157 case .insecureEndpoint(let m): m158 case .decoding(let m): "The response could not be read: \(m)"159 case .protocolViolation(let m): "The response stream was malformed: \(m)"160 case .unsupported(let m): m161 case .local(let m): m162 case .internalFailure(let m): m163 case .cancelled: "Generation was stopped."164 }165 }166167 /// True when retrying the same request later can succeed without changing anything.168 public var isTransient: Bool {169 switch self {170 case .rateLimited, .overloaded, .network, .timeout: true171 case .server(let status, _): status >= 500172 default: false173 }174 }175176 public static func wrap(_ error: Error) -> AstraError {177 if let e = error as? AstraError { return e }178 if error is CancellationError { return .cancelled }179 if let u = error as? URLError {180 switch u.code {181 case .cancelled: return .cancelled182 case .timedOut: return .timeout183 case .notConnectedToInternet, .dataNotAllowed: return .network("This device is offline.")184 case .networkConnectionLost: return .network("The connection was lost while the answer was arriving.")185 case .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed: return .network("The server could not be reached.")186 case .secureConnectionFailed, .serverCertificateUntrusted, .serverCertificateHasBadDate, .serverCertificateNotYetValid,187 .serverCertificateHasUnknownRoot, .clientCertificateRejected:188 return .network("A secure connection to the server could not be established.")189 case .appTransportSecurityRequiresSecureConnection: return .insecureEndpoint("iOS blocked this plain-HTTP connection.")190 default: return .network(u.localizedDescription)191 }192 }193 if let d = error as? DecodingError {194 let detail: String = switch d {195 case .dataCorrupted(let c), .keyNotFound(_, let c), .typeMismatch(_, let c), .valueNotFound(_, let c): c.debugDescription196 @unknown default: "unreadable data"197 }198 return .decoding(Redactor.redact(String(detail.prefix(300))))199 }200 if (error as NSError).domain == NSURLErrorDomain { return .network(Redactor.redact(String((error as NSError).localizedDescription.prefix(300)))) }201 // Anything else is a failure of the app itself (database, Keychain, file system): it is not a network problem and202 // must not be retried as one. The text is redacted because it comes from outside this type.203 let text = (error as? LocalizedError)?.errorDescription ?? (error as NSError).localizedDescription204 return .internalFailure(String(Redactor.redact(text).prefix(300)))205 }206207 /// True when re-sending the same request automatically cannot bill or execute it twice: the provider answered with a208 /// status that says it did not take the request, or the connection never carried it. An idle timeout proves neither.209 public var isSafeToRetryAutomatically: Bool {210 switch self {211 case .rateLimited, .overloaded, .network: true212 case .server(let status, _): status >= 500213 default: false214 }215 }216}217218/// Maps an HTTP failure to a typed error. `message` must already be the provider's human text, never a raw body with headers.219public func mapHTTPError(status: Int, code: String?, message: String?, retryAfter: TimeInterval?, model: String?) -> AstraError {220 let lowered = ((code ?? "") + " " + (message ?? "")).lowercased()221 // Redact first, cut second: a key straddling the cut would otherwise fall below the pattern lengths and leak its head.222 let clean = message.map { String(Redactor.redact(String($0.prefix(4_000))).prefix(400)) }223 switch status {224 case 401: return .unauthorized(clean)225 case 402: return .quotaExceeded(clean)226 case 403:227 if lowered.contains("moderation") || lowered.contains("flagged") { return .contentFiltered(clean) }228 return .forbidden(clean)229 case 404:230 if lowered.contains("model"), let model { return .modelNotFound(model) }231 return .invalidRequest(clean ?? "The endpoint was not found (HTTP 404).")232 case 408: return .timeout233 case 413: return .contextTooLong(clean)234 case 429:235 if lowered.contains("insufficient_quota") || lowered.contains("billing") || lowered.contains("credit") { return .quotaExceeded(clean) }236 return .rateLimited(retryAfter: retryAfter, message: clean)237 case 400, 422:238 if lowered.contains("context_length") || lowered.contains("context window") || lowered.contains("too long") || lowered.contains("maximum context")239 || lowered.contains("too many tokens") { return .contextTooLong(clean) }240 if lowered.contains("model_not_found") || lowered.contains("not a valid model"), let model { return .modelNotFound(model) }241 if lowered.contains("content_policy") || lowered.contains("content management") { return .contentFiltered(clean) }242 return .invalidRequest(clean ?? "The provider rejected the request (HTTP \(status)).")243 case 529, 503: return .overloaded(clean)244 default: return .server(status: status, message: clean)245 }246}247248/// Removes anything that looks like a credential before text reaches a log, a diagnostic record, an export or the screen.249public enum Redactor {250 private static let patterns: [(NSRegularExpression, String)] = {251 // `b` = not preceded by a character that can be part of a word or a key: "task-…", "risk-…", "disk-…" are prose.252 let b = #"(?<![A-Za-z0-9_\-])"#253 let raw: [(String, String)] = [254 (b + #"sk-ant-[A-Za-z0-9_\-]{8,}"#, "sk-ant-•••"),255 (b + #"sk-or-v1-[A-Za-z0-9]{8,}"#, "sk-or-v1-•••"),256 (b + #"sk-proj-[A-Za-z0-9_\-]{8,}"#, "sk-proj-•••"),257 (b + #"sk-[A-Za-z0-9_\-]{16,}"#, "sk-•••"),258 (b + #"hf_[A-Za-z0-9]{16,}"#, "hf_•••"),259 (b + #"gsk_[A-Za-z0-9]{16,}"#, "gsk_•••"),260 (b + #"xai-[A-Za-z0-9]{16,}"#, "xai-•••"),261 (b + #"csk-[A-Za-z0-9]{16,}"#, "csk-•••"),262 (b + #"mstrl_[A-Za-z0-9_]{16,}"#, "mstrl_•••"),263 (b + #"AIza[A-Za-z0-9_\-]{20,}"#, "AIza•••"),264 (#"(?i)([?&]key=)[A-Za-z0-9_\-]{8,}"#, "$1•••"),265 // An Authorization value with any scheme (Basic, Token, Bearer…): the scheme stays, the credential goes.266 (#"(?i)((?:proxy-)?authorization["']?\s*[:=]\s*["']?[A-Za-z]{3,12}\s+)[^\s"',;}]{6,}"#, "$1•••"),267 // "Bearer <token>" on its own: a token has a digit or at least 16 characters; "Bearer authentication is required" is prose.268 (#"(?i)\b(bearer)\s+(?=[A-Za-z0-9._~+/=\-]*[0-9]|[A-Za-z0-9._~+/=\-]{16,})[A-Za-z0-9._~+/=\-]{8,}"#, "$1 •••"),269 (#"(?i)((?:x-api-key|api-key|authorization|x-goog-api-key|proxy-authorization)["']?\s*[:=]\s*["']?)(?!(?:basic|bearer|token|digest)\s)[^\s"',;}]{6,}"#, "$1•••"),270 (#"(?i)((?:api[_-]?key|access[_-]?token|session[_-]?token|refresh[_-]?token|client[_-]?secret|secret|password|passwd)["']?\s*[:=]\s*["']?)[^\s"',;}&]{6,}"#, "$1•••"),271 (#"(?i)((?:^|[?&\s])(?:token|key|sig|signature)=)[A-Za-z0-9._~+/\-]{8,}"#, "$1•••"),272 ]273 // A pattern that does not compile is a programming error: fail loudly (every test run exercises this initialiser).274 return raw.map { p, r in (try! NSRegularExpression(pattern: p), r) }275 }()276277 public static func redact(_ text: String) -> String {278 var out = text279 for (regex, replacement) in patterns {280 out = regex.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: replacement)281 }282 return out283 }284285 /// Header names whose values are never recorded.286 public static let sensitiveHeaders: Set<String> = ["authorization", "x-api-key", "api-key", "proxy-authorization", "cookie", "set-cookie", "x-goog-api-key"]287288 public static func redact(headers: [String: String]) -> [String: String] {289 var out: [String: String] = [:]290 for (k, v) in headers { out[k] = sensitiveHeaders.contains(k.lowercased()) ? "•••" : redact(v) }291 return out292 }293294 /// Shows only enough of a key to recognise it: prefix and last four characters.295 public static func mask(key: String) -> String {296 let t = key.trimmingCharacters(in: .whitespacesAndNewlines)297 guard t.count > 12 else { return String(repeating: "•", count: max(t.count, 4)) }298 let prefixLength = t.hasPrefix("sk-ant-") ? 7 : t.hasPrefix("sk-or-") ? 6 : t.hasPrefix("sk-") ? 3 : t.hasPrefix("xai-") ? 4 : t.hasPrefix("csk-") ? 4 : t.hasPrefix("mstrl_") ? 6 : t.hasPrefix("AIza") ? 4 : 0299 return String(t.prefix(prefixLength)) + "••••••••" + String(t.suffix(4))300 }301}302