Repository Public
1// Activity: the hash-chained audit trail of the account, with the chain recomputed on this device.2// The server keeps the log; each entry carries the hash of the previous one, so an entry that was edited or removed3// in the middle of what is shown here breaks the chain. Entries describe events (kinds, device ids, counters), never4// the content of the vault.5import SharedVaultKit6import SwiftUI78struct ActivityPage: View {9 @Environment(AppModel.self) private var model10 @State private var events: [AuditEvent] = []11 @State private var verified: Bool?12 @State private var loading = false13 @State private var loadedOnce = false14 @State private var exhausted = false15 @State private var error: String?16 @State private var category: Category = .all1718 enum Category: String, CaseIterable, Identifiable {19 case all = "All", security = "Security", sharing = "Sharing", agents = "Agents"20 var id: String { rawValue }21 }2223 private var shown: [AuditEvent] { category == .all ? events : events.filter { ActivityNames.category(of: $0.kind) == category } }2425 var body: some View {26 ToolPage("Activity", subtitle: "What happened on your account, as recorded by the server and checked on this device.") {27 Button { Task { await reload() } } label: { Label("Refresh", systemImage: "arrow.clockwise") }28 .buttonStyle(.vaultCompact).disabled(loading).accessibilityIdentifier("activity-refresh")29 } content: {30 ErrorText(text: error)31 chainBanner32 if loadedOnce && events.isEmpty && error == nil {33 EmptyState(symbol: "waveform.path.ecg", title: "No activity yet", text: "Sign-ins, new devices, shares and exports will appear here.")34 .frame(minHeight: 220)35 } else if !loadedOnce && error == nil {36 HStack(spacing: 10) { ProgressView(); Text("Loading the activity log…").foregroundStyle(Palette.muted) }37 } else if !events.isEmpty {38 Picker("Category", selection: $category) {39 ForEach(Category.allCases) { Text($0.rawValue).tag($0) }40 }41 .pickerStyle(.segmented).labelsHidden().frame(maxWidth: 420).accessibilityIdentifier("activity-category")42 if shown.isEmpty {43 Text("Nothing in this category among the loaded entries.").font(.callout).foregroundStyle(Palette.muted)44 } else {45 SectionCard(footer: "Device identifiers are shortened. This device is \(shortDevice(model.identity?.deviceId) ?? "unknown").") {46 ForEach(Array(shown.enumerated()), id: \.element.id) { i, e in47 CardRow(last: i == shown.count - 1) { row(e) }48 }49 }50 }51 if !exhausted {52 Button { Task { await loadOlder() } } label: { Label(loading ? "Loading…" : "Load older", systemImage: "arrow.down.circle") }53 .buttonStyle(.vaultSecondary).disabled(loading).accessibilityIdentifier("activity-older")54 } else {55 Text("Beginning of the log.").font(.caption).foregroundStyle(Palette.muted)56 }57 }58 }59 .task(id: model.activityTick) { await reload() }60 .containerID("activity-page")61 }6263 @ViewBuilder private var chainBanner: some View {64 if let verified, !events.isEmpty {65 if verified {66 Callout(kind: .ok, title: "Chain verified",67 text: "The \(events.count) loaded entr\(events.count == 1 ? "y links" : "ies link") to one another without a gap: none was altered or removed in between. This check covers what is loaded here; it cannot show that the server left out the most recent events.")68 .accessibilityIdentifier("activity-chain-ok")69 } else {70 Callout(kind: .danger, title: "Security warning — the log was ALTERED",71 text: "The hash chain of the loaded entries does not hold: at least one entry was modified, removed or inserted after the fact. Do not rely on this log. Review your devices and consider an account rekey from a device you trust.")72 .accessibilityIdentifier("activity-chain-altered")73 }74 }75 }7677 private func row(_ e: AuditEvent) -> some View {78 let name = ActivityNames.label(e.kind)79 let detail = ActivityNames.detail(e)80 let notable = ActivityNames.notable.contains(e.kind)81 return HStack(alignment: .top, spacing: 12) {82 Image(systemName: name.symbol).font(.system(size: 14, weight: .medium)).foregroundStyle(notable ? Palette.brass : Palette.muted)83 .frame(width: 22, height: 22).accessibilityHidden(true)84 VStack(alignment: .leading, spacing: 3) {85 HStack(spacing: 8) {86 Text(name.title).font(.body.weight(.medium)).foregroundStyle(Palette.text)87 if e.actor != "user" { Pill(text: e.actor, tint: e.actor == "agent" ? Palette.brass : Palette.muted) }88 }89 if !detail.isEmpty { Text(detail).font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true) }90 HStack(spacing: 6) {91 Text(ItemMeta.relative(e.at))92 Text("·")93 Text(ItemMeta.date(e.at))94 if let d = shortDevice(e.deviceId) {95 Text("·")96 Text(e.deviceId == model.identity?.deviceId ? "this device" : "device \(d)").font(.caption.monospaced())97 }98 }99 .font(.caption).foregroundStyle(Palette.muted)100 }101 Spacer(minLength: 0)102 }103 .accessibilityElement(children: .combine)104 .accessibilityIdentifier("activity-row")105 }106107 private func shortDevice(_ id: String?) -> String? { id.flatMap { $0.isEmpty ? nil : String($0.prefix(8)) } }108109 // ── loading ──110 private func reload() async {111 guard model.isUnlocked, !loading else { return }112 loading = true113 defer { loading = false; loadedOnce = true }114 do {115 let page = try await model.engine.audit()116 let ok = await model.engine.verifyAuditPage(page)117 events = page; verified = ok; exhausted = page.count < 100; error = nil118 } catch { self.error = model.errorText(error) }119 }120121 private func loadOlder() async {122 guard let last = events.last, !loading else { return }123 loading = true124 defer { loading = false }125 do {126 let page = try await model.engine.audit(before: last.id)127 if page.isEmpty { exhausted = true; return }128 // the chain is checked over everything loaded, so the junction between two pages is covered too129 let all = events + page130 let ok = await model.engine.verifyAuditPage(all)131 events = all; verified = ok; exhausted = page.count < 100; error = nil132 } catch { self.error = model.errorText(error) }133 }134}135136enum ActivityNames {137 private static let names: [String: (String, String)] = [138 "account.created": ("Account created", "person.crop.circle.badge.plus"), "account.rekeyed": ("Account rekeyed", "arrow.triangle.2.circlepath"),139 "session.login": ("Signed in with passkey", "person.badge.key"),140 "passkey.added": ("Passkey added", "person.badge.key"), "passkey.removed": ("Passkey removed", "person.badge.key"),141 "device.enrolled": ("Device enrolled", "laptopcomputer.and.iphone"), "device.revoked": ("Device revoked", "laptopcomputer.slash"),142 "recovery.started": ("Recovery attempt started", "exclamationmark.triangle"), "recovery.rotated": ("Recovery key replaced", "key"),143 "vault.created": ("Vault created", "lock.square"), "vault.deleted": ("Vault deleted", "lock.square"), "vault.member_added": ("Vault member added", "person.2"),144 "vault.shared_with_you": ("A vault was shared with you", "person.2"), "vault.access_removed": ("Your access to a vault was removed", "person.2.slash"),145 "vault.key_rotated": ("Vault key rotated", "arrow.triangle.2.circlepath"),146 "share.created": ("Item shared", "square.and.arrow.up"), "share.received": ("Item received", "tray.and.arrow.down"),147 "share.opened": ("Shared item opened", "eye"), "share.revoked": ("Share revoked", "square.and.arrow.up.trianglebadge.exclamationmark"),148 "export.plaintext": ("Plaintext export", "exclamationmark.triangle"), "export.backup": ("Encrypted backup exported", "arrow.down.doc"),149 "import": ("Items imported", "arrow.up.doc"), "item.revealed-bulk": ("Many secrets revealed", "eye"),150 "connect.identity_created": ("Workload identity created", "cpu"), "connect.identity_revoked": ("Workload identity revoked", "cpu"),151 "connect.secret_created": ("Managed secret created", "key"), "connect.secret_rotated": ("Managed secret rotated", "arrow.triangle.2.circlepath"),152 "connect.secret_deleted": ("Managed secret deleted", "trash"),153 "connect.grant_created": ("Grant created", "checkmark.circle"), "connect.grant_revoked": ("Grant revoked", "xmark.circle"),154 "connect.approved": ("Agent request approved", "checkmark.circle"), "connect.denied": ("Agent request denied", "xmark.circle"),155 "connect.kill_engaged": ("Kill switch engaged", "power"), "connect.kill_released": ("Kill switch released", "power"),156 "agent.denied": ("Agent request refused by policy", "exclamationmark.triangle"), "agent.approval_requested": ("Agent asked for approval", "cpu"),157 "agent.secret_delivered": ("Secret delivered to a workload", "exclamationmark.triangle"), "agent.operation": ("Brokered operation", "cpu"),158 ]159160 static let notable: Set<String> = ["device.enrolled", "device.revoked", "recovery.started", "recovery.rotated", "account.rekeyed", "export.plaintext",161 "agent.secret_delivered", "connect.kill_engaged", "passkey.added", "passkey.removed"]162163 static func label(_ kind: String) -> (title: String, symbol: String) {164 if let n = names[kind] { return n }165 // unknown kind (newer server): show it readable rather than hide it166 return (kind.replacingOccurrences(of: ".", with: " · ").replacingOccurrences(of: "_", with: " ").capitalizedFirst, "circle.dashed")167 }168169 static func category(of kind: String) -> ActivityPage.Category? {170 if kind.hasPrefix("connect.") || kind.hasPrefix("agent.") { return .agents }171 if kind.hasPrefix("share.") || ["vault.member_added", "vault.shared_with_you", "vault.access_removed"].contains(kind) { return .sharing }172 if ["account.", "session.", "passkey.", "device.", "recovery.", "export.", "item."].contains(where: kind.hasPrefix) || kind == "import" || kind == "vault.key_rotated" { return .security }173 return nil174 }175176 /// Facts recorded with the event (platform, role, counters). Free text supplied by an agent is never shown here.177 static func detail(_ e: AuditEvent) -> String {178 let d = e.detail179 var parts: [String] = []180 func text(_ k: String) -> String? {181 if let s = d[k]?.stringValue, !s.isEmpty { return String(s.prefix(80)) }182 if let n = d[k]?.intValue { return String(n) }183 return nil184 }185 if let v = text("platform") { parts.append(v) }186 if let v = text("via") { parts.append(v == "recovery-key" ? "using the recovery key" : "via \(v)") }187 if let v = text("kind") {188 if e.kind.hasPrefix("share.") { parts.append(v == "link" ? "by link" : "to an account") }189 else if e.kind.hasPrefix("connect.") { parts.append(v) }190 }191 if let v = text("role") { parts.append("role \(v)") }192 if let v = text("views") { parts.append("view \(v)") }193 if let v = text("epoch") { parts.append("epoch \(v)") }194 if let v = text("keyEpoch") { parts.append("key epoch \(v)") }195 if let v = text("removed") { parts.append("\(v) member removed") }196 if let v = text("mode") { parts.append("mode \(v)") }197 if let v = d["approval"]?.stringValue, v.count < 10 { parts.append("approval \(v)") }198 if let v = text("op") { parts.append("operation \(v)") }199 if let m = text("method"), let h = text("host") { parts.append("\(m) \(h)") }200 if let v = text("reason") { parts.append(v) } // set by the server's policy check, not by the agent201 if let v = text("version") { parts.append("version \(v)") }202 for k in ["vault", "share", "secret", "identity", "grant", "device"] { if let v = d[k]?.stringValue { parts.append("\(k) \(v.prefix(8))…") } }203 return parts.joined(separator: " · ")204 }205}206