SPB Git

Repository Public

SPVaultApp.swift 10.1 KB 211 lines swift

1// SP Vault for macOS: one main window, a menu bar extra, menu commands, and the Mac-specific security behaviours2// (lock on sleep / screen lock, hide from screen capture, blur when inactive).3import AppKit4import CoreSpotlight5import SharedVaultKit6import SwiftUI78@main9struct SPVaultApp: App {10    @NSApplicationDelegateAdaptor(MacAppDelegate.self) private var delegate11    @State private var model = AppModel.shared1213    var body: some Scene {14        Window(AppEnvironment.isDev ? "SP Vault Dev" : "SP Vault", id: "main") {15            RootView()16                .environment(model)17                .background(WindowPrivacy(hidden: captureHidden))18                .overlay { if model.covered && model.isUnlocked { PrivacyCover() } }19                .onContinueUserActivity(CSSearchableItemActionType) { activity in20                    if let id = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { SpotlightIndex.open(id, in: model) }21                }22        }23        .defaultSize(width: 1180, height: 760)24        .commands { VaultCommands(model: model) }2526        MenuBarExtra {27            MenuBarView().environment(model)28        } label: {29            Image(systemName: model.isUnlocked ? "lock.open.fill" : "lock.fill").accessibilityLabel("SP Vault")30        }31        .menuBarExtraStyle(.window)32    }3334    private var captureHidden: Bool {35        #if SPV_DEV36        if DevSupport.env["SPV_DEV_ALLOW_CAPTURE"] == "1" { return false }37        #endif38        return model.prefs.hideFromCapture39    }40}4142/// Content shown instead of the vault while the app is not active (when "hide from screen capture" is on).43struct PrivacyCover: View {44    var body: some View {45        ZStack {46            Rectangle().fill(.ultraThinMaterial)47            VStack(spacing: 12) {48                BrandMark(size: 40)49                Text("Hidden while SP Vault is in the background").font(.callout).foregroundStyle(Palette.muted)50            }51        }52        .ignoresSafeArea()53        .containerID("privacy-cover")54    }55}5657/// Applies `NSWindow.sharingType`: `.none` keeps the window out of screenshots, recordings and screen sharing.58private struct WindowPrivacy: NSViewRepresentable {59    let hidden: Bool60    func makeNSView(context: Context) -> NSView { NSView() }61    func updateNSView(_ view: NSView, context: Context) {62        let hidden = hidden63        DispatchQueue.main.async { view.window?.sharingType = hidden ? .none : .readOnly }64    }65}6667struct MainView: View {68    var body: some View { SplitMainView() }69}7071// ── menus ──7273struct VaultCommands: Commands {74    let model: AppModel75    @Environment(\.openWindow) private var openWindow7677    var body: some Commands {78        CommandGroup(replacing: .appSettings) {79            Button("Settings…") { openWindow(id: "main"); if model.isUnlocked { model.section = .settings } }80                .keyboardShortcut(",", modifiers: .command).disabled(!model.isUnlocked)81        }82        CommandGroup(replacing: .newItem) {83            Button("New Item") { openWindow(id: "main"); model.newItem() }.keyboardShortcut("n", modifiers: .command).disabled(!model.isUnlocked)84            Menu("New") {85                ForEach(ItemType.allCases, id: \.self) { t in Button(t.template.label) { openWindow(id: "main"); model.newItem(t) } }86            }87            .disabled(!model.isUnlocked)88        }89        CommandMenu("Item") {90            // ⌘C stays the standard Copy while text is selected (Edit ▸ Copy comes first); otherwise it copies the password.91            Button("Copy Password") { model.copyPassword() }.keyboardShortcut("c", modifiers: .command).disabled(model.selectedItem == nil)92            Button("Copy Username") { model.copyUsername() }.keyboardShortcut("c", modifiers: [.command, .shift]).disabled(model.selectedItem == nil)93            Button("Copy One-Time Code") { model.copyOneTimeCode() }.keyboardShortcut("c", modifiers: [.command, .option]).disabled(model.selectedItem == nil)94            Divider()95            Button("Edit Item") { if let v = model.selectedItem { model.edit(v) } }.keyboardShortcut("e", modifiers: .command).disabled(model.selectedItem == nil)96            Button(model.selectedItem?.item.favorite == true ? "Remove from Favorites" : "Add to Favorites") { if let v = model.selectedItem { Task { await model.toggleFavorite(v) } } }97                .keyboardShortcut("d", modifiers: .command).disabled(model.selectedItem == nil)98            Button("Move to Trash") { if let v = model.selectedItem { Task { await model.trash(v) } } }99                .keyboardShortcut(.delete, modifiers: .command).disabled(model.selectedItem == nil || !(model.selectedItem?.item.trashedAt ?? "").isEmpty)100        }101        CommandMenu("Vault") {102            Button("Find") { openWindow(id: "main"); model.searchFocusTick += 1 }.keyboardShortcut("f", modifiers: .command).disabled(!model.isUnlocked)103            Button("Sync Now") { Task { await model.syncNow() } }.keyboardShortcut("r", modifiers: .command).disabled(!model.isUnlocked)104            Divider()105            Button("Generator") { openWindow(id: "main"); model.section = .generator }.keyboardShortcut("g", modifiers: [.command, .shift]).disabled(!model.isUnlocked)106            Button("Security Center") { openWindow(id: "main"); model.section = .security }.disabled(!model.isUnlocked)107            Divider()108            Button("Lock") { model.lock() }.keyboardShortcut("l", modifiers: .command).disabled(!model.isUnlocked)109        }110    }111}112113// ── app delegate: activity, sleep, screen lock ──114115@MainActor116final class MacAppDelegate: NSObject, NSApplicationDelegate {117    private var monitor: Any?118    private var observers: [NSObjectProtocol] = []119120    func applicationDidFinishLaunching(_ notification: Notification) {121        let model = AppModel.shared122        monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .rightMouseDown, .scrollWheel]) { event in123            MainActor.assumeIsolated { AppModel.shared.touch() }124            return event125        }126        let lock: @Sendable (Notification) -> Void = { _ in127            Task { @MainActor in if AppModel.shared.prefs.lockOnSleep { AppModel.shared.lock() } }128        }129        let ws = NSWorkspace.shared.notificationCenter130        for name in [NSWorkspace.willSleepNotification, NSWorkspace.screensDidSleepNotification, NSWorkspace.sessionDidResignActiveNotification] {131            observers.append(ws.addObserver(forName: name, object: nil, queue: .main, using: lock))132        }133        let dn = DistributedNotificationCenter.default()134        for name in ["com.apple.screenIsLocked", "com.apple.screensaver.didstart"] {135            observers.append(dn.addObserver(forName: Notification.Name(name), object: nil, queue: .main, using: lock))136        }137        let nc = NotificationCenter.default138        observers.append(nc.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { _ in139            Task { @MainActor in AppModel.shared.covered = AppModel.shared.prefs.hideFromCapture && !MacAppDelegate.captureAllowedForDev }140        })141        observers.append(nc.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ in142            Task { @MainActor in AppModel.shared.covered = false }143        })144        model.onItemsChanged = { items in SpotlightIndex.update(items, enabled: AppModel.shared.prefs.spotlightTitles) }145    }146147    static var captureAllowedForDev: Bool {148        #if SPV_DEV149        return DevSupport.env["SPV_DEV_ALLOW_CAPTURE"] == "1"150        #else151        return false152        #endif153    }154155    /// The app keeps running in the menu bar when its window is closed.156    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }157158    func application(_ application: NSApplication, open urls: [URL]) { urls.forEach { AppModel.shared.open(url: $0) } }159}160161// ── Spotlight (opt-in, titles only) ──162163enum SpotlightIndex {164    static let domain = "ai.spboucher.spvault.items"165166    /// Replaces the index with the titles of the items (nothing else), or erases it when the option is off.167    @MainActor168    static func update(_ items: [ItemView], enabled: Bool) {169        let entries: [(id: String, title: String, kind: String)] = enabled170            ? items.filter { ($0.item.trashedAt ?? "").isEmpty }.map { ($0.id, ItemMeta.displayTitle($0.item), $0.item.type.template.label) } : []171        Task.detached(priority: .utility) {172            let index = CSSearchableIndex.default()173            try? await index.deleteSearchableItems(withDomainIdentifiers: [domain])174            guard !entries.isEmpty else { return }175            try? await index.indexSearchableItems(entries.map { e in176                let attrs = CSSearchableItemAttributeSet(contentType: .item)177                attrs.title = e.title178                attrs.contentDescription = "SP Vault · \(e.kind)"179                return CSSearchableItem(uniqueIdentifier: e.id, domainIdentifier: domain, attributeSet: attrs)180            })181        }182    }183184    @MainActor185    static func open(_ id: String, in model: AppModel) {186        guard model.isUnlocked else { return } // locked: the user unlocks first; nothing is revealed from Spotlight187        model.reveal(id)188    }189}190191// ── printing the recovery kit ──192193enum RecoveryKitPrinter {194    @MainActor195    static func print(recoveryKey: String, handle: String) {196        let page = RecoveryKitSheet(recoveryKey: recoveryKey, handle: handle, server: AppEnvironment.relyingParty)197            .frame(width: 520, height: 700).environment(\.colorScheme, .light)198        let view = NSHostingView(rootView: page)199        view.frame = NSRect(x: 0, y: 0, width: 520, height: 700)200        let info = NSPrintInfo.shared.copy() as? NSPrintInfo ?? NSPrintInfo()201        info.horizontalPagination = .fit202        info.verticalPagination = .fit203        info.isHorizontallyCentered = true204        info.topMargin = 36; info.bottomMargin = 36; info.leftMargin = 36; info.rightMargin = 36205        let op = NSPrintOperation(view: view, printInfo: info)206        op.jobTitle = "SP Vault recovery kit"207        op.showsPrintPanel = true208        if let window = NSApp.keyWindow { op.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil) } else { op.run() }209    }210}211
Files main
Menu

Theme