SPB Git

Repository Public

DevScenario.swift 12.7 KB 212 lines swift

1// SP Vault Dev — scripted scenarios (SPV_DEV only, never in Release).2//3// macOS UI testing (XCUITest) needs "Automation Mode", which asks for an administrator authentication on this4// Mac. Where that is not available, the Dev app can run a scenario by itself: the steps below go through the same5// AppModel and engine calls the buttons make, against the real local server, and the app pictures its own window.6// It is NOT a click-level UI test; Scripts/mac-scenarios.sh says so in its output.7//8//   SPV_DEV_SCENARIO      steps separated by ";"  (see `run(step:)`)9//   SPV_DEV_SCENARIO_LOG  file receiving one line per step: "ok <step>" or "FAIL <step>: <reason>"10#if SPV_DEV11import Foundation12import SharedVaultKit13import SwiftUI14#if os(macOS)15import AppKit16#endif1718@MainActor19enum DevScenario {20    struct Failure: Error, CustomStringConvertible { let description: String }2122    static func runIfAsked(_ model: AppModel) {23        guard let script = DevSupport.env["SPV_DEV_SCENARIO"], !script.isEmpty else { return }24        Task {25            for step in script.split(separator: ";").map({ $0.trimmingCharacters(in: .whitespaces) }) where !step.isEmpty {26                if step == "quit" { log("done") }27                do { try await run(step: step, model); log("ok \(step)") }28                catch { log("FAIL \(step): \(error)"); break }29            }30            log("done")31        }32    }3334    private static func log(_ line: String) {35        guard let path = DevSupport.env["SPV_DEV_SCENARIO_LOG"] else { return }36        let url = URL(fileURLWithPath: path)37        let old = (try? String(contentsOf: url, encoding: .utf8)) ?? ""38        try? (old + line + "\n").write(to: url, atomically: true, encoding: .utf8)39    }4041    private static func wait(_ what: String, seconds: Double = 60, _ condition: () async -> Bool) async throws {42        let end = Date().addingTimeInterval(seconds)43        while Date() < end {44            if await condition() { return }45            try await Task.sleep(for: .milliseconds(300))46        }47        throw Failure(description: "timed out waiting for \(what)")48    }4950    private static func check(_ ok: Bool, _ what: String) throws { if !ok { throw Failure(description: what) } }51    private static func readFile(_ path: String) -> String? { try? String(contentsOfFile: path, encoding: .utf8) }5253    private static func login(_ title: String, user: String, password: String, totp: String? = nil, url: String? = nil) -> Item {54        var it = SPV1.newItem(.login, title: title)55        it.fields = ["username": user, "password": password]56        if let totp { it.fields["totp"] = totp }57        if let url { it.urls = [ItemUrl(url: url, match: .domain)] }58        return it59    }6061    private static func run(step: String, _ model: AppModel) async throws {62        let parts = step.split(separator: ":", maxSplits: 1).map(String.init)63        let arg = parts.count > 1 ? parts[1] : ""64        switch parts[0] {65        case "ready":66            try await wait("the first screen") { model.phase != .loading }67        case "join": // join:<invites file>|<account file>68            let files = arg.split(separator: "|").map(String.init)69            var lines = (readFile(files[0]) ?? "").split(separator: "\n").map(String.init)70            try check(!lines.isEmpty, "no invitation left")71            let invite = lines.removeFirst()72            try lines.joined(separator: "\n").write(toFile: files[0], atomically: true, encoding: .utf8)73            let handle = "mac" + String(UUID().uuidString.lowercased().filter { $0.isLetter || $0.isNumber }.prefix(8))74            try check(model.phase == .welcome, "expected the welcome screen, got \(model.phase)")75            model.setPhase(.join(invite: invite))76            if let e = await model.register(invite: invite, handle: handle) { throw Failure(description: e) }77            guard case .recoveryKit(let key, _) = model.phase else { throw Failure(description: "no recovery kit shown") }78            try "\(handle)\n\(key)\n".write(toFile: files[1], atomically: true, encoding: .utf8)79        case "kit-done":80            model.finishRecoveryKit()81            try check(model.phase == .main, "not in the main screen")82        case "seed":83            try await wait("the personal vault") { model.defaultVaultId != nil }84            guard let vault = model.defaultVaultId else { throw Failure(description: "no vault") }85            try await model.engine.saveItem(vaultId: vault, item: login("Example Bank", user: "ada@example.com", password: "correct-horse-ZQ9-battery", totp: "JBSWY3DPEHPK3PXP", url: "https://bank.example.com"))86            try await model.engine.saveItem(vaultId: vault, item: login("Pocket Mail", user: "mob@example.com", password: "m0bile-Only-pass!word-9", url: "https://mail.example.com"))87            var card = SPV1.newItem(.card, title: "Personal Visa")88            card.fields = ["holder": "Ada Example", "number": "4111111111111111", "expiry": "12/29", "cvv": "123"]89            try await model.engine.saveItem(vaultId: vault, item: card)90            var note = SPV1.newItem(.note, title: "Alarm code")91            note.notes = "Front door 4-digit code is in the safe."92            note.favorite = true93            try await model.engine.saveItem(vaultId: vault, item: note)94            try await wait("the items") { model.items.count >= 4 }95        case "create": // create:<title>96            guard let vault = model.defaultVaultId else { throw Failure(description: "no vault") }97            try await model.engine.saveItem(vaultId: vault, item: login(arg, user: "sync@example.com", password: "sync-both-ways-1"))98        case "wait-item": // wait-item:<title>99            try await wait("item \(arg)", seconds: 240) { model.items.contains { $0.item.title == arg } }100        case "select": // select:<title>101            try await wait("item \(arg)", seconds: 20) { model.items.contains { $0.item.title == arg } }102            guard let v = model.items.first(where: { $0.item.title == arg }) else { throw Failure(description: "no item \(arg)") }103            model.section = .allItems104            model.selectedItemID = v.id105        case "section":106            let map: [String: SidebarSection] = ["all": .allItems, "security": .security, "devices": .devices, "settings": .settings, "generator": .generator, "activity": .activity, "connect": .connect, "shared": .shared, "vaults": .vaults, "trash": .trash]107            guard let s = map[arg] else { throw Failure(description: "unknown section") }108            model.selectedItemID = nil109            model.section = s110        case "search":111            model.query = arg112            if !arg.isEmpty { try check(!model.items(in: .allItems).isEmpty, "search found nothing") }113        case "favorite-trash-restore": // on <title>114            guard let v = model.items.first(where: { $0.item.title == arg }) else { throw Failure(description: "no item \(arg)") }115            await model.toggleFavorite(v)116            try await wait("favorite") { model.item(v.id)?.item.favorite == true }117            await model.trash(v)118            try await wait("trash") { model.count(in: .trash) == 1 }119            if let t = model.item(v.id) { await model.restore(t) }120            try await wait("restore") { model.count(in: .trash) == 0 }121        case "copy-password":122            model.copyPassword()123            #if os(macOS)124            guard let v = model.selectedItem else { throw Failure(description: "nothing selected") }125            try check(NSPasteboard.general.string(forType: .string) == SPV1.primarySecret(v.item), "pasteboard does not hold the password")126            try check(NSPasteboard.general.types?.contains { $0.rawValue == "org.nspasteboard.ConcealedType" } == true, "copied secret not marked concealed")127            #endif128        case "import": // import:<csv path>129            guard let text = readFile(arg), let vault = model.defaultVaultId else { throw Failure(description: "cannot read \(arg)") }130            let parsed = try SPV1.importAny(fileName: (arg as NSString).lastPathComponent, text: text)131            try await model.engine.importItems(vaultId: vault, items: parsed.items)132            try await wait("the imported items") { model.items.filter { $0.item.title.hasPrefix("Imported") || $0.item.title == "Old Router" }.count >= parsed.items.count }133            let findings = SPV1.analyze(model.items.map { (id: $0.id, item: $0.item) }).map(\.kind)134            try check(findings.contains("weak") && findings.contains("reused"), "expected weak and reused findings, got \(Set(findings))")135        case "lock":136            model.lock()137            try await wait("locked") { model.phase == .locked }138            try check(model.items.isEmpty, "decrypted items still in memory after lock")139        case "unlock":140            try await wait("the locked screen") { model.phase == .locked }141            await model.unlock()142            try check(model.phase == .main, "unlock failed: \(model.notice ?? "")")143        case "recover": // recover:<account file>144            let lines = (readFile(arg) ?? "").split(separator: "\n").map(String.init)145            try check(lines.count >= 2, "no account file")146            try check(model.phase == .welcome, "expected the welcome screen")147            if let e = await model.recover(handle: lines[0], recoveryKey: lines[1]) { throw Failure(description: e) }148            try check(model.phase == .main, "not unlocked after recovery")149        case "approve": // approve:<pairing file>   (code on line 1, 6-digit fingerprint on line 2)150            var lines: [String] = []151            try await wait("the pairing code of the new device", seconds: 300) {152                lines = (readFile(arg) ?? "").split(separator: "\n").map(String.init)153                return lines.count >= 2154            }155            let req = try await model.engine.inspectPairing(code: lines[0])156            try check(req.sas == lines[1], "fingerprint mismatch: \(req.sas) here, \(lines[1]) on the new device")157            try await model.engine.approvePairing(req)158        case "write": // write:<file>159            try "ok\n".write(toFile: arg, atomically: true, encoding: .utf8)160        case "sleep":161            try await Task.sleep(for: .seconds(Double(arg) ?? 1))162        case "shot": // shot:<png path>   asks Scripts/mac-scenarios.sh for a real capture of the window; falls back to drawing it163            try await Task.sleep(for: .milliseconds(900))164            #if os(macOS)165            NSApp.activate(ignoringOtherApps: true)166            try? FileManager.default.removeItem(atPath: arg)167            try "shot\n".write(toFile: arg + ".request", atomically: true, encoding: .utf8)168            do { try await wait("the capture", seconds: 15) { FileManager.default.fileExists(atPath: arg) && !FileManager.default.fileExists(atPath: arg + ".request") } }169            catch { try? FileManager.default.removeItem(atPath: arg + ".request"); try shot(to: arg) }170            #endif171        case "shot-menubar":172            #if os(macOS)173            try await Task.sleep(for: .milliseconds(300))174            try shotMenuBar(to: arg, model)175            #endif176        case "quit":177            #if os(macOS)178            NSApp.terminate(nil)179            #endif180        default: throw Failure(description: "unknown step")181        }182    }183184    #if os(macOS)185    private static func write(_ view: NSView, to path: String) throws {186        guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { throw Failure(description: "cannot draw the window") }187        view.cacheDisplay(in: view.bounds, to: rep)188        guard let png = rep.representation(using: .png, properties: [:]) else { throw Failure(description: "cannot encode the picture") }189        try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)190        try png.write(to: URL(fileURLWithPath: path))191    }192193    private static func shot(to path: String) throws {194        guard let window = NSApp.windows.first(where: { $0.isVisible && $0.contentView != nil && $0.frame.width > 400 }), let frameView = window.contentView?.superview ?? window.contentView else {195            throw Failure(description: "no window")196        }197        try write(frameView, to: path)198    }199200    /// The menu bar panel exists only while it is open; this draws the same view off screen.201    private static func shotMenuBar(to path: String, _ model: AppModel) throws {202        let host = NSHostingView(rootView: MenuBarView().environment(model).preferredColorScheme(DevSupport.appearance == "light" ? .light : .dark))203        host.frame = NSRect(origin: .zero, size: host.fittingSize)204        let window = NSWindow(contentRect: host.frame, styleMask: [.borderless], backing: .buffered, defer: false)205        window.contentView = host206        host.layoutSubtreeIfNeeded()207        try write(host, to: path)208    }209    #endif210}211#endif212
Files main
Menu

Theme