Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/TradingAgents/TradingAPIStore.swift3// Description: State and operations of the programmable trading API as the owner manages it: keys, webhooks, usage, status. Creating, rotating or widening a key goes through the Core's verified key intent and the passkey; revoking and narrowing need the session only. A secret (key token or webhook signing secret) lives in memory only while its one-time sheet is open: it is never written to disk, defaults, logs or snapshots, and is dropped when the sheet closes.4import Foundation5import SPWalletCore67/// The form of a key (creation and edition). Nothing here is defaulted to "unlimited".8struct APIKeyForm: Equatable {9 var name = ""10 var scopes: Set<String> = []11 var days = ""12 var maxOrder = ""13 var maxDaily = ""14 var networks = ""15 var venues = ""16 var instruments = ""17 var ipAllow = ""18 var rate = ""19 var mandateId = ""2021 init() {}22 init(key k: APIKey) {23 name = k.name; scopes = Set(k.scopes)24 maxOrder = k.limits.maxOrderNotionalUsd.value.map(AgentCreateForm.plain) ?? ""; maxDaily = k.limits.maxDailyNotionalUsd.value.map(AgentCreateForm.plain) ?? ""25 networks = k.restrictions.networks.joined(separator: ", "); venues = k.restrictions.venues.joined(separator: ", "); instruments = k.restrictions.instruments.joined(separator: ", ")26 ipAllow = k.restrictions.ipAllow.joined(separator: ", "); rate = String(k.rateLimitPerMin); mandateId = k.mandateId ?? ""27 }2829 static func list(_ s: String) -> [String] { s.split(whereSeparator: { $0 == "," || $0 == "\n" || $0 == " " }).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } }30 var limits: APIKeyLimits { APIKeyLimits(maxOrderNotionalUsd: AgentText.decimal(maxOrder), maxDailyNotionalUsd: AgentText.decimal(maxDaily)) }31 var restrictions: APIKeyRestrictions { APIKeyRestrictions(networks: Self.list(networks), venues: Self.list(venues), instruments: Self.list(instruments), ipAllow: Self.list(ipAllow)) }3233 /// Why the form cannot be submitted. A key with a financial scope must carry both notional limits: an unbounded financial key is refused here.34 func problem(_ info: APIKeyList, creating: Bool) -> String? {35 let n = name.trimmingCharacters(in: .whitespacesAndNewlines)36 if n.isEmpty || n.count > 60 { return "Nom : 1 à 60 caractères." }37 if scopes.isEmpty { return "Choisissez au moins une permission." }38 if !scopes.isSubset(of: Set(info.scopes.map(\.scope))) { return "Une permission choisie n’est pas offerte par ce serveur." }39 if creating {40 guard let d = Int(days.trimmingCharacters(in: .whitespaces)), (1...info.bounds.maxDays).contains(d) else { return "Expiration : entre 1 et \(info.bounds.maxDays) jours (obligatoire, aucune clé sans échéance)." }41 if info.keys.filter(\.isActive).count >= info.bounds.maxKeys { return "Nombre maximal de clés atteint (\(info.bounds.maxKeys))." }42 }43 guard let r = Int(rate.trimmingCharacters(in: .whitespaces)), (1...info.bounds.maxRatePerMin).contains(r) else { return "Cadence : entre 1 et \(info.bounds.maxRatePerMin) requêtes par minute (obligatoire)." }44 let financial = !scopes.isDisjoint(with: Set(info.scopes.filter(\.execution).map(\.scope)))45 for (text, label) in [(maxOrder, "Plafond par ordre"), (maxDaily, "Plafond quotidien")] {46 let empty = text.trimmingCharacters(in: .whitespaces).isEmpty47 if empty { if financial { return "\(label) (USD) : obligatoire pour une clé à permission financière — une clé financière sans plafond est refusée." }; continue }48 guard let v = AgentText.decimal(text), v > 0 else { return "\(label) (USD) : nombre positif." }49 if let max = info.bounds.maxNotionalUsd, v > max { return "\(label) : au plus \(AgentCreateForm.plain(max)) USD." }50 }51 if let o = AgentText.decimal(maxOrder), let d = AgentText.decimal(maxDaily), o > d { return "Le plafond par ordre ne peut pas dépasser le plafond quotidien." }52 return nil53 }5455 func createRequest() -> APIKeyCreateRequest {56 APIKeyCreateRequest(name: name.trimmingCharacters(in: .whitespacesAndNewlines), scopes: scopes.sorted(), expiresInDays: Int(days.trimmingCharacters(in: .whitespaces)) ?? 0, limits: limits, restrictions: restrictions,57 rateLimitPerMin: Int(rate.trimmingCharacters(in: .whitespaces)) ?? 0, mandateId: nil)58 }5960 /// Only what differs from the key as the server holds it.61 func changes(from k: APIKey) -> APIKeyChanges {62 var c = APIKeyChanges()63 let n = name.trimmingCharacters(in: .whitespacesAndNewlines)64 if n != k.name { c.name = n }65 if scopes != Set(k.scopes) { c.scopes = scopes.sorted() }66 if limits != k.limits { c.limits = limits }67 if restrictions != k.restrictions { c.restrictions = restrictions }68 if let r = Int(rate.trimmingCharacters(in: .whitespaces)), r != k.rateLimitPerMin { c.rateLimitPerMin = r }69 if mandateId != (k.mandateId ?? "") { c.mandate = mandateId.isEmpty ? .unbind : .bind(mandateId) }70 return c71 }72}7374@MainActor @Observable final class TradingAPIStore {75 enum Pending { case create(APIKeyApproval), rotate(APIKeyApproval, APIKey), update(APIKeyApproval, APIKey)76 var approval: APIKeyApproval { switch self { case .create(let a), .rotate(let a, _), .update(let a, _): a } }77 }78 /// A secret shown once. Dropped by `dismissSecret()`; never stored anywhere else.79 struct Shown { let title: String; let subject: String; let secret: OneTimeSecret; let notes: [String]; let problems: [String] }8081 let model: AppModel82 let api: DeveloperAPI83 private(set) var keys: APIKeyList?84 private(set) var status: DeveloperStatus?85 private(set) var usage: APIKeyUsage?86 private(set) var webhooks: WebhookList?87 private(set) var mandates: [TradingMandateRecord]?88 private(set) var errors: [String: String] = [:]89 private(set) var busy: String?90 var actionError: String?91 var notice: String?92 private(set) var pending: Pending?93 private(set) var approving = false94 private(set) var shown: Shown?95 /// Set when a creation form was accepted by the server's preparation, so the form sheet can close.96 private(set) var formAccepted = 09798 init(model: AppModel) { self.model = model; api = DeveloperAPI(model.client) }99100 private func note<T: Sendable>(_ key: String, _ r: Result<T, Error>) -> T? {101 switch r { case .success(let v): errors[key] = nil; return v; case .failure(let e): errors[key] = model.describe(e); return nil }102 }103104 func refresh() async {105 guard model.phase == .signedIn else { return }106 let api = api, mandatesAPI = MandatesAPI(model.client)107 async let k = Result.catching { try await api.keys() }108 async let s = Result.catching { try await api.status() }109 async let u = Result.catching { try await api.usage(limit: 200) }110 async let w = Result.catching { try await api.webhooks() }111 async let m = Result.catching { try await mandatesAPI.list() }112 if let v = note("keys", await k) { keys = v }113 if let v = note("status", await s) { status = v }114 if let v = note("usage", await u) { usage = v }115 if let v = note("webhooks", await w) { webhooks = v }116 if let v = note("mandates", await m) { mandates = v }117 }118119 func poll() async {120 await refresh()121 while !Task.isCancelled {122 try? await Task.sleep(for: .seconds(30))123 guard !Task.isCancelled else { return }124 if AppActivity.isActive, !model.isOffline, busy == nil, pending == nil, shown == nil { await refresh() }125 }126 }127128 /// The mandates that name this key: the only ones it can be bound to.129 func mandates(for keyId: String) -> [TradingMandateRecord] { (mandates ?? []).filter { $0.principal.kind == "api_key" && $0.principal.id == keyId } }130131 private func run(_ name: String, sessionOnly: Bool = false, _ body: () async throws -> String?) async {132 guard busy == nil, sessionOnly ? model.phase == .signedIn : model.canOperate else { return }133 busy = name; actionError = nil; notice = nil134 do { notice = try await body() } catch { actionError = model.describe(error) }135 busy = nil136 await refresh()137 }138139 // MARK: keys140141 func prepareCreate(_ form: APIKeyForm) async {142 let api = api, r = form.createRequest()143 await run("prepare") { self.pending = .create(try await api.prepareCreate(r)); self.formAccepted += 1; return nil }144 }145146 func prepareRotate(_ key: APIKey) async {147 let api = api148 await run("prepare") { self.pending = .rotate(try await api.prepareRotate(id: key.id), key); return nil }149 }150151 /// Narrowing passes with the session alone. When the server says a change widens the key, the verified passkey intent is prepared instead.152 func update(_ key: APIKey, form: APIKeyForm) async {153 let api = api, changes = form.changes(from: key)154 guard !changes.isEmpty else { notice = "Aucun changement."; formAccepted += 1; return }155 await run("update") {156 do { _ = try await api.narrow(id: key.id, changes: changes); self.formAccepted += 1; return "Clé \(key.id) mise à jour (aucun élargissement : sans passkey)." }157 catch let e as APIError where e.code == "passkey_required" {158 self.pending = .update(try await api.prepareUpdate(id: key.id, changes: changes), key); self.formAccepted += 1159 return nil160 }161 }162 }163164 func cancelPending() { pending = nil; actionError = nil }165166 func approve() async {167 guard let p = pending, !approving, model.canOperate else { return }168 approving = true; actionError = nil; defer { approving = false }169 do {170 switch p {171 case .create(let a):172 let k = try await api.create(a, with: model.authenticator)173 pending = nil174 shown = Shown(title: "Clé d’API créée", subject: "\(k.key.name) · \(k.key.id)", secret: k.secret, notes: k.key.inertScopes.isEmpty ? [] : ["Permissions financières inertes tant qu’aucun mandat n’est lié à la clé : \(k.key.inertScopes.joined(separator: ", "))."],175 problems: k.discrepancies.isEmpty ? [] : ["La clé créée DIFFÈRE de l’intention approuvée sur : \(k.discrepancies.joined(separator: ", ")). Elle existe : révoquez-la."])176 case .rotate(let a, let old):177 let k = try await api.rotate(a, with: model.authenticator)178 pending = nil179 shown = Shown(title: "Clé d’API renouvelée", subject: "\(k.key.name) · \(k.key.id)", secret: k.secret,180 notes: ["L’ancienne clé \(k.revoked ?? old.id) ne fonctionne plus."] + (k.mandate.map { ["Mandat : \(JSONFlat.rows($0).map { "\($0.key) = \($0.value)" }.joined(separator: " · "))"] } ?? []),181 problems: k.discrepancies.isEmpty ? [] : ["La réponse DIFFÈRE de l’intention approuvée sur : \(k.discrepancies.joined(separator: ", ")). Révoquez la nouvelle clé."])182 case .update(let a, let key):183 _ = try await api.update(a, with: model.authenticator)184 pending = nil; notice = "Clé \(key.id) mise à jour avec votre passkey."185 }186 await refresh()187 } catch PasskeyError.cancelled {188 } catch {189 // a key-management intent is single use; after a failure the real state is read, nothing is signed twice190 pending = nil191 var text = model.describe(error)192 if case .create = p { text += " Si la clé apparaît dans la liste, sa valeur secrète est perdue : révoquez-la et créez-en une autre." }193 if case .rotate = p { text += " Vérifiez la liste : si une nouvelle clé y figure, son secret est perdu — révoquez-la." }194 actionError = text195 await refresh()196 }197 }198199 func revoke(_ key: APIKey) async {200 let api = api201 await run("revoke", sessionOnly: true) { let k = try await api.revoke(id: key.id, reason: "révoquée par le propriétaire depuis l’app macOS"); return "Clé \(k.id) : \(k.status)." }202 }203204 func dismissSecret() { shown = nil }205206 // MARK: webhooks207208 func createWebhook(url: String, events: [String], label: String) async -> Bool {209 let api = api210 await run("webhook") {211 let w = try await api.createWebhook(url: url, events: events, label: label)212 self.shown = Shown(title: "Webhook créé", subject: w.webhook.url, secret: w.secret, notes: ["Ce secret signe chaque livraison ; il sert à vérifier qu’elle vient bien de votre portefeuille."], problems: [])213 return nil214 }215 return actionError == nil216 }217218 func setWebhook(_ w: Webhook, enabled: Bool) async {219 let api = api, key = APIClient.newIdempotencyKey()220 await run("webhook") { let x = try await api.updateWebhook(id: w.id, enabled: enabled, idempotencyKey: key); return "Webhook \(x.enabled ? "activé" : "désactivé")." }221 }222223 func rotateWebhookSecret(_ w: Webhook) async {224 let api = api225 await run("webhook") {226 let x = try await api.rotateWebhookSecret(id: w.id)227 self.shown = Shown(title: "Nouveau secret de signature", subject: x.webhook.url, secret: x.secret, notes: ["L’ancien secret ne vérifie plus rien : mettez à jour votre récepteur."], problems: [])228 return nil229 }230 }231232 func deleteWebhook(_ w: Webhook) async {233 let api = api234 await run("webhook", sessionOnly: true) { try await api.deleteWebhook(id: w.id); return "Webhook supprimé." }235 }236}237