Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/composables/auth/useCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { whenever } from '@vueuse/core'
import { computed } from 'vue'
import { computed, watch } from 'vue'

import { useFirebaseAuthActions } from '@/composables/auth/useFirebaseAuthActions'
import { t } from '@/i18n'
Expand Down Expand Up @@ -37,6 +37,15 @@ export const useCurrentUser = () => {
const onUserResolved = (callback: (user: AuthUserInfo) => void) =>
whenever(resolvedUserInfo, callback, { immediate: true })

const onTokenRefreshed = (callback: () => void) =>
whenever(() => authStore.tokenRefreshTrigger, callback)

const onUserLogout = (callback: () => void) => {
watch(resolvedUserInfo, (user) => {
if (!user) callback()
})
}

const userDisplayName = computed(() => {
if (isApiKeyLogin.value) {
return apiKeyStore.currentUser?.name
Expand Down Expand Up @@ -133,6 +142,8 @@ export const useCurrentUser = () => {
handleSignOut,
handleSignIn,
handleDeleteAccount,
onUserResolved
onUserResolved,
onTokenRefreshed,
onUserLogout
}
}
25 changes: 25 additions & 0 deletions src/extensions/core/cloudSessionCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useSessionCookie } from '@/platform/auth/session/useSessionCookie'
import { useExtensionService } from '@/services/extensionService'

/**
* Cloud-only extension that manages session cookies for authentication.
* Creates session cookie on login, refreshes it when token refreshes, and deletes on logout.
*/
useExtensionService().registerExtension({
name: 'Comfy.Cloud.SessionCookie',

onAuthUserResolved: async () => {
const { createSession } = useSessionCookie()
await createSession()
},

onAuthTokenRefreshed: async () => {
const { createSession } = useSessionCookie()
await createSession()
},

onAuthUserLogout: async () => {
const { deleteSession } = useSessionCookie()
await deleteSession()
}
})
1 change: 1 addition & 0 deletions src/extensions/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import './widgetInputs'
if (isCloud) {
await import('./cloudRemoteConfig')
await import('./cloudBadges')
await import('./cloudSessionCookie')

if (window.__CONFIG__?.subscription_required) {
await import('./cloudSubscription')
Expand Down
65 changes: 65 additions & 0 deletions src/platform/auth/session/useSessionCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { api } from '@/scripts/api'
import { isCloud } from '@/platform/distribution/types'
import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore'

/**
* Session cookie management for cloud authentication.
* Creates and deletes session cookies on the ComfyUI server.
*/
export const useSessionCookie = () => {
/**
* Creates or refreshes the session cookie.
* Called after login and on token refresh.
*/
const createSession = async (): Promise<void> => {
if (!isCloud) return

const authStore = useFirebaseAuthStore()
const authHeader = await authStore.getAuthHeader()

if (!authHeader) {
throw new Error('No auth header available for session creation')
}

const response = await fetch(api.apiURL('/auth/session'), {
method: 'POST',
credentials: 'include',
headers: {
...authHeader,
'Content-Type': 'application/json'
}
})

if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(
`Failed to create session: ${errorData.message || response.statusText}`
)
}
}

/**
* Deletes the session cookie.
* Called on logout.
*/
const deleteSession = async (): Promise<void> => {
if (!isCloud) return

const response = await fetch(api.apiURL('/auth/session'), {
method: 'DELETE',
credentials: 'include'
})

if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(
`Failed to delete session: ${errorData.message || response.statusText}`
)
}
}

return {
createSession,
deleteSession
}
}
14 changes: 14 additions & 0 deletions src/services/extensionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,20 @@ export const useExtensionService = () => {
void extension.onAuthUserResolved?.(user, app)
})
}

if (extension.onAuthTokenRefreshed) {
const { onTokenRefreshed } = useCurrentUser()
onTokenRefreshed(() => {
void extension.onAuthTokenRefreshed?.()
})
}

if (extension.onAuthUserLogout) {
const { onUserLogout } = useCurrentUser()
onUserLogout(() => {
void extension.onAuthUserLogout?.()
})
}
}

/**
Expand Down
12 changes: 12 additions & 0 deletions src/stores/firebaseAuthStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
deleteUser,
getAdditionalUserInfo,
onAuthStateChanged,
onIdTokenChanged,
sendPasswordResetEmail,
setPersistence,
signInWithEmailAndPassword,
Expand Down Expand Up @@ -61,6 +62,9 @@ export const useFirebaseAuthStore = defineStore('firebaseAuth', () => {
const balance = ref<GetCustomerBalanceResponse | null>(null)
const lastBalanceUpdateTime = ref<Date | null>(null)

// Token refresh trigger - increments when token is refreshed
const tokenRefreshTrigger = ref(0)

// Providers
const googleProvider = new GoogleAuthProvider()
googleProvider.addScope('email')
Expand Down Expand Up @@ -95,6 +99,13 @@ export const useFirebaseAuthStore = defineStore('firebaseAuth', () => {
lastBalanceUpdateTime.value = null
})

// Listen for token refresh events
onIdTokenChanged(auth, (user) => {
if (user && isCloud) {
tokenRefreshTrigger.value++
}
})

const getIdToken = async (): Promise<string | undefined> => {
if (!currentUser.value) return
try {
Expand Down Expand Up @@ -421,6 +432,7 @@ export const useFirebaseAuthStore = defineStore('firebaseAuth', () => {
balance,
lastBalanceUpdateTime,
isFetchingBalance,
tokenRefreshTrigger,

// Getters
isAuthenticated,
Expand Down
12 changes: 12 additions & 0 deletions src/types/comfy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,5 +219,17 @@ export interface ComfyExtension {
*/
onAuthUserResolved?(user: AuthUserInfo, app: ComfyApp): Promise<void> | void

/**
* Fired whenever the auth token is refreshed.
* This is an experimental API and may be changed or removed in the future.
*/
onAuthTokenRefreshed?(): Promise<void> | void

/**
* Fired when user logs out.
* This is an experimental API and may be changed or removed in the future.
*/
onAuthUserLogout?(): Promise<void> | void

[key: string]: any
}
1 change: 1 addition & 0 deletions tests-ui/tests/store/firebaseAuthStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ vi.mock('firebase/auth', async (importOriginal) => {
createUserWithEmailAndPassword: vi.fn(),
signOut: vi.fn(),
onAuthStateChanged: vi.fn(),
onIdTokenChanged: vi.fn(),
signInWithPopup: vi.fn(),
GoogleAuthProvider: class {
addScope = vi.fn()
Expand Down
Loading