Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr SMS Gateway9// File : sdk/swift/Sources/MacLustrSMS/MacLustrSMS.swift10// Module : MacLustrSMS11// Repository : https://git.spboucher.ai/maclustr-sms12// Project Website : https://sms.spboucher.ai13// Created : 2026-11-3014// Last Modified : 2026-11-3015//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: admin@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 CryptoKit89import Foundation9091/// Client de l'API https://sms.spboucher.ai/v1.92///93/// Réessais : uniquement sur échec de connexion, réponse 5xx ou 429. Un envoi porte toujours une Idempotency-Key,94/// réutilisée à l'identique par les réessais : le serveur ne crée jamais deux messages pour un même appel.95public final class MacLustrSMS: @unchecked Sendable {96 public static let defaultBaseURL = URL(string: "https://sms.spboucher.ai")!97 public enum WaitUntil: Sendable { case submitted, final }9899 public let baseURL: URL100 private let apiKey: String101 private let session: URLSession102 private let maxRetries: Int103 private let retryDelay: TimeInterval104 private let sleep: @Sendable (TimeInterval) async throws -> Void105106 /// - Parameter apiKey: clé `mlsk_…` ; à défaut, variable d'environnement `MACLUSTR_SMS_API_KEY` (outils en ligne de commande).107 /// Dans une app, lisez la clé depuis le Trousseau, jamais depuis le code source.108 public init(apiKey: String? = nil, baseURL: URL? = nil, session: URLSession = .shared, maxRetries: Int = 3, retryDelay: TimeInterval = 0.5,109 sleep: (@Sendable (TimeInterval) async throws -> Void)? = nil) {110 let env = ProcessInfo.processInfo.environment111 self.apiKey = apiKey ?? env["MACLUSTR_SMS_API_KEY"] ?? ""112 precondition(!self.apiKey.isEmpty, "clé API manquante : passez apiKey ou définissez MACLUSTR_SMS_API_KEY")113 self.baseURL = baseURL ?? env["MACLUSTR_SMS_URL"].flatMap { URL(string: $0) } ?? MacLustrSMS.defaultBaseURL114 self.session = session; self.maxRetries = maxRetries; self.retryDelay = retryDelay115 self.sleep = sleep ?? { try await Task.sleep(nanoseconds: UInt64(max($0, 0) * 1_000_000_000)) }116 }117118 // MARK: Transport119120 private static let decoder: JSONDecoder = { let d = JSONDecoder(); d.keyDecodingStrategy = .convertFromSnakeCase; return d }()121 private struct ErrorBody: Decodable { struct E: Decodable { let code: String?; let message: String?; let details: JSONValue? }; let error: E? }122123 private func send<T: Decodable>(_ method: String, _ path: String, query: [String: String?] = [:], body: [String: Any]? = nil, headers: [String: String] = [:], auth: Bool = true, retry: Bool = true) async throws -> (T, HTTPURLResponse) {124 var comps = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!125 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }126 if !items.isEmpty {127 comps.queryItems = items128 // « + » doit être encodé (%2B) : les numéros E.164 passent en paramètre de requête.129 comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")130 }131 var req = URLRequest(url: comps.url!)132 req.httpMethod = method133 req.setValue("application/json", forHTTPHeaderField: "Accept")134 req.setValue("maclustr-sms-swift/1.0.0", forHTTPHeaderField: "User-Agent")135 if auth { req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") }136 if let body { req.httpBody = try JSONSerialization.data(withJSONObject: body); req.setValue("application/json", forHTTPHeaderField: "Content-Type") }137 for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) }138139 var attempt = 0140 while true {141 var failure: MacLustrSMSError142 var retryAfter: TimeInterval? = nil143 do {144 let (data, res) = try await session.data(for: req)145 let http = res as! HTTPURLResponse146 if (200..<300).contains(http.statusCode) {147 do { return (try MacLustrSMS.decoder.decode(T.self, from: data), http) }148 catch { throw MacLustrSMSError(status: http.statusCode, code: "invalid_response", message: "réponse inattendue : \(error)") }149 }150 let e = (try? MacLustrSMS.decoder.decode(ErrorBody.self, from: data))?.error151 retryAfter = http.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init)152 failure = MacLustrSMSError(status: http.statusCode, code: e?.code ?? "http_error", message: e?.message ?? "HTTP \(http.statusCode)", details: e?.details, retryAfter: http.statusCode == 429 ? retryAfter : nil)153 if http.statusCode != 429 && http.statusCode < 500 { throw failure }154 } catch let e as MacLustrSMSError {155 if e.status != 429 && e.status < 500 { throw e }156 failure = e157 } catch let e as CancellationError { throw e }158 catch { failure = MacLustrSMSError(status: 0, code: "network_error", message: error.localizedDescription) }159 if !retry || attempt >= maxRetries { throw failure } // retry = false : opération non idempotente, jamais réessayée160 try await sleep(min(retryAfter ?? retryDelay * pow(2, Double(attempt)) * (failure.status == 429 ? 4 : 1), 30))161 attempt += 1162 }163 }164 private func get<T: Decodable>(_ path: String, _ query: [String: String?] = [:], auth: Bool = true) async throws -> T { try await send("GET", path, query: query, auth: auth).0 }165 private struct ListBody<T: Decodable>: Decodable { let data: [T] }166 private static func seg(_ s: String) -> String { s.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(.init(charactersIn: "-_.~"))) ?? s }167168 // MARK: Messages169170 /// Met un SMS en file. Statut initial « queued » (ou « held » si l'application exige une approbation humaine).171 @discardableResult172 public func send(to: String, text: String, deviceId: String? = nil, simId: String? = nil, from: String? = nil, ttlSeconds: Int? = nil, deliveryReport: Bool? = nil, idempotencyKey: String? = nil) async throws -> Message {173 var body: [String: Any] = ["to": to, "text": text]174 if let deviceId { body["device_id"] = deviceId }175 if let simId { body["sim_id"] = simId }176 if let from { body["from"] = from }177 if let ttlSeconds { body["ttl_seconds"] = ttlSeconds }178 if let deliveryReport { body["delivery_report"] = deliveryReport }179 let (m, res): (Message, HTTPURLResponse) = try await send("POST", "v1/messages", body: body, headers: ["Idempotency-Key": idempotencyKey ?? UUID().uuidString])180 var out = m181 out.replayed = res.value(forHTTPHeaderField: "Idempotent-Replayed") == "true"182 return out183 }184 public func getMessage(_ id: String) async throws -> Message { try await get("v1/messages/\(MacLustrSMS.seg(id))") }185 public func listMessages(status: String? = nil, to: String? = nil, deviceId: String? = nil, simId: String? = nil, createdAfter: String? = nil, createdBefore: String? = nil, limit: Int? = nil, cursor: String? = nil) async throws -> Page<Message> {186 try await get("v1/messages", ["status": status, "to": to, "device_id": deviceId, "sim_id": simId, "created_after": createdAfter, "created_before": createdBefore, "limit": limit.map(String.init), "cursor": cursor])187 }188 /// Tout l'historique, page après page (au plus `max` messages).189 public func allMessages(status: String? = nil, to: String? = nil, pageSize: Int = 100, max: Int = 10_000) async throws -> [Message] {190 var out: [Message] = [], cursor: String? = nil191 repeat {192 let p = try await listMessages(status: status, to: to, limit: pageSize, cursor: cursor)193 out += p.data194 cursor = p.hasMore ? p.nextCursor : nil195 } while cursor != nil && out.count < max196 return out197 }198 /// Annule un message pas encore transmis à l'appareil (sinon erreur 409 `not_cancellable`).199 @discardableResult200 public func cancel(_ id: String) async throws -> Message { try await send("POST", "v1/messages/\(MacLustrSMS.seg(id))/cancel", body: [:]).0 }201 /// Attend que le message soit remis au réseau (`.submitted`, défaut) ou dans un statut final (`.final`).202 /// « submitted » ne signifie pas « livré » ; « unknown » = issue ambiguë : ne renvoyez pas à l'aveugle.203 public func wait(_ id: String, timeout: TimeInterval = 60, until: WaitUntil = .submitted, interval: TimeInterval = 1) async throws -> Message {204 let deadline = Date().addingTimeInterval(timeout)205 while true {206 let m = try await getMessage(id)207 if m.isFinal || (until == .submitted && m.status == "submitted") { return m }208 if Date().addingTimeInterval(interval) > deadline { throw MacLustrSMSError(status: 0, code: "wait_timeout", message: "statut « \(m.status) » après \(timeout) s", lastMessage: m) }209 try await sleep(interval)210 }211 }212213 // MARK: Réception214215 public func inbox(from: String? = nil, simId: String? = nil, createdAfter: String? = nil, limit: Int? = nil, cursor: String? = nil) async throws -> Page<Message> {216 try await get("v1/inbox", ["from": from, "sim_id": simId, "created_after": createdAfter, "limit": limit.map(String.init), "cursor": cursor])217 }218 public func conversations(simId: String? = nil, limit: Int? = nil, cursor: String? = nil) async throws -> Page<Conversation> {219 try await get("v1/conversations", ["sim_id": simId, "limit": limit.map(String.init), "cursor": cursor])220 }221 public func conversationMessages(_ id: String, limit: Int? = nil, cursor: String? = nil) async throws -> Page<Message> {222 try await get("v1/conversations/\(MacLustrSMS.seg(id))/messages", ["limit": limit.map(String.init), "cursor": cursor])223 }224225 // MARK: Appareils226227 public func devices() async throws -> [Device] { (try await get("v1/devices") as ListBody<Device>).data }228 public func device(_ id: String) async throws -> Device { try await get("v1/devices/\(MacLustrSMS.seg(id))") }229 public func sims(deviceId: String) async throws -> [Sim] { (try await get("v1/devices/\(MacLustrSMS.seg(deviceId))/sims") as ListBody<Sim>).data }230 public func numbers() async throws -> [PhoneNumber] { (try await get("v1/numbers") as ListBody<PhoneNumber>).data }231232 // MARK: Webhooks233234 /// Crée un webhook. Conservez `secret` : il n'est renvoyé qu'ici.235 public func createWebhook(url: String, events: [String], description: String? = nil) async throws -> Webhook {236 var body: [String: Any] = ["url": url, "events": events]237 if let description { body["description"] = description }238 return try await send("POST", "v1/webhooks", body: body).0239 }240 public func listWebhooks() async throws -> [Webhook] { (try await get("v1/webhooks") as ListBody<Webhook>).data }241 private struct Deleted: Decodable { let deleted: Bool }242 @discardableResult243 public func deleteWebhook(_ id: String) async throws -> Bool { (try await send("DELETE", "v1/webhooks/\(MacLustrSMS.seg(id))").0 as Deleted).deleted }244245 // MARK: Vérification par code246247 /// Envoie un code de vérification par SMS (scope `verify:manage`). Conservez `id` dans la session serveur de l'utilisateur.248 /// Jamais réessayée automatiquement : cette route n'a pas d'Idempotency-Key, un réessai aveugle pourrait envoyer deux codes.249 /// Sur 429 (`verification_too_soon`, `verification_rate_limited`), l'erreur porte `retryAfter` (secondes).250 public func startVerification(to: String, brand: String? = nil, locale: String? = nil, ttlSeconds: Int? = nil, codeLength: Int? = nil, simId: String? = nil, from: String? = nil) async throws -> Verification {251 var body: [String: Any] = ["to": to]252 if let brand { body["brand"] = brand }253 if let locale { body["locale"] = locale }254 if let ttlSeconds { body["ttl_seconds"] = ttlSeconds }255 if let codeLength { body["code_length"] = codeLength }256 if let simId { body["sim_id"] = simId }257 if let from { body["from"] = from }258 return try await send("POST", "v1/verifications", body: body, retry: false).0259 }260 /// Vérifie le code saisi. `valid` vaut true une seule fois. Jamais réessayée (un essai serait consommé deux fois).261 public func checkVerification(id: String, code: String) async throws -> VerificationCheck {262 try await send("POST", "v1/verifications/\(MacLustrSMS.seg(id))/check", body: ["code": code], retry: false).0263 }264 public func verification(id: String) async throws -> Verification { try await get("v1/verifications/\(MacLustrSMS.seg(id))") }265266 // MARK: Divers267268 public func usage(from: String? = nil, to: String? = nil) async throws -> Usage { try await get("v1/usage", ["from": from, "to": to]) }269 public func queue() async throws -> Queue { try await get("v1/queue") }270 public func health() async throws -> Health { try await get("v1/health", auth: false) }271272 /// Vérifie une livraison de webhook et renvoie l'événement décodé.273 /// `body` = corps BRUT reçu ; `timestamp` = en-tête X-MacLustr-Timestamp ; `signature` = en-tête X-MacLustr-Signature (« v1=<hex> »).274 /// Dédupliquez aussi sur `event.id` : une livraison peut être retentée.275 public static func verifyWebhook(secret: String, timestamp: String?, body: Data, signature: String?, tolerance: TimeInterval = 300, now: Date = Date()) throws -> WebhookEvent {276 guard let raw = timestamp?.trimmingCharacters(in: .whitespaces), let ts = Int(raw) else { throw WebhookVerificationError.invalidTimestamp }277 if tolerance > 0 && abs(now.timeIntervalSince1970 - TimeInterval(ts)) > tolerance { throw WebhookVerificationError.timestampOutOfTolerance }278 let key = SymmetricKey(data: Data(secret.utf8))279 let signed = Data("\(ts).".utf8) + body280 let candidates = (signature ?? "").split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("v1=") }.compactMap { hexData(String($0.dropFirst(3))) }281 // isValidAuthenticationCode compare en temps constant.282 guard candidates.contains(where: { HMAC<SHA256>.isValidAuthenticationCode($0, authenticating: signed, using: key) }) else { throw WebhookVerificationError.invalidSignature }283 guard let ev = try? decoder.decode(WebhookEvent.self, from: body) else { throw WebhookVerificationError.invalidBody }284 return ev285 }286 private static func hexData(_ s: String) -> Data? {287 guard s.count % 2 == 0, !s.isEmpty else { return nil }288 var d = Data(capacity: s.count / 2), i = s.startIndex289 while i < s.endIndex { let j = s.index(i, offsetBy: 2); guard let b = UInt8(s[i..<j], radix: 16) else { return nil }; d.append(b); i = j }290 return d291 }292}293