Cotton code
361 lines · 22.9 KB · SwiftRaw
import CottonKitimport XCTest@testable import CottonUI/// A business app against its business's object (`business.*`): the/// credential lives in the Keychain and goes nowhere but the request's/// `credential` field, the object decides every act, and the phone draws what/// the core answers.@MainActorfinal class BusinessClientTests: XCTestCase {    private func client(_ core: BusinessFake, _ store: InMemorySecretStore = InMemorySecretStore()) -> BusinessClient {        BusinessClient(core: core, address: BusinessFake.address, store: store)    }    private func model(_ core: BusinessFake, _ store: InMemorySecretStore = InMemorySecretStore()) -> HomeCustomerModel {        HomeCustomerModel(client: client(core, store), business: "Synthetic Studio", zone: "Asia/Kolkata")    }    /// Signed in on `store`, as an earlier launch left it.    private func signedIn(_ core: BusinessFake, _ store: InMemorySecretStore) async throws {        let client = client(core, store)        let challenge = try await client.askCode(phone: "+15550100123")        _ = try await client.signIn(phone: "+15550100123", challenge: challenge, code: "synthetic-code")    }    // RULE: The synthetic sign-in marker is protocol data and never part of the displayed number.    func testSignedInNumberHidesOnlyTheSyntheticMarker() {        XCTAssertEqual(HomeCustomerWords.signedIn("test:+15550100101"), HomeCustomerWords.signedIn("+15550100101"))        XCTAssertTrue(HomeCustomerWords.signedIn("+15550100101").contains("+15550100101"))    }    /// RULE: A launch syncs before it draws, and the sync carries the Keychain's credential: a relaunched phone reads the business as the person it signed in as (the member's own views), and the pages are read from the cache with no credential at all.    func testTheLaunchSyncCarriesTheKeychainCredential() async throws {        let core = BusinessFake()        let store = InMemorySecretStore()        try await signedIn(core, store)        let model = model(core, store)        await model.load()        XCTAssertEqual(model.session?.person.id, "p1")        let sync = try XCTUnwrap(core.requests(CottonMethod.businessSync).last)        XCTAssertEqual(sync["credential"], .string(BusinessFake.credential), "the launch sync carries no credential")        XCTAssertEqual(sync["server"], .string(BusinessFake.server))        XCTAssertEqual(sync["slug"], .string("studio"))        XCTAssertEqual(core.asked.suffix(2).map(\.method), [CottonMethod.businessSync, CottonMethod.businessPages], "sync, then pages")        XCTAssertNil(core.requests(CottonMethod.businessPages).last?["credential"], "the cache's read carries the credential")        XCTAssertEqual(model.pages?.role, .member)        XCTAssertTrue(model.pagesRead)    }    /// RULE: The credential never leaves the Keychain except on the request's `credential` field: signing in writes it to its one slot (one per business slug) and nowhere else; the session the app holds says nothing of it when described, reflected or dumped; the code, the sign-in and the pages never carry it; the sync, an act and the sign-out carry it on `credential` alone; sign-out forgets it; and no Swift source but `BusinessClient.swift` names the slot or the bearer, while that file neither logs nor prints.    func testTheCredentialNeverLeavesTheKeychain() async throws {        let core = BusinessFake()        let store = InMemorySecretStore()        let client = client(core, store)        let challenge = try await client.askCode(phone: "+15550100123")        let session = try await client.signIn(phone: "+15550100123", challenge: challenge, code: "123456")        XCTAssertEqual(store.occupied, [BusinessClient.slot(BusinessFake.address)])        XCTAssertEqual(BusinessClient.slot(BusinessFake.address), "business-session.studio")        XCTAssertTrue(try XCTUnwrap(store.read(BusinessClient.slot(BusinessFake.address))).contains(BusinessFake.credential))        var dumped = ""        dump(session, to: &dumped)        for said in [String(describing: session), String(reflecting: session), dumped, "\(session)"] {            XCTAssertFalse(said.contains(BusinessFake.credential), said)        }        XCTAssertEqual(client.session(), session, "read back from the Keychain")        _ = try await client.sync(zone: "Asia/Kolkata")        let pages = try await client.pages(zone: "Asia/Kolkata")        let book = try XCTUnwrap(pages.tools.first?.views.first?.rows.first?.acts.first)        _ = try await client.act(book, answers: ["1.0"], zone: "Asia/Kolkata")        await client.signOut()        for (method, body) in core.asked {            let request = try JSONDecoder().decode([String: JSONValue].self, from: Data(body.utf8))            var rest = request            rest["credential"] = nil            let elsewhere = String(decoding: try JSONEncoder().encode(rest), as: UTF8.self)            XCTAssertFalse(elsewhere.contains(BusinessFake.credential), "\(method) carries the credential outside `credential`")            let carries = request["credential"] == .string(BusinessFake.credential)            let should = [CottonMethod.businessSync, CottonMethod.businessAct, CottonMethod.businessSignOut].contains(method)            XCTAssertEqual(carries, should, "\(method) \(should ? "does not carry" : "carries") the credential")        }        XCTAssertTrue(store.occupied.isEmpty, "sign-out forgets the credential")        for (name, text) in try SourceSweep.swiftSources() where !name.hasSuffix("BusinessClient.swift") {            let code = SourceSweep.withoutComments(text)            XCTAssertFalse(code.contains("business-session"), "\(name) names the business's Keychain slot")            XCTAssertFalse(code.contains("personal-session"), "\(name) names Cotton's Keychain slot")            XCTAssertFalse(code.contains(".bearer"), "\(name) reads the credential")        }        let own = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonKit/BusinessClient.swift", ownedBy: "business"))        for spoken in ["Logger", "print(", "NSLog", "os_log", "Log.", "dump(", "UserDefaults", "FileManager"] {            XCTAssertFalse(own.contains(spoken), "BusinessClient.swift says `\(spoken)`")        }    }    /// RULE (NEXT-SIGNIN, owner, 28 Nov 2026): the name is never asked beside the code. The code goes alone; a number    /// with an account is signed in straight away; a number with none is asked its name on its own step once the code    /// is proved, and the same code goes again with it. Where the code went is the core's line, the number masked.    func testTheNameIsAskedOnlyOfANewAccountAfterTheCode() async throws {        for newAccount in [false, true] {            let core = BusinessFake()            core.newAccount = newAccount            let model = model(core)            model.start()            model.phone = "+15550100123"            await model.askCode()            guard case .code(let challenge) = model.pane else { return XCTFail("no code step") }            XCTAssertEqual(challenge.sentTo, "We sent a code by text message to +1 ••••••••23.")            model.code = "654321"            await model.confirm(challenge)            let first = try XCTUnwrap(core.requests(CottonMethod.businessSignIn).first)            XCTAssertEqual(first["nameAfter"], .bool(true))            XCTAssertNil(first["name"], "the code goes alone")            guard newAccount else {                XCTAssertNotNil(model.session, "an account goes straight in")                XCTAssertFalse(model.asking)                continue            }            XCTAssertEqual(model.pane, .name(challenge), "a new account is asked its name, after the code")            XCTAssertNil(model.session)            model.name = "Asha Invented"            await model.confirm(challenge)            let second = try XCTUnwrap(core.requests(CottonMethod.businessSignIn).last)            XCTAssertEqual(second["code"], .string("654321"), "the same code")            XCTAssertEqual(second["name"], .string("Asha Invented"))            XCTAssertNotNil(model.session)        }    }    /// RULE (NEXT-SIGNIN 3, owner, 28 Nov 2026): the asking card draws `personal.ask`'s square code from its `qr.rows`    /// (the getting-in page's shape); a core that sends none draws no square.    func testTheAskingCardReadsTheCoresSquareCode() {        let card: JSONValue = .object(["askId": .string("cta_synthetic"), "qr": .object(["size": .number(3), "rows": .array([.string("101"), .string("010"), .string("101")])])])        XCTAssertEqual(AskingCard.square(card), ["101", "010", "101"])        XCTAssertNil(AskingCard.square(.object(["askId": .string("cta_synthetic")])))        XCTAssertNil(AskingCard.square(.object(["qr": .null])))    }    /// RULE (coordinator, 25 Oct 2026): The code is the person's to type: the code sheet opens empty, the phone is never handed one to fill, and no Swift source holds a code.    func testTheCodeSheetOpensEmptyForThePersonToType() async throws {        let core = BusinessFake()        let model = model(core)        model.phone = "+15550100123"        model.code = "left over"        await model.askCode()        XCTAssertEqual(model.code, "")        for (name, text) in try SourceSweep.swiftSources() {            XCTAssertFalse(SourceSweep.withoutComments(text).contains(#""123456""#), "\(name) holds a sign-in code; the code is the person's to type")        }    }    /// RULE: Book is offered to everyone and the object decides who may take it: a signed-out Book is posted, the object's `not_signed_in` opens the sign-in sheet over the page, and once they sign in the business is synced for their role and that same Book is posted again, once, with the places picked — then the pages are read from the cache, showing the booking among their own.    func testASignedOutBookOpensTheSignInAndRunsAfter() async throws {        let core = BusinessFake()        let model = model(core)        await model.load()        XCTAssertNil(model.session)        let today = CustomerShellTiles.viewKey(tool: "yoga", view: "yoga_session")        let card = try XCTUnwrap(model.cards(today).first)        await model.acts(on: card)[0].perform(["2.0"])        XCTAssertTrue(model.asking, "the object's not_signed_in did not open the sign-in sheet")        XCTAssertNil(model.refusal)        XCTAssertEqual(core.requests(CottonMethod.businessAct).count, 1)        model.phone = "+15550100123"        await model.askCode()        guard case .code(let challenge) = model.pane else { return XCTFail("no code pane") }        await model.confirm(challenge)        XCTAssertFalse(model.asking)        let acts = core.requests(CottonMethod.businessAct)        XCTAssertEqual(acts.count, 2, "the act was not taken once after the sign-in")        let posted = try XCTUnwrap(acts.last)        XCTAssertEqual(posted["act"], .string("book"))        XCTAssertEqual(posted["args"], .object(["slot": .string("s1"), "quantity": .number(2)]))        XCTAssertEqual(posted["credential"], .string(BusinessFake.credential))        let signIn = core.asked.firstIndex { $0.method == CottonMethod.businessSignIn } ?? 0        let after = core.asked[signIn...].map(\.method)        XCTAssertEqual(Array(after), [CottonMethod.businessSignIn, CottonMethod.businessSync, CottonMethod.businessPages,                                      CottonMethod.businessAct, CottonMethod.businessPages])        XCTAssertEqual(model.cards(CustomerShellTiles.viewKey(tool: "yoga", view: "mine")).map(\.id), ["b1"])    }    /// RULE: A credential the object no longer takes is forgotten: a sync refused `credential_revoked` empties the Keychain and the business is synced again as a stranger, so the phone shows the public views — never a signed-in shell over a dead credential.    func testARevokedCredentialIsForgottenAndTheBusinessReadAsAStranger() async throws {        let core = BusinessFake()        let store = InMemorySecretStore()        try await signedIn(core, store)        core.revoked = true        let model = model(core, store)        await model.load()        XCTAssertNil(model.session)        XCTAssertTrue(store.occupied.isEmpty, "the revoked credential is kept")        let syncs = core.requests(CottonMethod.businessSync)        XCTAssertEqual(syncs.map { $0["credential"] != nil }, [true, false], "the stranger's sync carries the dead credential")        XCTAssertEqual(model.pages?.role, .public)        XCTAssertFalse(model.pages?.tools.first?.views.contains { $0.id == "mine" } ?? true)    }    /// RULE: An answered pick goes into the act's `args` at its `argument`: a dotted argument (`data.customer`) inside its object, a number as a number, an optional words pick left empty not sent, and an unanswered pick sends nothing at all.    func testEachAnswerGoesAtItsArgument() throws {        let act = try JSONDecoder().decode(BusinessAct.self, from: Data(#"""        {"id":"order","label":"Take an order","kind":"create","act":"record_act",         "args":{"table":"kitchen_menu_day","id":"m1","act":"order"},         "picks":[{"argument":"data.customer","kind":"record","table":"kitchen_customer","label":"Customer"},                  {"argument":"data.quantity","kind":"number","label":"Quantity","min":1,"default":1},                  {"argument":"note","kind":"text","optional":true}]}        """#.utf8))        XCTAssertEqual(act.picks.map(\.argument), ["data.customer", "data.quantity", "note"])        XCTAssertEqual(act.picks[1].min, 1)        XCTAssertEqual(act.arguments(answering: ["c1", "3.0", ""]), [            "table": .string("kitchen_menu_day"), "id": .string("m1"), "act": .string("order"),            "data": .object(["customer": .string("c1"), "quantity": .number(3)]),        ])        XCTAssertEqual(act.arguments(answering: ["c1", "3.0", "no onions"])?["note"], .string("no onions"))        XCTAssertNil(act.arguments(answering: ["c1"]), "an unanswered pick was sent")        XCTAssertNil(act.arguments(answering: ["c1", "many", ""]), "a number that does not read was sent")    }    /// RULE: A photo column holds a key, shown from the object's photos: `photos + key`, the base the pages answered — and the deck hands that base to every face it draws, so a studio's picture comes from its business and never from a phone store it does not have.    func testAPhotoKeyIsShownFromThePhotosBase() async throws {        let core = BusinessFake()        let model = model(core)        await model.load()        let pages = try XCTUnwrap(model.pages)        XCTAssertEqual(pages.photos, BusinessFake.photos)        let key = try XCTUnwrap(model.cards(CustomerShellTiles.viewKey(tool: "yoga_studio", view: "studio")).first?.record["photo"].text)        XCTAssertEqual(pages.photo(key), URL(string: BusinessFake.photos + key))        XCTAssertEqual(pages.photo(key)?.absoluteString, "https://cotton-business.synthetic.workers.dev/b/studio/v1/photos/studio/hall.jpg")        XCTAssertNil(pages.photo(""))        let deck = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Join/CustomerDeck.swift", ownedBy: "business"))        XCTAssertTrue(deck.contains(".environment(\\.facePhotoBase, model.pages?.photos)"), "the deck does not hand its faces the photos base")        let picture = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Faces/PagePicture.swift", ownedBy: "business"))        XCTAssertTrue(picture.contains("BusinessPages.photo(key, at: photoBase)"), "a page picture does not draw a business's photo")    }    /// RULE: A refusal is said on the page where it happened, by the kit's line for its code (`board` `customer.refusal.<code>`) — every code the object refuses an act with has a line of its own, never the dotted path and never the object's message.    func testEveryRefusalHasItsOwnLine() async throws {        let general = HomeCustomerRefusal.line(code: "refused", business: "Synthetic Studio")        XCTAssertFalse(general.isEmpty)        for code in ["not_signed_in", "full", "past", "not_yours", "act_not_available", "ledger_refused", "offline", "credential_revoked",                     "invalid_code", "not_synced", "no_database", "object_full", "too_many_sign_ups", "too_many_attempts", "not_owner",                     "sms_unavailable"] {            let line = HomeCustomerRefusal.line(code: code, business: "Synthetic Studio")            XCTAssertNotEqual(line, general, "\(code) has no line of its own")            XCTAssertFalse(line.contains("customer.refusal"), "\(code) says its line's path")            XCTAssertFalse(line.contains("{name}"), "\(code) leaves its fill unfilled")        }        XCTAssertEqual(HomeCustomerRefusal.line(code: "a_code_nobody_sends", business: "Synthetic Studio"), general)        let core = BusinessFake()        let store = InMemorySecretStore()        try await signedIn(core, store)        let model = model(core, store)        await model.load()        core.refuseOnce[CottonMethod.businessAct] = "full"        let card = try XCTUnwrap(model.cards(CustomerShellTiles.viewKey(tool: "yoga", view: "yoga_session")).first)        await model.acts(on: card)[0].perform(["1.0"])        XCTAssertEqual(model.refusal, HomeCustomerRefusal.line(code: "full", business: "Synthetic Studio"))        XCTAssertFalse(model.asking)        let deck = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Join/CustomerDeck.swift", ownedBy: "door"))        XCTAssertTrue(deck.contains("if !model.asking, let refusal = model.refusal {"), "a deck does not say its refusal")    }    /// RULE: The sign-in sheet never waits on the launch's sync: while the business is still being synced, a fresh sheet's arrow stands ready and Send code asks the business at once.    func testSendCodeNeverWaitsOnTheSync() async throws {        let core = BusinessFake()        core.holdsSync = true        let model = model(core)        let loading = Task { await model.load() }        await core.syncAsked()        model.start()        XCTAssertFalse(model.signing, "a fresh sheet's arrow turns while the business is synced")        model.phone = "+15550100123"        await model.askCode()        XCTAssertTrue(core.asked.contains { $0.method == CottonMethod.businessCode }, "Send code reached no business")        guard case .code = model.pane else { return XCTFail("the code is not asked while the business is synced") }        XCTAssertFalse(model.pagesRead, "the pages answered before the code; the test proves nothing")        core.release()        await loading.value        XCTAssertTrue(model.pagesRead)    }    /// RULE: A refused Send code is said on the sheet, by its code's line, and a new sheet starts without the last one's refusal or number.    func testARefusedCodeIsSaidOnTheSheet() async throws {        let core = BusinessFake()        core.refuseOnce[CottonMethod.businessCode] = "bad_phone"        let model = model(core)        model.start()        model.phone = "12345"        await model.askCode()        XCTAssertEqual(model.signInRefusal, HomeCustomerRefusal.line(code: "bad_phone", business: "Synthetic Studio"))        XCTAssertNil(model.refusal, "the sheet's refusal is said under the sheet, where nobody reads it")        XCTAssertEqual(HomeCustomerRefusal.path("bad_phone"), "customer.refusal.bad_phone")        model.start()        XCTAssertNil(model.signInRefusal, "a new sheet keeps the last one's refusal")        XCTAssertEqual(model.phone, "", "a new sheet keeps the last one's number, and typing appends to it")    }    /// RULE: Sign out at the business forgets the credential and reads the business again as a stranger: the member's own views go with it.    func testSignOutReadsTheBusinessAsAStranger() async throws {        let core = BusinessFake()        let store = InMemorySecretStore()        try await signedIn(core, store)        let model = model(core, store)        await model.load()        XCTAssertTrue(model.pages?.tools.first?.views.contains { $0.id == "mine" } == true)        await model.signOut()        XCTAssertNil(model.session)        XCTAssertTrue(store.occupied.isEmpty)        XCTAssertEqual(core.asked.suffix(3).map(\.method), [CottonMethod.businessSignOut, CottonMethod.businessSync, CottonMethod.businessPages])        XCTAssertEqual(model.pages?.role, .public)        XCTAssertFalse(model.pages?.tools.first?.views.contains { $0.id == "mine" } ?? true)    }}/// A credential granted another way than a code — another device's approval/// or a passkey — is kept exactly where a code's is.final class GrantedSignInTests: XCTestCase {    private let open = BusinessAddress(server: "https://cotton-open.synthetic.workers.dev")    // RULE: An approval's or a passkey's credential lands in the personal session slot, and the next launch reads it signed in.    func testAGrantedCredentialIsKeptAsACodesIs() throws {        let store = InMemorySecretStore()        let client = BusinessClient(core: BusinessFake(), address: open, store: store)        let granted: JSONValue = .object([            "state": "approved", "credential": "synthetic.granted.credential", "expiresIn": .number(7_776_000),            "databaseId": .string(BusinessFake.database), "person": .object(["id": "person-1", "phone": "+15550100123"]),        ])        let session = try client.keep(granted: granted, phone: "+15550100123")        XCTAssertEqual(session.databaseId, BusinessFake.database)        XCTAssertEqual(client.session()?.person.id, "person-1")        XCTAssertNotNil(store.read("personal-session"))        XCTAssertFalse(String(describing: session).contains("synthetic.granted.credential"), "the credential is never described")    }    // RULE: A grant naming no database is a refusal, never a signed-in phone with nowhere to connect.    func testAGrantWithNoDatabaseIsRefused() {        let store = InMemorySecretStore()        let client = BusinessClient(core: BusinessFake(), address: open, store: store)        let granted: JSONValue = .object(["credential": "synthetic.granted.credential", "expiresIn": .number(60), "person": .object(["id": "person-1"])])        XCTAssertThrowsError(try client.keep(granted: granted, phone: nil))        XCTAssertNil(store.read("personal-session"))    }    // RULE: The approving card reads the core's ask, comparing only once the other phone revealed.    func testTheApprovingCardReadsTheCoresAsk() throws {        let ask = try XCTUnwrap(SignInAsk(.object([            "askId": "ask-1", "name": "Synthetic Phone", "phase": "compare", "line": "Synthetic Phone wants to sign in.",            "type": "Type the code.", "never": "Only if you hold it.", "digits": .number(6), "when": "Asked just now",            "approve": "Approve", "refuse": "Refuse", "confirm": "It will not be signed in.",        ])))        XCTAssertTrue(ask.comparing)        XCTAssertEqual(ask.digits, 6)        let opening = try XCTUnwrap(SignInAsk(.object(["askId": "ask-2", "phase": "opening", "line": "l", "approve": "a", "refuse": "r"])))        XCTAssertFalse(opening.comparing)        XCTAssertEqual(opening.confirm, "r")    }}