SPB Git

Repository Public

DevicesPage.swift 13.3 KB 223 lines swift

1// Devices: every device holds its own key pair and a certificate signed by the account key. List, revoke, approve a2// new device (code + 6-digit fingerprint), account rekey after a compromise.3import SharedVaultKit4import SwiftUI56struct DevicesPage: View {7    @Environment(AppModel.self) private var model8    @State private var devices: [DeviceView]?9    @State private var error: String?10    @State private var adding = false11    @State private var confirm: ConfirmRequest?12    @State private var rekeying = false1314    var body: some View {15        ToolPage("Devices", subtitle: "Every device holds its own key pair and a certificate signed by your account key. The server cannot add a device on its own.") {16            Button { adding = true } label: { Label("Add a device", systemImage: "plus") }.buttonStyle(.vaultPrimary).accessibilityIdentifier("devices-add")17        } content: {18            ErrorText(text: error)19            if let devices, devices.contains(where: { !$0.verified }) {20                Callout(kind: .danger, title: "A device is not certified by your account key",21                        text: "The server lists a device this account never certified. It may have been inserted by the server. Revoke it now and do not approve anything from it.")22                    .accessibilityIdentifier("devices-unverified")23            }24            SectionCard("Devices of this account", footer: "The fingerprint is a short digest of the device's public keys. Native apps keep their keys in hardware (Secure Enclave); web browsers use software keys kept non-extractable in the browser's storage.") {25                if let devices {26                    ForEach(Array(devices.enumerated()), id: \.element.id) { i, d in27                        CardRow(last: i == devices.count - 1) { row(d) }.accessibilityIdentifier("device-row-\(i)")28                    }29                } else {30                    CardRow(last: true) { HStack(spacing: 10) { if error == nil { ProgressView().controlSize(.small) }; Text(error == nil ? "Loading…" : "The device list could not be loaded.").foregroundStyle(Palette.muted) } }31                }32            }33            SectionCard("Danger zone") {34                CardRow(last: true) {35                    VStack(alignment: .leading, spacing: 10) {36                        Text("Account rekey").font(.vaultHeadline).foregroundStyle(Palette.text)37                        Text("For when a device was lost or compromised while it was unlocked. Revoke that device first. A new account root key is created and wrapped for each remaining certified device; every vault you own gets a new key epoch and is re-encrypted; a new recovery key is issued and the old one stops working.")38                            .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)39                        if rekeying {40                            HStack(spacing: 10) { ProgressView().controlSize(.small); Text("Working — keep the app open…").foregroundStyle(Palette.muted) }.frame(height: 30)41                        } else {42                            Button { askRekey() } label: { Label("Rekey account…", systemImage: "key.viewfinder") }.buttonStyle(.vaultDanger)43                                .disabled(devices == nil).accessibilityIdentifier("devices-rekey")44                        }45                    }46                }47            }48        }49        .task(id: model.devicesTick) { await load() }50        .onAppear { model.pairingHint = false }51        .sheet(isPresented: $adding, onDismiss: { Task { await load() } }) { AddDeviceSheet() }52        .confirmSheet($confirm)53    }5455    @ViewBuilder private func row(_ d: DeviceView) -> some View {56        HStack(alignment: .center, spacing: 12) {57            Image(systemName: Self.symbol(d.platform)).font(.system(size: 20)).foregroundStyle(d.verified ? Palette.muted : Palette.danger).frame(width: 30).accessibilityHidden(true)58            VStack(alignment: .leading, spacing: 5) {59                HStack(spacing: 6) {60                    Text(d.platform.isEmpty ? "Unnamed device" : d.platform).font(.body.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)61                    if d.current { Pill(text: "This device", tint: Palette.accent) }62                }63                HStack(spacing: 6) {64                    if d.verified { Pill(text: "Verified", tint: Palette.accent) } else { Pill(text: "NOT certified", tint: Palette.danger) }65                    Pill(text: d.hardware ? "Secure Enclave" : "Software keys", tint: d.hardware ? Palette.accent : Palette.brass)66                    Text(d.fingerprint).font(.system(.caption, design: .monospaced)).foregroundStyle(Palette.muted)67                        .accessibilityLabel("Fingerprint").accessibilityValue(d.fingerprint)68                }69                Text("Added \(ItemMeta.date(d.addedAt)) · last seen \(ItemMeta.relative(d.lastSeenAt))").font(.caption).foregroundStyle(Palette.muted)70            }71            Spacer(minLength: 8)72            if d.current {73                Text("Remove it from Settings").font(.caption).foregroundStyle(Palette.muted).multilineTextAlignment(.trailing)74            } else {75                Button("Revoke") { askRevoke(d) }.buttonStyle(.vaultDangerGhost).accessibilityLabel("Revoke \(d.platform)")76            }77        }78    }7980    static func symbol(_ platform: String) -> String {81        let p = platform.lowercased()82        if p.contains("ios") || p.contains("iphone") { return p.contains("ipad") ? "ipad" : "iphone" }83        if p.contains("ipad") { return "ipad" }84        if p.contains("web") { return "globe" }85        if p.contains("mac") { return "laptopcomputer" }86        return "desktopcomputer"87    }8889    private func load() async {90        do { devices = try await model.engine.devices(); error = nil }91        catch { if let t = model.errorText(error) { self.error = t } }92    }9394    private func askRevoke(_ d: DeviceView) {95        confirm = ConfirmRequest(title: "Revoke “\(d.platform)”?",96            message: "The server deletes this device's key envelope, certificate and sessions. It can no longer sign in or sync. Revocation cannot erase what the device already holds: if it was compromised while unlocked, run an account rekey afterwards and change the passwords it could read. This device may ask to confirm your presence.",97            confirmLabel: "Revoke device") {98            error = await model.perform("Device revoked") { try await model.engine.revokeDevice(deviceId: d.deviceId) }99            await load()100        }101    }102103    private func askRekey() {104        if let devices, devices.contains(where: { !$0.verified }) {105            error = "A listed device is not certified by your account key. Revoke it before rekeying."106            return107        }108        confirm = ConfirmRequest(title: "Rekey this account?",109            message: "A new account root key replaces the current one and is wrapped for each remaining certified device. Every vault you own gets a new key and is re-encrypted on this device. A NEW recovery key is shown once at the end; the old one stops working. It does not change the passwords stored in the vault: rotate those on their websites as well. Keep the app open until it finishes.",110            confirmLabel: "Rekey account", typed: "REKEY") {111            rekeying = true112            defer { rekeying = false }113            error = await model.perform {114                let key = try await model.engine.rekeyAccount()115                model.setPhase(.recoveryKit(key: key, reason: .rekeyed))116            }117        }118    }119}120121// ── approve a new device ──122123private struct AddDeviceSheet: View {124    @Environment(AppModel.self) private var model125    @Environment(\.dismiss) private var dismiss126    @State private var code = ""127    @State private var request: PairingRequest?128    @State private var error: String?129    @State private var approved = false130    #if os(iOS)131    @State private var scanning = false132    #endif133134    private var codeLooksValid: Bool { (try? SPV1.decodePairingCode(code.trimmingCharacters(in: .whitespacesAndNewlines))) != nil }135136    var body: some View {137        ToolSheet(title: approved ? "Device approved" : "Add a device") {138            if approved {139                Callout(kind: .ok, text: "Device approved. It can now decrypt the vault and will finish by itself in a few seconds.").accessibilityIdentifier("devices-approved")140                HStack { Spacer(); Button("Done") { dismiss() }.buttonStyle(.vaultPrimary).accessibilityIdentifier("devices-done") }141            } else if let request { compare(request) } else { enter }142        }143        #if os(iOS)144        .sheet(isPresented: $scanning) {145            CodeScannerView(prompt: "Point the camera at the QR code shown by the new device") { scanned in146                code = scanned147                inspect()148            }149        }150        #endif151    }152153    @ViewBuilder private var enter: some View {154        Text("On the new device, sign in with your passkey. It shows a QR code and a text code. Enter that code here.")155            .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)156        #if os(iOS)157        Button { scanning = true } label: { Label("Scan QR code with the camera", systemImage: "qrcode.viewfinder") }.buttonStyle(.vaultSecondaryBlock)158            .accessibilityIdentifier("devices-scan")159        #endif160        LabeledField(label: "Pairing code", hint: "Starts with spvault-pair: — valid for five minutes, usable once.",161                     error: !code.isEmpty && !codeLooksValid ? "This is not an SP Vault pairing code." : nil) {162            TextField("spvault-pair:…", text: $code, axis: .vertical).lineLimit(2...4).textFieldStyle(.vaultMono).rawTextInput()163                .accessibilityLabel("Pairing code").accessibilityIdentifier("devices-code")164        }165        ErrorText(text: error)166        Text("The code never passes through the server in a usable form: it proves to this device that the keys really come from the device that displays it.")167            .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)168        HStack {169            Spacer()170            Button("Cancel") { dismiss() }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction)171            Button(model.busy ? "Checking…" : "Check code", action: inspect).buttonStyle(.vaultPrimary).disabled(!codeLooksValid || model.busy)172                .accessibilityIdentifier("devices-inspect")173        }174    }175176    @ViewBuilder private func compare(_ r: PairingRequest) -> some View {177        Callout(kind: .ok, title: "The code matches the keys relayed by the server", text: "The request really comes from the device that displayed this code.")178        HStack(spacing: 12) {179            Image(systemName: DevicesPage.symbol(r.platform)).font(.system(size: 22)).foregroundStyle(Palette.muted).accessibilityHidden(true)180            VStack(alignment: .leading, spacing: 4) {181                Text(r.platform.isEmpty ? "Unnamed device" : r.platform).font(.body.weight(.semibold)).foregroundStyle(Palette.text)182                Pill(text: r.hardware ? "Secure Enclave" : "Software keys", tint: r.hardware ? Palette.accent : Palette.brass)183            }184        }185        VStack(spacing: 6) {186            Eyebrow("Fingerprint — compare on both screens")187            Text(TotpRow.spaced(r.sas)).font(.system(size: 44, weight: .bold, design: .monospaced)).foregroundStyle(Palette.brass).minimumScaleFactor(0.6).lineLimit(1)188                .accessibilityLabel("Fingerprint").accessibilityValue(r.sas).accessibilityIdentifier("devices-sas")189        }190        .frame(maxWidth: .infinity).padding(.vertical, 14)191        .background(Palette.brassSoft, in: RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous))192        .overlay(RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous).strokeBorder(Palette.brassLine, lineWidth: 1))193        Text("Compare these six digits with the other screen. Approve only if they are identical and you started this yourself: the new device will be able to decrypt everything in your vault. Approving may ask to confirm your presence on this device.")194            .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)195        ErrorText(text: error)196        HStack {197            Button("They differ — reject") { decide(r, approve: false) }.buttonStyle(.vaultDangerGhost).disabled(model.busy).accessibilityIdentifier("devices-reject")198            Spacer()199            Button("The digits match — approve") { decide(r, approve: true) }.buttonStyle(.vaultPrimary).disabled(model.busy).accessibilityIdentifier("devices-approve")200        }201    }202203    private func inspect() {204        let c = code.trimmingCharacters(in: .whitespacesAndNewlines)205        guard (try? SPV1.decodePairingCode(c)) != nil else { error = "This is not an SP Vault pairing code."; return }206        Task {207            error = await model.perform { request = try await model.engine.inspectPairing(code: c) }208        }209    }210211    private func decide(_ r: PairingRequest, approve: Bool) {212        Task {213            if approve {214                error = await model.perform("Device approved") { try await model.engine.approvePairing(r) }215                if error == nil { approved = true }216            } else {217                error = await model.perform("Pairing refused") { try await model.engine.rejectPairing(r) }218                if error == nil { dismiss() }219            }220        }221    }222}223
Files main
Menu

Theme