SPB Git

Repository Public

DeveloperKeysView.swift 30.5 KB 424 lines swift

1// SP Wallet iOS2// File: Features/Security/DeveloperKeysView.swift3// Description: API keys of the trading API, from the owner's session: the list (permissions, limits, restrictions, last use,4//              expiry, state as served), creation / rotation / widening through the review of the verified intent and the passkey,5//              revocation and narrowing with the session alone. A key's secret is shown ONCE (DeveloperSecretSheet) and never6//              stored. Every value of a new key — permissions, expiry, rate — is typed by the owner.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213/** What the owner types for a key (creation, or change of an existing one). Nothing is preselected. */14struct DeveloperKeyDraft: Equatable {15    var name = ""16    var scopes: Set<String> = []17    var days = ""18    var rate = ""19    var maxOrder = ""20    var maxDaily = ""21    var networks = ""22    var venues = ""23    var instruments = ""24    var ipAllow = ""2526    init() {}27    /** For a change: starts from what the KEY has (the server's values of that key, not defaults). */28    init(key: APIKey) {29        name = key.name; scopes = Set(key.scopes); rate = String(key.rateLimitPerMin)30        maxOrder = key.limits.maxOrderNotionalUsd.value.map(Self.number) ?? ""; maxDaily = key.limits.maxDailyNotionalUsd.value.map(Self.number) ?? ""31        networks = key.restrictions.networks.joined(separator: ", "); venues = key.restrictions.venues.joined(separator: ", ")32        instruments = key.restrictions.instruments.joined(separator: ", "); ipAllow = key.restrictions.ipAllow.joined(separator: ", ")33    }34    static func number(_ d: Double) -> String { d == d.rounded() && abs(d) < 1e15 ? String(Int64(d)) : String(d) }3536    private func amount(_ s: String) -> Double?? {37        let t = s.trimmingCharacters(in: .whitespaces)38        if t.isEmpty { return .some(nil) }39        guard let d = RiskInput.positiveDecimal(t), let v = Double(d) else { return nil }40        return .some(v)41    }42    var limits: APIKeyLimits? {43        guard let a = amount(maxOrder), let b = amount(maxDaily) else { return nil }44        return APIKeyLimits(maxOrderNotionalUsd: a, maxDailyNotionalUsd: b)45    }46    var restrictions: APIKeyRestrictions { .init(networks: RiskInput.list(networks), venues: RiskInput.list(venues), instruments: RiskInput.list(instruments), ipAllow: RiskInput.list(ipAllow)) }4748    func problems(bounds: APIKeyList.Bounds, creating: Bool) -> [String] {49        var p: [String] = []50        let n = name.trimmingCharacters(in: .whitespacesAndNewlines)51        if creating, n.isEmpty || n.count > 60 { p.append(String(localized: "nom")) }52        if scopes.isEmpty { p.append(String(localized: "permissions")) }53        if creating { if let d = RiskInput.integer(days), d >= 1, d <= bounds.maxDays {} else { p.append(String(localized: "durée (1 à \(bounds.maxDays) jours)")) } }54        if let r = RiskInput.integer(rate), r >= 1, r <= bounds.maxRatePerMin {} else { p.append(String(localized: "requêtes par minute (1 à \(bounds.maxRatePerMin))")) }55        if limits == nil { p.append(String(localized: "plafonds")) }56        return p57    }5859    func request(offered: [String], bounds: APIKeyList.Bounds) -> APIKeyCreateRequest? {60        guard problems(bounds: bounds, creating: true).isEmpty, let d = RiskInput.integer(days), let r = RiskInput.integer(rate), let l = limits else { return nil }61        return APIKeyCreateRequest(name: name.trimmingCharacters(in: .whitespacesAndNewlines), scopes: offered.filter(scopes.contains), expiresInDays: d, limits: l, restrictions: restrictions, rateLimitPerMin: r, mandateId: nil)62    }6364    /** Only the members that differ from the key. */65    func changes(from key: APIKey, offered: [String]) -> APIKeyChanges? {66        guard let l = limits, let r = RiskInput.integer(rate) else { return nil }67        var c = APIKeyChanges()68        let s = offered.filter(scopes.contains) + scopes.filter { !offered.contains($0) }.sorted()69        if Set(s) != Set(key.scopes) { c.scopes = s }70        if l != key.limits { c.limits = l }71        if restrictions.networks.sorted() != key.restrictions.networks.sorted() || restrictions.venues.sorted() != key.restrictions.venues.sorted()72            || restrictions.instruments.sorted() != key.restrictions.instruments.sorted() || restrictions.ipAllow.sorted() != key.restrictions.ipAllow.sorted() { c.restrictions = restrictions }73        if r != key.rateLimitPerMin { c.rateLimitPerMin = r }74        return c75    }76}7778enum DeveloperWords {79    static func status(_ s: String) -> (String, Tone) {80        switch s { case "active": (String(localized: "active"), .ok); case "expired": (String(localized: "expirée"), .neutral); case "revoked": (String(localized: "révoquée"), .neutral); default: (s, .neutral) }81    }82    static func limits(_ l: APIKeyLimits) -> String {83        func one(_ v: Double?) -> String { v.map { Money.exact(DeveloperKeyDraft.number($0)) + " USD" } ?? String(localized: "aucun plafond propre à la clé") }84        return String(localized: "par ordre : \(one(l.maxOrderNotionalUsd.value)) · par jour : \(one(l.maxDailyNotionalUsd.value))")85    }86    static func restrictions(_ r: APIKeyRestrictions) -> String {87        let parts = [(String(localized: "réseaux"), r.networks), (String(localized: "plateformes"), r.venues), (String(localized: "marchés"), r.instruments), ("IP", r.ipAllow)].filter { !$0.1.isEmpty }.map { "\($0.0) : \($0.1.joined(separator: ", "))" }88        return parts.isEmpty ? String(localized: "aucune restriction") : parts.joined(separator: " · ")89    }90}9192/** A secret being shown once. Held only in view-model memory, dropped when the sheet closes. Never cached, never logged. */93struct DeveloperIssuedSecret: Identifiable {94    let id = UUID()95    let title: String96    let subject: String97    let secret: OneTimeSecret98    var discrepancies: [String] = []99    /** set for an API key whose creation answer differed from the approved intent: immediate revocation is offered */100    var revokeKeyId: String?101    var notes: [String] = []102}103104@MainActor @Observable105final class DeveloperKeysModel {106    enum Pending: Identifiable {107        case create(APIKeyApproval), rotate(APIKeyApproval, APIKey), update(APIKeyApproval, APIKey)108        var approval: APIKeyApproval { switch self { case .create(let a), .rotate(let a, _), .update(let a, _): a } }109        var id: String { approval.intent.intentId }110    }111    var list = Loaded<APIKeyList>()112    var busy = false113    var error: Error?114    var notice: String?115    var pending: Pending?116    var pendingError: Error?117    var issued: DeveloperIssuedSecret?118119    func load(_ app: AppModel) async { list = await SnapshotRead.read(APIKeyList.self, path: "/developer/keys", key: "risk-developer-keys", app: app, current: list) }120121    private func run(_ app: AppModel, _ work: (DeveloperAPI) async throws -> Void) async {122        guard !busy else { return }123        busy = true; error = nil; notice = nil; pendingError = nil; defer { busy = false }124        do { try await work(DeveloperAPI(app.env.client)) } catch { self.error = error }125    }126    func prepareCreate(_ r: APIKeyCreateRequest, app: AppModel) async -> Bool {127        await run(app) { self.pending = .create(try await $0.prepareCreate(r)) }128        return pending != nil129    }130    func prepareRotate(_ key: APIKey, app: AppModel) async { await run(app) { self.pending = .rotate(try await $0.prepareRotate(id: key.id), key) } }131132    /** Session first: the server accepts it only when nothing widens. Otherwise (403 `passkey_required`) an intent is prepared for review. */133    func change(_ key: APIKey, _ c: APIKeyChanges, app: AppModel) async -> Bool {134        var done = false135        await run(app) { api in136            do { _ = try await api.narrow(id: key.id, changes: c); self.notice = String(localized: "Clé restreinte (rien n’élargit : session seule)."); done = true }137            catch let e as APIError where e.code == "passkey_required" { self.pending = .update(try await api.prepareUpdate(id: key.id, changes: c), key) }138        }139        await load(app)140        return done || pending != nil141    }142143    func revoke(_ id: String, app: AppModel) async {144        await run(app) { let k = try await $0.revoke(id: id, reason: "owner, SP Wallet iOS"); self.notice = String(localized: "Clé \(k.id) : état renvoyé par le serveur « \(k.status) ».") }145        await load(app)146    }147148    func approve(_ app: AppModel) async {149        guard !busy, let p = pending else { return }150        busy = true; pendingError = nil; defer { busy = false }151        let api = DeveloperAPI(app.env.client)152        do {153            switch p {154            case .create(let a):155                let k = try await api.create(a, with: app.env.passkeys)156                issued = DeveloperIssuedSecret(title: String(localized: "Clé d’API créée"), subject: "\(k.key.name) · \(k.key.id)", secret: k.secret, discrepancies: k.discrepancies, revokeKeyId: k.key.id)157            case .rotate(let a, _):158                let k = try await api.rotate(a, with: app.env.passkeys)159                var notes = [k.revoked.map { String(localized: "L’ancienne clé \($0) ne fonctionne plus.") } ?? String(localized: "Le serveur n’a pas confirmé l’identifiant de l’ancienne clé.")]160                if let m = k.mandate, !m.isNull { notes.append(String(localized: "Mandat : \(JSONFields.text(m).isEmpty ? String(describing: m) : JSONFields.text(m))")) }161                issued = DeveloperIssuedSecret(title: String(localized: "Clé d’API renouvelée"), subject: "\(k.key.name) · \(k.key.id)", secret: k.secret, discrepancies: k.discrepancies, revokeKeyId: k.key.id, notes: notes)162            case .update(let a, _):163                let k = try await api.update(a, with: app.env.passkeys)164                notice = String(localized: "Clé \(k.id) modifiée (approuvé par la clé d’accès).")165            }166            pending = nil167            await load(app)168        } catch PasskeyError.cancelled {169        } catch let e as APIError where e.isOffline {170            // a lost answer of a creation or rotation cannot be replayed: the secret is gone. The key may exist: say so.171            pending = nil; error = e172            notice = String(localized: "La réponse a été perdue. Si la clé a été créée, son secret est irrécupérable : relis la liste et révoque-la.")173            await load(app)174        } catch { pendingError = error }175    }176}177178struct DeveloperKeysView: View {179    @Environment(AppModel.self) private var model180    @State private var dev = DeveloperKeysModel()181    @State private var creating = false182    @State private var revoking: APIKey?183184    var body: some View {185        @Bindable var dev = dev186        ScrollView {187            VStack(alignment: .leading, spacing: Theme.Space.section) {188                FreshnessBanner()189                if let l = dev.list.value {190                    if !dev.list.live { RiskSnapshotNotice(savedAt: dev.list.savedAt, error: dev.list.error) }191                    if let x = l.execution {192                        Notice(tone: x.liveEnabled == true ? .warn : .info,193                               title: x.liveEnabled == true ? String(localized: "Exécution réelle par l’API : ouverte sur ce serveur") : String(localized: "Exécution réelle par l’API : fermée sur ce serveur (SPW_TRADING_API_EXECUTION)"),194                               message: x.note)195                    }196                    if let n = dev.notice { Notice(tone: .info, title: n).accessibilityIdentifier("developer.notice") }197                    if let e = dev.error { ErrorNotice(error: e).accessibilityIdentifier("developer.error") }198                    if l.keys.isEmpty { EmptyState(icon: "key.horizontal", title: String(localized: "Aucune clé d’API")).accessibilityIdentifier("developer.empty") }199                    ForEach(l.keys) { k in keyCard(k, offered: l) }200                    Button { creating = true } label: { Label(String(localized: "Nouvelle clé d’API"), systemImage: "plus") }201                        .buttonStyle(.spPrimary).disabled(!model.canOperate || !dev.list.live || l.keys.count >= l.bounds.maxKeys).accessibilityIdentifier("developer.new")202                    NavigationLink { DeveloperWebhooksView().wallet(model) } label: {203                        HStack { Label(String(localized: "Webhooks"), systemImage: "antenna.radiowaves.left.and.right").font(.spHeadline).foregroundStyle(Theme.ink); Spacer(); Image(systemName: "chevron.right").foregroundStyle(Theme.mute) }.frame(minHeight: 44)204                    }.spCard().accessibilityIdentifier("developer.webhooks")205                } else if let e = dev.list.error { ErrorNotice(error: e) { Task { await dev.load(model) } } }206                else if model.offlineBrowsing { EmptyState(icon: "key.horizontal", title: String(localized: "Clés d’API indisponibles hors ligne")) }207                else { ProgressView().frame(maxWidth: .infinity).padding(.top, 40) }208            }209            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)210            .frame(maxWidth: 900).frame(maxWidth: .infinity)211        }212        .spPage()213        .navigationTitle(String(localized: "Clés d’API")).navigationBarTitleDisplayMode(.inline)214        .refreshable { await dev.load(model) }215        .task { await dev.load(model) }216        .sheet(isPresented: $creating) { if let l = dev.list.value { DeveloperKeyForm(dev: dev, offered: l, key: nil).wallet(model) } }217        .sheet(item: $dev.pending) { p in DeveloperKeyReview(dev: dev, pending: p).wallet(model) }218        .sheet(item: $dev.issued, onDismiss: { dev.issued = nil }) { s in219            DeveloperSecretSheet(issued: s) { id in await dev.revoke(id, app: model) }.wallet(model)220        }221        .confirmationDialog(String(localized: "Révoquer cette clé ?"), isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }), titleVisibility: .visible) {222            Button(String(localized: "Révoquer"), role: .destructive) { if let k = revoking { Task { await dev.revoke(k.id, app: model) } }; revoking = nil }.accessibilityIdentifier("developer.revoke.confirm")223            Button(String(localized: "Annuler"), role: .cancel) { revoking = nil }224        } message: { Text(String(localized: "Elle cesse de fonctionner immédiatement. Définitif, sans clé d’accès : révoquer ne fait que retirer de l’autorité.")) }225    }226227    private func keyCard(_ k: APIKey, offered: APIKeyList) -> some View {228        let (status, tone) = DeveloperWords.status(k.status)229        return VStack(alignment: .leading, spacing: 0) {230            HStack(alignment: .top) {231                VStack(alignment: .leading, spacing: 2) {232                    Text(k.name).font(.spHeadline).foregroundStyle(Theme.ink)233                    Text(k.id).font(.spMono).foregroundStyle(Theme.mute).textSelection(.enabled)234                }235                Spacer()236                Pill(text: status, tone: tone).accessibilityIdentifier("developer.key.status")237            }.padding(.bottom, 6)238            FieldRow(label: String(localized: "Permissions"), value: k.scopes.joined(separator: ", "), mono: true)239            if !k.inertScopes.isEmpty { Notice(tone: .warn, title: String(localized: "Permissions d’exécution inertes : aucun mandat de trading lié"), message: k.inertScopes.joined(separator: ", ")).padding(.vertical, 4) }240            Divider()241            FieldRow(label: String(localized: "Plafonds de la clé"), value: DeveloperWords.limits(k.limits)); Divider()242            FieldRow(label: String(localized: "Restrictions"), value: DeveloperWords.restrictions(k.restrictions)); Divider()243            FieldRow(label: String(localized: "Requêtes par minute"), value: String(k.rateLimitPerMin)); Divider()244            FieldRow(label: String(localized: "Mandat lié"), value: k.mandateId ?? String(localized: "aucun"), mono: k.mandateId != nil); Divider()245            FieldRow(label: String(localized: "Dernière utilisation"), value: k.lastUsedAt.flatMap { Fmt.date(ms: $0) }.map { $0 + (k.lastUsedIp.map { " · \($0)" } ?? "") } ?? String(localized: "jamais")); Divider()246            FieldRow(label: String(localized: "Créée · expire"), value: "\(Fmt.date(ms: k.createdAt) ?? "—") · \(Fmt.date(ms: k.expiresAt) ?? "—")")247            if let r = k.revokedAt { Divider(); FieldRow(label: String(localized: "Révoquée"), value: (Fmt.date(ms: r) ?? "") + (k.revokedReason.map { " · \($0)" } ?? "")) }248            if let r = k.rotatedFrom { Divider(); FieldRow(label: String(localized: "Remplace la clé"), value: r, mono: true) }249            if k.isActive {250                HStack(spacing: 8) {251                    NavigationLink { DeveloperKeyForm(dev: dev, offered: offered, key: k).wallet(model) } label: { Text(String(localized: "Modifier")).font(.spCallout.weight(.semibold)).frame(maxWidth: .infinity, minHeight: 44) }252                        .buttonStyle(.bordered).accessibilityIdentifier("developer.key.edit")253                    Button { Task { await dev.prepareRotate(k, app: model) } } label: { Text(String(localized: "Renouveler")).font(.spCallout.weight(.semibold)).frame(maxWidth: .infinity, minHeight: 44) }254                        .buttonStyle(.bordered).accessibilityIdentifier("developer.key.rotate")255                    Button(role: .destructive) { revoking = k } label: { Text(String(localized: "Révoquer")).font(.spCallout.weight(.semibold)).frame(maxWidth: .infinity, minHeight: 44) }256                        .buttonStyle(.bordered).accessibilityIdentifier("developer.key.revoke")257                }258                .padding(.top, 10).disabled(!model.canOperate || !dev.list.live || dev.busy)259            }260        }261        .spCard()262    }263}264265/** Creation (key == nil, in a sheet) or change (pushed) of a key. */266struct DeveloperKeyForm: View {267    @Environment(AppModel.self) private var model268    @Environment(\.dismiss) private var dismiss269    let dev: DeveloperKeysModel270    let offered: APIKeyList271    let key: APIKey?272    @State private var draft = DeveloperKeyDraft()273    @State private var loaded = false274275    var body: some View {276        if key == nil { NavigationStack { content.toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { dismiss() }.accessibilityIdentifier("developer.form.close") } } } }277        else { content }278    }279280    private var content: some View {281        let scopes = offered.scopes.map(\.scope)282        let problems = draft.problems(bounds: offered.bounds, creating: key == nil)283        let changes = key.flatMap { draft.changes(from: $0, offered: scopes) }284        return ScrollView {285            VStack(alignment: .leading, spacing: Theme.Space.section) {286                Text(key == nil ? String(localized: "Aucune valeur n’est présélectionnée. La création passe par la revue de l’intention exacte puis par ta clé d’accès. Le secret ne sera montré qu’une fois.")287                     : String(localized: "Restreindre s’applique tout de suite avec la session seule. Tout ce qui ÉLARGIT (permission ajoutée, plafond relevé, restriction retirée, cadence augmentée) passe par la revue puis la clé d’accès."))288                    .font(.spFootnote).foregroundStyle(Theme.mute)289                if key == nil {290                    VStack(alignment: .leading, spacing: 10) {291                        Text(String(localized: "Nom")).font(.spHeadline)292                        input(String(localized: "1 à 60 caractères"), $draft.name, .default, "developer.form.name")293                        Text(String(localized: "Durée de validité en jours (1 à \(offered.bounds.maxDays))")).font(.spFootnote).foregroundStyle(Theme.mute)294                        input(String(localized: "à saisir"), $draft.days, .numberPad, "developer.form.days")295                    }.spCard()296                }297                VStack(alignment: .leading, spacing: 4) {298                    Text(String(localized: "Permissions")).font(.spHeadline)299                    Text(String(localized: "Une permission d’exécution n’agit qu’avec un mandat de trading approuvé et lié à la clé.")).font(.spFootnote).foregroundStyle(Theme.mute)300                    ForEach(offered.scopes, id: \.scope) { s in301                        Button { if draft.scopes.contains(s.scope) { draft.scopes.remove(s.scope) } else { draft.scopes.insert(s.scope) } } label: {302                            HStack(spacing: 10) {303                                Image(systemName: draft.scopes.contains(s.scope) ? "checkmark.square.fill" : "square").font(.system(size: 20)).foregroundStyle(draft.scopes.contains(s.scope) ? Theme.blue : Theme.mute)304                                Text(s.scope).font(.spMono).foregroundStyle(Theme.ink)305                                Spacer()306                                if s.execution { Pill(text: String(localized: "exécution"), tone: .warn, icon: "bolt.fill") }307                            }.frame(minHeight: 44).contentShape(Rectangle())308                        }.buttonStyle(.plain).accessibilityIdentifier("developer.form.scope.\(s.scope)")309                    }310                }.spCard()311                VStack(alignment: .leading, spacing: 10) {312                    Text(String(localized: "Cadence et plafonds")).font(.spHeadline)313                    Text(String(localized: "Requêtes par minute (1 à \(offered.bounds.maxRatePerMin))")).font(.spFootnote).foregroundStyle(Theme.mute)314                    input(String(localized: "à saisir"), $draft.rate, .numberPad, "developer.form.rate")315                    Text(String(localized: "Plafond par ordre, USD (vide = aucun plafond propre à la clé)")).font(.spFootnote).foregroundStyle(Theme.mute)316                    input(String(localized: "vide = aucun"), $draft.maxOrder, .decimalPad, "developer.form.maxOrder")317                    Text(String(localized: "Plafond par jour, USD (vide = aucun plafond propre à la clé)")).font(.spFootnote).foregroundStyle(Theme.mute)318                    input(String(localized: "vide = aucun"), $draft.maxDaily, .decimalPad, "developer.form.maxDaily")319                }.spCard()320                VStack(alignment: .leading, spacing: 10) {321                    Text(String(localized: "Restrictions (vide = aucune)")).font(.spHeadline)322                    input(String(localized: "réseaux, séparés par des virgules"), $draft.networks, .asciiCapable, "developer.form.networks")323                    input(String(localized: "plateformes"), $draft.venues, .asciiCapable, "developer.form.venues")324                    input(String(localized: "marchés (plateforme:symbole)"), $draft.instruments, .asciiCapable, "developer.form.instruments")325                    input(String(localized: "adresses IP ou plages autorisées"), $draft.ipAllow, .asciiCapable, "developer.form.ip")326                }.spCard()327                if !problems.isEmpty { Text(String(localized: "Reste à saisir : \(problems.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("developer.form.problems") }328                if let e = dev.error { ErrorNotice(error: e).accessibilityIdentifier("developer.form.error") }329                if let key {330                    Button { Task { if let c = changes, await dev.change(key, c, app: model) { dismiss() } } } label: { HStack { if dev.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Enregistrer les changements")) } }331                        .buttonStyle(.spPrimary).disabled(!problems.isEmpty || changes?.isEmpty != false || dev.busy || !model.canOperate).accessibilityIdentifier("developer.form.save")332                } else {333                    Button { Task { if let r = draft.request(offered: scopes, bounds: offered.bounds), await dev.prepareCreate(r, app: model) { dismiss() } } } label: { HStack { if dev.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer et vérifier")) } }334                        .buttonStyle(.spPrimary).disabled(!problems.isEmpty || dev.busy || !model.canOperate).accessibilityIdentifier("developer.form.prepare")335                }336            }337            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)338            .frame(maxWidth: 680).frame(maxWidth: .infinity)339        }340        .spPage()341        .navigationTitle(key == nil ? String(localized: "Nouvelle clé d’API") : String(localized: "Modifier la clé")).navigationBarTitleDisplayMode(.inline)342        .onAppear { if !loaded { loaded = true; if let key { draft = DeveloperKeyDraft(key: key) } } }343    }344345    private func input(_ placeholder: String, _ text: Binding<String>, _ kb: UIKeyboardType, _ id: String) -> some View {346        TextField(placeholder, text: text).keyboardType(kb).textInputAutocapitalization(.never).autocorrectionDisabled().font(.spBody).monospacedDigit()347            .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier(id)348    }349}350351/** Review of a key-management intent before the passkey: every member of the intent, as it hashes. */352struct DeveloperKeyReview: View {353    @Environment(AppModel.self) private var model354    let dev: DeveloperKeysModel355    let pending: DeveloperKeysModel.Pending356357    var body: some View {358        let a = pending.approval, i = a.intent359        NavigationStack {360            ScrollView {361                VStack(alignment: .leading, spacing: 14) {362                    VStack(alignment: .leading, spacing: 4) {363                        Text(String(localized: "Clé d’API")).spEyebrow()364                        Text(title).font(.system(size: 26, weight: .semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("developer.review.title")365                    }366                    switch pending {367                    case .create:368                        if let k = i.key { keyRows(k) }369                    case .rotate(_, let old):370                        Notice(tone: .warn, title: String(localized: "L’ancienne clé cessera de fonctionner"), message: String(localized: "Un nouvel identifiant et un nouveau secret, avec les mêmes permissions, plafonds, restrictions et expiration."))371                        VStack(alignment: .leading, spacing: 0) {372                            FieldRow(label: String(localized: "Clé renouvelée"), value: "\(old.name) · \(i.keyId ?? "")", mono: true); Divider()373                            FieldRow(label: String(localized: "Nouvel identifiant"), value: i.newKeyId ?? "", mono: true)374                        }.spCard(padding: 16)375                    case .update(_, let key):376                        if let w = i.widening, !w.isEmpty { Notice(tone: .warn, title: String(localized: "Ce que le serveur considère comme un élargissement"), message: w.joined(separator: " · ")).accessibilityIdentifier("developer.review.widening") }377                        VStack(alignment: .leading, spacing: 0) {378                            FieldRow(label: String(localized: "Clé modifiée"), value: "\(key.name) · \(i.keyId ?? "")", mono: true)379                            if let c = i.changes {380                                if let s = c.scopes { Divider(); FieldRow(label: String(localized: "Permissions : de → à"), value: key.scopes.joined(separator: ", ") + "\n→ " + s.joined(separator: ", "), mono: true) }381                                if let l = c.limits { Divider(); FieldRow(label: String(localized: "Plafonds : de → à"), value: DeveloperWords.limits(key.limits) + "\n→ " + DeveloperWords.limits(l)) }382                                if let r = c.restrictions { Divider(); FieldRow(label: String(localized: "Restrictions : de → à"), value: DeveloperWords.restrictions(key.restrictions) + "\n→ " + DeveloperWords.restrictions(r)) }383                                if let r = c.rateLimitPerMin { Divider(); FieldRow(label: String(localized: "Requêtes par minute : de → à"), value: "\(key.rateLimitPerMin) → \(r)") }384                                if let n = c.name { Divider(); FieldRow(label: String(localized: "Nom : de → à"), value: "\(key.name) → \(n)") }385                                if let e = c.expiresAt { Divider(); FieldRow(label: String(localized: "Expiration"), value: e, mono: true) }386                                if c.mandate != .unchanged { Divider(); FieldRow(label: String(localized: "Mandat"), value: String(describing: c.mandate), mono: true) }387                            }388                        }.spCard(padding: 16)389                    }390                    VStack(alignment: .leading, spacing: 0) {391                        Text(String(localized: "Intention complète, telle qu’elle est signée")).spEyebrow().padding(.bottom, 4)392                        JSONFields(value: (try? JSONValue.from(i)) ?? .null)393                    }.spCard(padding: 16)394                    RiskApprovalFacts(expiry: a.expiry, digest: a.approval.digest, domain: APIKeyIntent.domain)395                    if let e = dev.pendingError { ErrorNotice(error: e).accessibilityIdentifier("developer.review.error") }396                    RiskApproveButtons(expiry: a.expiry, busy: dev.busy, identifier: "developer.review.approve", approve: { Task { await dev.approve(model) } }, cancel: { dev.pending = nil })397                }398                .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)399                .frame(maxWidth: 620).frame(maxWidth: .infinity)400            }401            .spPage()402            .navigationTitle(String(localized: "Vérifier et approuver")).navigationBarTitleDisplayMode(.inline)403        }404        .interactiveDismissDisabled()405    }406407    private var title: String {408        switch pending { case .create: String(localized: "Créer une clé"); case .rotate: String(localized: "Renouveler une clé"); case .update: String(localized: "Élargir une clé") }409    }410411    private func keyRows(_ k: APIKeyIntent.Key) -> some View {412        VStack(alignment: .leading, spacing: 0) {413            FieldRow(label: String(localized: "Nom"), value: k.name); Divider()414            FieldRow(label: String(localized: "Identifiant"), value: k.id, mono: true); Divider()415            FieldRow(label: String(localized: "Permissions"), value: k.scopes.joined(separator: ", "), mono: true).accessibilityIdentifier("developer.review.scopes"); Divider()416            FieldRow(label: String(localized: "Expire le"), value: ISO8601.parse(k.expiresAt).map { $0.formatted(date: .abbreviated, time: .standard) + " (\(k.expiresAt))" } ?? k.expiresAt); Divider()417            FieldRow(label: String(localized: "Plafonds"), value: DeveloperWords.limits(k.limits)); Divider()418            FieldRow(label: String(localized: "Restrictions"), value: DeveloperWords.restrictions(k.restrictions)); Divider()419            FieldRow(label: String(localized: "Requêtes par minute"), value: String(k.rateLimitPerMin)); Divider()420            FieldRow(label: String(localized: "Mandat lié"), value: k.mandateId.value ?? String(localized: "aucun"))421        }.spCard(padding: 16)422    }423}424
Files main
Menu

Theme