Repository Public
1import MCCCore2import SwiftUI34/// Audit log (read), chain verification and signed export.5struct AuditScreen: View {6 @Environment(\.mccTheme) private var theme7 @Session private var session8 @State private var outcome: API.AuditOutcome?9 @State private var period: AuditLogic.Period = .all10 @State private var query = ""11 @State private var selected: SelectedEntry?12 @State private var exporting = false1314 private struct SelectedEntry: Identifiable { let entry: API.AuditEntry; var id: Int64 { entry.seq } }1516 private var resource: Resource<[API.AuditEntry]> { session.audit.entries[AuditLogic.filter(outcome: outcome, period: period)] }1718 var body: some View {19 let resource = resource20 ScreenStack {21 verification22 MutationButton(title: tr("audit.export"), systemImage: "square.and.arrow.up", permission: "audit.export", identifier: "audit-export") { exporting = true }23 TileGrid(minimum: 200) {24 Picker(tr("audit.filter.outcome"), selection: $outcome) {25 Text(tr("audit.filter.outcome.all")).tag(API.AuditOutcome?.none)26 ForEach(API.AuditOutcome.allCases, id: \.self) { Text($0.label).tag(API.AuditOutcome?.some($0)) }27 }28 .pickerStyle(.menu).frame(minHeight: Tokens.Size.touchMin).accessibilityIdentifier("audit-filter-outcome")29 Picker(tr("audit.filter.period"), selection: $period) {30 ForEach(AuditLogic.Period.allCases) { Text($0.title).tag($0) }31 }32 .pickerStyle(.menu).frame(minHeight: Tokens.Size.touchMin).accessibilityIdentifier("audit-filter-period")33 }34 ResourceSection(resource: resource) { all in35 let items = AuditLogic.sorted(all.filter { AuditLogic.matches($0, text: query) })36 if items.isEmpty {37 EmptyStateView(tr("audit.empty"), systemImage: "checkmark.shield").accessibilityIdentifier("audit-empty")38 } else {39 LazyVStack(spacing: Tokens.Space.s3) {40 ForEach(items, id: \.seq) { e in41 Button { selected = SelectedEntry(entry: e) } label: { row(e) }42 .buttonStyle(.plain)43 .hoverEffect(.highlight)44 .accessibilityIdentifier("audit-row-\(e.seq)")45 }46 }47 }48 }49 .id(ObjectIdentifier(resource))50 }51 .screen("audit", title: tr("section.audit"), load: load, reload: reload)52 .searchable(text: $query, prompt: tr("audit.search.prompt"))53 .task(id: ObjectIdentifier(resource)) { await resource.loadIfNeeded() }54 .sheet(item: $selected) { AuditEntrySheet(entry: $0.entry) }55 .sheet(isPresented: $exporting) { AuditExportSheet() }56 }5758 private func load() async {59 async let a: Void = resource.loadIfNeeded()60 async let b: Void = session.audit.verification.loadIfNeeded(maxAge: 120)61 _ = await (a, b)62 }63 private func reload() async {64 async let a: Void = resource.load()65 async let b: Void = session.audit.verification.load()66 _ = await (a, b)67 }6869 private func row(_ e: API.AuditEntry) -> some View {70 VStack(alignment: .leading, spacing: Tokens.Space.s1) {71 AdaptiveRow {72 Text(e.action).font(.callout.monospaced().weight(.medium)).foregroundStyle(theme.textPrimary).multilineTextAlignment(.leading)73 } trailing: {74 StatusBadge(e.outcome.label, tone: e.outcome.tone, compact: true)75 }76 Text([e.actorLabel, AuditLogic.targetText(e)].compactMap { $0 }.joined(separator: " → ")).font(.footnote).foregroundStyle(theme.textSecondary).multilineTextAlignment(.leading)77 Text("#\(e.seq) · " + Format.dateTime(e.ts)).font(.footnote).foregroundStyle(theme.textTertiary)78 }79 .padding(.vertical, Tokens.Space.s3)80 .padding(.horizontal, Tokens.Space.s4)81 .frame(maxWidth: .infinity, minHeight: Tokens.Size.touchMin, alignment: .leading)82 .background(theme.surface, in: RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous))83 .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous).strokeBorder(theme.borderSubtle, lineWidth: 1))84 .contentShape(RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous))85 }8687 @ViewBuilder private var verification: some View {88 let r = session.audit.verification89 SectionCard(tr("audit.chain")) {90 if let v = r.value {91 StatusLabel(tr(v.ok ? "audit.chain.ok" : "audit.chain.broken"), tone: v.ok ? .ok : .critical)92 .accessibilityIdentifier("audit-chain-status")93 InfoRow(tr("audit.chain.checked"), Format.integer(Int(v.checkedEntries)))94 if let s = v.firstBrokenSeq { InfoRow(tr("audit.chain.first_broken"), "#\(s)") }95 if let reason = v.reason, !reason.isEmpty { InfoRow(tr("audit.chain.reason"), reason) }96 if let h = v.headHash { InfoRow(tr("audit.chain.head"), h, monospaced: true) }97 InfoRow(tr("audit.chain.verified_at"), Format.dateTime(v.verifiedAt))98 DataStamp(receivedAt: r.receivedAt, stale: r.isShowingStaleData)99 } else if let reason = r.state.unavailableReason {100 UnavailableStateView(reason: reason, error: r.state.error) { Task { await r.load() } }101 } else if let e = r.state.error {102 InlineErrorView(e)103 } else {104 ProgressView(tr("state.loading"))105 }106 }107 }108}109110/// Every field of one audit entry.111private struct AuditEntrySheet: View {112 @Environment(\.dismiss) private var dismiss113 @Environment(\.mccTheme) private var theme114 let entry: API.AuditEntry115116 var body: some View {117 NavigationStack {118 ScrollView {119 VStack(alignment: .leading, spacing: Tokens.Space.s4) {120 Card {121 VStack(alignment: .leading, spacing: Tokens.Space.s3) {122 InfoRow(tr("audit.entry.seq"), "#\(entry.seq)")123 InfoRow(tr("audit.entry.time"), Format.dateTime(entry.ts) + " · " + Format.utc(entry.ts))124 InfoRow(tr("audit.entry.action"), entry.action, monospaced: true)125 InfoRow(tr("audit.entry.outcome"), entry.outcome.label)126 InfoRow(tr("audit.entry.actor"), entry.actorLabel + " (" + entry.actorKind.rawValue + ")")127 InfoRow(tr("audit.entry.actor_id"), entry.actorId, monospaced: true)128 InfoRow(tr("audit.entry.target"), AuditLogic.targetText(entry), monospaced: true)129 InfoRow(tr("audit.entry.detail"), entry.detail)130 InfoRow(tr("audit.entry.ip"), entry.ip, monospaced: true)131 InfoRow(tr("audit.entry.device"), entry.deviceId, monospaced: true)132 InfoRow(tr("audit.entry.session"), entry.sessionId, monospaced: true)133 }134 }135 SectionCard(tr("audit.entry.params")) {136 Text(JSONValue(entry.params.additionalProperties).prettyPrinted())137 .font(.footnote.monospaced()).foregroundStyle(theme.textPrimary).textSelection(.enabled)138 .frame(maxWidth: .infinity, alignment: .leading)139 }140 SectionCard(tr("audit.entry.integrity")) {141 InfoRow(tr("audit.entry.prev_hash"), entry.prevHash, monospaced: true)142 InfoRow(tr("audit.entry.hash"), entry.hash, monospaced: true)143 CorrelationIDView(entry.correlationId)144 }145 }146 .padding(Tokens.Space.s5)147 }148 .background(theme.canvas.ignoresSafeArea())149 .navigationTitle(tr("audit.entry.title"))150 .navigationBarTitleDisplayMode(.inline)151 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(tr("common.close")) { dismiss() } } }152 .accessibilityIdentifier("screen-audit-entry")153 }154 .mccThemed()155 }156}157158/// Export of a period: the server requires `audit.export` and a recent passkey verification; the file is then159/// handed to the system share sheet.160private struct AuditExportSheet: View {161 @Environment(\.dismiss) private var dismiss162 @Environment(\.mccTheme) private var theme163 @Session private var session164 @State private var from = Date().addingTimeInterval(-7 * 86_400)165 @State private var to = Date()166 @State private var format: AuditRepository.ExportFormat = .ndjson167 @State private var working = false168 @State private var error: APIError?169 @State private var file: URL?170 @State private var size = 0171172 var body: some View {173 NavigationStack {174 Form {175 Section {176 DatePicker(tr("audit.export.from"), selection: $from, in: ...to, displayedComponents: [.date]).accessibilityIdentifier("audit-export-from")177 DatePicker(tr("audit.export.to"), selection: $to, in: from..., displayedComponents: [.date]).accessibilityIdentifier("audit-export-to")178 Picker(tr("audit.export.format"), selection: $format) {179 Text("NDJSON").tag(AuditRepository.ExportFormat.ndjson)180 Text("CSV").tag(AuditRepository.ExportFormat.csv)181 }182 .accessibilityIdentifier("audit-export-format")183 } footer: {184 Text(tr("audit.export.note"))185 }186 if let error { Section { InlineErrorView(error).accessibilityIdentifier("audit-export-error") } }187 Section {188 Button { run() } label: {189 HStack { if working { ProgressView() }; Text(tr("audit.export.run")) }.frame(maxWidth: .infinity, minHeight: Tokens.Size.touchMin)190 }191 .disabled(working || !session.canMutate)192 .accessibilityIdentifier("audit-export-run")193 }194 if let file {195 Section(tr("audit.export.ready")) {196 Text(file.lastPathComponent + " · " + Format.bytes(Int64(size))).font(.callout.monospaced())197 ShareLink(item: file) { Label(tr("audit.export.share"), systemImage: "square.and.arrow.up").frame(minHeight: Tokens.Size.touchMin) }198 .accessibilityIdentifier("audit-export-share")199 }200 }201 }202 .onChange(of: from) { file = nil }203 .onChange(of: to) { file = nil }204 .onChange(of: format) { file = nil }205 .navigationTitle(tr("audit.export"))206 .navigationBarTitleDisplayMode(.inline)207 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(tr("common.close")) { dismiss() } } }208 .accessibilityIdentifier("screen-audit-export")209 }210 .mccThemed()211 .onDisappear { if let file { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) } }212 }213214 private func run() {215 working = true216 error = nil217 file = nil218 let cal = Calendar.current219 let start = cal.startOfDay(for: from)220 let end = min(Date(), cal.date(byAdding: .day, value: 1, to: cal.startOfDay(for: to)) ?? to)221 let fmt = format222 Task {223 do {224 let data = try await session.audit.export(from: start, to: end, format: fmt)225 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("audit-export-" + UUID().uuidString, isDirectory: true)226 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)227 let url = dir.appendingPathComponent(AuditLogic.exportFileName(from: start, to: end, format: fmt))228 try data.write(to: url, options: [.atomic, .completeFileProtection])229 size = data.count230 file = url231 } catch {232 let e = APIError.from(error)233 if !e.isCancelled && !e.isPasskeyCancelled { self.error = e }234 }235 working = false236 }237 }238}239