SPB Git

Repository Public

TokenManager.swift 4.6 KB 110 lines swift

1import Foundation23/// Why the session ended without the user asking for it.4public enum SessionEndReason: Sendable, Equatable {5    /// The server rejected the refresh token (expired, revoked session or device, or reuse of a rotated token).6    case refreshRejected(APIError)7    /// The user signed out.8    case signedOut9}1011/// Owns the native session tokens: hands out the access token, performs the single-flight refresh and wipes the12/// session when the server rejects the refresh token.13public actor TokenManager {14    public typealias Refresher = @Sendable (_ refreshToken: String) async throws -> SessionTokens1516    private let store: SessionStore17    private let refresher: Refresher18    private var tokens: SessionTokens?19    private var refreshTask: Task<SessionTokens, any Error>?20    private var endObservers: [UUID: AsyncStream<SessionEndReason>.Continuation] = [:]21    private var refreshCount = 022    /// Refresh this long before the access token expires, so that a request rarely starts with a dying token.23    private let leeway: TimeInterval2425    public init(store: SessionStore, leeway: TimeInterval = 20, refresher: @escaping Refresher) {26        self.store = store27        self.refresher = refresher28        self.leeway = leeway29        self.tokens = store.loadTokens()30    }3132    public var hasSession: Bool { tokens != nil }33    public var deviceID: String? { store.loadDeviceID() }34    /// Number of refresh requests actually sent (tests assert the single flight with it).35    public var refreshRequestCount: Int { refreshCount }36    public var accessExpiresAt: Date? { tokens?.accessExpiresAt }3738    /// Installs the tokens of a fresh sign-in.39    public func install(_ new: SessionTokens, deviceID: String) throws {40        tokens = new41        try store.saveDeviceID(deviceID)42        try store.save(new)43    }4445    /// The access token to send, refreshed first when it is about to expire. Nil when signed out.46    public func accessToken() async throws -> String? {47        guard let t = tokens else { return nil }48        if t.accessExpiresAt.timeIntervalSinceNow < leeway {49            return try await refresh().accessToken50        }51        return t.accessToken52    }5354    /// Called after a `401` obtained with `rejected`. If another request already rotated the tokens the new access55    /// token is returned without any network call; otherwise exactly one refresh runs and every concurrent caller56    /// awaits it.57    public func refreshAfterRejection(of rejected: String) async throws -> String {58        guard let t = tokens else { throw APIError.signedOut }59        if t.accessToken != rejected { return t.accessToken }60        return try await refresh().accessToken61    }6263    private func refresh() async throws -> SessionTokens {64        if let running = refreshTask { return try await running.value }65        guard let current = tokens else { throw APIError.signedOut }66        refreshCount += 167        // Unstructured on purpose: the refresh must complete even if the request that triggered it is cancelled,68        // otherwise a rotated refresh token could be lost and the session with it.69        let task = Task { try await refresher(current.refreshToken) }70        refreshTask = task71        do {72            let new = try await task.value73            refreshTask = nil74            tokens = new75            try? store.save(new)76            return new77        } catch {78            refreshTask = nil79            let e = APIError.from(error)80            if e.status == 401 || e.status == 403 {81                // refresh_rejected (expired, revoked, device revoked, or reuse detected → session revoked server-side).82                endSession(.refreshRejected(e), wipeDevice: true)83                throw APIError(status: 401, code: APIError.codeSignedOut, message: e.message, correlationID: e.correlationID)84            }85            throw e86        }87    }8889    /// Local sign-out (the caller has already told the server, or cannot reach it).90    public func signOut() {91        endSession(.signedOut, wipeDevice: false)92    }9394    private func endSession(_ reason: SessionEndReason, wipeDevice: Bool) {95        tokens = nil96        if wipeDevice { store.wipeAll() } else { store.wipeTokens() }97        endObservers.values.forEach { $0.yield(reason) }98    }99100    /// Emits when the session ends.101    public func sessionEnds() -> AsyncStream<SessionEndReason> {102        AsyncStream { cont in103            let id = UUID()104            endObservers[id] = cont105            cont.onTermination = { [weak self] _ in Task { await self?.removeObserver(id) } }106        }107    }108    private func removeObserver(_ id: UUID) { endObservers[id] = nil }109}110
Files main
Menu

Theme