Repository Public
1// SP Wallet iOS2// File: Features/Security/DeveloperWebhooksView.swift3// Description: Webhooks of the trading API: the list with each endpoint's events, state and last delivery result as served,4// creation, enabling / disabling, deletion and rotation of the signing secret. A signing secret is shown ONCE in the5// same one-time sheet as an API key's and is never stored.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112@MainActor @Observable13final class DeveloperWebhooksModel {14 var list = Loaded<WebhookList>()15 var busy = false16 var error: Error?17 var notice: String?18 var issued: DeveloperIssuedSecret?19 var url = ""20 var label = ""21 var events: Set<String> = []2223 func load(_ app: AppModel) async { list = await SnapshotRead.read(WebhookList.self, path: "/developer/webhooks", key: "risk-developer-webhooks", app: app, current: list) }2425 var urlProblem: String? {26 let t = url.trimmingCharacters(in: .whitespaces)27 guard !t.isEmpty else { return nil }28 guard let u = URL(string: t), u.scheme == "https", u.host?.isEmpty == false else { return String(localized: "Une adresse https:// complète est exigée.") }29 return nil30 }31 var canCreate: Bool { !url.trimmingCharacters(in: .whitespaces).isEmpty && urlProblem == nil && !events.isEmpty && !label.trimmingCharacters(in: .whitespaces).isEmpty && !busy }3233 private func run(_ app: AppModel, _ work: (DeveloperAPI) async throws -> Void) async {34 guard !busy else { return }35 busy = true; error = nil; notice = nil; defer { busy = false }36 do { try await work(DeveloperAPI(app.env.client)) } catch { self.error = error }37 await load(app)38 }39 func create(_ app: AppModel) async {40 let offered = list.value?.events.map(\.event) ?? []41 await run(app) { api in42 let w = try await api.createWebhook(url: self.url.trimmingCharacters(in: .whitespaces), events: offered.filter(self.events.contains), label: self.label.trimmingCharacters(in: .whitespaces))43 self.issued = DeveloperIssuedSecret(title: String(localized: "Webhook créé"), subject: "\(w.webhook.label ?? "") · \(w.webhook.url)", secret: w.secret,44 notes: [String(localized: "Ce secret signe chaque livraison ; ton serveur s’en sert pour vérifier la signature.")])45 self.url = ""; self.label = ""; self.events = []46 }47 }48 func setEnabled(_ w: Webhook, _ on: Bool, app: AppModel) async {49 let key = APIClient.newIdempotencyKey()50 await run(app) { let r = try await $0.updateWebhook(id: w.id, enabled: on, idempotencyKey: key); self.notice = r.enabled ? String(localized: "Webhook activé (confirmé par le serveur).") : String(localized: "Webhook désactivé (confirmé par le serveur).") }51 }52 func rotate(_ w: Webhook, app: AppModel) async {53 await run(app) { let r = try await $0.rotateWebhookSecret(id: w.id)54 self.issued = DeveloperIssuedSecret(title: String(localized: "Nouveau secret de signature"), subject: r.webhook.url, secret: r.secret, notes: [String(localized: "L’ancien secret ne vérifie plus les livraisons.")]) }55 }56 func delete(_ w: Webhook, app: AppModel) async { await run(app) { try await $0.deleteWebhook(id: w.id); self.notice = String(localized: "Webhook supprimé.") } }57}5859struct DeveloperWebhooksView: View {60 @Environment(AppModel.self) private var model61 @State private var hooks = DeveloperWebhooksModel()62 @State private var deleting: Webhook?63 @State private var rotating: Webhook?6465 var body: some View {66 @Bindable var hooks = hooks67 ScrollView {68 VStack(alignment: .leading, spacing: Theme.Space.section) {69 FreshnessBanner()70 if let l = hooks.list.value {71 if !hooks.list.live { RiskSnapshotNotice(savedAt: hooks.list.savedAt, error: hooks.list.error) }72 if let s = l.signature { Text(s).font(.spFootnote).foregroundStyle(Theme.mute) }73 if let n = hooks.notice { Notice(tone: .info, title: n).accessibilityIdentifier("webhooks.notice") }74 if let e = hooks.error { ErrorNotice(error: e).accessibilityIdentifier("webhooks.error") }75 if l.webhooks.isEmpty { EmptyState(icon: "antenna.radiowaves.left.and.right", title: String(localized: "Aucun webhook")).accessibilityIdentifier("webhooks.empty") }76 ForEach(l.webhooks) { w in card(w, deliveries: l.deliveries.filter { $0.webhookId == w.id }) }77 createCard(l)78 } else if let e = hooks.list.error { ErrorNotice(error: e) { Task { await hooks.load(model) } } }79 else if model.offlineBrowsing { EmptyState(icon: "antenna.radiowaves.left.and.right", title: String(localized: "Webhooks indisponibles hors ligne")) }80 else { ProgressView().frame(maxWidth: .infinity).padding(.top, 40) }81 }82 .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)83 .frame(maxWidth: 900).frame(maxWidth: .infinity)84 }85 .spPage()86 .navigationTitle(String(localized: "Webhooks")).navigationBarTitleDisplayMode(.inline)87 .refreshable { await hooks.load(model) }88 .task { await hooks.load(model) }89 .sheet(item: $hooks.issued, onDismiss: { hooks.issued = nil }) { s in DeveloperSecretSheet(issued: s) { _ in }.wallet(model) }90 .confirmationDialog(String(localized: "Supprimer ce webhook ?"), isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {91 Button(String(localized: "Supprimer"), role: .destructive) { if let w = deleting { Task { await hooks.delete(w, app: model) } }; deleting = nil }92 Button(String(localized: "Annuler"), role: .cancel) { deleting = nil }93 }94 .confirmationDialog(String(localized: "Changer le secret de signature ?"), isPresented: Binding(get: { rotating != nil }, set: { if !$0 { rotating = nil } }), titleVisibility: .visible) {95 Button(String(localized: "Changer le secret")) { if let w = rotating { Task { await hooks.rotate(w, app: model) } }; rotating = nil }96 Button(String(localized: "Annuler"), role: .cancel) { rotating = nil }97 } message: { Text(String(localized: "L’ancien secret cessera de vérifier les livraisons. Le nouveau ne sera montré qu’une fois.")) }98 }99100 private func card(_ w: Webhook, deliveries: [WebhookDelivery]) -> some View {101 VStack(alignment: .leading, spacing: 0) {102 HStack(alignment: .top) {103 Text(w.label?.isEmpty == false ? w.label! : w.id).font(.spHeadline).foregroundStyle(Theme.ink)104 Spacer()105 Pill(text: w.enabled ? String(localized: "activé") : String(localized: "désactivé"), tone: w.enabled ? .ok : .neutral)106 }.padding(.bottom, 6)107 FieldRow(label: String(localized: "Adresse"), value: w.url, mono: true, copyable: true); Divider()108 FieldRow(label: String(localized: "Événements"), value: w.events.joined(separator: ", "), mono: true); Divider()109 FieldRow(label: String(localized: "Dernière livraison réussie"), value: w.lastOkAt.flatMap { Fmt.date(ms: $0) } ?? String(localized: "aucune"))110 if let e = w.lastError { Divider(); FieldRow(label: String(localized: "Dernière erreur · échecs"), value: e + (w.failures.map { " · \($0)" } ?? ""), tone: .danger) }111 if !deliveries.isEmpty {112 DisclosureGroup(String(localized: "Livraisons récentes (\(deliveries.count))")) {113 ForEach(deliveries.prefix(10)) { d in114 FieldRow(label: "\(d.event) · \(Fmt.date(ms: d.createdAt) ?? "")", value: d.state + (d.lastStatus.map { " · HTTP \($0)" } ?? "") + (d.lastError.map { " · \($0)" } ?? ""), tone: d.state == "failed" ? .danger : nil)115 }116 }.font(.spCallout.weight(.semibold)).padding(.top, 6)117 }118 HStack(spacing: 8) {119 Button(w.enabled ? String(localized: "Désactiver") : String(localized: "Activer")) { Task { await hooks.setEnabled(w, !w.enabled, app: model) } }.buttonStyle(.bordered).accessibilityIdentifier("webhook.toggle")120 Button(String(localized: "Nouveau secret")) { rotating = w }.buttonStyle(.bordered).accessibilityIdentifier("webhook.rotate")121 Button(String(localized: "Supprimer"), role: .destructive) { deleting = w }.buttonStyle(.bordered).accessibilityIdentifier("webhook.delete")122 }123 .font(.spCallout.weight(.semibold)).padding(.top, 10).disabled(!model.canOperate || !hooks.list.live || hooks.busy)124 }125 .spCard()126 }127128 private func createCard(_ l: WebhookList) -> some View {129 @Bindable var hooks = hooks130 return VStack(alignment: .leading, spacing: 10) {131 Text(String(localized: "Nouveau webhook")).font(.spHeadline)132 TextField(String(localized: "https://…"), text: $hooks.url).keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled().font(.spMono)133 .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("webhook.new.url")134 if let p = hooks.urlProblem { Label(p, systemImage: "xmark.octagon.fill").font(.spFootnote).foregroundStyle(Theme.danger) }135 TextField(String(localized: "Nom"), text: $hooks.label).padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("webhook.new.label")136 Text(String(localized: "Événements à livrer")).font(.spCallout.weight(.semibold))137 ForEach(l.events, id: \.event) { e in138 Button { if hooks.events.contains(e.event) { hooks.events.remove(e.event) } else { hooks.events.insert(e.event) } } label: {139 HStack(alignment: .top, spacing: 10) {140 Image(systemName: hooks.events.contains(e.event) ? "checkmark.square.fill" : "square").font(.system(size: 20)).foregroundStyle(hooks.events.contains(e.event) ? Theme.blue : Theme.mute)141 VStack(alignment: .leading, spacing: 2) {142 Text(e.event).font(.spMono).foregroundStyle(Theme.ink)143 Text(e.description + (e.emitted ? "" : " — " + String(localized: "pas encore émis par ce serveur"))).font(.system(size: 12)).foregroundStyle(Theme.mute).multilineTextAlignment(.leading)144 }145 Spacer()146 }.frame(minHeight: 44).contentShape(Rectangle())147 }.buttonStyle(.plain).accessibilityIdentifier("webhook.new.event.\(e.event)")148 }149 Button { Task { await hooks.create(model) } } label: { HStack { if hooks.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Créer le webhook")) } }150 .buttonStyle(.spPrimary).disabled(!hooks.canCreate || !model.canOperate || !hooks.list.live).accessibilityIdentifier("webhook.new.create")151 }.spCard()152 }153}154