importCottonKitimportCottonValuesimport XCTest@testable importCottonUI/// Cotton Secrets' sharing on iPhone (launch-ios, CONTRACT row 17): each `secrets.*` answer reads as the core shapes it/// (crates/cotton-ffi/src/phone/secrets_app.rs), a refusal comes back in the core's words for the screen to say in/// place, a share goes behind the phone's lock with the vault key, Bring in from Dashlane opens Secrets' own page, and/// the counted words read from the `secrets` set. Invented people and secrets only; no value is printed.#if os(iOS)@MainActorfinalclassSecretsSharingTests: XCTestCase {privatestaticlet scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"privatefunc 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) }privatefunc decode<T: Decodable>(_ json: String, as type: T.Type) throws -> T {try JSONDecoder().decode(type, from: Data(json.utf8)) }/// RULE: People, one person and who holds what read as the core answers them: waiting first, the checked line, holds now and before, Take back all as an act.func testPeopleAndOnePersonReadAsTheCoreAnswersThem() throws {let people = try decode(#""" {"title":"People","people":[{"number":"+910000000001","name":"Ravi Invented","line":"Holds 1 of yours","checked":true,"holds":1,"shares":0,"waiting":true}], "byPerson":"By person","bySecret":"By secret"} """#, as: SecretsPeople.self) XCTAssertEqual(people.people.first?.waiting, true) XCTAssertNil(people.empty)let empty = try decode(#"{"title":"People","people":[],"empty":{"title":"No people yet","line":"Add someone inComms."}}"#, as: SecretsPeople.self) XCTAssertEqual(empty.empty?.title, "No people yet")let person = try decode(#""" {"number":"+910000000001","name":"Ravi Invented","checked":false,"checkedLine":"Not checked yet", "now":[{"share":"s1","secretId":"i-1","secret":"Invented Mail","number":"+910000000001","may":"copy","until":null,"opens":3,"lastOpen":null,"state":"holds","line":"See and copy · until 30 Nov · opened 3 times"}], "nowTitle":"Holds 1 of yours","before":[],"beforeTitle":"Had before","theirs":[{"share":"t1","title":"Netflix","kind":"login"}],"theirsTitle":"Shares with you","none":"Nothing.", "takeAll":{"label":"Take back all 1","method":"secrets.take","request":{"number":"+910000000001","all":true}}} """#, as: SecretsPersonPage.self) XCTAssertEqual(person.now.first?.opens, 3) XCTAssertEqual(person.takeAll?.act()?.method, "secrets.take") XCTAssertEqual(person.takeAll?.act()?.request["all"], .bool(true))let held = try decode(#""" {"rows":[{"id":"i-2","title":"AWS deploy key","kind":"api_key","line":"Still known to Arjun","holders":[],"stillKnown":true, "act":{"label":"Change it","method":"vault.item","request":{"id":"i-2"}}}],"line":"1 of your 11 secrets are with someone else."} """#, as: SecretsHeld.self) XCTAssertTrue(held.rows[0].stillKnown) }/// RULE: The check, the share plan, who holds it with its still-known block, and the take back plan read whole; the plan's defaults are its own.func testCheckShareHoldersAndTakeBackReadWhole() throws {let check = try decode(#""" {"number":"+910000000001","title":"Check Ravi","line":"Do this once.","words":["amber","otter","quill","harbor","maple","drift"],"wordsLine":"Read these six words.", "a11y":"The six words: amber, otter","qr":"cotton-secrets:check:invented","scan":"Scan their code","show":"Show my code","match":"They match","noMatch":"They don't match", "checked":false,"changed":true,"changedLine":"Ravi's key changed."} """#, as: SecretsCheck.self) XCTAssertEqual(check.words.count, 6) XCTAssertTrue(check.changed)let plan = try decode(#""" {"id":"i-1","title":"Share Invented Mail","with":"With","people":[{"number":"+910000000001","name":"Ravi","checked":true,"line":"Checked"}], "may":[{"id":"see","label":"See it","line":"Read it","default":false},{"id":"copy","label":"See and copy","line":"Copy it","default":true}],"mayTitle":"They may", "until":[{"id":"day","label":"A day","default":false},{"id":"week","label":"A week","default":true},{"id":"date","label":"Pick a date","default":false}],"untilTitle":"Until", "empty":{"title":"No people yet","line":"Add someone in Comms."}} """#, as: SecretsSharePlan.self) XCTAssertEqual(plan.may.first(where: \.isDefault)?.id, "copy") XCTAssertEqual(plan.until.first(where: \.isDefault)?.id, "week")let holders = try decode(#""" {"id":"i-2","title":"Who holds it","holders":[{"share":"s2","secretId":"i-2","secret":"AWS deploy key","number":"+910000000002","may":"see","until":null,"opens":1,"lastOpen":null,"state":"still_known","line":"Still known: not changed yet","name":"Arjun"}], "none":"Only you.","stillKnown":{"title":"Still known to Arjun","stepsTitle":"Change it at AWS", "steps":[{"id":"open","label":"Open AWS","url":"https://console.aws.amazon.com/iam"},{"id":"make","label":"Make a new one there"},{"id":"paste","label":"Paste the new one here","method":"vault.edit","request":{"id":"i-2"}}], "changed":{"label":"I changed it","method":"secrets.changed","request":{"id":"i-2"}},"remind":{"label":"Remind me tonight","platform":"remind_tonight"}}} """#, as: SecretsHolders.self) XCTAssertEqual(holders.holders.first?.name, "Arjun") XCTAssertEqual(holders.stillKnown?.steps.map(\.id), ["open", "make", "paste"]) XCTAssertEqual(holders.stillKnown?.remind.platform, "remind_tonight") XCTAssertNil(holders.stillKnown?.remind.act())let take = try decode(#""" {"id":"i-1","number":"+910000000001","title":"Take back Invented Mail from Ravi?","does":"Their copy is deleted.","after":"Ravi opened it 3 times.", "others":[{"number":"+910000000003","name":"Neha","line":"Neha keeps their copy","detail":"They'll get the new one.","also":"Take it back from Neha too"}],"go":"Take it back"} """#, as: SecretsTakePlan.self) XCTAssertEqual(take.others.first?.also, "Take it back from Neha too") }/// RULE: Shared with him, an ask, what sits above the list and the Dashlane plan read whole; a shared secret's fields carry no value.func testSharedWithHimAsksNeedsAndImportReadWhole() throws {let shared = try decode(#""" {"share":"t1","title":"Netflix","kind":"login","site":"netflix.example","username":"family@example.invalid","from":"From Priya","whose":"This stays Priya's.", "may":"You may see it","mayCopy":false,"until":"Until 2 Dec","fields":[{"key":"username","concealed":true},{"key":"password","concealed":true}], "offline":"Opening needs a connection.","longer":{"label":"Ask Priya for longer","method":"secrets.shared.longer","request":{"share":"t1"}}, "remove":{"label":"Remove from my list","method":"secrets.shared.remove","request":{"share":"t1"}},"secure":true} """#, as: SecretsShared.self) XCTAssertTrue(shared.secure) XCTAssertEqual(shared.fields.map(\.key), ["username", "password"])let asks = try decode(#""" {"rows":[{"ask":"a1","from":"+910000000001","title":"Ravi asks","what":"the Play Console login","why":null,"longer":false,"line":"Ravi asks for the Play Console login", "suggest":{"id":"i-9","title":"Google Play Console","line":"The secret you probably mean","change":"Change"},"share":"Share with Ravi","no":"Say no","reply":"Reply in Comms","until":"day"}], "none":"No asks."} """#, as: SecretsAsks.self) XCTAssertEqual(asks.rows.first?.suggest?.id, "i-9") XCTAssertEqual(asks.rows.first?.until, "day")let needs = try decode(#"{"rows":[{"kind":"ask","line":"Ravi asks for x","act":{"label":"Answer","method":"secrets.asks","request":{"ask":"a1"}}},{"kind":"still_known","title":"AWS deploy key","line":"Still known to Arjun","act":{"label":"Change it","method":"vault.item","request":{"id":"i-2"}}}]}"#, as: SecretsNeeds.self) XCTAssertEqual(needs.rows.map(\.kind), ["ask", "still_known"])let plan = try decode(#""" {"title":"Bring in from Dashlane","steps":"In Dashlane…","found":"Found 9 to bring in", "kinds":[{"kind":"card","count":1,"label":"Cards"},{"kind":"note","count":1,"label":"Notes"},{"kind":"login","count":4,"label":"Passwords"},{"kind":"identity","count":3,"label":"Notes"}], "lost":"Passkeys do not come across.","go":"Bring in 9","after":"Afterwards, delete the CSV files.","skipped":0,"unknown":[],"notDashlane":null} """#, as: SecretsImportPlan.self)let rows = SecretsImportPage.byLabel(plan.kinds) XCTAssertEqual(rows.map(\.label), ["Cards", "Notes", "Passwords"]) XCTAssertEqual(rows.map(\.count), [1, 4, 4]) }/// RULE: A sharing read that is refused comes back in the core's words, said in its place and never as a toast.func testARefusedReadComesBackInTheCoresWords() async {let core = ScriptedCore(["secrets.people": .refuse(code: "offline", message: "You're offline.")])let (model, toasts) = model(core)guardcase .refused(let line) = await model.secrets("secrets.people", as: SecretsPeople.self) else { return XCTFail("a refusal reads as refused") } XCTAssertEqual(line, "You're offline.") XCTAssertNil(toasts.current) }/// RULE: A share goes behind the phone's lock and carries the vault key; a take back carries none.func testAShareCarriesTheVaultKeyAndATakeBackDoesNot() async {let core = ScriptedCore(["secrets.share": .ok(#"{"share":"s9","line":"Shared with Ravi."}"#),"secrets.take": .ok(#"{"taken":1,"lines":["Taken back from Ravi."]}"#), ])let (model, _) = model(core)let done = await model.secretsSend("secrets.share", ["id": "i-1", "number": "+910000000001", "may": "copy", "until": "week"], presence: true, as: SecretsShareDone.self) XCTAssertEqual(done?.line, "Shared with Ravi.") _ = await model.secretsSend("secrets.take", ["id": "i-1", "numbers": .array(["+910000000001"])], as: SecretsTaken.self)let calls = await core.calls XCTAssertTrue(calls[0].requestJSON.contains("privateKey")) XCTAssertFalse(calls[1].requestJSON.contains("privateKey")) }/// RULE: Bring in from Dashlane opens Secrets' own page, and an ask above the list opens its answer; neither sends anything.func testDashlaneAndAnAskOpenTheirOwnPages() async {let core = ScriptedCore([:])let (model, _) = model(core)await model.run(VaultAct(id: "import", label: "From Dashlane", method: "vault.act", request: .object(["act": "import", "from": "dashlane"]))) XCTAssertEqual(model.sheet?.id, "dashlane")await model.run(VaultAct(id: "ask", label: "Answer", method: "secrets.asks", request: .object(["ask": "a1"]))) XCTAssertEqual(model.sheet?.id, "answer:a1")let calls = await core.calls XCTAssertTrue(calls.isEmpty) }/// RULE: A counted line reads its one or other form from the `secrets` set, with its number.func testCountedWordsReadTheirForm() { XCTAssertEqual(SecretsWords.count("list.search", 1), ShellLines.line("secrets", "list.search.one", ["n": "1"])) XCTAssertEqual(SecretsWords.count("list.search", 11), ShellLines.line("secrets", "list.search.other", ["n": "11"])) XCTAssertFalse(SecretsWords.count("list.search", 11).hasPrefix("secrets.")) }}#endif