Skip to content

Open source CapCut alternative.

TypeScript

feat(app): sync sign-out across the app and website

David Le2c002a0f5f74
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
index 1bc910c7..bd0893e3 100644
--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
@@ -24,6 +24,12 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
/// common "topped up in the browser, came back" path. Both are torn down on sign-out.
private var creditReloadPollTimer: Timer?
private var creditReloadActiveObserver: NSObjectProtocol?
+ /// Periodically reconciles the app's session against the server, so a sign-out performed on the website
+ /// (or another device) takes effect here without a relaunch. A periodic tick plus an app-reactivation
+ /// observer fire a cheap auth-gated probe; a 401 routes through the usual session-expiry handling. Both
+ /// run only while signed in and are torn down on sign-out.
+ private var sessionHeartbeatTimer: Timer?
+ private var sessionHeartbeatActiveObserver: NSObjectProtocol?
func applicationDidFinishLaunching(_ notification: Notification) {
if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {
@@ -169,9 +175,10 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
}
// A mid-run 401 expired the session: sign out (clears the dead cookie, flips phase to signedOut)
// so the $phase observer below sets needsLogin — surfacing the notch login WITHOUT tearing down
- // the overlay or opening the window, so running tasks stay put and re-auth happens inline.
+ // the overlay or opening the window, so running tasks stay put and re-auth happens inline. The
+ // server already revoked this session (that's what the 401 means), so this is local cleanup only.
model.sessionExpired = { [weak self] in
- self?.authCoordinator?.signOut()
+ self?.authCoordinator?.signOut(revokingRemoteSessions: false)
}
if let authCoordinator {
model.updateNeedsLogin(!authCoordinator.isAuthenticated)
@@ -182,10 +189,6 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
}
}
- // A locally-stored session can already be expired server-side, which otherwise only surfaces on
- // the first query's 401. Probe the backend on launch so the notch shows login right away.
- validateStoredSession(model: model)
-
// Keep the out-of-credits CTA honest: poll the balance while any task is credit-blocked and clear
// the CTA the moment a top-up lands, so it doesn't linger until the next relaunch.
startCreditReloadReconciler(model: model)
@@ -236,17 +239,58 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
if isSignedIn {
uiUnderstandingCoordinator?.start()
model?.resumeLiveSession()
+ if let model { startSessionHeartbeat(model: model) }
} else {
uiUnderstandingCoordinator?.stop()
model?.suspendLiveSession()
+ stopSessionHeartbeat()
+ }
+ }
+
+ // MARK: - Session heartbeat
+
+ /// Starts the session heartbeat: a periodic tick plus an app-reactivation observer, each firing a cheap
+ /// session-validity probe, plus one immediate probe. Idempotent — a no-op while already running, so the
+ /// auth-phase observer can call it freely. Torn down by `stopSessionHeartbeat` on sign-out.
+ private func startSessionHeartbeat(model: UserQueryOverlayModel) {
+ guard sessionHeartbeatTimer == nil else { return }
+
+ sessionHeartbeatTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self, weak model] _ in
+ Task { @MainActor in
+ guard let self, let model else { return }
+ self.probeSessionValidity(model: model)
+ }
+ }
+ sessionHeartbeatActiveObserver = NotificationCenter.default.addObserver(
+ forName: NSApplication.didBecomeActiveNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self, weak model] _ in
+ Task { @MainActor in
+ guard let self, let model else { return }
+ self.probeSessionValidity(model: model)
+ }
+ }
+
+ // A locally-stored session can already be dead server-side; probe right away so the notch shows
+ // login immediately instead of only on the first real query's 401.
+ probeSessionValidity(model: model)
+ }
+
+ private func stopSessionHeartbeat() {
+ sessionHeartbeatTimer?.invalidate()
+ sessionHeartbeatTimer = nil
+ if let sessionHeartbeatActiveObserver {
+ NotificationCenter.default.removeObserver(sessionHeartbeatActiveObserver)
+ self.sessionHeartbeatActiveObserver = nil
}
}
- /// Confirms a locally-stored session is still valid server-side. Fires one cheap, auth-gated GET
+ /// Confirms the session is still valid server-side. Fires one cheap, auth-gated GET
/// (`/api/inference/models/`); a 401 routes through the model's session-expiry handling (sign out →
- /// notch login) via the inference client's auth-expiry callback. Network or other errors are
- /// ignored so a transient hiccup never signs the user out. Runs off the launch path.
- private func validateStoredSession(model: UserQueryOverlayModel) {
+ /// notch login) via the inference client's auth-expiry callback. Network or other errors are ignored
+ /// so a transient hiccup never signs the user out.
+ private func probeSessionValidity(model: UserQueryOverlayModel) {
guard authCoordinator?.isAuthenticated == true,
let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment()
else { return }
@@ -344,7 +388,9 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
}
private func signOut() {
- authCoordinator?.signOut()
+ // User-initiated: revoke every session for this user so the website (and any other device) signs
+ // out too, then tear down local surfaces and surface login.
+ authCoordinator?.signOut(revokingRemoteSessions: true)
teardownAuthenticatedSurfaces()
showLoginWindow()
}
@@ -354,6 +400,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
private func teardownAuthenticatedSurfaces() {
authStateCancellable = nil
stopCreditReloadReconciler()
+ stopSessionHeartbeat()
uiUnderstandingCoordinator?.stop()
uiUnderstandingCoordinator = nil
overlayController?.stop()
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift
index 1a2554c9..6d9900ca 100644
--- a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift
+++ b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift
@@ -96,17 +96,24 @@ final class DonkeyAuthCoordinator: ObservableObject {
private let configuration: DonkeyAuthConfiguration
private let stateStore: DonkeyAuthStateStoring
private let nativeSessionExchanger: any DonkeyNativeSessionExchanging
+ private let remoteSessionRevoker: any DonkeyRemoteSessionRevoking
private let cookieStorage: HTTPCookieStorage
+ /// The in-flight best-effort remote revoke spawned by a user-initiated sign-out. Exposed so it can
+ /// be awaited in tests; production code never reads it.
+ private(set) var pendingRemoteRevokeTask: Task<Void, Never>?
+
init(
configuration: DonkeyAuthConfiguration = .current(),
stateStore: DonkeyAuthStateStoring = DonkeyAuthStateStore(),
nativeSessionExchanger: any DonkeyNativeSessionExchanging = DonkeyNativeSessionCookieExchanger(),
+ remoteSessionRevoker: any DonkeyRemoteSessionRevoking = DonkeyRemoteSessionRevoker(),
cookieStorage: HTTPCookieStorage = .shared
) {
self.configuration = configuration
self.stateStore = stateStore
self.nativeSessionExchanger = nativeSessionExchanger
+ self.remoteSessionRevoker = remoteSessionRevoker
self.cookieStorage = cookieStorage
if let session = stateStore.loadSession() {
@@ -220,20 +227,39 @@ final class DonkeyAuthCoordinator: ObservableObject {
phase = stateStore.loadSession().map(DonkeyAuthPhase.signedIn) ?? .signedOut
}
- /// Drops the local session and its native session cookie, returning to the
- /// signed-out state. Callers should then surface the login flow again.
- func signOut() {
+ /// Drops the local session and its native session cookie, returning to the signed-out state. Callers
+ /// should then surface the login flow again.
+ ///
+ /// When `revokingRemoteSessions` is true (a user-initiated sign-out), it also fires a best-effort call
+ /// to revoke every Better Auth session for this user, so the browser — and any other device — signs out
+ /// too. The 401-driven path passes false: the server already revoked the session, so this is only local
+ /// cleanup. Local cleanup always runs, even if the revoke call can't be made (e.g. offline).
+ func signOut(revokingRemoteSessions: Bool = true) {
+ // Snapshot the session cookie before clearing local state, so the best-effort remote revoke can
+ // authenticate even though the cookie jar is wiped immediately below.
+ let cookies = revokingRemoteSessions ? sessionCookies() : []
+ if revokingRemoteSessions, !cookies.isEmpty {
+ let revoker = remoteSessionRevoker
+ let webBaseURL = configuration.webBaseURL
+ pendingRemoteRevokeTask = Task {
+ await revoker.revokeAllSessions(webBaseURL: webBaseURL, cookies: cookies)
+ }
+ } else {
+ pendingRemoteRevokeTask = nil
+ }
+
stateStore.clearSession()
stateStore.clearPendingState()
clearSessionCookies()
phase = .signedOut
}
+ private func sessionCookies() -> [HTTPCookie] {
+ cookieStorage.cookies(for: configuration.webBaseURL) ?? []
+ }
+
private func clearSessionCookies() {
- guard let cookies = cookieStorage.cookies(for: configuration.webBaseURL) else {
- return
- }
- for cookie in cookies {
+ for cookie in sessionCookies() {
cookieStorage.deleteCookie(cookie)
}
}
diff --git a/apps/Donkey/Sources/Donkey/DonkeyRemoteSessionRevoker.swift b/apps/Donkey/Sources/Donkey/DonkeyRemoteSessionRevoker.swift
new file mode 100644
index 00000000..5644be5e
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/DonkeyRemoteSessionRevoker.swift
@@ -0,0 +1,49 @@
+import Foundation
+
+/// Revokes every Better Auth session for the signed-in user by calling the web app's
+/// `/api/auth/revoke-sessions` endpoint. This is what makes sign-out symmetric: signing
+/// out in the app tears down the browser's session too, and vice versa. The browser's own
+/// sign-out calls the same endpoint.
+protocol DonkeyRemoteSessionRevoking: Sendable {
+ /// Best-effort revoke of all sessions for the user authenticated by `cookies`.
+ /// Never throws: a network failure must not block the local sign-out.
+ func revokeAllSessions(webBaseURL: URL, cookies: [HTTPCookie]) async
+}
+
+struct DonkeyRemoteSessionRevoker: DonkeyRemoteSessionRevoking {
+ var urlSession: URLSession
+
+ init(urlSession: URLSession = .shared) {
+ self.urlSession = urlSession
+ }
+
+ func revokeAllSessions(webBaseURL: URL, cookies: [HTTPCookie]) async {
+ guard !cookies.isEmpty, let url = revokeURL(webBaseURL: webBaseURL) else { return }
+
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ // Send the captured session cookie explicitly rather than leaning on shared cookie
+ // storage: sign-out clears that storage immediately after spawning this call, so a
+ // storage-backed request could race and go out with no cookie at all.
+ request.httpShouldHandleCookies = false
+ for (field, value) in HTTPCookie.requestHeaderFields(with: cookies) {
+ request.setValue(value, forHTTPHeaderField: field)
+ }
+
+ // `/revoke-sessions` reads the user from the session cookie and takes no body. The
+ // result doesn't matter to the caller — a dead cookie 401s, which is the same as
+ // "already signed out everywhere".
+ _ = try? await urlSession.data(for: request)
+ }
+
+ private func revokeURL(webBaseURL: URL) -> URL? {
+ var components = URLComponents(url: webBaseURL, resolvingAgainstBaseURL: false)
+ let basePath = components?.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? ""
+ components?.path = "/" + [basePath, "api/auth/revoke-sessions"]
+ .filter { !$0.isEmpty }
+ .joined(separator: "/")
+ components?.query = nil
+ components?.fragment = nil
+ return components?.url
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyAuthCoordinatorSignOutTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyAuthCoordinatorSignOutTests.swift
new file mode 100644
index 00000000..d9048d19
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyAuthCoordinatorSignOutTests.swift
@@ -0,0 +1,114 @@
+@testable import Donkey
+import Foundation
+import Testing
+
+/// Sign-out is symmetric: a user-initiated sign-out revokes every Better Auth session for the user (so the
+/// website and other devices sign out too), while a 401-driven sign-out is local cleanup only because the
+/// server already revoked the session.
+@MainActor
+@Suite
+struct DonkeyAuthCoordinatorSignOutTests {
+ @Test
+ func userInitiatedSignOutRevokesAllSessionsRemotely() async {
+ let host = "revoke-test.example"
+ let configuration = DonkeyAuthConfiguration(
+ webBaseURL: URL(string: "https://\(host)")!,
+ callbackScheme: "donkey"
+ )
+ let storage = Self.isolatedCookieStorage()
+ Self.seedSessionCookie(in: storage, host: host)
+ let revoker = RecordingRevoker()
+
+ let coordinator = DonkeyAuthCoordinator(
+ configuration: configuration,
+ stateStore: StubAuthStateStore(),
+ remoteSessionRevoker: revoker,
+ cookieStorage: storage
+ )
+
+ coordinator.signOut(revokingRemoteSessions: true)
+ await coordinator.pendingRemoteRevokeTask?.value
+
+ #expect(revoker.calls.count == 1)
+ #expect(revoker.calls.first?.webBaseURL == configuration.webBaseURL)
+ #expect(revoker.calls.first?.cookies.contains { $0.name.contains("session_token") } == true)
+ #expect(coordinator.isAuthenticated == false)
+ // The local cookie jar is wiped as part of sign-out.
+ #expect((storage.cookies(for: configuration.webBaseURL) ?? []).isEmpty)
+ }
+
+ @Test
+ func sessionExpirySignOutDoesNotRevokeRemotely() async {
+ let host = "norevoke-test.example"
+ let configuration = DonkeyAuthConfiguration(
+ webBaseURL: URL(string: "https://\(host)")!,
+ callbackScheme: "donkey"
+ )
+ let storage = Self.isolatedCookieStorage()
+ Self.seedSessionCookie(in: storage, host: host)
+ let revoker = RecordingRevoker()
+
+ let coordinator = DonkeyAuthCoordinator(
+ configuration: configuration,
+ stateStore: StubAuthStateStore(),
+ remoteSessionRevoker: revoker,
+ cookieStorage: storage
+ )
+
+ coordinator.signOut(revokingRemoteSessions: false)
+
+ #expect(coordinator.pendingRemoteRevokeTask == nil)
+ #expect(revoker.calls.isEmpty)
+ #expect(coordinator.isAuthenticated == false)
+ }
+
+ // MARK: - Helpers
+
+ private static func isolatedCookieStorage() -> HTTPCookieStorage {
+ HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "donkey-signout-test-\(UUID().uuidString)")
+ }
+
+ private static func seedSessionCookie(in storage: HTTPCookieStorage, host: String) {
+ let cookie = HTTPCookie(properties: [
+ .domain: host,
+ .path: "/",
+ .name: "better-auth.session_token",
+ .value: "test-session-token",
+ ])!
+ storage.setCookie(cookie)
+ }
+}
+
+/// Records the revoke calls the coordinator makes, in place of a real network round-trip.
+private final class RecordingRevoker: DonkeyRemoteSessionRevoking, @unchecked Sendable {
+ struct Call {
+ let webBaseURL: URL
+ let cookies: [HTTPCookie]
+ }
+
+ private let lock = NSLock()
+ private var storedCalls: [Call] = []
+
+ var calls: [Call] {
+ lock.withLock { storedCalls }
+ }
+
+ func revokeAllSessions(webBaseURL: URL, cookies: [HTTPCookie]) async {
+ lock.withLock { storedCalls.append(Call(webBaseURL: webBaseURL, cookies: cookies)) }
+ }
+}
+
+/// In-memory auth state, so sign-out doesn't touch the shared user defaults.
+private final class StubAuthStateStore: DonkeyAuthStateStoring, @unchecked Sendable {
+ var session: DonkeyAuthSession?
+ var hasEverSignedIn = false
+
+ func loadSession() -> DonkeyAuthSession? { session }
+ func saveSession(_ session: DonkeyAuthSession) { self.session = session }
+ func clearSession() { session = nil }
+ func loadPendingState() -> String? { nil }
+ func savePendingState(_ state: String) {}
+ func clearPendingState() {}
+ func loadHasEverSignedIn() -> Bool { hasEverSignedIn }
+ func markHasEverSignedIn() { hasEverSignedIn = true }
+}