import Foundation import RastrilloApple import RastrilloTestSupport import Testing @testable import EquipoKit private final class IDClock: @unchecked Sendable { private let lock = NSLock() private var date = Date() var now: Date { lock.withLock { date } } func advance(_ seconds: TimeInterval) { lock.withLock { date += seconds } } } @MainActor private final class IDFixture { let service = FakeOficinaIDService() let shared = OficinaMemoryStore() let privateStore = OficinaMemoryStore() let secrets = MemorySecretStore() let transport = ScriptedTransport() let clock = IDClock() let notifications = FakeNotifications() let suite = "EquipoIDTests.\(UUID().uuidString)" let defaults: UserDefaults let model: OficinaIDModel let app: EquipoAppModel init(held: (any EquipoTransport)? = nil) { defaults = UserDefaults(suiteName: suite)! let store = OficinaIDStore(shared: shared, appPrivate: privateStore, group: defaults) let clock = clock model = OficinaIDModel(configuration: EquipoOficinaID.configuration, store: store, service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.now }, appDefaults: defaults) let transport = transport app = EquipoAppModel(store: secrets, notifications: notifications, push: PushRegistrar(environment: nil), oficinaModel: model, makeTransport: { _ in if let held { held } else { transport } }, now: { clock.now }, deviceLabel: { "Test phone" }) service.addPerson(email: "person@example.test", identityID: "id-1") service.setTeams([team()], for: "id-1") service.admit("id-1", at: transport.origin, as: .linked) transport.on("POST /auth/devices/native", fixture: "device-credential") transport.on("GET /auth/devices", fixture: "devices") transport.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack") } deinit { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) } func team(_ id: String = "t1", app: String = "equipo") -> OficinaTeam { OficinaTeam(sqid: id, label: id, name: "Team \(id)", role: "member", apps: [ OficinaTeamApp(app: app, origin: transport.origin.absoluteString, consumerID: id) ]) } func signIn() async { await app.start() model.continueWithEmail(); model.email = "person@example.test" await model.submitEmail(); model.code = FakeOficinaIDService.goodCode await model.submitCode() await app.oficina.synchronize() } func seedIdentity() async throws { let key = OficinaSoftwareKey() let start = try await service.startCode(email: "person@example.test", key: key, platform: "macos") guard case .granted(let grant) = try await service.verifyCode(start: start.start, code: FakeOficinaIDService.goodCode, key: key) else { throw EquipoAPIError.signedOut } _ = try model.store.add(grant: grant, key: key, label: "Person", labelSource: .email, method: "code", now: clock.now) } } @MainActor @Suite struct OficinaIDTests { @Test func firstAppShowsWelcomeThenKeepsDeviceAndFreshKey() async throws { let f = IDFixture() await f.app.start() #expect(f.model.step == .welcome) #expect(f.app.session == nil) #expect(!f.app.showingPairing) await f.signIn() let account = try #require(f.app.session?.account) #expect(account.oficinaIdentity == "id-1") #expect(account.oficinaTeam == "t1") #expect(f.app.accounts.all() == [account]) let request = try #require(f.transport.sent("POST /auth/devices/native").first) let body = try JSONDecoder().decode([String: String].self, from: #require(request.body)) #expect(body == ["public_key": try account.publicKey(), "label": "Test phone"]) let wire = try request.urlRequest(origin: f.transport.origin) #expect(wire.url?.path == "/api/v1/auth/devices/native") #expect(wire.value(forHTTPHeaderField: "Origin") == f.transport.origin.absoluteString) #expect(wire.value(forHTTPHeaderField: "Cookie")?.hasPrefix("__Host-rastrillo_session=") == true) #expect(wire.value(forHTTPHeaderField: "Authorization") == nil) #expect(wire.value(forHTTPHeaderField: "Content-Type") == "application/json") #expect(!wire.httpShouldHandleCookies) await f.app.oficina.synchronize() #expect(f.transport.sent("POST /auth/devices/native").count == 1) let bearer = try APIRequest("GET", "/snapshot", bearer: account.credential?.token).urlRequest(origin: account.origin) #expect(bearer.value(forHTTPHeaderField: "Cookie") == nil) } @Test func oneIdentityGoesStraightInAndSeveralTeamsOrNoneUseKit() async throws { for count in [0, 1, 2] { let f = IDFixture() f.service.setTeams((0.. 0) await f.app.push.attach(f.app.session?.client) let generation = f.app.push.generation f.app.needsYouChanged(3) await f.app.signOut() #expect(f.notifications.unregistered == 1) #expect(f.app.accounts.all().isEmpty) #expect(f.notifications.badges.last == 0) #expect(f.app.session == nil) await f.app.oficina.cleanup?.value #expect(f.app.push.generation == generation + 1) #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1) let count = f.transport.sent("POST /auth/devices/native").count await f.app.oficina.renewIfNeeded() #expect(f.transport.sent("POST /auth/devices/native").count == count) #expect(f.model.step == .welcome) } @Test func replacementThroughKitAlsoForgetsDeviceAndPushes() async throws { let f = IDFixture(); await f.signIn() f.model.useAnother() #expect(f.app.session != nil) f.model.cancelReplace() #expect(f.app.session != nil) f.model.useAnother(); f.model.confirmReplace() #expect(f.app.session == nil) #expect(f.app.accounts.all().isEmpty) #expect(f.notifications.unregistered == 1) #expect(f.model.step == .email) } @Test func sharedIdentityRemovalLeavesAnActiveFallbackPairingAlone() async throws { let f = IDFixture(); await f.signIn() f.app.otherWays() var paired = DeviceAccount.new(origin: f.transport.origin, label: "Paired") paired.credential = try Fixture.decode("device-credential") try f.app.accounts.commit(.save(paired), lifetime: f.app.accounts.lifetimes.current) f.app.adopt(paired, transport: f.transport) f.model.signOut() #expect(f.app.session?.account == paired) #expect(f.app.accounts.all() == [paired]) } @Test func onlyDeviceRegistrationMaySendTheSessionCookie() throws { for path in ["/snapshot", "/auth/devices", "/auth/devices/exchange"] { #expect(throws: EquipoAPIError.badOrigin) { try APIRequest("POST", path, nativeSession: NativeSession(name: "session", value: "fixture")) .urlRequest(origin: URL(string: "https://example.test")!) } } } @Test func deviceEndpointRejectionRemintsTheKitSession() async throws { let f = IDFixture() f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 403, data: Data()))) f.transport.on("POST /auth/devices/native", fixture: "device-credential") await f.signIn() #expect(f.app.session != nil) #expect(f.transport.sent("POST /auth/devices/native").count == 2) let cookies = f.transport.sent("POST /auth/devices/native").compactMap { $0.nativeSession?.value } #expect(Set(cookies).count == 2) } @Test func nativeCredentialWhoseIdentityWasRemovedCannotSurviveRelaunch() async throws { let f = IDFixture(); await f.signIn() try f.model.store.remove("id-1") let transport = f.transport let freshModel = OficinaIDModel(configuration: EquipoOficinaID.configuration, store: OficinaIDStore(shared: f.shared, appPrivate: f.privateStore, group: f.defaults), service: f.service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: f.defaults) let relaunched = EquipoAppModel(store: f.secrets, push: PushRegistrar(environment: nil), oficinaModel: freshModel, makeTransport: { _ in transport }) await relaunched.start() #expect(relaunched.session == nil) #expect(relaunched.accounts.all().isEmpty) } @Test func lateRegistrationCannotRestoreSignedOutDevice() async throws { let held = HeldIDTransport() let f = IDFixture(held: held) try await f.seedIdentity() let start = Task { await f.app.start() } await held.waitUntilEntered() await f.app.signOut() await held.release() await start.value #expect(f.app.session == nil) #expect(f.app.accounts.all().isEmpty) #expect(f.model.identity == nil) } @Test func lateSnapshotCannotRestoreSignedOutDevice() async throws { let held = HeldEquipoRead() let f = IDFixture(held: held) await f.signIn() let departed = try #require(f.app.session) await held.hold("/snapshot") let refresh = Task { await departed.refresh() } await held.waitUntilEntered() await f.app.signOut() #expect(f.app.accounts.all().isEmpty) await held.release() await refresh.value #expect(departed.status == .signedOut) #expect(departed.me == nil) #expect(f.app.session == nil) #expect(f.app.accounts.all().isEmpty) } @Test func lateRenewalCannotRestoreSignedOutDevice() async throws { let held = HeldEquipoRead() let f = IDFixture(held: held) await f.signIn() let departed = try #require(f.app.session) let oldAccount = departed.account f.clock.advance(86401) await held.nativeToken("ABANDONED") await held.hold("/auth/devices/native") let renewal = Task { await f.app.oficina.renewIfNeeded() } await held.waitUntilEntered() await f.app.signOut() await held.release() await renewal.value #expect(f.app.session == nil) #expect(f.app.accounts.all().isEmpty) #expect(f.app.oficina.account == nil) #expect(f.model.identity == nil) #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains { $0.bearer == "equipo.person.v1.ABANDONED" }) // Even a queued adoption and direct metadata update cannot reopen // the departed session or save its private key again. departed.renew(oldAccount, transport: held) departed.apply(try Fixture.decode("thin/snapshot")) #expect(departed.status == .signedOut) #expect(f.app.accounts.all().isEmpty) } @Test(arguments: ["pairing", "replacement", "ended"]) func departingSessionCannotPersistAfterItsReplacement(_ route: String) async throws { let held = HeldEquipoRead() let f = IDFixture(held: held); await f.signIn() let departed = try #require(f.app.session) await held.hold("/snapshot") let refresh = Task { await departed.refresh() } await held.waitUntilEntered() switch route { case "pairing": f.app.otherWays() case "replacement": var next = departed.account next.oficinaTeam = "replacement" try f.app.accounts.commit(.save(next), lifetime: f.app.accounts.lifetimes.current) f.app.adopt(next, transport: held) default: f.app.sessionEnded() } let saved = f.app.accounts.all() await held.release() await refresh.value #expect(departed.status == .signedOut) #expect(departed.me == nil) #expect(f.app.accounts.all() == saved) } @Test func latePairingRevocationCannotRemoveANewCredential() async throws { let held = HeldEquipoRead() let accounts = DeviceAccounts(store: MemorySecretStore()) var old = DeviceAccount.new(origin: held.origin, label: "Old phone") old.credential = try Fixture.decode("device-credential") try accounts.commit(.save(old), lifetime: accounts.lifetimes.current) let departed = EquipoSession(account: old, accounts: accounts, transport: held) await held.hold("/auth/devices") let signOut = Task { await departed.signOut() } await held.waitUntilEntered() #expect(departed.status == .signedOut) #expect(accounts.all().isEmpty) var replacement = old replacement.keySeed = DeviceAccount.new(origin: held.origin, label: "New phone").keySeed accounts.lifetimes.begin() try accounts.commit(.save(replacement), lifetime: accounts.lifetimes.current) await held.release() await signOut.value #expect(accounts.all() == [replacement]) } @Test func unavailableRenewalShowsRecoveryWithoutAnErrorString() async throws { let f = IDFixture(); await f.signIn() let original = try #require(f.app.session) #expect(EquipoOficinaNotice(model: f.app).message == nil) f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline) f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data()))) _ = try? await original.client.me() guard case .unavailable = f.model.step else { Issue.record("expected an unavailable team"); return } #expect(f.app.oficina.error == nil) #expect(f.model.error == nil) #expect(EquipoOficinaNotice(model: f.app).message == OficinaIDText.text("unavailable.title")) #expect(f.app.session === original) await f.app.oficina.renewIfNeeded() #expect(EquipoOficinaNotice(model: f.app).message == nil) #expect(f.app.session === original) } @Test(arguments: ["/auth/devices/exchange", "/me"], [false, true]) func cancelledPairingCannotOverwriteNativeSignIn(_ boundary: String, _ signOut: Bool) async throws { let held = HeldEquipoRead() let f = IDFixture(held: held) try await f.seedIdentity() f.app.otherWays(); await f.app.start() await held.hold(boundary) f.app.pairing.start(origin: held.origin, label: "Abandoned pairing") await held.waitUntilEntered() await held.nativeToken("NEW_SIGN_IN") await f.app.useOficinaID() let native = try #require(f.app.session?.account) if signOut { await f.app.signOut(); await f.app.oficina.cleanup?.value } await held.release() // Wait for the abandoned pairing's network cleanup as well as /me. for _ in 0..<200 { if await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains(where: { $0.bearer == "equipo.person.v1.TOKENFIXTURE" }) { break } try await Task.sleep(for: .milliseconds(5)) } #expect(f.app.accounts.all() == (signOut ? [] : [native])) #expect(f.app.pairing.account == nil) #expect(f.app.pairing.step == .enterTeam) #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains { $0.bearer == "equipo.person.v1.TOKENFIXTURE" }) } @Test func departedWriteCannotRetryWithALaterSignInsBearer() async throws { let held = HeldEquipoRead() let f = IDFixture(held: held); await f.signIn() let departed = try #require(f.app.session) let outer = try #require(departed.client.transport as? LifetimeTransport) let renewing = try #require(outer.inner as? EquipoRenewingTransport) let snapshot: Snapshot = try Fixture.decode("thin/snapshot") let card = try #require(snapshot.cards?.first { $0.isOpen }) let route = "POST /cards/\(card.id)/answer" await held.answerFailure(route) await held.hold("/cards/\(card.id)/answer") let answer = Task { await departed.answer(card, choice: "wait_mac") } await held.waitUntilEntered() await f.app.signOut() await f.app.oficina.cleanup?.value await f.model.cleanup?.value await held.nativeToken("NEW_SIGN_IN") await f.signIn() #expect(f.app.session?.account.credential?.token == "equipo.person.v1.NEW_SIGN_IN") #expect(renewing.credential() == nil) await held.release() #expect(await answer.value == .failed) #expect(await held.sent(route).count == 1) // A retained client is also bound, independently of the write loop. _ = try? await departed.client.me() #expect(await held.sent("GET /me").isEmpty) } @Test(arguments: [false, true]) func endedWriteLoopsDoNotWaitOrRetry(_ aside: Bool) async throws { let held = HeldEquipoRead() let f = IDFixture(held: held); await f.signIn() let current = try #require(f.app.session) let sleeps = Sleeps() let worker = EquipoSession(account: current.account, accounts: f.app.accounts, transport: current.client.transport, lifetime: current.lifetime, sleep: sleeps.sleep) let snapshot: Snapshot = try Fixture.decode("thin/snapshot") let card = try #require(snapshot.cards?.first { $0.kind == "merge" && $0.isOpen }) let path = "/cards/\(card.id)/" + (aside ? "visibility" : "answer") await held.answerFailure("POST " + path) await held.hold(path) let write = Task { aside ? await worker.setAside(card, true) : await worker.answer(card, choice: "wait_mac") } await held.waitUntilEntered() await f.app.signOut() await held.release() #expect(await write.value == .failed) #expect(sleeps.waits.isEmpty) #expect(await held.sent("POST " + path).count == 1) } @Test func endedTransportRefusesLateResponsesAndNewRequests() async throws { let held = HeldEquipoRead() let lifetimes = SignInLifetimes() let lifetime = lifetimes.current let transport = LifetimeTransport(inner: held, lifetime: lifetime) await held.hold("/me") let read = Task { try await transport.send(APIRequest("GET", "/me", bearer: "old")) } await held.waitUntilEntered() lifetimes.begin() await held.release() var rejected = false do { _ = try await read.value } catch is CancellationError { rejected = true } #expect(rejected) _ = try? await transport.send(APIRequest("GET", "/snapshot", bearer: "old")) #expect(await held.sent("GET /snapshot").isEmpty) } @Test(arguments: [false, true]) func cancellingPairingAloneEndsItsLifetime(_ signOut: Bool) async throws { let held = HeldEquipoRead() let f = IDFixture(held: held) f.app.otherWays(); await f.app.start() await held.hold("/auth/devices/exchange") f.app.pairing.start(origin: held.origin, label: "Cancelled") await held.waitUntilEntered() let lifetime = try #require(f.app.pairing.lifetime) if signOut { await f.app.signOut() } else { f.app.pairing.cancel() } #expect(!lifetime.isActive) await held.release() for _ in 0..<200 { if !(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X")).isEmpty { break } try await Task.sleep(for: .milliseconds(5)) } #expect(f.app.accounts.all().isEmpty) #expect(f.app.pairing.step == .enterTeam) #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1) } @Test(arguments: [false, true]) func signOutBeforeRegistrationEndsThePendingLifetime(_ throughKit: Bool) async { let f = IDFixture() let lifetime = f.app.accounts.lifetimes.current if throughKit { f.app.oficina.signOut() } else { await f.app.signOut() } #expect(!lifetime.isActive) #expect(f.app.accounts.all().isEmpty) } @Test func signingOutAfterTheSessionEndsStillForgetsItsCredential() async throws { let f = IDFixture(); await f.signIn() f.app.sessionEnded() await f.app.signOut() #expect(f.app.accounts.all().isEmpty) await f.app.oficina.cleanup?.value #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1) } @Test(arguments: ["continueAs", "unavailable"], ["appSignOut", "bridgeSignOut", "replacement", "pairing"]) func leavingBeforeBridgeSynchronizesForgetsEveryNativeAccount(_ landing: String, _ route: String) async throws { let f = IDFixture() try await f.seedIdentity() var native = DeviceAccount.new(origin: f.transport.origin, label: "Saved native") native.credential = try Fixture.decode("device-credential") native.oficinaIdentity = "id-1" var another = native another.origin = URL(string: "https://another.example.test")! another.oficinaIdentity = "another-identity" var paired = native paired.origin = URL(string: "https://paired.example.test")! paired.oficinaIdentity = nil for account in [native, another, paired] { try f.app.accounts.commit(.save(account), lifetime: f.app.accounts.lifetimes.current) } f.service.failNext("assert", with: .offline) await f.app.start() if landing == "unavailable" { f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline) await f.model.choose(f.team()) } if landing == "continueAs" { guard case .continueAs = f.model.step else { Issue.record("expected Continue as"); return } } else { guard case .unavailable = f.model.step else { Issue.record("expected unavailable"); return } } #expect(f.app.oficina.account == nil) #expect(f.app.session == nil) switch route { case "appSignOut": await f.app.signOut() case "bridgeSignOut": f.app.oficina.signOut() case "replacement": f.model.useAnother(); f.model.confirmReplace() default: f.app.otherWays() } #expect(f.app.accounts.all() == [paired]) await f.app.oficina.cleanup?.value #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 2) #expect(f.app.accounts.all() == [paired]) } @Test(arguments: ["appSignOut", "bridgeSignOut", "pairing"]) func leavingBeforeIdentityLoadsForgetsTheSavedBearer(_ route: String) async throws { let f = IDFixture() var native = DeviceAccount.new(origin: f.transport.origin, label: "Saved native") native.credential = try Fixture.decode("device-credential") native.oficinaIdentity = "id-1" try f.app.accounts.commit(.save(native), lifetime: f.app.accounts.lifetimes.current) #expect(f.model.identity == nil) switch route { case "appSignOut": await f.app.signOut() case "bridgeSignOut": f.app.oficina.signOut() default: f.app.otherWays() } #expect(f.app.accounts.all().isEmpty) await f.app.oficina.cleanup?.value #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1) } @Test(arguments: ["appSignOut", "bridgeSignOut", "replacement", "server"]) func onlyServerSessionEndShowsTheEndedTeamNotice(_ route: String) async throws { let f = IDFixture(); await f.signIn() let team = try #require(f.app.session?.teamName) switch route { case "appSignOut": await f.app.signOut() case "bridgeSignOut": f.app.oficina.signOut() case "replacement": f.model.useAnother(); f.model.confirmReplace() default: f.app.sessionEnded() } f.app.otherWays() #expect(f.app.endedTeam == (route == "server" ? team : nil)) } @Test func permissionRefusalDuringHomeOutageKeepsTheKitSession() async throws { let f = IDFixture(); await f.signIn() let original = try #require(f.app.session) let credential = try #require(try f.model.store.credential("id-1")) let stored = try #require(f.model.store.session(grantID: credential.grantID, origin: f.transport.origin)) f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline) f.transport.on("GET /me", .success(APIResponse(status: 403, data: Data()))) do { _ = try await original.client.me() Issue.record("expected the permission refusal") } catch let error as EquipoAPIError { #expect(error.status == 403) } // The kit's only forced re-mint API deletes before contacting Home. // Keep this executable reproduction until the kit can preserve a usable // session during forced renewal. Unexpected success fails this test. withKnownIssue("Kit sessionRejected deletes the usable session before an offline re-mint") { #expect(f.model.store.session(grantID: credential.grantID, origin: f.transport.origin)?.session == stored.session) } #expect(f.app.session === original) } @Test func oldSavedPairingStillLoadsWithoutOficinaID() throws { let f = IDFixture() var account = DeviceAccount.new(origin: f.transport.origin, label: "Old phone") account.credential = try Fixture.decode("device-credential") try f.app.accounts.commit(.save(account), lifetime: f.app.accounts.lifetimes.current) let relaunched = EquipoAppModel(store: f.secrets, push: PushRegistrar(environment: nil), oficinaModel: f.model) #expect(relaunched.session?.account == account) #expect(relaunched.showingPairing) } } /// Holds the first device answer until sign-out has invalidated its request. private actor HeldIDTransport: EquipoTransport { nonisolated let origin = URL(string: "https://oficina.example.test")! private var entered = false private var continuation: CheckedContinuation? func send(_ request: APIRequest) async throws -> APIResponse { if request.path == "/auth/devices/native" { entered = true await withCheckedContinuation { continuation = $0 } return APIResponse(status: 200, data: Fixture.data("device-credential")) } return APIResponse(status: 404, data: Data()) } func lines(_ request: APIRequest) async throws -> AsyncThrowingStream { throw EquipoAPIError.offline } func waitUntilEntered() async { while !entered { await Task.yield() } } func release() { continuation?.resume(); continuation = nil } } private actor IDDailySleep { let clock: IDClock var waits: [Duration] = [] init(clock: IDClock) { self.clock = clock } func wait(_ duration: Duration) throws { waits.append(duration) if waits.count > 1 { throw CancellationError() } clock.advance(86401) } } /// Lets an actual scripted response arrive after its caller has signed out. /// Cancellation deliberately does not release it: a network reply can be late. private actor HeldEquipoRead: EquipoTransport { nonisolated let origin = URL(string: "https://oficina.example.test")! private let script = ScriptedTransport() private var path: String? private var entered = false private var continuation: CheckedContinuation? init() { script.on("POST /auth/devices/native", fixture: "device-credential") script.on("POST /auth/devices", fixture: "device-challenge") script.on("POST /auth/devices/exchange", fixture: "device-credential") script.on("GET /me", fixture: "me") script.on("GET /auth/devices", fixture: "devices") script.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack") script.on("GET /snapshot", fixture: "thin/snapshot") script.on("GET /tasks", fixture: "thin/tasks") script.on("GET /needs-you", fixture: "thin/needs-you") } func hold(_ path: String) { self.path = path; entered = false } func send(_ request: APIRequest) async throws -> APIResponse { let response: Result do { response = .success(try await script.send(request)) } catch { response = .failure(error) } if request.path == path { path = nil entered = true await withCheckedContinuation { continuation = $0 } } return try response.get() } func nativeToken(_ value: String) { let data = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: value) script.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(data.utf8)))) } func answerFailure(_ route: String) { script.on(route, .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("thin/answered")))) } func sent(_ route: String) -> [APIRequest] { script.sent(route) } func lines(_ request: APIRequest) async throws -> AsyncThrowingStream { throw EquipoAPIError.offline } func waitUntilEntered() async { while !entered { await Task.yield() } } func release() { continuation?.resume(); continuation = nil } }