diff --git a/src/components/dialog/content/setting/UserPanel.test.ts b/src/components/dialog/content/setting/UserPanel.test.ts index 6384e63b80c..0b2784a95d8 100644 --- a/src/components/dialog/content/setting/UserPanel.test.ts +++ b/src/components/dialog/content/setting/UserPanel.test.ts @@ -1,3 +1,4 @@ +import { fromPartial } from '@total-typescript/shoehorn' import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -5,14 +6,37 @@ import { computed, defineComponent } from 'vue' import { createI18n } from 'vue-i18n' import { createMemoryHistory, createRouter } from 'vue-router' +import type { FirebaseIdentity } from '@comfyorg/account-core/firebase' +import type { WebSessionCommandResult } from '@comfyorg/account-core/webSession' +import type { WebSessionIdentityState } from '@comfyorg/account-core/webSessionIdentity' + import { useCurrentUser } from '@/composables/auth/useCurrentUser' import enMessages from '@/locales/en/main.json' with { type: 'json' } +import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore' +import { useToastStore } from '@/platform/updates/common/toastStore' +import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' +import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' +import { api } from '@/scripts/api' import { useDialogService } from '@/services/dialogService' +import { useAuthStore } from '@/stores/authStore' import UserPanel from './UserPanel.vue' vi.mock(import('@/composables/auth/useCurrentUser')) vi.mock(import('@/services/dialogService')) +vi.mock(import('@/platform/distribution/types'), () => ({ + DISTRIBUTION: 'cloud' as const, + isCloud: true, + isDesktop: false, + isNightly: false +})) +vi.mock(import('@/platform/auth/firebaseIdentity'), () => ({ + firebaseIdentity: fromPartial({ + onUserChanged: () => () => {}, + onTokenChanged: () => () => {}, + currentUser: () => null + }) +})) const i18n = createI18n({ legacy: false, @@ -100,3 +124,147 @@ describe('UserPanel update password', () => { expect(location.assign).not.toHaveBeenCalled() }) }) + +describe('UserPanel sign out of all devices', () => { + const signOutEverywhere = { name: 'Sign out of all devices' } + + beforeEach(() => { + vi.spyOn(api, 'reconnectSocket').mockResolvedValue() + vi.spyOn(useAuthStore(), 'logout').mockResolvedValue() + vi.stubGlobal('location', { href: '/' }) + }) + + function withUnsavedWorkflow() { + const workflow = fromPartial({ + path: 'a.json', + isModified: true + }) + Object.assign(useWorkflowStore(), { modifiedWorkflows: [workflow] }) + } + + const signedInSession: WebSessionIdentityState = { + phase: 'signed_in', + session: { + user: { + id: 'user-a', + email: 'user-a@example.com', + emailVerified: true, + signInProvider: 'google.com' + }, + csrfToken: 'csrf-user-a', + expiresAt: Date.now() + 86_400_000, + absoluteExpiresAt: Date.now() + 604_800_000 + } + } + + function onWebSession(revokeAll: WebSessionCommandResult) { + const webSession = useCloudWebSessionStore() + webSession.state = signedInSession + return vi + .spyOn(webSession, 'revokeAllSessions') + .mockResolvedValue(revokeAll) + } + + it.for<{ + name: string + session: WebSessionIdentityState + firebaseLogin: boolean + }>([ + { + name: 'the web session is off', + session: { phase: 'idle' }, + firebaseLogin: true + }, + { + name: 'the web session is signed out', + session: { phase: 'signed_out', outcome: 'signed_out' }, + firebaseLogin: true + }, + { + name: 'the tab has no Firebase login to prove identity', + session: signedInSession, + firebaseLogin: false + } + ])('renders nothing when $name', async ({ session, firebaseLogin }) => { + signInAsEmailUser({ hasFirebaseLogin: firebaseLogin }) + useCloudWebSessionStore().state = session + await renderPanel() + + expect(screen.getByRole('button', { name: 'Log Out' })).toBeVisible() + expect(screen.queryByRole('button', signOutEverywhere)).toBeNull() + }) + + it('revokes every session once, then signs this tab out', async () => { + signInAsEmailUser({ hasFirebaseLogin: true }) + const revokeAll = onWebSession({ status: 'ok' }) + await renderPanel() + + await userEvent.click(screen.getByRole('button', signOutEverywhere)) + + expect(revokeAll).toHaveBeenCalledOnce() + expect(useAuthStore().logout).toHaveBeenCalledOnce() + expect(revokeAll.mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(useAuthStore().logout).mock.invocationCallOrder[0] + ) + expect(useToastStore().messagesToAdd).toContainEqual( + expect.objectContaining({ + severity: 'success', + summary: 'Signed out of all devices' + }) + ) + }) + + it('asks about unsaved work before revoking anything', async () => { + signInAsEmailUser({ hasFirebaseLogin: true }) + withUnsavedWorkflow() + vi.mocked(useDialogService().confirm).mockResolvedValue(false) + const revokeAll = onWebSession({ status: 'ok' }) + await renderPanel() + + await userEvent.click(screen.getByRole('button', signOutEverywhere)) + + expect(useDialogService().confirm).toHaveBeenCalledWith( + expect.objectContaining({ title: 'Unsaved Changes' }) + ) + expect( + vi.mocked(useDialogService().confirm).mock.invocationCallOrder[0] + ).toBeLessThan(revokeAll.mock.invocationCallOrder[0]) + expect(useAuthStore().logout).toHaveBeenCalledOnce() + }) + + it('sends no revoke and stays signed in when the unsaved-work prompt is cancelled', async () => { + signInAsEmailUser({ hasFirebaseLogin: true }) + withUnsavedWorkflow() + vi.mocked(useDialogService().confirm).mockResolvedValue(null) + const revokeAll = onWebSession({ status: 'ok' }) + await renderPanel() + + await userEvent.click(screen.getByRole('button', signOutEverywhere)) + + expect(revokeAll).not.toHaveBeenCalled() + expect(useAuthStore().logout).not.toHaveBeenCalled() + expect(useToastStore().messagesToAdd).toEqual([]) + }) + + it('keeps the user signed in and shows why when the revoke fails', async () => { + signInAsEmailUser({ hasFirebaseLogin: true }) + onWebSession({ + status: 'error', + code: 'SESSION_UNAVAILABLE', + retryable: true + }) + await renderPanel() + + await userEvent.click(screen.getByRole('button', signOutEverywhere)) + + expect(useAuthStore().logout).not.toHaveBeenCalled() + expect(useToastStore().messagesToAdd).toEqual([ + expect.objectContaining({ + severity: 'error', + summary: "Couldn't sign out of all devices", + detail: enMessages.auth.webSession.token.unavailable + }) + ]) + expect(screen.getByRole('button', signOutEverywhere)).toBeEnabled() + }) +}) diff --git a/src/components/dialog/content/setting/UserPanel.vue b/src/components/dialog/content/setting/UserPanel.vue index 6a8ecde39b2..09b45f99429 100644 --- a/src/components/dialog/content/setting/UserPanel.vue +++ b/src/components/dialog/content/setting/UserPanel.vue @@ -55,10 +55,13 @@
- +
+ + +
{ ) }) + it.for([ + { name: 'the prompt is dismissed', answer: null, runsHook: false }, + { name: 'a workflow save is cancelled', answer: true, runsHook: false }, + { name: 'the user signs out anyway', answer: false, runsHook: true } + ])( + 'beforeSignOut runs only once unsaved work is settled: $name', + async ({ answer, runsHook }) => { + Object.assign(mockWorkflowStore, { + modifiedWorkflows: [makeWorkflow('a.json')] + }) + vi.mocked(useDialogService().confirm).mockResolvedValueOnce(answer) + vi.mocked(useWorkflowService().saveWorkflow).mockResolvedValueOnce(false) + const beforeSignOut = vi.fn(async () => true) + const { logout } = useAuthActions() + + await logout({ beforeSignOut }) + + expect(beforeSignOut).toHaveBeenCalledTimes(runsHook ? 1 : 0) + expect(mockAuthStore.logout).toHaveBeenCalledTimes(runsHook ? 1 : 0) + } + ) + + it('signs out after beforeSignOut allows it', async () => { + const beforeSignOut = vi.fn(async () => true) + const { logout } = useAuthActions() + + await logout({ beforeSignOut }) + + expect(mockAuthStore.logout).toHaveBeenCalledOnce() + expect(beforeSignOut.mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(mockAuthStore.logout).mock.invocationCallOrder[0] + ) + }) + + it('keeps the user signed in when beforeSignOut refuses', async () => { + const { logout } = useAuthActions() + + await logout({ beforeSignOut: async () => false }) + + expect(mockAuthStore.logout).not.toHaveBeenCalled() + expect(mockClearAllWorkspaceStorage).not.toHaveBeenCalled() + expect(mockToastStore.add).not.toHaveBeenCalled() + }) + it('passes denyLabel "Sign out anyway" to the dialog', async () => { Object.assign(mockWorkflowStore, { modifiedWorkflows: [makeWorkflow('a.json')] diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index 2b452924fab..1abc2931bee 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -106,58 +106,66 @@ export const useAuthActions = () => { } } - const logout = wrapWithErrorHandlingAsync(async () => { - if (isCloud) { - const workflowStore = useWorkflowStore() - const modifiedWorkflows = workflowStore.modifiedWorkflows - if (modifiedWorkflows.length > 0) { - const dialogService = useDialogService() - const confirmed = await dialogService.confirm({ - title: t('auth.signOut.unsavedChangesTitle'), - message: t('auth.signOut.unsavedChangesMessage'), - type: 'dirtyClose', - denyLabel: t('auth.signOut.signOutAnyway') - }) - if (confirmed === null) return - - if (confirmed) { - const workflowService = useWorkflowService() - for (const workflow of modifiedWorkflows) { - try { - const saved = await workflowService.saveWorkflow(workflow) - if (!saved) return - } catch { - throw new Error( - t('auth.signOut.saveFailed', { workflow: workflow.path }) - ) + /** `beforeSignOut` runs once unsaved work is settled; false keeps the user signed in. */ + const logout = wrapWithErrorHandlingAsync( + async ({ + beforeSignOut + }: { beforeSignOut?: () => Promise } = {}) => { + if (isCloud) { + const workflowStore = useWorkflowStore() + const modifiedWorkflows = workflowStore.modifiedWorkflows + if (modifiedWorkflows.length > 0) { + const dialogService = useDialogService() + const confirmed = await dialogService.confirm({ + title: t('auth.signOut.unsavedChangesTitle'), + message: t('auth.signOut.unsavedChangesMessage'), + type: 'dirtyClose', + denyLabel: t('auth.signOut.signOutAnyway') + }) + if (confirmed === null) return + + if (confirmed) { + const workflowService = useWorkflowService() + for (const workflow of modifiedWorkflows) { + try { + const saved = await workflowService.saveWorkflow(workflow) + if (!saved) return + } catch { + throw new Error( + t('auth.signOut.saveFailed', { workflow: workflow.path }) + ) + } } } } } - } - await authStore.logout() - if (isCloud) { - prepareWorkflowLogoutTransition() - clearAllWorkspaceStorage() - } + if (beforeSignOut && !(await beforeSignOut())) return - toastStore.add({ - severity: 'success', - summary: t('auth.signOut.success'), - detail: t('auth.signOut.successDetail'), - life: 5000 - }) + await authStore.logout() + if (isCloud) { + prepareWorkflowLogoutTransition() + clearAllWorkspaceStorage() + } - if (isCloud) { - try { - window.location.href = '/cloud/login' - } catch { - // needed for local development until we bring in cloud login pages. - window.location.reload() + toastStore.add({ + severity: 'success', + summary: t('auth.signOut.success'), + detail: t('auth.signOut.successDetail'), + life: 5000 + }) + + if (isCloud) { + try { + window.location.href = '/cloud/login' + } catch { + // needed for local development until we bring in cloud login pages. + window.location.reload() + } } - } - }, reportError) + }, + reportError + ) const sendPasswordReset = wrapWithErrorHandlingAsync( async (email: string) => { diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 0f67e5db6cc..d9ef5d701cf 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2722,6 +2722,12 @@ "signOutAnyway": "Sign out anyway", "saveFailed": "Sign-out cancelled because saving \"{workflow}\" failed." }, + "signOutEverywhere": { + "action": "Sign out of all devices", + "success": "Signed out of all devices", + "successDetail": "Every device signed in to your account has been signed out.", + "failed": "Couldn't sign out of all devices" + }, "accountChanged": { "title": "Account changed", "detail": "Another tab or Comfy site signed in as {email}, so this page was reset." diff --git a/src/platform/auth/session/cloudWebSessionStore.ts b/src/platform/auth/session/cloudWebSessionStore.ts index d3a579197bb..46cc7fa8bee 100644 --- a/src/platform/auth/session/cloudWebSessionStore.ts +++ b/src/platform/auth/session/cloudWebSessionStore.ts @@ -11,6 +11,7 @@ import type { } from '@comfyorg/account-core/webSessionIdentity' import type { WebSession, + WebSessionCommandResult, WebSessionErrorCode, WebSessionOptions } from '@comfyorg/account-core/webSession' @@ -24,6 +25,7 @@ import { createSessionTokenMint, SessionTokenError } from '@comfyorg/account-core/sessionTokenMint' +import { revokeAllWebSessions } from '@comfyorg/account-core/webSession' import { createWebSessionIdentity } from '@comfyorg/account-core/webSessionIdentity' import { webSessionTelemetryHooks } from '@comfyorg/account-core/telemetry' import { @@ -88,6 +90,10 @@ const TOKEN_FAILURE_COPY: Readonly< SESSION_REQUEST_REFUSED: 'auth.webSession.token.refused' } +export function webSessionFailureMessage(code: WebSessionErrorCode): string { + return t(TOKEN_FAILURE_COPY[code]) +} + const LIFECYCLE_RACES: ReadonlySet = new Set([ 'NO_SESSION', 'IDENTITY_CHANGED' @@ -287,7 +293,7 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { } throw new WebSessionTokenError( error, - t(TOKEN_FAILURE_COPY[failure.code]) + webSessionFailureMessage(failure.code) ) } } @@ -319,6 +325,21 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { }) } + async function revokeAllSessions(): Promise { + const session = currentSession() + const user = firebaseIdentity.currentUser() + if (!session || !user) { + return { status: 'error', code: 'NO_SESSION', retryable: false } + } + return revokeAllWebSessions(sessionOptions(), session.csrfToken, () => + user.getIdToken() + ).catch(() => ({ + status: 'error', + code: 'SESSION_UNAVAILABLE', + retryable: true + })) + } + function currentSession(): WebSession | undefined { const state = identity?.getState() return state?.phase === 'signed_in' ? state.session : undefined @@ -411,6 +432,7 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { whenSessionCreated: () => creating, whenDecided, signedInInteractively, - signOut + signOut, + revokeAllSessions } }) diff --git a/src/platform/auth/session/components/SignOutEverywhereButton.vue b/src/platform/auth/session/components/SignOutEverywhereButton.vue new file mode 100644 index 00000000000..629c69dcbcb --- /dev/null +++ b/src/platform/auth/session/components/SignOutEverywhereButton.vue @@ -0,0 +1,60 @@ + + + diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index 8516e9a3699..5d78f839a4c 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -218,6 +218,11 @@ function installServer( session: initial, requests: [] as SessionRequest[], dropPosts: false, + revokeAllStatus: 200, + revokeAllRequests: [] as { + authorization: string | null + csrf: string | null + }[], featureReads: [] as { credentials: RequestCredentials | null client: string | null @@ -253,6 +258,20 @@ function installServer( return answerRead() } + const answerRevokeAll = (init: RequestInit | undefined): Response => { + const headers = new Headers(init?.headers) + server.revokeAllRequests.push({ + authorization: headers.get('authorization'), + csrf: headers.get('x-csrf-token') + }) + if (server.revokeAllStatus !== 200) { + const error = { code: 'unavailable', message: 'down' } + return jsonResponse(error, server.revokeAllStatus) + } + server.session = 'revoked' + return jsonResponse({ revoked: 2 }) + } + const answerFeatures = (init: RequestInit | undefined): Response => { const client = new Headers(init?.headers).get('x-comfy-client') const credentials = init?.credentials ?? null @@ -275,6 +294,9 @@ function installServer( const url = new URL(String(input), location.href) const method = (init?.method ?? 'GET').toUpperCase() if (url.pathname === '/api/features') return answerFeatures(init) + if (url.pathname === '/api/auth/sessions/revoke-all') { + return answerRevokeAll(init) + } if (url.pathname !== '/api/auth/session') { return jsonResponse({ id: 'customer-1' }, 201) } @@ -429,6 +451,41 @@ describe('cloud app on the shared web session (unified_web_session on)', () => { }) }) + it.for([ + { name: 'ok revokes every session', status: 200, result: { status: 'ok' } }, + { + name: 'a server failure is returned, not thrown', + status: 503, + result: { status: 'error', code: 'SESSION_UNAVAILABLE' } + } + ])('revoke-all: $name', async ({ status, result }) => { + const server = installServer({ userId: 'user-a' }) + server.revokeAllStatus = status + await refreshRemoteConfig({ useAuth: false }) + identity.signIn(USER_A) + await useSessionCookie().ensureSessionCookie() + const webSession = useCloudWebSessionStore() + + expect(await webSession.revokeAllSessions()).toMatchObject(result) + expect(server.revokeAllRequests).toEqual([ + { authorization: 'Bearer firebase-id-token', csrf: 'csrf-user-a' } + ]) + }) + + it('revoke-all sends nothing without a Firebase login to prove identity', async () => { + const server = installServer({ userId: 'user-a' }) + await refreshRemoteConfig({ useAuth: false }) + await useSessionCookie().ensureSessionCookie() + const webSession = useCloudWebSessionStore() + expect(webSession.state.phase).toBe('signed_in') + + expect(await webSession.revokeAllSessions()).toMatchObject({ + status: 'error', + code: 'NO_SESSION' + }) + expect(server.revokeAllRequests).toEqual([]) + }) + it('resets the tab and tells the user when another account takes the session', async () => { const server = installServer({ userId: 'user-a' }) await refreshRemoteConfig({ useAuth: false })