SPB Git

Repository Public

SettingsPage.swift 28.5 KB 483 lines swift

1// Settings: locking, clipboard, privacy, AutoFill, import / backup / export, recovery key, passkeys, session, About security.2import AuthenticationServices3import LocalAuthentication4import SharedVaultKit5import SwiftUI6import UniformTypeIdentifiers78/// A text file handed to the system exporter (encrypted backup, or a plaintext export after typed confirmation).9struct TextFileDocument: FileDocument {10    static let readableContentTypes: [UTType] = [.json, .commaSeparatedText, .plainText]11    var text: String12    init(text: String) { self.text = text }13    init(configuration: ReadConfiguration) throws { text = String(decoding: configuration.file.regularFileContents ?? Data(), as: UTF8.self) }14    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: Data(text.utf8)) }15}1617struct SettingsPage: View {18    @Environment(AppModel.self) private var model19    @State private var confirm: ConfirmRequest?20    @State private var error: String?21    @State private var providerEnabled: Bool?2223    // import24    @State private var importing = false25    @State private var parsed: ImportResult?26    @State private var parsedName = ""27    @State private var importVault = ""28    @State private var importProgress: Double?29    @State private var imported = 030    // backup / export31    @State private var exportDoc: TextFileDocument?32    @State private var exportName = ""33    @State private var exportType: UTType = .json34    @State private var restoring = false35    @State private var restoreText: String?36    @State private var restoreKey = ""37    @State private var askRestoreKey = false38    // passkeys39    @State private var passkeys: [PasskeyInfo]?4041    private static let formats: [ImportFormat: String] = [.apple: "Apple Passwords CSV", .onePassword: "1Password CSV", .bitwardenCsv: "Bitwarden CSV", .bitwardenJson: "Bitwarden JSON", .chrome: "Chrome / Edge CSV", .generic: "Generic CSV"]42    private var stamp: String { String(ISO8601DateFormatter().string(from: Date()).prefix(10)) }4344    var body: some View {45        @Bindable var prefs = model.prefs46        ToolPage("Settings", subtitle: "Signed in as \(model.handle) on this device.") {47            ErrorText(text: error)48            locking(prefs)49            privacy(prefs)50            autofill(prefs)51            importSection52            backupSection53            accessSection54            deviceSection55            dangerSection56            about57        }58        .containerID("settings-page")59        .confirmSheet($confirm)60        .fileImporter(isPresented: $importing, allowedContentTypes: [.commaSeparatedText, .json, .plainText]) { r in if case .success(let u) = r { readImport(u) } }61        .fileImporter(isPresented: $restoring, allowedContentTypes: [.json, .plainText, .data]) { r in if case .success(let u) = r { readBackup(u) } }62        .fileExporter(isPresented: Binding(get: { exportDoc != nil }, set: { if !$0 { exportDoc = nil } }), document: exportDoc, contentType: exportType, defaultFilename: exportName) { result in63            if case .success = result { model.show("Saved \(exportName)") }64            exportDoc = nil65        }66        .sheet(isPresented: $askRestoreKey) { restoreKeySheet }67        .task { providerEnabled = await CredentialIdentitySync.isProviderEnabled(); await loadPasskeys() }68    }6970    // ── locking ──71    private func locking(_ prefs: Preferences) -> some View {72        @Bindable var prefs = prefs73        return SectionCard("Locking", footer: "Locking wipes the vault keys and every decrypted item from memory. Unlocking uses this device's keys, which need \(Self.presence) each time — the keys are created with the “user presence” policy, so enrolling a new fingerprint or face does not lock you out.") {74            CardRow {75                Picker("Auto-lock after inactivity", selection: $prefs.autoLockSeconds) {76                    ForEach(Preferences.autoLockChoices, id: \.seconds) { Text($0.label).tag($0.seconds) }77                }78                .accessibilityIdentifier("pref-autolock")79            }80            #if os(macOS)81            CardRow { Toggle("Lock when the Mac sleeps, the screen locks or the screen saver starts", isOn: $prefs.lockOnSleep).accessibilityIdentifier("pref-lock-sleep") }82            #else83            CardRow {84                Picker("Lock when in the background", selection: $prefs.lockInBackgroundSeconds) {85                    ForEach(Preferences.backgroundChoices, id: \.seconds) { Text($0.label).tag($0.seconds) }86                }87                .accessibilityIdentifier("pref-lock-background")88            }89            #endif90            CardRow(last: true) {91                Picker("Clear copied secrets after", selection: $prefs.clipboardClearSeconds) {92                    ForEach(Preferences.clipboardChoices, id: \.seconds) { Text($0.label).tag($0.seconds) }93                }94                .accessibilityIdentifier("pref-clipboard")95            }96        }97        .tint(Palette.accent)98    }99100    private static var presence: String {101        let ctx = LAContext()102        _ = ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)103        switch ctx.biometryType {104        case .touchID: return "Touch ID or the login password"105        case .faceID: return "Face ID or the device passcode"106        default: return "the device passcode"107        }108    }109110    // ── privacy ──111    private func privacy(_ prefs: Preferences) -> some View {112        @Bindable var prefs = prefs113        #if os(macOS)114        let footer = "Copied secrets are marked as concealed for clipboard managers and removed after the delay if the clipboard still holds them. Hiding from screen capture also blurs the window when SP Vault is not the active app. Spotlight indexing is off by default: when on, only item titles (never usernames, addresses or secrets) are given to the system index of this Mac, where other apps with Spotlight access can find them."115        #else116        let footer = "Copied secrets stay on this device (they are not offered to Universal Clipboard) and expire after the delay. The app content is covered in the app switcher and whenever the app is not active."117        #endif118        return SectionCard("Privacy", footer: footer) {119            #if os(macOS)120            CardRow { Toggle("Hide SP Vault from screenshots, recordings and screen sharing", isOn: $prefs.hideFromCapture).accessibilityIdentifier("pref-hide-capture") }121            CardRow { Toggle("Index item titles in Spotlight", isOn: $prefs.spotlightTitles).accessibilityIdentifier("pref-spotlight") }122            #endif123            CardRow(last: true) { Toggle("Notify about pairing requests and agent approvals (no content)", isOn: $prefs.notifications).accessibilityIdentifier("pref-notifications") }124        }125        .tint(Palette.accent)126    }127128    // ── AutoFill ──129    private func autofill(_ prefs: Preferences) -> some View {130        @Bindable var prefs = prefs131        #if os(macOS)132        let where_ = "System Settings → General → AutoFill & Passwords"133        #else134        let where_ = "Settings → General → AutoFill & Passwords"135        #endif136        return SectionCard("AutoFill", footer: "AutoFill works where the operating system offers third-party credential providers: Safari, and apps that use the system AutoFill for passwords, passkeys and verification codes. Other browsers only when they use the system AutoFill. Each fill asks for \(Self.presence).") {137            CardRow {138                HStack {139                    VStack(alignment: .leading, spacing: 2) {140                        Text("SP Vault as an AutoFill provider").foregroundStyle(Palette.text)141                        Text(providerEnabled == true ? "Enabled in the system settings." : "Not enabled yet. Turn it on in \(where_).").font(.caption).foregroundStyle(providerEnabled == true ? Palette.accent : Palette.muted)142                            .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("autofill-state")143                    }144                    Spacer()145                    Button(providerEnabled == true ? "Open settings" : "Turn on…") {146                        Task {147                            if providerEnabled == true { try? await ASSettingsHelper.openCredentialProviderAppSettings() }148                            else { _ = await ASSettingsHelper.requestToTurnOnCredentialProviderExtension() }149                            providerEnabled = await CredentialIdentitySync.isProviderEnabled()150                            model.autofillPreferenceChanged()151                        }152                    }153                    .buttonStyle(.vaultCompact).accessibilityIdentifier("autofill-open-settings")154                }155            }156            CardRow(last: true) {157                VStack(alignment: .leading, spacing: 4) {158                    Toggle("Suggest my logins in the keyboard and in Safari", isOn: $prefs.autofillSuggestions).accessibilityIdentifier("pref-autofill-suggestions")159                        .onChange(of: prefs.autofillSuggestions) { _, _ in model.autofillPreferenceChanged() }160                    Text("When on, the operating system keeps a list of the site names and usernames of your logins, the sites and account names of your passkeys and the sites of your one-time codes — never a password, a key or a code — so that it can offer them above the keyboard. Turning this off erases that list; you can still pick an item from the SP Vault list when filling.")161                        .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)162                }163            }164        }165        .tint(Palette.accent)166    }167168    // ── import ──169    private var importSection: some View {170        SectionCard("Import") {171            CardRow(last: parsed == nil && imported == 0 && importProgress == nil) {172                HStack {173                    Text("CSV exports from Apple Passwords, 1Password, Chrome or Bitwarden, and Bitwarden JSON. The file is read on this device only; each entry is encrypted before it is sent.")174                        .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)175                    Spacer()176                    Button("Choose a file…") {177                        #if SPV_DEV178                        if let f = DevSupport.importFile { readImport(f); return }179                        #endif180                        importing = true181                    }.buttonStyle(.vaultCompact).disabled(importProgress != nil).accessibilityIdentifier("import-choose")182                }183            }184            if let parsed {185                CardRow(last: true) {186                    VStack(alignment: .leading, spacing: 10) {187                        Text("\(parsed.items.count) item\(parsed.items.count == 1 ? "" : "s") found in \(parsedName) · format: \(Self.formats[parsed.format] ?? parsed.format.rawValue)\(parsed.skipped > 0 ? " · \(parsed.skipped) row\(parsed.skipped == 1 ? "" : "s") skipped" : "")")188                            .foregroundStyle(Palette.text).accessibilityIdentifier("import-preview")189                        if !parsed.warnings.isEmpty { Callout(kind: .warn, title: "Warnings", text: parsed.warnings.joined(separator: "\n")) }190                        if model.writableVaults.count > 1 {191                            Picker("Import into", selection: $importVault) { ForEach(model.writableVaults) { Text($0.meta.name).tag($0.vaultId) } }.accessibilityIdentifier("import-vault")192                        }193                        if let p = importProgress { ProgressView(value: p) { Text("Encrypting…").font(.caption) }.tint(Palette.accent) }194                        else {195                            HStack {196                                Spacer()197                                Button("Discard") { self.parsed = nil }.buttonStyle(.vaultSecondary)198                                Button("Import \(parsed.items.count) item\(parsed.items.count == 1 ? "" : "s")") { Task { await runImport(parsed) } }.buttonStyle(.vaultPrimary)199                                    .disabled(parsed.items.isEmpty || importVault.isEmpty).accessibilityIdentifier("import-run")200                            }201                        }202                    }203                }204            }205            if imported > 0 {206                CardRow(last: true) {207                    Callout(kind: .warn, title: "\(imported) item\(imported == 1 ? "" : "s") imported", text: "The file you imported contains your passwords in clear text. Delete it and empty the trash.")208                        .accessibilityIdentifier("import-done")209                }210            }211        }212    }213214    private func readText(_ url: URL, limit: Int = 20 * 1024 * 1024) -> String? {215        let scoped = url.startAccessingSecurityScopedResource()216        defer { if scoped { url.stopAccessingSecurityScopedResource() } }217        guard let data = try? Data(contentsOf: url) else { error = "The file could not be read."; return nil }218        guard data.count <= limit else { error = "This file is larger than 20 MB."; return nil }219        return String(decoding: data, as: UTF8.self)220    }221222    private func readImport(_ url: URL) {223        imported = 0; parsed = nil; error = nil224        guard let text = readText(url) else { return }225        do {226            parsed = try SPV1.importAny(fileName: url.lastPathComponent, text: text)227            parsedName = url.lastPathComponent228            importVault = model.defaultVaultId ?? ""229        } catch { self.error = "This file is not a supported export (CSV with a header row, or Bitwarden JSON)." }230    }231232    private func runImport(_ p: ImportResult) async {233        importProgress = 0234        defer { importProgress = nil }235        let vault = importVault236        var n = 0237        error = await model.perform {238            for it in p.items {239                try await model.engine.importItems(vaultId: vault, items: [it])240                n += 1241                importProgress = Double(n) / Double(p.items.count)242            }243        }244        imported = n245        parsed = nil246    }247248    // ── backup ──249    private var backupSection: some View {250        SectionCard("Backup", footer: "A backup is one encrypted file that holds every item of every vault you can read (attachments are not included). It opens with the vault itself or with the recovery key that was valid when it was made — without the server.") {251            CardRow {252                HStack {253                    Text("Export an encrypted backup").foregroundStyle(Palette.text)254                    Spacer()255                    Button("Export…") {256                        Task {257                            error = await model.perform {258                                let text = try await model.engine.exportBackup()259                                exportType = .json; exportName = "sp-vault-backup-\(stamp).spvault.json"; exportDoc = TextFileDocument(text: text)260                            }261                        }262                    }263                    .buttonStyle(.vaultCompact).accessibilityIdentifier("backup-export")264                }265            }266            CardRow(last: true) {267                HStack {268                    VStack(alignment: .leading, spacing: 2) {269                        Text("Restore from a backup").foregroundStyle(Palette.text)270                        Text("Items are restored into new vaults named “… (restored)”. Nothing existing is overwritten.").font(.caption).foregroundStyle(Palette.muted)271                    }272                    Spacer()273                    Button("Restore…") { restoring = true }.buttonStyle(.vaultCompact).accessibilityIdentifier("backup-restore")274                }275            }276        }277    }278279    private func readBackup(_ url: URL) {280        error = nil281        guard let text = readText(url, limit: 200 * 1024 * 1024) else { return }282        restoreText = text283        Task { await restore(key: nil) }284    }285286    private func restore(key: String?) async {287        guard let text = restoreText else { return }288        do {289            model.busy = true290            defer { model.busy = false }291            let n = try await model.engine.restoreBackup(text: text, recoveryKey: key)292            model.show("\(n) item\(n == 1 ? "" : "s") restored")293            restoreText = nil; askRestoreKey = false; restoreKey = ""294        } catch EngineError.backupNeedsRecoveryKey {295            askRestoreKey = true296        } catch { self.error = model.errorText(error); askRestoreKey = false }297    }298299    private var restoreKeySheet: some View {300        VStack(alignment: .leading, spacing: 14) {301            Text("Recovery key needed").font(.vaultTitle).foregroundStyle(Palette.text)302            Text("This backup was made under another account key. Enter the recovery key that was valid when the backup was created.").font(.callout).foregroundStyle(Palette.muted)303            TextField("SPV1-…", text: $restoreKey, axis: .vertical).lineLimit(2...4).textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("restore-key")304            HStack {305                Spacer()306                Button("Cancel") { askRestoreKey = false; restoreText = nil }.buttonStyle(.vaultSecondary)307                Button("Restore") { Task { await restore(key: restoreKey) } }.buttonStyle(.vaultPrimary).disabled((try? SPV1.decodeRecoveryKey(restoreKey)) == nil)308            }309        }310        .padding(22).frame(minWidth: 320, idealWidth: 460).background(Palette.s1)311    }312313    // ── account access ──314    private var accessSection: some View {315        SectionCard("Account access") {316            CardRow {317                HStack {318                    VStack(alignment: .leading, spacing: 2) {319                        Text("Recovery key").foregroundStyle(Palette.text)320                        Text("The only way back in when no trusted device is left. Issue a new one after using it, or if the printed kit may have been seen.").font(.caption).foregroundStyle(Palette.muted)321                            .fixedSize(horizontal: false, vertical: true)322                    }323                    Spacer()324                    Button("New recovery key…") {325                        confirm = ConfirmRequest(title: "Issue a new recovery key?", message: "The current recovery key stops working immediately. The new one is shown once: be ready to print it or write it down now.", confirmLabel: "Issue a new key", destructive: false) {326                            error = await model.perform {327                                let key = try await model.engine.rotateRecoveryKey()328                                model.setPhase(.recoveryKit(key: key, reason: .rotated))329                            }330                        }331                    }332                    .buttonStyle(.vaultCompact).accessibilityIdentifier("rotate-recovery")333                }334            }335            CardRow {336                HStack {337                    VStack(alignment: .leading, spacing: 2) {338                        Text("Passkeys").foregroundStyle(Palette.text)339                        Text("Passkeys sign you in to the server; they do not hold the vault key. Add one after a recovery if the old one is gone.").font(.caption).foregroundStyle(Palette.muted)340                            .fixedSize(horizontal: false, vertical: true)341                    }342                    Spacer()343                    Button("Add passkey") {344                        Task { error = await model.perform("Passkey added") { try await model.engine.addPasskey(label: AppEnvironment.deviceLabel) }; await loadPasskeys() }345                    }346                    .buttonStyle(.vaultCompact).accessibilityIdentifier("add-passkey")347                }348            }349            if let passkeys {350                ForEach(Array(passkeys.enumerated()), id: \.element.id) { i, p in351                    CardRow {352                        HStack {353                            Image(systemName: "person.badge.key").foregroundStyle(Palette.muted).accessibilityHidden(true)354                            VStack(alignment: .leading, spacing: 1) {355                                Text(p.label?.isEmpty == false ? p.label! : "Passkey").foregroundStyle(Palette.text)356                                Text("Added \(ItemMeta.date(p.createdAt)) · last used \(ItemMeta.relative(p.lastUsedAt))").font(.caption).foregroundStyle(Palette.muted)357                            }358                            Spacer()359                            if passkeys.count > 1 {360                                IconButton(systemName: "trash", label: "Remove this passkey", tint: Palette.danger) {361                                    confirm = ConfirmRequest(title: "Remove this passkey?", message: "It will no longer sign you in. Your other passkeys and your devices are not affected.", confirmLabel: "Remove passkey") {362                                        error = await model.perform("Passkey removed") { try await model.engine.removePasskey(id: p.id) }363                                        await loadPasskeys()364                                    }365                                }366                            }367                        }368                    }369                }370            }371            CardRow(last: true) {372                HStack {373                    VStack(alignment: .leading, spacing: 2) {374                        Text("Your account fingerprint").foregroundStyle(Palette.text)375                        Text("Read it to someone who is about to share with you, over another channel, so they can check the keys the server gave them.").font(.caption).foregroundStyle(Palette.muted)376                            .fixedSize(horizontal: false, vertical: true)377                    }378                    Spacer()379                    Text(fingerprint ?? "—").font(.system(.callout, design: .monospaced).weight(.semibold)).foregroundStyle(Palette.brass).textSelection(.enabled)380                        .accessibilityIdentifier("account-fingerprint")381                }382            }383        }384    }385386387388    /// Fingerprint of this account's public keys, to read to someone who is about to share with you.389    private var fingerprint: String? {390        guard let a = model.account, let sig = try? SPV1.unb64u(a.sigPub), let enc = try? SPV1.unb64u(a.encPub) else { return nil }391        return try? SPV1.accountFingerprint(sigPub: sig, encPub: enc)392    }393394    private func loadPasskeys() async { passkeys = try? await model.engine.listPasskeys() }395396    // ── this device ──397    private var deviceSection: some View {398        SectionCard("This device") {399            CardRow {400                HStack {401                    VStack(alignment: .leading, spacing: 2) {402                        Text("Sign out").foregroundStyle(Palette.text)403                        Text("Ends the server session and locks. The encrypted local copy stays; unlocking still works offline and the passkey is asked to sync again.").font(.caption).foregroundStyle(Palette.muted)404                            .fixedSize(horizontal: false, vertical: true)405                    }406                    Spacer()407                    Button("Sign out") { Task { await model.signOut() } }.buttonStyle(.vaultCompact).accessibilityIdentifier("signout")408                }409            }410            CardRow(last: true) {411                HStack {412                    VStack(alignment: .leading, spacing: 2) {413                        Text("Remove this device").foregroundStyle(Palette.text)414                        Text("Erases the device keys, the encrypted local copy and the AutoFill suggestions from this device.").font(.caption).foregroundStyle(Palette.muted)415                            .fixedSize(horizontal: false, vertical: true)416                    }417                    Spacer()418                    Button("Remove…") {419                        confirm = ConfirmRequest(title: "Remove this device?", message: "Everything SP Vault stored on this device is erased. Your account and your other devices are not affected. To come back you will need to pair this device again or use your recovery key. Also revoke it from another device (Devices) so the server forgets its keys.", confirmLabel: "Remove this device") {420                            await model.removeThisDevice()421                        }422                    }423                    .buttonStyle(VaultButtonStyle(kind: .danger, compact: true)).accessibilityIdentifier("forget-device")424                }425            }426        }427    }428429    // ── danger zone ──430    private var dangerSection: some View {431        SectionCard("Danger zone", footer: "A plaintext export contains every password in clear text. It needs a fresh confirmation with this device's key and is recorded in the activity log of every device.") {432            CardRow(last: true) {433                HStack {434                    Text("Export everything unencrypted").foregroundStyle(Palette.danger)435                    Spacer()436                    Menu("Export…") {437                        Button("CSV (logins)") { askPlaintext(.csv) }438                        Button("JSON (everything)") { askPlaintext(.json) }439                    }440                    .menuStyle(.button).buttonStyle(VaultButtonStyle(kind: .secondary, compact: true)).fixedSize().accessibilityIdentifier("export-plaintext")441                }442            }443        }444    }445446    private func askPlaintext(_ format: VaultEngine.ExportFormat) {447        confirm = ConfirmRequest(title: "Export in clear text?", message: "The file will contain every secret of your vaults, readable by anyone and by any app that can open it. Store it on an encrypted disk and delete it as soon as you are done.", confirmLabel: "Export in clear text", typed: "EXPORT") {448            error = await model.perform {449                let text = try await model.engine.exportPlaintext(format: format)450                exportType = format == .csv ? .commaSeparatedText : .json451                exportName = "sp-vault-PLAINTEXT-\(stamp).\(format.rawValue)"452                exportDoc = TextFileDocument(text: text)453            }454        }455    }456457    // ── about ──458    private var about: some View {459        SectionCard("About security") {460            CardRow(last: true) {461                VStack(alignment: .leading, spacing: 12) {462                    aboutBlock("What protects you", "Items, vault names, file names and attachments are encrypted on this device with keys the server never receives. Each device has its own key pair, certified by your account key; the server cannot enrol a device or read a vault on its own.")463                    aboutBlock("Why the native app", "This app is signed code installed on your device: the server cannot change it between two launches. The web app is delivered by the server each time it is opened, so a compromised server could serve altered code. Use the native apps for your most sensitive vaults.")464                    aboutBlock("What the server sees", "Your account handle; passkey and device public keys and platform labels; the number of vaults and who is a member of which; for each record an opaque identifier, its vault, a type tag, a revision count, the ciphertext length (rounded to 256 bytes), timestamps and which device wrote it; attachment sizes; IP addresses and timing. It never receives titles, addresses, usernames, passwords, notes, tags, one-time-code seeds, file names, vault names or search terms. Search runs entirely on this device.")465                    aboutBlock("What it cannot prevent", "A server can refuse service, delete data or withhold recent changes from a device that has not seen them. Rollbacks of data a device already saw are detected and reported in the Security Center. Revoking a device or removing a vault member cannot erase what they already downloaded.")466                    aboutBlock("Managed secrets are different", "Secrets placed under Connect & Agents are not end-to-end encrypted: the server decrypts them to act on your behalf.")467                    aboutBlock("Audit status", "The SPV1 protocol and this implementation have not yet been independently audited. The specification and the threat model are published with the source so that they can be reviewed.")468                    Text("SP Vault \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "") (\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "")) · \(AppEnvironment.relyingParty)\(AppEnvironment.isDev ? " · development build" : "")")469                        .font(.caption.monospaced()).foregroundStyle(Palette.muted)470                }471                .containerID("about-security")472            }473        }474    }475476    private func aboutBlock(_ title: String, _ text: String) -> some View {477        VStack(alignment: .leading, spacing: 3) {478            Text(title).font(.callout.weight(.semibold)).foregroundStyle(Palette.text)479            Text(text).font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)480        }481    }482}483
Files main
Menu

Theme