From dc9df89cfd6e1279c575a788bfed53829089cdcd Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 4 Oct 2026 21:31:59 -0400 Subject: [PATCH 1/9] test(cloud): pin a session tab's workspace against the unified login mint --- src/platform/auth/webSessionFlagOn.test.ts | 105 ++++++++++++++++++ .../workspace/auth/WorkspaceAuthGate.test.ts | 36 +++++- 2 files changed, 140 insertions(+), 1 deletion(-) diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index ac7f680aa63..b1cd05478d4 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -1910,6 +1910,111 @@ describe.for([{ unified: false }, { unified: true }])( } ) +describe('a sibling tab under unified_cloud_auth', () => { + const openChannels = new Set() + + class InMemoryChannel extends EventTarget { + constructor(readonly name: string) { + super() + openChannels.add(this) + } + + postMessage(data: unknown) { + for (const peer of openChannels) { + if (peer !== this && peer.name === this.name) { + peer.dispatchEvent(new MessageEvent('message', { data })) + } + } + } + + close() { + openChannels.delete(this) + } + } + + const followerLocks = fromPartial({ + request: (_name: string, options: LockOptions) => + new Promise((_resolve, reject) => { + options.signal?.addEventListener('abort', () => + reject(new DOMException('abandoned', 'AbortError')) + ) + }) + }) + + const publishFromSibling = () => { + const sibling = new InMemoryChannel( + 'comfy-account-refresh:user-a:ws-personal' + ) + sibling.postMessage({ + token: 'sibling-jwt', + expiresAt: Date.now() + 60 * 60_000, + uid: 'user-a', + workspace: { id: 'ws-personal', name: 'Personal', type: 'personal' }, + role: 'owner', + permissions: [] + }) + sibling.close() + } + + const firebaseExchanges = () => + vi + .mocked(fetch) + .mock.calls.map(([input, init]) => recordApiRequest(input, init)) + .filter( + ({ path, headers }) => + path === '/api/auth/token' && + headers.authorization === 'Bearer firebase-id-token' + ) + + beforeEach(() => { + identity.reset() + openChannels.clear() + vi.spyOn(api, 'resetSocket').mockResolvedValue() + vi.stubGlobal('BroadcastChannel', InMemoryChannel) + vi.spyOn(navigator, 'locks', 'get').mockReturnValue(followerLocks) + }) + + afterEach(() => { + remoteConfig.value = {} + localStorage.clear() + }) + + it('leaves a session tab on its own workspace, and its Run carries that workspace', async () => { + const ingest = await bootOnSession({ unified_cloud_auth: true }) + const workspaceAuth = useWorkspaceAuthStore() + + await workspaceAuth.mintAtLogin() + await workspaceAuth.switchWorkspace('ws-team') + publishFromSibling() + await postPrompt() + + expect(workspaceAuth.currentWorkspace?.id).toBe('ws-team') + expect(ingest.requests.at(-1)).toEqual( + sessionRequest('POST', '/api/prompt', { + 'x-comfy-workspace-id': 'ws-team', + ...PROMPT_HEADERS, + 'x-csrf-token': 'csrf-1' + }) + ) + expect(firebaseExchanges()).toEqual([]) + }) + + it('still mints at login and adopts the sibling token with the web session off', async () => { + await bootOnSession({ + unified_cloud_auth: true, + unified_web_session: false + }) + const workspaceAuth = useWorkspaceAuthStore() + + await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + publishFromSibling() + + expect(firebaseExchanges()).toHaveLength(1) + expect(workspaceAuth.currentWorkspace?.id).toBe('ws-personal') + expect(workspaceAuth.getUnifiedToken()).toBe('sibling-jwt') + }) +}) + describe('billing on a tab that arrived by session', () => { const bootSessionOnly = async () => { const ingest = installIngest() diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 11aba74ee40..f6ef9759a30 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -1,6 +1,11 @@ import { fromPartial } from '@total-typescript/shoehorn' import type { WebSession } from '@comfyorg/account-core/webSession' +import type { + WebSessionRequestScope, + WebSessionRequests +} from '@/platform/auth/session/webSessionFetch' +import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch' import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' @@ -9,7 +14,7 @@ import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuth import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { useAuthActions } from '@/composables/auth/useAuthActions' @@ -412,6 +417,35 @@ describe('WorkspaceAuthGate', () => { }) }) + describe('cloud builds - Firebase user signed in on the web session', () => { + let releaseRequests = () => {} + + beforeEach(() => { + Object.assign(useAuthStore(), { isInitialized: true }) + Object.assign(useAuthStore(), { currentUser: { uid: 'user-a' } }) + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( + undefined + ) + releaseRequests = provideWebSessionRequests( + fromPartial({ + scope: async () => fromPartial({}) + }) + ) + }) + + afterEach(() => releaseRequests()) + + it('initializes the workspace without minting a unified token', async () => { + mountComponent() + await flushPromises() + + expect(useWorkspaceAuthStore().mintAtLogin).not.toHaveBeenCalled() + expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() + expect(screen.getByTestId('slot-content')).toBeInTheDocument() + }) + }) + describe('error handling', () => { beforeEach(() => { Object.assign(useAuthStore(), { isInitialized: true }) From cb11ef8fe4f990e448d80fdab5cf2420ca686441 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 4 Oct 2026 21:40:56 -0400 Subject: [PATCH 2/9] fix(cloud): skip the unified login mint on a web session tab --- src/platform/auth/session/webSessionFetch.ts | 5 +++++ .../workspace/auth/WorkspaceAuthGate.vue | 16 ++++++++++++---- .../workspace/stores/workspaceAuthStore.ts | 10 +++++++++- src/stores/authStore.ts | 6 ++++-- 4 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/platform/auth/session/webSessionFetch.ts b/src/platform/auth/session/webSessionFetch.ts index 2ca68a6ce24..c1a5e0102bc 100644 --- a/src/platform/auth/session/webSessionFetch.ts +++ b/src/platform/auth/session/webSessionFetch.ts @@ -121,6 +121,11 @@ export function webSessionRequests(): WebSessionRequests | undefined { return provided } +/** True when the session is on and this tab is signed in on it. */ +export async function signedInOnWebSession(): Promise { + return (await provided?.scope()) !== undefined +} + export type WebSessionSend = ( url: string, init: RequestInit diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index c7ef4d69ada..cf4c8c45724 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -71,6 +71,7 @@ import { import Button from '@/components/ui/button/Button.vue' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { signedInOnWebSession } from '@/platform/auth/session/webSessionFetch' import { isCloud } from '@/platform/distribution/types' import { remoteConfigErrorStatus, @@ -106,6 +107,15 @@ function cancelInitialization(): void { backgroundInitializationUserId = undefined } +/** A tab signed in on the web session carries its workspace on the session. */ +async function requiresUnifiedToken(): Promise { + return ( + useFeatureFlags().flags.unifiedCloudAuthEnabled && + useAuthStore().currentUser !== null && + !(await signedInOnWebSession()) + ) +} + async function initialize(): Promise { if (!isCloud) { void initializeWorkspacesInBackground() @@ -118,7 +128,7 @@ async function initialize(): Promise { initializationController = controller const authStore = useAuthStore() - const { isInitialized, isAuthenticated, currentUser } = storeToRefs(authStore) + const { isInitialized, isAuthenticated } = storeToRefs(authStore) try { // Step 1: Wait for Firebase auth to resolve @@ -156,10 +166,8 @@ async function initialize(): Promise { throw new Error('Failed to load authenticated remote config') } - const { flags } = useFeatureFlags() const workspaceAuthStore = useWorkspaceAuthStore() - const needsUnifiedToken = - flags.unifiedCloudAuthEnabled && currentUser.value !== null + const needsUnifiedToken = await requiresUnifiedToken() if (needsUnifiedToken) { const authenticated = await workspaceAuthStore.mintAtLogin() if (generation !== initializationGeneration) return diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index 584d9d8e77c..656488295c0 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -18,7 +18,10 @@ import { zCurrentWorkspaceResponse } from '@comfyorg/ingest-types/zod' import { t } from '@/i18n' import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import type { WebSessionRequests } from '@/platform/auth/session/webSessionFetch' -import { webSessionRequests } from '@/platform/auth/session/webSessionFetch' +import { + signedInOnWebSession, + webSessionRequests +} from '@/platform/auth/session/webSessionFetch' import enMessages from '@/locales/en/main.json' with { type: 'json' } import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' @@ -558,6 +561,11 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { if (getUnifiedToken()) { return true } + // A unified credential on a session tab would join a sibling's cross-tab + // lease and overwrite currentWorkspace when it adopts their token. + if (await signedInOnWebSession()) { + return false + } const authUser = await unifiedUser() // Re-check after the wait: a rollback that flips the flag off while a mint // is parked on unifiedUser() must not let the resumed mint commit a token. diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 2320cf5144b..d8f3d02c0a9 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -189,9 +189,11 @@ export const useAuthStore = defineStore('auth', () => { isInitialized.value = true if (user === null) { lastTokenUserId.value = null - } else if (isCloud) { + } else if (isCloud && !flags.unifiedWebSessionEnabled) { // Mint the single Cloud JWT at login (flag-guarded inside the store; a - // no-op when unified_cloud_auth is off). + // no-op when unified_cloud_auth is off). With the web session on, this + // runs before the router decides the session, so WorkspaceAuthGate + // mints instead, and only for a tab the session did not sign in. void mintUnifiedToken(user.uid) } From c030161e00384da08f675c98291735ecb8bb7f35 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 4 Oct 2026 22:01:04 -0400 Subject: [PATCH 3/9] fix(cloud): stop a cancelled gate before the unified mint --- .../workspace/auth/WorkspaceAuthGate.test.ts | 22 +++++++++++++++++++ .../workspace/auth/WorkspaceAuthGate.vue | 1 + 2 files changed, 23 insertions(+) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index f6ef9759a30..58669b1f214 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -444,6 +444,28 @@ describe('WorkspaceAuthGate', () => { expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() expect(screen.getByTestId('slot-content')).toBeInTheDocument() }) + + it('mints nothing when unmounted while the session lookup is pending', async () => { + releaseRequests() + let settleScope = (_scope: WebSessionRequestScope | undefined) => {} + const pendingScope = new Promise( + (resolve) => { + settleScope = resolve + } + ) + releaseRequests = provideWebSessionRequests( + fromPartial({ scope: () => pendingScope }) + ) + + const { unmount } = mountComponent() + await flushPromises() + unmount() + settleScope(undefined) + await flushPromises() + + expect(useWorkspaceAuthStore().mintAtLogin).not.toHaveBeenCalled() + expect(useTeamWorkspaceStore().initialize).not.toHaveBeenCalled() + }) }) describe('error handling', () => { diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index cf4c8c45724..d23f1206cea 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -168,6 +168,7 @@ async function initialize(): Promise { const workspaceAuthStore = useWorkspaceAuthStore() const needsUnifiedToken = await requiresUnifiedToken() + if (generation !== initializationGeneration) return if (needsUnifiedToken) { const authenticated = await workspaceAuthStore.mintAtLogin() if (generation !== initializationGeneration) return From 1a303649f4828d0de66687ef06c2ff2eb43a0111 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 5 Oct 2026 07:50:58 -0400 Subject: [PATCH 4/9] test(cloud): a session sign-in after the token-rail fallback keeps the tab's workspace --- src/platform/auth/webSessionFlagOn.test.ts | 39 ++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index b1cd05478d4..2d70cf2c4ec 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -635,6 +635,7 @@ function installIngest(features: Record = {}) { userId: 'user-a', csrfToken: 'csrf-1', sessionDown: false, + sessionMissing: false, refusals: [] as string[], mintRefusal: undefined as (() => Response) | undefined, mintGate: undefined as Promise | undefined, @@ -702,17 +703,22 @@ function installIngest(features: Record = {}) { ) } - const answerSession = (): Response => - ingest.sessionDown + const answerSession = (method: string): Response => { + if (ingest.sessionMissing) { + return jsonResponse({ code: 'no_session', message: 'no_session' }, 401) + } + if (method === 'POST') return jsonResponse({ success: true }) + return ingest.sessionDown ? jsonResponse({ code: 'unavailable', message: 'down' }, 503) : jsonResponse({ ...sessionBody(ingest.userId), csrf_token: ingest.csrfToken }) + } const respond = (request: ApiRequest, body: unknown): Response => { const { path, headers } = request - if (path === '/api/auth/session') return answerSession() + if (path === '/api/auth/session') return answerSession(request.method) if (path === '/api/auth/token') return mint(body) if (path === '/api/workspaces/current') { if (ingest.currentWorkspaceDown) return ingest.currentWorkspaceDown() @@ -2013,6 +2019,33 @@ describe('a sibling tab under unified_cloud_auth', () => { expect(workspaceAuth.currentWorkspace?.id).toBe('ws-personal') expect(workspaceAuth.getUnifiedToken()).toBe('sibling-jwt') }) + it('drops the fallback credential once the session signs the tab in, so a sibling token cannot move its Run', async () => { + const ingest = installIngest({ unified_cloud_auth: true }) + ingest.sessionMissing = true + await refreshRemoteConfig({ useAuth: false }) + useAuthStore() + const workspaceAuth = useWorkspaceAuthStore() + identity.signIn(USER_A) + await useSessionCookie().ensureSessionCookie() + await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + + ingest.sessionMissing = false + const webSession = useCloudWebSessionStore() + webSession.signedInInteractively(USER_A) + await webSession.whenSessionCreated() + await workspaceAuth.switchWorkspace('ws-team') + publishFromSibling() + await postPrompt() + + expect(workspaceAuth.currentWorkspace?.id).toBe('ws-team') + expect(ingest.requests.at(-1)).toEqual( + sessionRequest('POST', '/api/prompt', { + 'x-comfy-workspace-id': 'ws-team', + ...PROMPT_HEADERS, + 'x-csrf-token': 'csrf-1' + }) + ) + }) }) describe('billing on a tab that arrived by session', () => { From f64e0fd8a6b55c24829e8d9d705a75767ee9b7e8 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 5 Oct 2026 07:51:06 -0400 Subject: [PATCH 5/9] fix(cloud): drop the fallback unified credential once the web session signs the tab in --- src/platform/auth/session/cloudWebSessionStore.ts | 9 +++++++++ src/platform/workspace/stores/workspaceAuthStore.ts | 1 + 2 files changed, 10 insertions(+) diff --git a/src/platform/auth/session/cloudWebSessionStore.ts b/src/platform/auth/session/cloudWebSessionStore.ts index ebc95a8199b..1d0d8bdd782 100644 --- a/src/platform/auth/session/cloudWebSessionStore.ts +++ b/src/platform/auth/session/cloudWebSessionStore.ts @@ -193,6 +193,15 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { } ) + // A unified credential from a token-rail fallback would adopt a sibling's + // token and overwrite the workspace this tab's session requests carry. + watch( + () => signedInUser.value?.id, + (userId) => { + if (userId) useWorkspaceAuthStore().clearUnifiedContext() + } + ) + const reconnecting = shallowRef(false) const readsFailing = computed( () => 'failures' in state.value && state.value.failures > 0 diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index 656488295c0..7ade23311d0 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -697,6 +697,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { getUnifiedSessionClient, getUnifiedMintWorkspaceId, clearWorkspaceContext, + clearUnifiedContext, dropDeniedWorkspace } }) From 472ebb2992fa90bee0a14217329453724fb08e98 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 6 Oct 2026 15:48:41 -0400 Subject: [PATCH 6/9] fix(cloud): let a session sign-in mid-gate render the app instead of the unified-auth error --- .../workspace/auth/WorkspaceAuthGate.test.ts | 68 +++++++++++++++++-- .../workspace/auth/WorkspaceAuthGate.vue | 8 ++- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 0c2eaaf123c..fe11e5bc261 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -419,6 +419,16 @@ describe('WorkspaceAuthGate', () => { }) describe('cloud builds - Firebase user signed in on the web session', () => { + const signedInScope: WebSessionRequestScope = { + session: { + user: { id: 'user-a', email: 'a@example.com', emailVerified: true }, + csrfToken: 'csrf-1', + expiresAt: Date.now() + 60 * 60_000, + absoluteExpiresAt: Date.now() + 24 * 60 * 60_000 + }, + epoch: 1 + } + let sessionScope: WebSessionRequestScope | undefined let releaseRequests = () => {} beforeEach(() => { @@ -428,10 +438,9 @@ describe('WorkspaceAuthGate', () => { vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( undefined ) + sessionScope = signedInScope releaseRequests = provideWebSessionRequests( - fromPartial({ - scope: async () => fromPartial({}) - }) + fromPartial({ scope: async () => sessionScope }) ) }) @@ -439,11 +448,47 @@ describe('WorkspaceAuthGate', () => { it('initializes the workspace without minting a unified token', async () => { mountComponent() - await flushPromises() + expect(await screen.findByTestId('slot-content')).toBeInTheDocument() expect(useWorkspaceAuthStore().mintAtLogin).not.toHaveBeenCalled() expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() - expect(screen.getByTestId('slot-content')).toBeInTheDocument() + }) + + it('renders the app when the session signs the tab in while the login mint is refused', async () => { + sessionScope = undefined + vi.mocked(useWorkspaceAuthStore().mintAtLogin).mockImplementation( + async () => { + sessionScope = signedInScope + return false + } + ) + + mountComponent() + + expect(await screen.findByTestId('slot-content')).toBeInTheDocument() + expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() + }) + + it('renders the app when the session signs the tab in during workspace setup', async () => { + sessionScope = undefined + vi.mocked(useWorkspaceAuthStore().mintAtLogin).mockResolvedValue(true) + vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( + 'cloud-jwt' + ) + vi.mocked(useTeamWorkspaceStore().initialize).mockImplementation( + async () => { + sessionScope = signedInScope + vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( + undefined + ) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + } + ) + + mountComponent() + + expect(await screen.findByTestId('slot-content')).toBeInTheDocument() + expect(useWorkspaceAuthStore().mintAtLogin).toHaveBeenCalledOnce() }) it('mints nothing when unmounted while the session lookup is pending', async () => { @@ -454,12 +499,21 @@ describe('WorkspaceAuthGate', () => { settleScope = resolve } ) + let lookupStarted = () => {} + const lookupStarting = new Promise((resolve) => { + lookupStarted = resolve + }) releaseRequests = provideWebSessionRequests( - fromPartial({ scope: () => pendingScope }) + fromPartial({ + scope: () => { + lookupStarted() + return pendingScope + } + }) ) const { unmount } = mountComponent() - await flushPromises() + await lookupStarting unmount() settleScope(undefined) await flushPromises() diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index f95db8bff01..f4ad59520b6 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -198,7 +198,7 @@ async function initialize(): Promise { if (needsUnifiedToken) { const authenticated = await workspaceAuthStore.mintAtLogin() if (generation !== initializationGeneration) return - if (!authenticated) { + if (!authenticated && (await requiresUnifiedToken())) { throw new Error('Failed to initialize unified cloud auth') } } @@ -206,7 +206,11 @@ async function initialize(): Promise { await initializeWorkspaceMode() if (generation !== initializationGeneration) return void billingCapabilities.initialize(controller.signal) - if (needsUnifiedToken && !workspaceAuthStore.getUnifiedToken()) { + if ( + needsUnifiedToken && + !workspaceAuthStore.getUnifiedToken() && + (await requiresUnifiedToken()) + ) { throw new Error('Unified cloud auth was cleared during workspace setup') } From 2d85cd4d92b675a32a21788753e8762f2ba0da83 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 6 Oct 2026 15:49:11 -0400 Subject: [PATCH 7/9] fix(cloud): refuse a login mint the session signed in on while it waited for the identity --- .../workspace/stores/useWorkspaceAuth.test.ts | 52 ++++++++++++++++++- .../workspace/stores/workspaceAuthStore.ts | 8 ++- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index 9b824e3c76c..4a249e2bde8 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -8,9 +8,14 @@ import type { User } from 'firebase/auth' import { storeToRefs } from 'pinia' import { nextTick } from 'vue' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' +import type { + WebSessionRequestScope, + WebSessionRequests +} from '@/platform/auth/session/webSessionFetch' +import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { t } from '@/i18n' import { useTelemetry } from '@/platform/telemetry' @@ -3186,6 +3191,51 @@ describe('useWorkspaceAuthStore', () => { expect(unifiedToken.value).toBeNull() }) + it('refuses a mint that parked on the identity before the session signed the tab in', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(personalTokenResponse) + }) + vi.stubGlobal('fetch', mockFetch) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + const heldPort = replayIdentityPort(() => null) + vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation( + heldPort.register + ) + const signedInScope: WebSessionRequestScope = { + session: { + user: { id: 'user-1', email: 'a@example.com', emailVerified: true }, + csrfToken: 'csrf-1', + expiresAt: Date.now() + 60 * 60_000, + absoluteExpiresAt: Date.now() + 24 * 60 * 60_000 + }, + epoch: 1 + } + let signedIn = false + onTestFinished( + provideWebSessionRequests( + fromPartial({ + scope: async () => (signedIn ? signedInScope : undefined) + }) + ) + ) + + const store = useWorkspaceAuthStore() + const { unifiedToken } = storeToRefs(store) + Object.assign(useAuthStore(), { currentUser: { uid: 'user-1' } }) + const parked = store.mintAtLogin() + + signedIn = true + await nextTick() + heldPort.emit(portUser({ uid: 'user-1' })) + + await expect(parked).resolves.toBe(false) + expect(mockFetch).not.toHaveBeenCalled() + expect(unifiedToken.value).toBeNull() + }) + it('is fully dormant under the flag OFF: no unified network, timer, or rotation', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false vi.mocked(useAuthStore().getIdToken).mockResolvedValue( diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index ed39400671a..d83148bc98b 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -583,9 +583,13 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return false } const authUser = await unifiedUser() - // Re-check after the wait: a rollback that flips the flag off while a mint + // Re-check after the wait: a rollback or a session sign-in while a mint // is parked on unifiedUser() must not let the resumed mint commit a token. - if (!unifiedRailEnabled() || !authUser) { + if ( + !unifiedRailEnabled() || + !authUser || + (webSessionRequests() !== undefined && (await signedInOnWebSession())) + ) { return false } const target = currentUnifiedTarget() ?? personalWorkspaceTarget() From 10bf5b4afd41c98e3cbfeb630ca151ebcec4d67a Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 6 Oct 2026 15:49:21 -0400 Subject: [PATCH 8/9] test(cloud): cover the Firebase listener's login mint instead of calling it by hand --- src/platform/auth/webSessionFlagOn.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index cb5ff64dba5..e93a2b08ea7 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -2121,7 +2121,9 @@ describe('a sibling tab under unified_cloud_auth', () => { }) const workspaceAuth = useWorkspaceAuthStore() - await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + await vi.waitFor(() => + expect(workspaceAuth.getUnifiedToken()).toBeDefined() + ) publishFromSibling() expect(firebaseExchanges()).toHaveLength(1) From 0b66ba1a4fddf752268619e91bb70f71483dd42c Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 6 Oct 2026 15:50:28 -0400 Subject: [PATCH 9/9] refactor(cloud): name the gate's missing-token check --- src/platform/workspace/auth/WorkspaceAuthGate.vue | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index f4ad59520b6..6af36533f7c 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -142,6 +142,11 @@ async function requiresUnifiedToken(): Promise { ) } +/** A session sign-in mid-setup lifts the need for the token that went missing. */ +async function missingUnifiedToken(hasToken: boolean): Promise { + return !hasToken && (await requiresUnifiedToken()) +} + async function initialize(): Promise { if (!isCloud) { void initializeWorkspacesInBackground() @@ -198,7 +203,7 @@ async function initialize(): Promise { if (needsUnifiedToken) { const authenticated = await workspaceAuthStore.mintAtLogin() if (generation !== initializationGeneration) return - if (!authenticated && (await requiresUnifiedToken())) { + if (await missingUnifiedToken(authenticated)) { throw new Error('Failed to initialize unified cloud auth') } } @@ -206,11 +211,8 @@ async function initialize(): Promise { await initializeWorkspaceMode() if (generation !== initializationGeneration) return void billingCapabilities.initialize(controller.signal) - if ( - needsUnifiedToken && - !workspaceAuthStore.getUnifiedToken() && - (await requiresUnifiedToken()) - ) { + const hasUnifiedToken = Boolean(workspaceAuthStore.getUnifiedToken()) + if (needsUnifiedToken && (await missingUnifiedToken(hasUnifiedToken))) { throw new Error('Unified cloud auth was cleared during workspace setup') }