oficina / base Public

Sign in to Base, and set Ask up with Oficina ID, without a step

Sign-in is the kit's Oficina ID flow in Base's look (mockups mac-signin,
phone-signin): the sky, the wordmark, Sign in to Base and which account
this is, a glass card with the email field, Email me a code, or, and
Sign in with a passkey; the code step says where the code went and sends
a new one. Errors are the kit's own words. Steps copy review hasn't
drawn for Base stay the kit's onboarding. A person Base doesn't know yet
(P3, the kit's notMember) is told to sign in on the web once, with a
button to Base's /signin.

AskSetup connects Ask with no code (spec 3.8): when /ask/state says
connect or reconnect (a write's 409 reconnect and a stream's state too)
or renew_after has passed, it fetches the kit's assertion for Equipo's
origin, posts it to /api/v1/ask/oficina and reads the state again. A 422
failed tries once more with a fresh assertion; not_linked shows its
state and is never retried by itself; superseded isn't retried and the
state decides; the kit's CancellationError is quiet and waits for the
next trigger. Never more than once a minute but for the person pressing
Set it up. The session runs it after each refresh, so at sign-in and on
every foreground, and only for the account it started under.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 23219b67fcc4ccb03a7ec18b89b7eab49f18006b parent 7b66d99
31 files changed, +538 −19
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +6 −1
  • native/apple/Sources/BaseKit/Resources/Localizable.xcstrings +12 −0
  • native/apple/Sources/BaseKit/Session/AskSetup.swift +105 −0
  • native/apple/Sources/BaseKit/Session/BaseSession.swift +22 −2
  • native/apple/Sources/BaseKit/SignIn/BaseOnboarding.swift +171 −5
  • native/apple/Sources/BaseMac/BaseMacApp.swift +1 −1
  • native/apple/Sources/BaseMac/MacActions.swift +1 −5
  • native/apple/Sources/BasePhone/BasePhoneApp.swift +2 −5
  • native/apple/Tests/BaseKitTests/AskSetupTests.swift +129 −0
  • native/apple/Tests/BaseKitTests/SessionTests.swift +20 −0
  • native/apple/Tests/BaseSnapshots/SignInSnapshots.swift +50 −0
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/ENVIRONMENT +10 −0
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/ENVIRONMENT +9 −0
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-light-default.png binary
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index 7000eb5..1c3e68e 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -70,7 +70,12 @@ import Observation
}
}
- public private(set) var phase: AskPhase = .loading
+ public private(set) var phase: AskPhase = .loading {
+ didSet { if phase != oldValue, phase == .connect || phase == .reconnect { onNeedsSetup?() } }
+ }
+ /// Ask became connect or reconnect (a state read, a stream's state, a
+ /// write's 409 reconnect): the session runs AskSetup.
+ @ObservationIgnored public var onNeedsSetup: (@MainActor () -> Void)?
public private(set) var entries: [Entry] = []
/// The person's turn in flight (never a quiet one): Stop shows while
/// there is one.
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
index 5674bec..65c5f94 100644
--- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
@@ -1260,6 +1260,18 @@
}
}
}
+ },
+ "native.wordmark": {
+ "comment": "Not in copy review: Base's wordmark, as the web's templates write it (lowercase), beside the mark on the sign-in screen.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "base"
+ }
+ }
+ }
}
},
"version": "1.0"
diff --git a/native/apple/Sources/BaseKit/Session/AskSetup.swift b/native/apple/Sources/BaseKit/Session/AskSetup.swift
new file mode 100644
index 0000000..9437c53
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Session/AskSetup.swift
@@ -0,0 +1,105 @@
+import Foundation
+import RastrilloApple
+
+/// Ask set up during sign-in, with no code to approve (spec 3.8, P1, P2):
+/// the app fetches an Oficina ID assertion addressed to Equipo and posts it
+/// to Base, which finishes Equipo's own native sign-in for the person and
+/// keeps the key. Equipo's key from Oficina ID lasts seven days, so Base
+/// says when to renew it (`renew_after`) and this does, silently.
+///
+/// It runs when `/ask/state` says `connect` or `reconnect` (a write's 409
+/// reconnect too), or `renew_after` has passed:
+///
+/// 1. `assertion(for: equipo_origin)`;
+/// 2. `POST /api/v1/ask/oficina`;
+/// 3. read `/ask/state` again, whatever happened.
+///
+/// - `ready`: done. `not_linked` (Equipo doesn't know this person): Ask
+/// shows it, with the web's set-up; never retried by itself.
+/// - `422 failed`: once more at once, with a fresh assertion.
+/// - `409 superseded` (the person disconnected or reconnected another way
+/// meanwhile): not retried; the state read afresh says how things are.
+/// - The kit's CancellationError (the sign-in changed while Home answered,
+/// its own silent re-sign-in after a 401 included): nothing shown, tried
+/// again at the next foreground or state load.
+/// - Anything else: Ask stays as Base reports it; tried again later.
+///
+/// Never more than once a minute, whatever triggers it, but for a person
+/// pressing Set it up.
+@MainActor public final class AskSetup {
+ public typealias Assertion = @MainActor (URL) async throws -> (assertion: String, verifier: String)
+
+ let client: BaseClient
+ let ask: AskModel
+ let assertion: Assertion
+ let now: () -> Date
+ /// The Equipo Ask relays to, when `/ask/state` hasn't said yet.
+ var fallbackEquipo: () -> URL?
+ private(set) var lastAttempt: Date?
+ private(set) var running = false
+ /// Equipo answered not_linked: no more automatic attempts this session.
+ private(set) var notLinked = false
+
+ public init(client: BaseClient, ask: AskModel, assertion: @escaping Assertion, now: @escaping () -> Date = Date.init,
+ fallbackEquipo: @escaping () -> URL? = { nil }) {
+ self.client = client; self.ask = ask; self.assertion = assertion; self.now = now; self.fallbackEquipo = fallbackEquipo
+ }
+
+ /// Whether Ask wants setting up now, by its state.
+ public var wanted: Bool {
+ switch ask.phase {
+ case .connect, .reconnect: true
+ case .ready, .norunner, .oldrunner: ask.renewAfter.map { $0 <= now() } ?? false
+ default: false
+ }
+ }
+
+ /// Runs the set-up if Ask wants it and the minute has passed (`force`:
+ /// the person pressed Set it up, which also clears a not_linked).
+ @discardableResult
+ public func runIfNeeded(force: Bool = false) async -> Bool {
+ // Base still says connect after not_linked: Ask keeps saying why.
+ if notLinked, !force, ask.phase == .connect || ask.phase == .reconnect { ask.show(.notLinked); return false }
+ guard !running, wanted || (force && ask.phase != .loading) else { return false }
+ if !force {
+ guard !notLinked else { return false }
+ if let last = lastAttempt, now().timeIntervalSince(last) < 60 { return false }
+ }
+ guard let equipo = ask.equipoOrigin ?? fallbackEquipo() else { return false }
+ running = true
+ defer { running = false }
+ lastAttempt = now()
+ notLinked = false
+ var tries = 0
+ while tries < 2 {
+ tries += 1
+ let proof: (assertion: String, verifier: String)
+ do {
+ proof = try await assertion(equipo)
+ } catch {
+ // CancellationError (the sign-in moved under it) and any other
+ // failure to get a proof: nothing to show; next time.
+ return false
+ }
+ do {
+ let answer = try await client.connectAsk(assertion: proof.assertion, verifier: proof.verifier)
+ if answer.state == .notLinked { notLinked = true; ask.show(.notLinked); return false }
+ await ask.load()
+ return true
+ } catch .server(422, _, "failed") where tries < 2 {
+ continue
+ } catch .server(409, _, "not_linked") {
+ notLinked = true
+ ask.show(.notLinked)
+ return false
+ } catch {
+ // superseded, unavailable, Ask off, a refused session: Ask as
+ // Base says it is now.
+ await ask.load()
+ return false
+ }
+ }
+ await ask.load()
+ return false
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift
index a488a30..7a51513 100644
--- a/native/apple/Sources/BaseKit/Session/BaseSession.swift
+++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift
@@ -32,6 +32,7 @@ import RastrilloApple
public private(set) var ask: AskModel?
public private(set) var me: Me?
public private(set) var home: HomeData?
+ @ObservationIgnored public private(set) var askSetup: AskSetup?
@ObservationIgnored private var transport: SwappableTransport?
@ObservationIgnored private var watching: AnyCancellable?
@@ -66,6 +67,10 @@ import RastrilloApple
/// older generation publishes nothing.
@ObservationIgnored private(set) var generation = 0
@ObservationIgnored private(set) var refreshing: Task<Void, Never>?
+ /// An Oficina ID assertion addressed to `audience` (Equipo): the kit's.
+ @ObservationIgnored lazy var assertion: @MainActor (URL) async throws -> (assertion: String, verifier: String) = { [oficina] audience in
+ try await oficina.assertion(for: audience)
+ }
/// Base refused the session: the kit mints a new one silently.
@ObservationIgnored lazy var rejected: @MainActor () async -> Void = { [oficina] in await oficina.sessionRejected() }
@@ -91,7 +96,17 @@ import RastrilloApple
transport = swappable
self.client = client
signedIn = state
- ask = AskModel(client: client)
+ let ask = AskModel(client: client)
+ let setup = AskSetup(client: client, ask: ask, assertion: { [weak self] equipo in
+ guard let self, self.generation == epoch else { throw CancellationError() }
+ return try await self.assertion(equipo)
+ }, fallbackEquipo: { [weak self] in self?.me?.equipoOrigin })
+ ask.onNeedsSetup = { [weak self, weak setup] in
+ guard let self, self.generation == epoch, let setup else { return }
+ Task { await setup.runIfNeeded() }
+ }
+ self.ask = ask
+ askSetup = setup
refreshing = Task { await self.refresh() }
}
@@ -102,7 +117,7 @@ import RastrilloApple
refreshing?.cancel()
refreshing = nil
ask?.pause()
- ask = nil; client = nil; transport = nil; account = nil
+ ask = nil; askSetup = nil; client = nil; transport = nil; account = nil
signedIn = nil; me = nil; home = nil
}
@@ -118,8 +133,13 @@ import RastrilloApple
guard generation == epoch, !Task.isCancelled else { return }
if let newMe { self.me = newMe }
if let newHome { self.home = newHome }
+ // Ask set up (or renewed) with Oficina ID, if it wants it.
+ await askSetup?.runIfNeeded()
}
+ /// Set it up (the person pressed the button): now, whatever the minute.
+ public func setUpAsk() async { await askSetup?.runIfNeeded(force: true) }
+
/// The app came forward.
public func foreground() async {
await oficina.renewIfNeeded()
diff --git a/native/apple/Sources/BaseKit/SignIn/BaseOnboarding.swift b/native/apple/Sources/BaseKit/SignIn/BaseOnboarding.swift
index 8ff8a33..671ef65 100644
--- a/native/apple/Sources/BaseKit/SignIn/BaseOnboarding.swift
+++ b/native/apple/Sources/BaseKit/SignIn/BaseOnboarding.swift
@@ -1,15 +1,181 @@
import RastrilloApple
import SwiftUI
-/// Signing in, when the kit can't go straight in: its Oficina ID
-/// onboarding over Base's sky (Task 12 draws Base's copy round it).
+/// Signing in, on the rare device with no Oficina ID yet (the kit goes
+/// straight in otherwise): the kit's Oficina ID flow drawn in Base's look
+/// (mockups mac-signin, phone-signin). The sky; the wordmark; "Sign in to
+/// Base" and which account this is; then a glass card with the email field,
+/// Email me a code, or, and Sign in with a passkey. The code step says
+/// where the code went, and sends a new one. Errors are the kit's own.
+///
+/// The kit's model drives every step. The few that copy review hasn't
+/// drawn for Base (choosing among several IDs or teams, Continue as, no
+/// teams, Oficina ID unreachable) are the kit's own onboarding. P3: a
+/// person Base doesn't know yet (the kit's notMember) is told to sign in
+/// to Base on the web once.
public struct BaseSignIn: View {
@ObservedObject var model: OficinaIDModel
- public init(model: OficinaIDModel) { self.model = model }
+ let openURL: (URL) -> Void
+ @State private var typed = ""
+ @FocusState private var focused: Bool
+ @Environment(\.colorScheme) private var scheme
+
+ public init(model: OficinaIDModel, openURL: @escaping (URL) -> Void = { _ in }) {
+ self.model = model
+ self.openURL = openURL
+ }
+
public var body: some View {
- ZStack {
- Sky()
+ switch model.step {
+ case .welcome, .email, .code, .passkey, .notMember, .loading:
+ door
+ default:
OficinaOnboardingView(model: model)
}
}
+
+ private var door: some View {
+ let p = Palette(scheme)
+ return ZStack {
+ Sky()
+ ScrollView {
+ VStack(spacing: 0) {
+ HStack(spacing: 10) {
+ BaseMark(size: 20)
+ Text(BaseText.text("native.wordmark")).font(BaseFont.heading(24, .semibold, relativeTo: .title2))
+ }
+ .accessibilityHidden(true)
+ .padding(.top, 54)
+ if model.step == .loading {
+ ProgressView().controlSize(.large).padding(.top, 60)
+ } else {
+ Text(heading).font(BaseFont.heading(30, .medium, relativeTo: .largeTitle))
+ .multilineTextAlignment(.center)
+ .padding(.top, 22).padding(.bottom, 6)
+ .accessibilityAddTraits(.isHeader)
+ Text(lede).font(BaseFont.body(15)).foregroundStyle(p[.haze])
+ .multilineTextAlignment(.center).frame(maxWidth: 360)
+ .padding(.bottom, 22)
+ card(p)
+ if case .code = model.step {
+ Text(BaseText.text("native.signin.code.passkey_next"))
+ .font(BaseFont.body(12.5, relativeTo: .footnote)).foregroundStyle(p[.haze])
+ .multilineTextAlignment(.center).frame(maxWidth: 380).padding(.top, 18)
+ }
+ }
+ }
+ .padding(.horizontal, 22).padding(.bottom, 22)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .foregroundStyle(p[.frost])
+ .onChange(of: model.error) { _, value in if let value { AccessibilityNotification.Announcement(value).post() } }
+ }
+
+ private var heading: String {
+ switch model.step {
+ case .code: BaseText.text("native.signin.code.title")
+ default: BaseText.text("native.signin.title")
+ }
+ }
+
+ private var lede: String {
+ switch model.step {
+ case .code(let email): BaseText.format("native.signin.code.lede", ["email": email])
+ case .notMember: BaseText.text("native.signin.unknown")
+ default: BaseText.text("native.signin.lede")
+ }
+ }
+
+ @ViewBuilder private func card(_ p: Palette) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ switch model.step {
+ case .code:
+ TextField(text: $model.code, prompt: Text(verbatim: "000000")) { Text(BaseText.text("native.signin.code.title")) }
+ .textContentType(.oneTimeCode)
+ #if os(iOS)
+ .keyboardType(.numberPad)
+ #endif
+ .font(BaseFont.heading(24, .semibold).monospacedDigit())
+ .multilineTextAlignment(.center)
+ .modifier(FieldStyle())
+ .focused($focused)
+ .onAppear { focused = true }
+ .onChange(of: model.code) { _, value in
+ if value.filter(\.isNumber).count == 6, !model.busy { Task { await model.submitCode() } }
+ }
+ .onSubmit { Task { await model.submitCode() } }
+ Button { Task { await model.resend() } } label: { Text(BaseText.text("native.signin.code.resend")) }
+ .buttonStyle(BaseButtonStyle(.ghost, expands: true))
+ .disabled(model.busy || (model.resendAvailableAt.map { $0 > .now } ?? false))
+ case .notMember(let team):
+ Button { if let base = team.origin(for: "base") { openURL(base.appendingPathComponent("signin")) } } label: {
+ Text(BaseText.text("native.signin.unknown.button"))
+ }
+ .buttonStyle(BaseButtonStyle(.primary, expands: true))
+ case .passkey:
+ passkeyButton(primary: true)
+ default:
+ Text(BaseText.text("native.signin.email.label")).font(BaseFont.body(13, .semibold))
+ TextField(text: $typed, prompt: Text(verbatim: "")) { Text(BaseText.text("native.signin.email.label")) }
+ .textContentType(.emailAddress)
+ #if os(iOS)
+ .keyboardType(.emailAddress).textInputAutocapitalization(.never)
+ #endif
+ .autocorrectionDisabled()
+ .font(BaseFont.body(16))
+ .modifier(FieldStyle())
+ .focused($focused)
+ .onSubmit(sendCode)
+ Button(action: sendCode) { Text(BaseText.text("native.signin.email.send")) }
+ .buttonStyle(BaseButtonStyle(.primary, expands: true))
+ .disabled(typed.trimmingCharacters(in: .whitespaces).isEmpty)
+ HStack(spacing: 10) {
+ Rectangle().fill(p[.rule]).frame(height: 1)
+ Text(BaseText.text("native.signin.or")).font(BaseFont.body(13)).foregroundStyle(p[.haze])
+ Rectangle().fill(p[.rule]).frame(height: 1)
+ }
+ passkeyButton(primary: false)
+ }
+ if model.busy { ProgressView().controlSize(.small).frame(maxWidth: .infinity) }
+ // The kit's own words for what went wrong (the coordinator's
+ // ruling: they stay the kit's).
+ if let error = model.error { OficinaErrorLine(error) }
+ }
+ .disabled(model.busy)
+ .padding(18)
+ .frame(maxWidth: 380)
+ .glass(cornerRadius: 20)
+ }
+
+ private func passkeyButton(primary: Bool) -> some View {
+ Button { Task { await model.usePasskey() } } label: {
+ HStack(spacing: 8) {
+ Image(systemName: "person.badge.key").accessibilityHidden(true)
+ Text(BaseText.text("native.signin.passkey"))
+ }
+ }
+ .buttonStyle(BaseButtonStyle(primary ? .primary : .ghost, expands: true))
+ }
+
+ private func sendCode() {
+ let email = typed.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !email.isEmpty else { return }
+ if model.step == .welcome { model.continueWithEmail() }
+ model.email = email
+ Task { await model.submitEmail() }
+ }
+}
+
+/// The web's field (`.input`): 44 pt, 10 pt corners, its fill and edge.
+struct FieldStyle: ViewModifier {
+ @Environment(\.colorScheme) private var scheme
+ func body(content: Content) -> some View {
+ let p = Palette(scheme)
+ content
+ .textFieldStyle(.plain)
+ .padding(.horizontal, 14).frame(minHeight: 44)
+ .background(p[.field], in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ .overlay { RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(p[.fieldEdge], lineWidth: 1) }
+ }
}
diff --git a/native/apple/Sources/BaseMac/BaseMacApp.swift b/native/apple/Sources/BaseMac/BaseMacApp.swift
index 830697a..9cc98c9 100644
--- a/native/apple/Sources/BaseMac/BaseMacApp.swift
+++ b/native/apple/Sources/BaseMac/BaseMacApp.swift
@@ -122,7 +122,7 @@ struct MacRoot: View {
NativeOfflineBanner(origin: state.origin, message: BaseText.text("native.offline")).padding(.top, 8)
}
} else {
- BaseSignIn(model: session.oficina)
+ BaseSignIn(model: session.oficina, openURL: { NSWorkspace.shared.open($0) })
}
}
.ignoresSafeArea()
diff --git a/native/apple/Sources/BaseMac/MacActions.swift b/native/apple/Sources/BaseMac/MacActions.swift
index 8363eac..45338b7 100644
--- a/native/apple/Sources/BaseMac/MacActions.swift
+++ b/native/apple/Sources/BaseMac/MacActions.swift
@@ -16,11 +16,7 @@ import SwiftUI
signOut: { session.signOut() },
teams: { await session.teams() },
switchTo: { await session.switchTo($0) },
- setUpAsk: {
- // Task 12 sets Ask up with Oficina ID; until then, the web's.
- guard let origin = session.signedIn?.origin else { return }
- NSWorkspace.shared.open(origin.appendingPathComponent("ask"))
- })
+ setUpAsk: { Task { await session.setUpAsk() } })
}
static func installed(_ bundleID: String) -> URL? { NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) }
diff --git a/native/apple/Sources/BasePhone/BasePhoneApp.swift b/native/apple/Sources/BasePhone/BasePhoneApp.swift
index 9332d52..fde8074 100644
--- a/native/apple/Sources/BasePhone/BasePhoneApp.swift
+++ b/native/apple/Sources/BasePhone/BasePhoneApp.swift
@@ -42,7 +42,7 @@ struct PhoneRoot: View {
NativeOfflineBanner(origin: state.origin, message: BaseText.text("native.offline"))
}
} else {
- BaseSignIn(model: session.oficina)
+ BaseSignIn(model: session.oficina, openURL: { UIApplication.shared.open($0) })
}
}
.baseAppearance(session.me?.appearance ?? .system)
@@ -70,9 +70,6 @@ struct PhoneRoot: View {
signOut: { session.signOut() },
teams: { await session.teams() },
switchTo: { await session.switchTo($0) },
- setUpAsk: {
- guard let origin = session.signedIn?.origin else { return }
- UIApplication.shared.open(origin.appendingPathComponent("ask"))
- })
+ setUpAsk: { Task { await session.setUpAsk() } })
}
}
diff --git a/native/apple/Tests/BaseKitTests/AskSetupTests.swift b/native/apple/Tests/BaseKitTests/AskSetupTests.swift
new file mode 100644
index 0000000..52b33aa
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/AskSetupTests.swift
@@ -0,0 +1,129 @@
+@testable import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import XCTest
+
+/// Task 12: Ask set up with Oficina ID, without a step.
+@MainActor final class AskSetupTests: XCTestCase {
+ let equipo = URL(string: "https://equipo.fennel.example")!
+ var clock = Date(timeIntervalSince1970: 1_800_000_000)
+ var audiences: [URL] = []
+ var failNext: Error?
+
+ func state(_ phase: String, renewAfter: String = "") -> ScriptedTransport.Step {
+ json(200, #"{"state":"\#(phase)","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"renew_after":"\#(renewAfter)","equipo_origin":"https://equipo.fennel.example"}"#)
+ }
+
+ func make(_ steps: [ScriptedTransport.Step]) async -> (AskSetup, AskModel, ScriptedTransport) {
+ let t = ScriptedTransport(steps)
+ let ask = AskModel(client: BaseClient(transport: t) {}, schedule: { _, _ in })
+ let setup = AskSetup(client: BaseClient(transport: t) {}, ask: ask, assertion: { [unowned self] audience in
+ self.audiences.append(audience)
+ if let error = self.failNext { self.failNext = nil; throw error }
+ return ("assertion-\(self.audiences.count)", "verifier-\(self.audiences.count)")
+ }, now: { [unowned self] in self.clock })
+ await ask.load()
+ return (setup, ask, t)
+ }
+
+ func paths(_ t: ScriptedTransport) -> [String] { t.calls.map(\.path) }
+
+ func testConnectSetsAskUpAndReadsTheStateAgain() async throws {
+ let (setup, ask, t) = await make([state("connect"), json(200, #"{"state":"ready","renew_after":"2026-11-28T10:00:00Z"}"#), state("ready"), .hang])
+ let done = await setup.runIfNeeded()
+ XCTAssertTrue(done)
+ XCTAssertEqual(audiences, [equipo], "the assertion is addressed to Equipo")
+ XCTAssertEqual(paths(t).prefix(3), ["/ask/state", "/api/v1/ask/oficina", "/ask/state"])
+ let body = try JSONSerialization.jsonObject(with: t.calls[1].body!) as? [String: String]
+ XCTAssertEqual(body, ["assertion": "assertion-1", "verifier": "verifier-1"])
+ XCTAssertEqual(ask.phase, .ready)
+ ask.pause()
+ }
+
+ func testReconnectAndAPassedRenewalRunIt() async {
+ let (setup, ask, _) = await make([state("ready", renewAfter: "2027-02-01T07:00:00Z")])
+ XCTAssertFalse(setup.wanted, "renew_after hasn't passed")
+ clock = Date(timeIntervalSince1970: 1_900_000_000)
+ XCTAssertTrue(setup.wanted, "renew_after has passed")
+ ask.pause()
+ let (reconnect, _, _) = await make([state("reconnect")])
+ XCTAssertTrue(reconnect.wanted)
+ let (ready, _, _) = await make([state("ready")])
+ XCTAssertFalse(ready.wanted, "a code-flow key has no renew_after")
+ }
+
+ func testNotLinkedShowsItsStateAndNeverLoops() async {
+ let (setup, ask, t) = await make([state("connect"), json(409, #"{"state":"not_linked"}"#)])
+ let first = await setup.runIfNeeded()
+ XCTAssertFalse(first)
+ XCTAssertEqual(ask.phase, .notLinked)
+ clock += 3600
+ let again = await setup.runIfNeeded()
+ XCTAssertFalse(again)
+ XCTAssertEqual(audiences.count, 1, "no second attempt by itself")
+ XCTAssertEqual(paths(t), ["/ask/state", "/api/v1/ask/oficina"])
+ }
+
+ func testFailedRetriesOnceWithAFreshAssertion() async throws {
+ let (setup, _, t) = await make([state("connect"), json(422, #"{"state":"failed"}"#), json(422, #"{"state":"failed"}"#), state("connect")])
+ _ = await setup.runIfNeeded()
+ XCTAssertEqual(audiences.count, 2)
+ XCTAssertEqual(paths(t), ["/ask/state", "/api/v1/ask/oficina", "/api/v1/ask/oficina", "/ask/state"])
+ let second = try JSONSerialization.jsonObject(with: t.calls[2].body!) as? [String: String]
+ XCTAssertEqual(second?["assertion"], "assertion-2", "a fresh assertion")
+ }
+
+ func testSupersededIsNotRetriedAndTheStateDecides() async {
+ let (setup, ask, t) = await make([state("connect"), json(409, #"{"state":"superseded"}"#), state("ready"), .hang])
+ _ = await setup.runIfNeeded()
+ XCTAssertEqual(audiences.count, 1)
+ XCTAssertEqual(paths(t).prefix(3), ["/ask/state", "/api/v1/ask/oficina", "/ask/state"])
+ XCTAssertEqual(ask.phase, .ready)
+ ask.pause()
+ }
+
+ /// A failure leaves Ask as Base reports it, and tries again at the next
+ /// trigger, never more than once a minute.
+ func testAFailureWaitsAMinute() async {
+ let (setup, ask, t) = await make([state("connect"), json(502, #"{"state":"unavailable"}"#), state("connect"),
+ json(200, #"{"state":"ready"}"#), state("ready"), .hang])
+ _ = await setup.runIfNeeded()
+ XCTAssertEqual(ask.phase, .connect)
+ clock += 30
+ let early = await setup.runIfNeeded()
+ XCTAssertFalse(early)
+ XCTAssertEqual(audiences.count, 1)
+ clock += 31
+ let later = await setup.runIfNeeded()
+ XCTAssertTrue(later)
+ XCTAssertEqual(paths(t).count, 5)
+ ask.pause()
+ }
+
+ /// The kit's CancellationError (the sign-in moved under it): nothing
+ /// shown, no post, tried again later.
+ func testACancelledAssertionIsQuiet() async {
+ let (setup, ask, t) = await make([state("connect"), json(200, #"{"state":"ready"}"#), state("ready"), .hang])
+ failNext = CancellationError()
+ _ = await setup.runIfNeeded()
+ XCTAssertEqual(ask.phase, .connect)
+ XCTAssertEqual(paths(t), ["/ask/state"])
+ clock += 61
+ _ = await setup.runIfNeeded()
+ XCTAssertEqual(ask.phase, .ready)
+ ask.pause()
+ }
+
+ /// Pressing Set it up runs it at once, inside the minute.
+ func testPressingSetItUpRunsAtOnce() async {
+ let (setup, ask, _) = await make([state("connect"), json(502, #"{"state":"unavailable"}"#), state("connect"),
+ json(200, #"{"state":"ready"}"#), state("ready"), .hang])
+ _ = await setup.runIfNeeded()
+ clock += 5
+ let pressed = await setup.runIfNeeded(force: true)
+ XCTAssertTrue(pressed)
+ XCTAssertEqual(ask.phase, .ready)
+ ask.pause()
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/SessionTests.swift b/native/apple/Tests/BaseKitTests/SessionTests.swift
index 04397b5..e97c3b4 100644
--- a/native/apple/Tests/BaseKitTests/SessionTests.swift
+++ b/native/apple/Tests/BaseKitTests/SessionTests.swift
@@ -84,3 +84,23 @@ extension SessionTests {
XCTAssertEqual(rejections, 1, "the current account's refusal still reaches the kit")
}
}
+
+extension SessionTests {
+ /// Task 12: signing in sets Ask up when /ask/state says connect, with
+ /// an assertion addressed to Equipo, and reads the state again.
+ func testSigningInSetsAskUp() async {
+ let session = BaseSession(oficina: memoryOficina())
+ var audiences: [URL] = []
+ session.assertion = { audiences.append($0); return ("a", "v") }
+ let t = gated("alice", "Alice's", "Hello Alice")
+ t.answer("/ask/state", #"{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"equipo_origin":"https://equipo.alice.example"}"#)
+ t.answer("/api/v1/ask/oficina", #"{"state":"ready","renew_after":"2026-11-28T10:00:00Z"}"#)
+ for path in ["/api/v1/me", "/api/v1/home", "/ask/state", "/api/v1/ask/oficina"] { t.release(path) }
+ session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: t)
+ await session.refreshing?.value
+ XCTAssertEqual(audiences, [URL(string: "https://equipo.alice.example")!])
+ XCTAssertTrue(t.calls.contains("/api/v1/ask/oficina"))
+ XCTAssertGreaterThanOrEqual(t.calls.filter { $0 == "/ask/state" }.count, 2)
+ session.end()
+ }
+}
diff --git a/native/apple/Tests/BaseSnapshots/SignInSnapshots.swift b/native/apple/Tests/BaseSnapshots/SignInSnapshots.swift
new file mode 100644
index 0000000..632e2a8
--- /dev/null
+++ b/native/apple/Tests/BaseSnapshots/SignInSnapshots.swift
@@ -0,0 +1,50 @@
+import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloSnapshots
+import RastrilloTestSupport
+import SwiftUI
+import XCTest
+
+/// Sign-in (Task 12, mockups mac-signin, phone-signin): the email step,
+/// the code step and P3's "sign in on the web once", walked to through the
+/// kit's in-memory Oficina ID (no keychain, App Group or network).
+final class SignInSnapshots: XCTestCase {
+ @MainActor func testSignIn() async throws {
+ try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil, "Run with native/scripts/snapshots.sh")
+ BaseFonts.register()
+ let email = model(), code = model(), unknown = model(admission: .nonMember)
+ await email.start()
+ await walk(code)
+ await walk(unknown, signIn: true)
+ await assertSnapshots(of: SnapshotCatalog(app: "base-signin", settings: SnapshotSettings(tint: LookSnapshots.tint), screens: [
+ SnapshotScreen("email", mac: .fixed(width: 560, height: 640), iphone: .fixed(width: 402, height: 874)) { BaseSignIn(model: email).skyFrozen() },
+ SnapshotScreen("code", mac: .fixed(width: 560, height: 640), iphone: .fixed(width: 402, height: 874)) { BaseSignIn(model: code).skyFrozen() },
+ SnapshotScreen("unknown", mac: .fixed(width: 560, height: 640), iphone: .fixed(width: 402, height: 874)) { BaseSignIn(model: unknown).skyFrozen() },
+ ]))
+ }
+
+ @MainActor func model(admission: FakeOficinaIDService.Admission = .linked) -> OficinaIDModel {
+ let service = FakeOficinaIDService()
+ service.addPerson(email: "paul@fennel.example", identityID: "id-paul")
+ let team = OficinaTeam(sqid: "t1", label: "fennel", name: "Fennel & Rye", role: "member",
+ apps: [OficinaTeamApp(app: "base", origin: "https://fennel.base.oficina.works", consumerID: "t1-base")])
+ service.setTeams([team], for: "id-paul")
+ service.admit("id-paul", at: team.origin(for: "base")!, as: admission)
+ let suite = "SignInSnapshots.\(UUID().uuidString)"
+ let defaults = UserDefaults(suiteName: suite)!
+ let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults)
+ return OficinaIDModel(configuration: BaseSession.configuration, store: store, service: service, passkeys: FakePasskeys(),
+ makeKey: { OficinaSoftwareKey() }, now: { SnapshotSettings.now }, appDefaults: defaults)
+ }
+
+ @MainActor func walk(_ model: OficinaIDModel, signIn: Bool = false) async {
+ await model.start()
+ model.continueWithEmail()
+ model.email = "paul@fennel.example"
+ await model.submitEmail()
+ guard signIn else { return }
+ model.code = FakeOficinaIDService.goodCode
+ await model.submitCode()
+ }
+}
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/ENVIRONMENT b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/ENVIRONMENT
new file mode 100644
index 0000000..a26fa8a
--- /dev/null
+++ b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/ENVIRONMENT
@@ -0,0 +1,10 @@
+os: iOS 27.0.0
+device: iPhone19,2
+runtime: 27.0 (24A434)
+toolchain: Xcode 27.2 Build version 27B52
+language: en
+locale: en_IE
+time zone: Europe/Dublin
+increase contrast: off
+reduce transparency: off
+differentiate without colour: off
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-ax3.png
new file mode 100644
index 0000000..ad99837
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-default.png
new file mode 100644
index 0000000..a115e96
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-ax3.png
new file mode 100644
index 0000000..2ec25ec
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-default.png
new file mode 100644
index 0000000..6b5b29a
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/code-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-ax3.png
new file mode 100644
index 0000000..5cba223
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-default.png
new file mode 100644
index 0000000..ecc7fac
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-ax3.png
new file mode 100644
index 0000000..bac70ea
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-default.png
new file mode 100644
index 0000000..48ca26a
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/email-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-ax3.png
new file mode 100644
index 0000000..9fddd3e
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-default.png
new file mode 100644
index 0000000..e992e88
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-ax3.png
new file mode 100644
index 0000000..41ec81a
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-default.png
new file mode 100644
index 0000000..d6a064b
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/iphone/unknown-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/ENVIRONMENT b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/ENVIRONMENT
new file mode 100644
index 0000000..2a04923
--- /dev/null
+++ b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/ENVIRONMENT
@@ -0,0 +1,9 @@
+os: macOS 27.0.0
+toolchain: Xcode 27.2 Build version 27B52
+language: en
+accent: #007AFF
+locale: en_IE
+time zone: Europe/Dublin
+increase contrast: off
+reduce transparency: off
+differentiate without colour: off
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-dark-default.png
new file mode 100644
index 0000000..127d311
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-light-default.png
new file mode 100644
index 0000000..6f24c6a
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/code-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-dark-default.png
new file mode 100644
index 0000000..006cd55
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-light-default.png
new file mode 100644
index 0000000..09e3bcc
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/email-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-dark-default.png
new file mode 100644
index 0000000..27714e1
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-light-default.png
new file mode 100644
index 0000000..cdf7263
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-signin/mac/unknown-light-default.png differ