Repository Public
1import Foundation2import Observation34/// Extracts the invitation token from a setup link (`https://clustr.spboucher.ai/setup#<token>`) or accepts a bare5/// token. The token is a credential: callers keep it in memory only and never log it.6public enum SetupLink {7 public static func token(from text: String) -> String? {8 let s = text.trimmingCharacters(in: .whitespacesAndNewlines)9 guard !s.isEmpty else { return nil }10 if let url = URL(string: s), url.scheme != nil {11 guard url.path == "/setup" || url.host == "setup" || url.path.hasSuffix("/setup") else { return nil }12 guard let f = url.fragment, isToken(f) else { return nil }13 return f14 }15 return isToken(s) ? s : nil16 }1718 public static func isSetupURL(_ url: URL) -> Bool { token(from: url.absoluteString) != nil }1920 private static func isToken(_ s: String) -> Bool {21 s.count >= 20 && s.count <= 200 && s.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }22 }23}2425/// The invitation setup flow, shared by macOS and iOS: exchange → who and which role → (profile) → passkey, or,26/// for an invitation aimed at an existing account, sign-in → step-up → explicit confirmation.27@MainActor28@Observable29public final class InvitationSetupModel {30 public enum Step: Sendable, Equatable {31 case exchanging32 /// Expired, already used or revoked: a dead end, a new invitation is needed.33 case invalid34 case review35 case profile36 case createPasskey37 case linkSignIn38 case linkConfirm39 case done40 }4142 public private(set) var step: Step = .exchanging43 public private(set) var transaction: API.InvitationTransaction?44 public private(set) var error: APIError?45 public private(set) var isWorking = false46 public private(set) var linkedUser: API.User?47 public var handle = ""48 public var displayName = ""49 public var passkeyLabel = ""50 public var linkConfirmed = false5152 @ObservationIgnored private let session: AppSession5354 public init(session: AppSession) {55 self.session = session56 passkeyLabel = DeviceInfo.storedLabel()57 }5859 public var isLink: Bool { transaction?.requiresExistingAccount ?? false }6061 /// Exchanges the token immediately (it is single use and consumed by this call).62 public func begin(token: String) async {63 step = .exchanging64 error = nil65 do {66 let tx = try await session.auth.exchangeInvitation(token: token)67 apply(tx)68 step = .review69 } catch {70 self.error = APIError.from(error)71 step = .invalid72 }73 }7475 private func apply(_ tx: API.InvitationTransaction) {76 transaction = tx77 if let h = tx.handle, handle.isEmpty { handle = h }78 if let n = tx.displayName, displayName.isEmpty { displayName = n }79 }8081 /// The user has read who invites them and with which role.82 public func acceptReview() {83 guard let tx = transaction else { return }84 error = nil85 if tx.requiresExistingAccount {86 step = session.phase == .signedIn ? .linkConfirm : .linkSignIn87 } else {88 step = tx.profileRequired ? .profile : .createPasskey89 }90 }9192 private func perform(_ op: () async throws -> Void) async {93 isWorking = true94 error = nil95 defer { isWorking = false }96 do { try await op() } catch {97 let e = APIError.from(error)98 if e.isPasskeyCancelled { return }99 self.error = e100 if e.isGone { step = .invalid }101 }102 }103104 public func submitProfile() async {105 await perform {106 let tx = try await session.auth.setInvitationProfile(handle: handle.trimmingCharacters(in: .whitespaces).lowercased(),107 displayName: displayName.trimmingCharacters(in: .whitespaces))108 apply(tx)109 step = .createPasskey110 }111 }112113 /// Creates the passkey; the server completes the invitation and opens the session.114 public func createPasskey() async {115 await perform {116 let label = passkeyLabel.trimmingCharacters(in: .whitespaces)117 try await session.auth.completeInvitation(passkeyLabel: label.isEmpty ? nil : label)118 step = .done119 await session.sessionOpened()120 }121 }122123 public func signInForLink() async {124 await perform {125 try await session.signIn()126 step = .linkConfirm127 }128 }129130 /// Explicit confirmation by the signed-in account; the step-up ceremony runs if the server asks for it.131 public func confirmLink() async {132 guard linkConfirmed else { return }133 await perform {134 let r = try await session.auth.linkInvitation(confirmed: true)135 linkedUser = r.user136 step = .done137 await session.account.me.load()138 }139 }140141 public func cancel() async {142 await session.auth.abandonInvitation()143 }144}145