SPB Git

Repository Public

SecurityView.swift 14.4 KB 204 lines swift

1// SP Wallet iOS2// File: Features/Security/SecurityView.swift3// Description: Security centre: state of the isolated signer and its limits as it reports them, the passkeys that can approve,4//              enrolment of this device's passkey (approved by an existing one, verified by the signer), sessions, the hash-chained5//              audit journal, and the emergency halt — one-way from the app.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112struct SecurityView: View {13    @Environment(AppModel.self) private var model14    @State private var overview: SecurityOverview?15    @State private var error: Error?16    @State private var actionError: Error?17    @State private var confirmHalt = false18    @State private var haltText = ""19    @State private var addingPasskey = false20    @State private var passkeyLabel = UIDevice.current.name21    @State private var busy = false22    @State private var done: String?2324    var body: some View {25        ScrollView {26            VStack(alignment: .leading, spacing: Theme.Space.section) {27                FreshnessBanner()28                if let o = overview {29                    signerCard(o)30                    if let policy = o.signer.policy, !policy.isNull { limitsCard(policy, spent: o.signer.spentToday ?? [:]) }31                    devicesCard(o)32                    sessionsCard(o)33                    NavigationLink { AuditJournalView().wallet(model) } label: {34                        HStack { Label(String(localized: "Journal d’audit"), systemImage: "list.bullet.clipboard").font(.spHeadline).foregroundStyle(Theme.ink); Spacer(); Image(systemName: "chevron.right").foregroundStyle(Theme.mute) }35                    }.spCard()36                    haltCard(o)37                } else if let error { ErrorNotice(error: error) { Task { await load() } } }38                else if model.offlineBrowsing { EmptyState(icon: "lock.shield", title: String(localized: "État de sécurité indisponible hors ligne")) }39                else { ProgressView().frame(maxWidth: .infinity).padding(.top, 60) }40            }41            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)42            .frame(maxWidth: 820).frame(maxWidth: .infinity)43        }44        .spPage()45        .navigationTitle(AppSection.security.title)46        .refreshable { await load() }47        .task { await load() }48        .alert(String(localized: "Arrêt d’urgence"), isPresented: $confirmHalt) {49            TextField(String(localized: "Tape ARRET pour confirmer"), text: $haltText).textInputAutocapitalization(.characters).autocorrectionDisabled()50            Button(String(localized: "Arrêter le signataire"), role: .destructive) { if ["ARRET", "ARRÊT", "HALT"].contains(haltText.trimmingCharacters(in: .whitespaces).uppercased()) { Task { await halt() } }; haltText = "" }51            Button(String(localized: "Annuler"), role: .cancel) { haltText = "" }52        } message: {53            Text(String(localized: "Le signataire refusera toute opération qui sort des fonds ou ajoute de l’exposition. Depuis l’app, c’est IRRÉVERSIBLE : seul l’opérateur peut lever l’arrêt, sur la machine du signataire."))54        }55        .sheet(isPresented: $addingPasskey) { addPasskeySheet.wallet(model) }56    }5758    private func load() async {59        guard !model.offlineBrowsing else { return }60        do { overview = try await model.env.wallet.securityOverview(); error = nil } catch let e { if overview == nil { error = e } }61    }6263    private func signerCard(_ o: SecurityOverview) -> some View {64        VStack(alignment: .leading, spacing: 0) {65            HStack { SectionHeader(title: String(localized: "Signataire isolé")); SecurityIndicator(reachable: o.signer.reachable, halted: o.signer.halted, compact: true) }.padding(.bottom, 6)66            Text(String(localized: "Les clés du portefeuille vivent uniquement dans ce processus, sur une machine MacLustr dédiée. Cet appareil n’en détient aucune.")).font(.spFootnote).foregroundStyle(Theme.mute).padding(.bottom, 6)67            if let k = o.signer.keyId { FieldRow(label: String(localized: "Identifiant de la clé"), value: k, mono: true, copyable: true); Divider() }68            if let n = o.signer.journalLength { FieldRow(label: String(localized: "Journal du signataire"), value: String(localized: "\(n) décisions enregistrées")); Divider() }69            if let h = o.signer.journalHead { FieldRow(label: String(localized: "Tête du journal"), value: h, mono: true); Divider() }70            FieldRow(label: String(localized: "Diffusion des transactions"), value: o.broadcast == false ? String(localized: "désactivée sur ce serveur (pile de test)") : String(localized: "active"), tone: o.broadcast == false ? .warn : nil)71            if let origin = o.origin { Divider(); FieldRow(label: String(localized: "Origine vérifiée par le signataire"), value: origin, mono: true) }72        }.spCard()73    }7475    private func limitsCard(_ policy: JSONValue, spent: [String: String]) -> some View {76        VStack(alignment: .leading, spacing: 6) {77            SectionHeader(title: String(localized: "Limites appliquées par le signataire"))78            Text(String(localized: "Valeurs en vigueur sur la machine du signataire, appliquées indépendamment de cette app. Elles ne se modifient pas depuis l’app."))79                .font(.spFootnote).foregroundStyle(Theme.mute)80            if let v = policy["version"]?.intValue { FieldRow(label: String(localized: "Version de la politique"), value: "v\(v)") }81            if let w = policy["maxApprovalWindowSec"]?.intValue ?? policy["maxTtlSec"]?.intValue { FieldRow(label: String(localized: "Fenêtre d’approbation maximale"), value: "\(w) s") }82            if !spent.isEmpty {83                DisclosureGroup(String(localized: "Dépensé aujourd’hui (UTC)")) {84                    ForEach(spent.keys.sorted(), id: \.self) { k in FieldRow(label: k, value: spent[k] ?? "", mono: true) }85                }.font(.spCallout.weight(.semibold))86            }87            DisclosureGroup(String(localized: "Politique complète, telle que rapportée")) { JSONFields(value: policy) }.font(.spCallout.weight(.semibold))88        }.spCard()89    }9091    private func devicesCard(_ o: SecurityOverview) -> some View {92        VStack(alignment: .leading, spacing: 8) {93            SectionHeader(title: String(localized: "Clés d’accès"))94            ForEach(o.devices) { d in95                HStack(alignment: .top, spacing: 10) {96                    Image(systemName: "person.badge.key.fill").foregroundStyle(Theme.blue).frame(width: 28)97                    VStack(alignment: .leading, spacing: 2) {98                        Text(d.label).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)99                        Text([d.deviceType == "multiDevice" ? String(localized: "synchronisée") : d.deviceType == "singleDevice" ? String(localized: "liée à un appareil") : d.deviceType,100                              d.lastUsedAt.map { String(localized: "utilisée \(Money.age($0))") }].compactMap { $0 }.joined(separator: " · ")).font(.spFootnote).foregroundStyle(Theme.mute)101                        if d.enrolledOnSigner == true { Pill(text: String(localized: "Épinglée par le signataire"), tone: .ok, icon: "checkmark.seal.fill") }102                        else if d.enrolledOnSigner == false { Pill(text: String(localized: "Non reconnue par le signataire : ne peut rien approuver"), tone: .warn, icon: "exclamationmark.triangle.fill") }103                    }104                }.padding(.vertical, 4)105            }106            if let done { Notice(tone: .ok, title: done) }107            if let e = actionError { ErrorNotice(error: e) }108            Button { addingPasskey = true } label: { Label(String(localized: "Ajouter une clé d’accès pour cet appareil"), systemImage: "plus") }109                .buttonStyle(.spSecondary).disabled(!model.canOperate).accessibilityIdentifier("security.addPasskey")110        }.spCard()111    }112113    private var addPasskeySheet: some View {114        NavigationStack {115            VStack(alignment: .leading, spacing: 16) {116                Text(String(localized: "Deux étapes, deux demandes du système :")).font(.spHeadline)117                Label(String(localized: "1. Création d’une nouvelle clé d’accès sur cet appareil."), systemImage: "1.circle.fill").font(.spCallout)118                Label(String(localized: "2. Approbation par une clé d’accès DÉJÀ enrôlée : c’est cette signature que le signataire isolé vérifie avant d’épingler la nouvelle clé."), systemImage: "2.circle.fill").font(.spCallout)119                TextField(String(localized: "Nom de la clé"), text: $passkeyLabel).padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))120                if let e = actionError { ErrorNotice(error: e) }121                Spacer()122                Button { Task { await addPasskey() } } label: { HStack { if busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Continuer")) } }123                    .buttonStyle(.spPrimary).disabled(busy || passkeyLabel.trimmingCharacters(in: .whitespaces).isEmpty)124            }125            .padding(Theme.Space.gutter)126            .navigationTitle(String(localized: "Nouvelle clé d’accès")).navigationBarTitleDisplayMode(.inline)127            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { addingPasskey = false } } }128        }.presentationDetents([.medium, .large])129    }130131    private func addPasskey() async {132        busy = true; actionError = nil; defer { busy = false }133        do {134            try await model.env.auth.addPasskey(label: passkeyLabel, authenticator: model.env.passkeys)135            addingPasskey = false; done = String(localized: "Clé d’accès ajoutée et épinglée par le signataire.")136            await load()137        } catch PasskeyError.cancelled {} catch { actionError = error }138    }139140    private func sessionsCard(_ o: SecurityOverview) -> some View {141        VStack(alignment: .leading, spacing: 8) {142            SectionHeader(title: String(localized: "Sessions ouvertes"))143            Text(String(localized: "Une session expire après 30 minutes d’inactivité et au plus tard après 12 heures.")).font(.spFootnote).foregroundStyle(Theme.mute)144            ForEach(Array(o.sessions.enumerated()), id: \.offset) { _, s in145                VStack(alignment: .leading, spacing: 2) {146                    Text(s.ua ?? String(localized: "Client inconnu")).font(.spCallout.weight(.medium)).foregroundStyle(Theme.ink).lineLimit(2)147                    Text([s.ip, s.lastSeen.map { String(localized: "vue \(Money.age($0))") }].compactMap { $0 }.joined(separator: " · ")).font(.spFootnote).foregroundStyle(Theme.mute)148                }.padding(.vertical, 3)149            }150            Button(role: .destructive) { Task { do { try await model.env.auth.revokeAllSessions(); await model.wipeLocalData(); model.phase = .signedOut } catch { actionError = error } } } label: {151                Label(String(localized: "Révoquer toutes les sessions"), systemImage: "rectangle.portrait.and.arrow.right")152            }.buttonStyle(.spSecondary).disabled(!model.canOperate)153        }.spCard()154    }155156    private func haltCard(_ o: SecurityOverview) -> some View {157        VStack(alignment: .leading, spacing: 10) {158            SectionHeader(title: String(localized: "Arrêt d’urgence"))159            if o.signer.halted == true {160                Notice(tone: .danger, title: String(localized: "L’arrêt d’urgence est actif"), message: String(localized: "Pour le lever : commande de l’opérateur sur la machine du signataire. Aucune app ne peut le faire."), icon: "hand.raised.fill")161            } else {162                Text(String(localized: "En cas de doute (appareil perdu, activité inconnue), arrête immédiatement le signataire. Aucune clé d’accès n’est demandée : s’arrêter doit toujours être possible."))163                    .font(.spFootnote).foregroundStyle(Theme.mute)164                Button { confirmHalt = true } label: { Label(String(localized: "Arrêt d’urgence"), systemImage: "hand.raised.fill") }165                    .buttonStyle(.spDestructive).disabled(model.offlineBrowsing || model.offline || busy).accessibilityIdentifier("security.halt")166            }167        }.spCard()168    }169170    private func halt() async {171        busy = true; actionError = nil; defer { busy = false }172        do { try await model.env.wallet.emergencyHalt(); await load(); await model.refreshPortfolio() } catch { actionError = error }173    }174}175176struct AuditJournalView: View {177    @Environment(AppModel.self) private var model178    @State private var journal: AuditJournal?179    @State private var error: Error?180    var body: some View {181        List {182            if let j = journal {183                Section {184                    if j.intact { Label(String(localized: "Chaîne de hachage intacte (\(j.total) événements, vérifiée par le serveur)"), systemImage: "checkmark.seal.fill").foregroundStyle(Theme.emerald).font(.spCallout.weight(.semibold)) }185                    else { Notice(tone: .danger, title: String(localized: "Chaîne d’audit rompue"), message: j.brokenAt.map { String(localized: "Première rupture à l’événement \($0). Le journal a pu être altéré.") }) }186                }187                ForEach(j.events) { e in188                    VStack(alignment: .leading, spacing: 3) {189                        HStack { Text(e.type).font(.system(size: 14.5, weight: .semibold, design: .monospaced)).foregroundStyle(Theme.ink); Spacer(); Text("#\(e.seq)").font(.spFootnote).foregroundStyle(Theme.mute) }190                        Text(e.ts.formatted(date: .abbreviated, time: .standard) + " · " + e.actor).font(.spFootnote).foregroundStyle(Theme.mute)191                        if let d = e.data, let o = d.objectValue, !o.isEmpty {192                            Text(o.keys.sorted().compactMap { k in o[k].map { "\(k): \(JSONFields.text($0))" } }.filter { !$0.hasSuffix(": ") }.joined(separator: " · "))193                                .font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).lineLimit(4)194                        }195                    }196                }197            } else if let error { ErrorNotice(error: error) } else { ProgressView() }198        }199        .navigationTitle(String(localized: "Journal d’audit")).navigationBarTitleDisplayMode(.inline)200        .task { do { journal = try await model.env.wallet.audit(limit: 300) } catch let e { error = e } }201        .refreshable { do { journal = try await model.env.wallet.audit(limit: 300) } catch let e { error = e } }202    }203}204
Files main
Menu

Theme