SPB Git

Repository Public

SecurityView.swift 8.4 KB 132 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Account/SecurityView.swift4//  Description: Account security: passkeys (add this device, rename, revoke), open sessions, recovery codes.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import SwiftUI11import UIKit1213struct SecurityView: View {14    @Environment(AppEnvironment.self) private var env15    @State private var passkeys: [Passkey] = []16    @State private var sessions: [DeviceSession] = []17    @State private var recoveryRemaining: Int?18    @State private var isLoading = true19    @State private var message: String?20    @State private var isError = false21    @State private var renaming: Passkey?22    @State private var renameText = ""23    @State private var codes: [String]?24    @State private var busy = false2526    var body: some View {27        List {28            if let message { Section { Text(message).font(.footnote).foregroundStyle(isError ? Color.danger : Color.success) } }29            Section {30                ForEach(passkeys) { p in31                    VStack(alignment: .leading, spacing: 3) {32                        HStack { Text(p.label ?? String(localized: "Clé d’accès")).font(.body); if p.current { Text("cette session").font(.caption2.weight(.medium)).foregroundStyle(Color.accentColor).padding(.horizontal, 6).padding(.vertical, 2).background(Color.accentColor.opacity(0.14), in: .capsule) } }33                        Text([p.synced ? String(localized: "synchronisée") : String(localized: "liée à l’appareil"), p.lastUsedAt.map { String(localized: "utilisée \(Format.relative($0))") }].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Color.muted)34                    }35                    .swipeActions {36                        Button(role: .destructive) { Task { await revoke(p) } } label: { Label("Révoquer", systemImage: "trash") }37                        Button { renameText = p.label ?? ""; renaming = p } label: { Label("Renommer", systemImage: "pencil") }.tint(.accentColor)38                    }39                }40                Button { Task { await addThisDevice() } } label: { Label("Ajouter une clé d’accès sur cet appareil", systemImage: "plus.circle") }.disabled(busy)41            } header: { Text("Clés d’accès") } footer: {42                Text("Ajouter, renommer ou révoquer une clé demande une vérification récente : iOS te la demandera. La dernière clé ne peut pas être révoquée.")43            }4445            Section {46                ForEach(sessions) { s in47                    VStack(alignment: .leading, spacing: 3) {48                        HStack { Text(s.label ?? String(localized: "Appareil")); if s.current { Text("ici").font(.caption2.weight(.medium)).foregroundStyle(Color.accentColor).padding(.horizontal, 6).padding(.vertical, 2).background(Color.accentColor.opacity(0.14), in: .capsule) } }49                        Text([s.lastSeen.map { String(localized: "vue \(Format.relative($0))") }, s.ip].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Color.muted)50                    }51                    .swipeActions { if !s.current { Button(role: .destructive) { Task { await revoke(s) } } label: { Label("Fermer", systemImage: "xmark.circle") } } }52                }53                if sessions.count > 1 { Button("Fermer toutes les autres sessions", role: .destructive) { Task { await act { let n = try await env.api.revokeOtherSessions(); return String(localized: "\(n) session(s) fermée(s).") } } }.disabled(busy) }54            } header: { Text("Sessions ouvertes") }5556            Section {57                if let n = recoveryRemaining { LabeledContent("Codes restants", value: "\(n)") }58                Button("Générer 8 nouveaux codes") { Task { await rotateCodes() } }.disabled(busy)59            } header: { Text("Codes de récupération") } footer: {60                Text("Chaque code sert une seule fois à enrôler un nouvel appareil si toutes tes clés d’accès sont perdues. En générer de nouveaux invalide les anciens.")61            }62        }63        .overlay { if isLoading && passkeys.isEmpty { ProgressView() } }64        .navigationTitle("Sécurité").navigationBarTitleDisplayMode(.inline)65        .task { await load() }66        .refreshable { await load() }67        .alert("Renommer la clé d’accès", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {68            TextField("Nom", text: $renameText)69            Button("Annuler", role: .cancel) { renaming = nil }70            Button("Renommer") { if let p = renaming { let t = renameText.trimmingCharacters(in: .whitespacesAndNewlines); if !t.isEmpty { Task { await act { try await env.api.renamePasskey(p.id, label: String(t.prefix(60))); return nil } } } }; renaming = nil }71        }72        .sheet(item: Binding(get: { codes.map { IdentifiedString(value: $0.joined(separator: "\n")) } }, set: { if $0 == nil { codes = nil } })) { c in73            NavigationStack {74                VStack(alignment: .leading, spacing: 16) {75                    Text("Note ces codes maintenant : ils ne seront plus jamais affichés.").font(.subheadline).foregroundStyle(Color.textSecondary)76                    Text(c.value).font(.system(.body, design: .monospaced)).textSelection(.enabled).padding(16).frame(maxWidth: .infinity, alignment: .leading).background(Color.surface2, in: .rect(cornerRadius: 12, style: .continuous))77                    Button { UIPasteboard.general.setItems([[UIPasteboard.typeAutomatic: c.value]], options: [.expirationDate: Date().addingTimeInterval(120), .localOnly: true]) } label: { Label("Copier (effacé du presse-papiers après 2 min)", systemImage: "square.on.square") }.buttonStyle(.bordered)78                    Spacer()79                }80                .padding(20).navigationTitle("Codes de récupération").navigationBarTitleDisplayMode(.inline)81                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("J’ai noté") { codes = nil } } }82            }83        }84    }8586    private func load() async {87        isLoading = true; defer { isLoading = false }88        do {89            async let p = env.api.passkeys(); async let s = env.api.sessions()90            let (pk, ss) = try await (p, s)91            // this device first in both lists92            passkeys = pk.passkeys.sorted { $0.current && !$1.current }; recoveryRemaining = pk.recoveryRemaining; sessions = ss.sorted { $0.current && !$1.current }93        } catch { show((error as? APIError)?.message ?? String(localized: "Chargement impossible."), error: true) }94    }9596    private func show(_ text: String, error: Bool) { message = text; isError = error }9798    /// Runs a sensitive operation (the HTTP client prompts for the passkey when the server asks), then reloads.99    private func act(_ op: @escaping () async throws -> String?) async {100        busy = true; defer { busy = false }101        do { let m = try await op(); if let m { show(m, error: false) } else { message = nil }; await load() }102        catch let e as PasskeyError { if e.kind != .cancelled { show(e.message, error: true) } }103        catch { show((error as? APIError)?.message ?? error.localizedDescription, error: true) }104    }105106    private func addThisDevice() async {107        await act {108            let label = UIDevice.current.userInterfaceIdiom == .pad ? "iPad · SP Chat" : "iPhone · SP Chat"109            do { try await env.auth.passkeys.register(label: label) }110            catch let e as PasskeyError where e.kind == .refused {111                // the server wants a verification younger than 10 minutes: verify, then try once more112                try await env.auth.passkeys.reauthenticate()113                try await env.auth.passkeys.register(label: label)114            }115            return String(localized: "Clé d’accès ajoutée.")116        }117    }118119    private func revoke(_ p: Passkey) async {120        await act { _ = try await env.api.revokePasskey(p.id); return String(localized: "Clé d’accès révoquée.") }121    }122    private func revoke(_ s: DeviceSession) async {123        await act { _ = try await env.api.revokeSession(s.id); return String(localized: "Session fermée.") }124    }125    private func rotateCodes() async {126        busy = true; defer { busy = false }127        do { codes = try await env.api.rotateRecoveryCodes(); await load() }128        catch let e as PasskeyError { if e.kind != .cancelled { show(e.message, error: true) } }129        catch { show((error as? APIError)?.message ?? error.localizedDescription, error: true) }130    }131}132
Files main
Menu

Theme