Repository Public
1// Security Center: analysis computed on this device from the decrypted items, an opt-in breach check (k-anonymity)2// and the health of the sync (rollback warnings are security warnings).3import SharedVaultKit4import SwiftUI56struct SecurityCenterPage: View {7 @Environment(AppModel.self) private var model8 @State private var breached: [Finding] = []9 @State private var breachDone = false10 @State private var breachProgress: (done: Int, total: Int)?11 @State private var breachError: String?12 @State private var digest = ""1314 private struct Group: Identifiable {15 let kind: String, title: String, text: String, symbol: String, danger: Bool16 var rows: [(id: String, detail: String)]17 var id: String { kind }18 }1920 private var live: [ItemView] { model.items.filter { ($0.item.trashedAt ?? "").isEmpty } }2122 private var groups: [Group] {23 let findings = SPV1.analyze(live.map { (id: $0.id, item: $0.item) }) + breached24 var g: [String: Group] = [25 "breached": Group(kind: "breached", title: "Found in breaches", text: "These passwords appear in public breach corpora. Change them.", symbol: "exclamationmark.octagon", danger: true, rows: []),26 "weak": Group(kind: "weak", title: "Weak passwords", text: "Estimated below 50 bits: guessable offline if a site leaks its hashes.", symbol: "gauge.with.dots.needle.33percent", danger: true, rows: []),27 "reused": Group(kind: "reused", title: "Reused passwords", text: "One leak exposes every account sharing the password.", symbol: "square.on.square", danger: true, rows: []),28 "duplicate": Group(kind: "duplicate", title: "Duplicates", text: "Several items for the same site and username.", symbol: "doc.on.doc", danger: false, rows: []),29 "insecure-url": Group(kind: "insecure-url", title: "Insecure addresses", text: "Saved with http:// — credentials would travel unencrypted.", symbol: "lock.open", danger: false, rows: []),30 "expiring": Group(kind: "expiring", title: "Expiring", text: "Expired, or expiring within 30 days.", symbol: "calendar.badge.exclamationmark", danger: false, rows: []),31 "rotation-due": Group(kind: "rotation-due", title: "Rotation due", text: "Secrets past their rotation schedule.", symbol: "arrow.triangle.2.circlepath", danger: false, rows: []),32 ]33 for f in findings {34 switch f {35 case .weak(let id, let bits): g["weak"]?.rows.append((id, "about \(bits) bits"))36 case .reused(let ids): for id in ids { g["reused"]?.rows.append((id, "shared by \(ids.count) items")) }37 case .duplicate(let ids): for id in ids { g["duplicate"]?.rows.append((id, "\(ids.count) copies")) }38 case .insecureUrl(let id): g["insecure-url"]?.rows.append((id, "http://"))39 case .expiring(let id, let at, let expired): g["expiring"]?.rows.append((id, expired ? "expired \(String(at.prefix(10)))" : "expires \(String(at.prefix(10)))"))40 case .rotationDue(let id, let due): g["rotation-due"]?.rows.append((id, "due \(String(due.prefix(10)))"))41 case .breached(let id, let count): g["breached"]?.rows.append((id, "seen \(count.formatted()) time\(count == 1 ? "" : "s")"))42 }43 }44 return ["breached", "weak", "reused", "duplicate", "insecure-url", "expiring", "rotation-due"].compactMap { g[$0] }.filter { !$0.rows.isEmpty }45 }4647 private func score(_ groups: [Group]) -> Int {48 guard !live.isEmpty else { return 100 }49 var penalty = 0.050 for g in groups {51 let weight: Double = switch g.kind { case "breached": 12; case "weak": 8; case "reused": 6; case "insecure-url": 4; case "expiring", "rotation-due": 3; default: 1 }52 penalty += weight * Double(g.rows.count)53 }54 return max(0, 100 - Int((penalty * 10 / Double(max(live.count, 5))).rounded()))55 }5657 var body: some View {58 let groups = groups59 ToolPage("Security Center", subtitle: "Computed on this device from your decrypted items. Nothing about your passwords is sent anywhere unless you start the breach check below.") {60 if live.isEmpty {61 EmptyState(symbol: "checkmark.shield", title: "Nothing to analyse yet", text: "Add a few items and their health will be summarised here.").frame(height: 220)62 } else {63 scoreCard(groups)64 if groups.isEmpty { Callout(kind: .ok, text: "No weak, reused, duplicate, insecure or expiring item was detected.") }65 ForEach(groups) { group in findingGroup(group) }66 }67 breachCard68 syncCard69 }70 .task(id: model.items.count) { digest = await model.engine.stateDigest() }71 .onChange(of: model.isUnlocked) { _, _ in breached = []; breachDone = false }72 }7374 @ViewBuilder private func scoreCard(_ groups: [Group]) -> some View {75 let s = score(groups)76 let (grade, tint): (String, Color) = s >= 90 ? ("excellent", Palette.accent) : s >= 70 ? ("good", Palette.accent) : s >= 45 ? ("needs attention", Palette.brass) : ("at risk", Palette.danger)77 let issues = groups.reduce(0) { $0 + $1.rows.count }78 HStack(spacing: 18) {79 ZStack {80 Circle().stroke(Palette.line, lineWidth: 7)81 Circle().trim(from: 0, to: CGFloat(s) / 100).stroke(tint, style: StrokeStyle(lineWidth: 7, lineCap: .round)).rotationEffect(.degrees(-90))82 Text("\(s)").font(.system(size: 26, weight: .semibold, design: .serif)).foregroundStyle(Palette.text)83 }84 .frame(width: 78, height: 78)85 VStack(alignment: .leading, spacing: 4) {86 Text("Vault health: \(grade)").font(.vaultHeadline).foregroundStyle(Palette.text)87 Text("\(live.count) item\(live.count == 1 ? "" : "s") analysed · \(issues) finding\(issues == 1 ? "" : "s")").font(.callout).foregroundStyle(Palette.muted)88 Text("The score is a simple local heuristic to rank what to fix first, not a guarantee.").font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)89 }90 Spacer(minLength: 0)91 }92 .vaultCard(padding: 16)93 .accessibilityElement(children: .ignore)94 .accessibilityLabel("Overall score \(s) out of 100: \(grade)")95 .accessibilityValue("\(s)")96 .accessibilityIdentifier("security-score")97 }9899 @ViewBuilder private func findingGroup(_ group: Group) -> some View {100 SectionCard("\(group.title) · \(group.rows.count)", footer: group.text) {101 ForEach(Array(group.rows.enumerated()), id: \.offset) { i, row in102 if let v = model.item(row.id) {103 Button {104 model.reveal(v.id)105 } label: {106 CardRow(last: i == group.rows.count - 1) {107 HStack(spacing: 10) {108 Image(systemName: group.symbol).foregroundStyle(group.danger ? Palette.danger : Palette.brass).frame(width: 22).accessibilityHidden(true)109 VStack(alignment: .leading, spacing: 1) {110 Text(ItemMeta.displayTitle(v.item)).foregroundStyle(Palette.text).lineLimit(1)111 Text(ItemMeta.subtitle(v.item)).font(.caption).foregroundStyle(Palette.muted).lineLimit(1)112 }113 Spacer(minLength: 8)114 Text(row.detail).font(.caption).foregroundStyle(Palette.muted)115 Image(systemName: "chevron.right").font(.caption).foregroundStyle(Palette.muted).accessibilityHidden(true)116 }117 .contentShape(Rectangle())118 }119 }120 .buttonStyle(.plain)121 .accessibilityLabel("\(group.title): \(ItemMeta.displayTitle(v.item)), \(row.detail)")122 .accessibilityHint("Opens the item")123 .accessibilityIdentifier("security-finding-\(group.kind)")124 }125 }126 }127 }128129 // ── breach check ──130131 private var passwords: [(id: String, password: String)] {132 live.compactMap { v in133 guard v.item.type == .login, let p = v.item.fields["password"], !p.isEmpty else { return nil }134 return (v.id, p)135 }136 }137138 @ViewBuilder private var breachCard: some View {139 @Bindable var prefs = model.prefs140 let n = passwords.count141 SectionCard("Breach check") {142 CardRow {143 Toggle(isOn: $prefs.breachCheck) {144 VStack(alignment: .leading, spacing: 3) {145 Text("Allow the breach check").foregroundStyle(Palette.text)146 Text("Optional. For each login password, this device computes a SHA-1 hash and sends only its first 5 hexadecimal characters to the vault server, which relays them to Have I Been Pwned. The reply lists hundreds of unrelated hash endings; the comparison happens here. The password and its full hash never leave this device (k-anonymity), and Have I Been Pwned never sees your address. The server learns that a check ran and which prefixes were asked — about a million passwords share each prefix. Results stay in memory and disappear when you lock.")147 .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)148 }149 }150 .accessibilityIdentifier("breach-toggle")151 }152 CardRow(last: true) {153 HStack(spacing: 10) {154 if let p = breachProgress {155 ProgressView(value: Double(p.done), total: Double(max(p.total, 1))).frame(maxWidth: 180)156 Text("\(p.done) of \(p.total)").font(.caption.monospacedDigit()).foregroundStyle(Palette.muted)157 } else if let breachError {158 ErrorText(text: breachError)159 } else if breachDone {160 Label(breached.isEmpty ? "None of your login passwords appear in the corpus." : "\(breached.count) password\(breached.count == 1 ? "" : "s") found — see above.",161 systemImage: breached.isEmpty ? "checkmark.circle" : "exclamationmark.octagon")162 .font(.callout).foregroundStyle(breached.isEmpty ? Palette.accent : Palette.danger).accessibilityIdentifier("breach-result")163 } else {164 Text(n == 0 ? "No login password to check." : "Not run in this session.").font(.callout).foregroundStyle(Palette.muted)165 }166 Spacer(minLength: 8)167 Button("Check \(n) password\(n == 1 ? "" : "s")") { Task { await runBreachCheck() } }.buttonStyle(.vaultSecondary)168 .disabled(!model.prefs.breachCheck || n == 0 || breachProgress != nil).accessibilityIdentifier("breach-run")169 }170 .frame(minHeight: 30)171 }172 }173 }174175 private func runBreachCheck() async {176 let list = passwords177 var byPassword: [String: [String]] = [:]178 for p in list { byPassword[p.password, default: []].append(p.id) }179 breachError = nil; breachDone = false180 var found: [Finding] = []181 var done = 0182 breachProgress = (0, byPassword.count)183 defer { breachProgress = nil }184 for (password, ids) in byPassword {185 guard model.isUnlocked else { return }186 do {187 let count = try await model.engine.breachCheck(password: password)188 if count > 0 { found += ids.map { .breached(id: $0, count: count) } }189 } catch {190 breachError = model.errorText(error) ?? "The breach check was interrupted."191 return192 }193 done += 1194 breachProgress = (done, byPassword.count)195 }196 breached = found197 breachDone = true198 }199200 // ── sync health ──201202 @ViewBuilder private var syncCard: some View {203 let h = model.health204 let warnings = h?.warnings ?? []205 if !warnings.isEmpty {206 VStack(alignment: .leading, spacing: 8) {207 ForEach(warnings, id: \.self) { w in208 Callout(kind: .danger, title: "Security warning", text: w)209 }210 }211 .accessibilityIdentifier("sync-warnings")212 }213 SectionCard("Sync health", footer: "Two devices in the same state show the same digest. If they differ after both have synced, one of them was shown a different history.") {214 CardRow { stat("Connection", h?.online == false ? "Offline — changes are queued" : (h?.needsSignIn == true ? "Session expired — sign in again" : "Online"), warn: h?.online == false || h?.needsSignIn == true) }215 CardRow { stat("Last sync", ItemMeta.relative(h?.lastSyncAt)) }216 CardRow { stat("Changes waiting to be sent", "\(h?.pending ?? 0)") }217 CardRow { stat("Records that failed authentication", "\(h?.undecryptable ?? 0)", warn: (h?.undecryptable ?? 0) > 0) }218 CardRow(last: true) {219 HStack {220 Text("State digest").foregroundStyle(Palette.text)221 Spacer(minLength: 8)222 Text(digest.isEmpty ? "—" : digest).font(.secret).foregroundStyle(Palette.text).textSelection(.enabled)223 .accessibilityLabel("State digest").accessibilityValue(digest).accessibilityIdentifier("state-digest")224 Button("Sync now") { Task { await model.syncNow(); digest = await model.engine.stateDigest() } }.buttonStyle(.vaultCompact).accessibilityIdentifier("sync-now")225 }226 }227 }228 }229230 private func stat(_ label: String, _ value: String, warn: Bool = false) -> some View {231 HStack {232 Text(label).foregroundStyle(Palette.text)233 Spacer(minLength: 8)234 Text(value).foregroundStyle(warn ? Palette.brass : Palette.muted).multilineTextAlignment(.trailing)235 }236 .accessibilityElement(children: .combine)237 }238}239