Cotton code
177 lines · 11.0 KB · SwiftRaw
import CottonKitimport CottonValuesimport SwiftUIimport XCTest@testable import CottonUI/// Cotton Vault on iPhone: the screens' answers read as the/// core publishes them (`keys::app::shapes`), the look's colours by role, and/// the one model sending each act back as it came: presence adds the vault key/// only where the method takes it, a shut vault asks the lock once, a trash/// goes back to the list with its Undo, and Sign out opens this device's own/// flow. Synthetic rows and keys only; no value is printed.@MainActorfinal class VaultAppTests: XCTestCase {    private static let scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"    private static let items = #"""    {"title":"Items","searchPlaceholder":"Search your vault","q":"","filter":"all",     "chips":[{"id":"all","label":"All","count":2,"on":true},{"id":"login","label":"Logins","count":2,"on":false}],     "sections":[{"id":"favourites","title":"Favourites","rows":[]},       {"id":"all","title":"All items","rows":[{"id":"i-1","kind":"login","title":"Invented Mail","subtitle":"ada@invented.test",         "picture":{"initials":"IM","tint":3},"favourite":true,"marks":[{"id":"weak","label":"Weak","tone":"danger"}],"badge":"Passkey",         "quick":[{"id":"copy_password","label":"Copy password","method":"vault.field","request":{"id":"i-1","field":"password"},"presence":true,"tone":"neutral"}]}]}],     "total":2,"bin":{"id":"bin","label":"Recently deleted · 1","method":"vault.items","request":{"filter":"bin"},"tone":"neutral"},     "add":{"label":"Add","kinds":[{"id":"login","label":"Login","method":"vault.edit","request":{"kind":"login"},"symbol":"login","tone":"neutral"}]},     "open":false}    """#    private static let item = #"""    {"id":"i-1","kind":"login","kindLabel":"Login","title":"Invented Mail","subtitle":"ada","picture":{"initials":"IM","tint":3},"favourite":false,     "blocks":[{"id":"fields","fields":[{"key":"password","label":"Password","concealed":true,"mono":true,        "acts":[{"id":"reveal","label":"Show","method":"vault.field","request":{"id":"i-1","field":"password"},"presence":true,"tone":"neutral"}]},       {"key":"totp","label":"One-time code","concealed":false,"mono":true,"liveCode":true,"acts":[]}]}],     "acts":[{"id":"trash","label":"Move to bin","method":"vault.act","request":{"act":"trash","id":"i-1"},"tone":"danger",        "confirm":{"title":"Move this to the bin?","body":"Kept 30 days.","yes":"Move to bin","no":"Keep it"}}],     "open":true,"inBin":false}    """#    // VaultModel is the iPhone's alone (its file is iOS-only); the shapes and    // the look are read on the Mac too.    #if os(iOS)    private func model(_ core: ScriptedCore) -> (VaultModel, ToastCenter) {        let toasts = ToastCenter()        let vault = VaultAccess(keyring: VaultKeyring(keys: InMemoryVaultKeyStore(seeded: Self.scalar), cache: InMemorySecretStore()), ask: { .allowed })        let unlock = UnlockAsks(core: core, vault: vault, say: { _, _ in })        let signIn = SignInAsks(core: core, vault: vault, say: { _, _ in })        return (VaultModel(core: core, toasts: toasts, unlockAsks: unlock, signInAsks: signIn, vault: vault), toasts)    }    #endif    private func decode<T: Decodable>(_ json: String, as type: T.Type) throws -> T {        try JSONDecoder().decode(type, from: Data(json.utf8))    }    /// RULE: The Items answer and an item read whole as the core shapes them: chips, sections, a row's marks, badge and quick acts, the bin and Add; a concealed field carries no value, a live code says so.    func testTheItemsAndAnItemReadAsTheCoreShapesThem() throws {        let items = try decode(Self.items, as: VaultItems.self)        XCTAssertEqual(items.chips.map(\.id), ["all", "login"])        let row = try XCTUnwrap(items.sections.last?.rows.first)        XCTAssertEqual(row.marks.map(\.tone), [.danger])        XCTAssertEqual(row.badge, "Passkey")        XCTAssertEqual(row.quick.first?.presence, true)        XCTAssertEqual(items.bin?.request["filter"]?.string, "bin")        XCTAssertEqual(items.add.kinds.first?.symbol, "login")        let item = try decode(Self.item, as: VaultItem.self)        let password = try XCTUnwrap(item.blocks.first?.fields.first)        XCTAssertTrue(password.concealed)        XCTAssertNil(password.value)        XCTAssertTrue(item.blocks.first?.fields.last?.liveCode ?? false)        XCTAssertEqual(item.acts.first?.confirm?.yes, "Move to bin")    }    /// RULE: The look's colours are read by role in the mode drawn, `#RRGGBB` and `#RRGGBBAA` alike; a face is the nearest weight it ships.    func testTheLookReadsColoursByRoleAndFacesByWeight() {        XCTAssertNotNil(Color(vaultHex: "#000000A3"))        XCTAssertNotNil(Color(vaultHex: "#FAFAFA"))        XCTAssertNil(Color(vaultHex: "#FFF"))        let look = VaultLook(fonts: [:], colours: ["light": ["text": "#09090B"], "dark": ["text": "#FAFAFA"]], type: [:], space: ["m": 12], corners: ["card": 16], roles: ["row_title": "text"])        XCTAssertEqual(look.colour("row_title", .dark), look.colour("text", .dark))        XCTAssertNotEqual(look.colour("text", .light), look.colour("text", .dark))        XCTAssertEqual(look.gap("m"), 12)        XCTAssertEqual(look.corner("card"), 16)        XCTAssertTrue(VaultFonts.postScriptName(family: "mono", weight: 700).contains("JetBrainsMono"))        XCTAssertTrue(VaultFonts.postScriptName(family: "sans", weight: 600).contains("Inter"))    }    #if os(iOS)    /// RULE: An act behind presence hands the vault key to a `vault.*` method as `privateKey`, and sends any other method (an open window's End now) as it came.    func testPresenceAddsTheKeyOnlyWhereTheMethodTakesIt() async throws {        let core = ScriptedCore([            "vault.field": .ok(#"{"id":"i-1","field":"password","value":"SYNTHETIC","mono":true,"clearAfter":60,"copiedToast":"Copied."}"#),            "unlock.end": .ok(#"{"ended":"g-1"}"#),        ])        let (model, toasts) = model(core)        let copy = VaultAct(id: "copy", label: "Copy", method: "vault.field", request: .object(["id": "i-1", "field": "password"]), presence: true)        await model.run(copy)        XCTAssertEqual(toasts.current?.message, "Copied.")        let end = VaultAct(id: "end", label: "End now", method: "unlock.end", request: .object(["grantId": "g-1"]), presence: true)        await model.run(end)        let calls = await core.calls        XCTAssertEqual(calls.map(\.method), ["vault.field", "unlock.end"])        XCTAssertTrue(calls[0].requestJSON.contains("privateKey"))        XCTAssertFalse(calls[1].requestJSON.contains("privateKey"))    }    /// RULE: A shut vault's refusal (`vault_locked`) asks the lock once and sends the same request again with the key.    func testAShutVaultAsksTheLockOnceAndSendsAgain() async {        let core = ScriptedCore(["vault.save": .refuse(code: "vault_locked", message: "Open your vault")])        let (model, _) = model(core)        let save = VaultAct(id: "save", label: "Save", method: "vault.save", request: .object(["kind": "login"]))        _ = await model.send(save, adding: ["fields": .object(["password": "SYNTHETIC"])])        let calls = await core.calls        XCTAssertEqual(calls.count, 2)        XCTAssertFalse(calls[0].requestJSON.contains("privateKey"))        XCTAssertTrue(calls[1].requestJSON.contains("privateKey"))    }    /// RULE: Move to bin answers `gone` and a toast with Undo: the item's screen goes back to the list and the receipt carries Undo.    func testATrashGoesBackToTheListWithItsUndo() async {        let core = ScriptedCore(["vault.act": .ok(#"{"act":"trash","id":"i-1","gone":true,"toast":{"text":"Moved to the bin.","undo":{"id":"undo","label":"Undo","method":"vault.act","request":{"act":"restore","id":"i-1"},"tone":"neutral"}}}"#)])        let (model, toasts) = model(core)        model.push(.item("i-1"))        let trash = VaultAct(id: "trash", label: "Move to bin", method: "vault.act", request: .object(["act": "trash", "id": "i-1"]), tone: .danger)        await model.run(trash)        XCTAssertEqual(model.paths[.secrets] ?? [], [])        XCTAssertEqual(toasts.current?.message, "Moved to the bin.")        XCTAssertNotNil(toasts.current?.undo)    }    /// RULE: Sign out answers this device's own flow (`platform_action: open_flow`), which the app's root runs.    func testSignOutOpensThisDevicesOwnFlow() async {        let core = ScriptedCore(["vault.act": .ok(#"{"act":"sign_out","platform":{"platform_action":"open_flow","flow":"signOut","origin":{"table":"device","id":"d-1"},"database":null}}"#)])        let (model, _) = model(core)        var ran: [RecordKeptFlow.Flow] = []        model.nativeFlow = { flow in            ran.append(flow.flow)            return true        }        await model.run(VaultAct(id: "sign_out", label: "Sign out", method: "vault.act", request: .object(["act": "sign_out"])))        XCTAssertEqual(ran, [.signOut])    }    /// RULE: An act with an `input` asks its one field in a panel first, then sends what was typed under the input's key (a trusted person's number).    func testAnActWithAnInputAsksItFirst() async {        let core = ScriptedCore(["recovery.trust": .ok(#"{"said":"Asked."}"#)])        let (model, _) = model(core)        var trust = VaultAct(id: "trust", label: "Choose", method: "recovery.trust", request: .object([:]), presence: true)        trust.input = VaultPrompt(key: "number", label: "Their phone number", input: "phone", placeholder: nil)        await model.run(trust)        XCTAssertEqual(model.sheet?.id, "input:trust")        let none = await core.calls        XCTAssertTrue(none.isEmpty)        await model.run(trust, adding: ["number": .string("+15550100")])        let calls = await core.calls        XCTAssertEqual(calls.map(\.method), ["recovery.trust"])        XCTAssertTrue(calls[0].requestJSON.contains("+15550100"))        XCTAssertTrue(calls[0].requestJSON.contains("privateKey"))    }    /// RULE: Check for breaches is two steps under one presence: the core names the ranges, the phone hands the bodies to `then` with the same lent key, and the core's toast is said.    func testTheBreachCheckSendsTheRangesBackWithTheSameKey() async {        let core = ScriptedCore([            "vault.breach": .ok(#"{"act":"breach","platform":{"action":"fetch_ranges","prefixes":[],"addresses":[],"headers":{"Add-Padding":"true"},"then":"vault.breachChecked"}}"#),            "vault.breachChecked": .ok(#"{"act":"breach","toast":{"text":"No breaches found."}}"#),        ])        let (model, toasts) = model(core)        await model.run(VaultAct(id: "check", label: "Check for breaches", method: "vault.breach", request: .object([:]), presence: true))        let calls = await core.calls        XCTAssertEqual(calls.map(\.method), ["vault.breach", "vault.breachChecked"])        XCTAssertTrue(calls[0].requestJSON.contains("privateKey"))        XCTAssertTrue(calls[1].requestJSON.contains("privateKey"))        XCTAssertTrue(calls[1].requestJSON.contains("ranges"))        XCTAssertEqual(toasts.current?.message, "No breaches found.")    }    #endif}