Line data Source code
1 : import { isSsoRequiredRefusal } from '@comfyorg/account-core/sso'
2 : import { zErrorResponse } from '@comfyorg/ingest-types/zod'
3 :
4 : import { useCurrentUserAccess } from '@/platform/auth/currentUserAccess'
5 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
6 : import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore'
7 : import {
8 : SessionRevokedError,
9 : revokedCodeOf
10 : } from '@/platform/auth/session/sessionRevokedError'
11 : import { isCloud } from '@/platform/distribution/types'
12 : import { reportError } from '@comfyorg/telemetry/reportError'
13 : import { api } from '@/scripts/api'
14 : import { useAuthStoreAccess } from '@/platform/auth/authStoreAccess'
15 :
16 : interface InFlightCreateSession {
17 : ownerUid: string | null
18 : promise: Promise<void>
19 : }
20 :
21 : class SsoRequiredSessionError extends Error {
22 : readonly code = 'SSO_REQUIRED'
23 : }
24 :
25 : let inFlightCreateSession: InFlightCreateSession | null = null
26 : let confirmedSessionOwnerUid: string | null = null
27 2355 : let sessionMutationTail = Promise.resolve()
28 : let pendingSessionMutations = 0
29 :
30 : /**
31 : * Session cookie management for cloud authentication.
32 : * Creates and deletes session cookies on the ComfyUI server.
33 : */
34 2355 : export const useSessionCookie = () => {
35 : const createSessionWithHeader = async (
36 : authHeader: Record<string, string>
37 : ): Promise<Response> => {
38 : return await fetch(api.apiURL('/auth/session'), {
39 : method: 'POST',
40 : credentials: 'include',
41 : headers: {
42 : ...authHeader,
43 : 'Content-Type': 'application/json'
44 : }
45 : })
46 : }
47 :
48 : const readSessionError = async (response: Response): Promise<Error> => {
49 : const errorData: unknown = await response.json().catch(() => null)
50 : const refusal = zErrorResponse.partial().safeParse(errorData).data
51 : const text = refusal?.message ?? response.statusText
52 : if (isSsoRequiredRefusal(response.status, errorData)) {
53 : return new SsoRequiredSessionError(text)
54 : }
55 : const revokedCode =
56 : response.status === 401 ? revokedCodeOf(refusal?.code) : null
57 : return revokedCode
58 : ? new SessionRevokedError(text, revokedCode)
59 : : new Error(text)
60 : }
61 :
62 : const getSessionHeaderOrThrow = async (): Promise<Record<string, string>> => {
63 : const authStore = useAuthStoreAccess()
64 : const firebaseToken = await authStore.getIdToken()
65 : if (!firebaseToken) {
66 : throw new Error('No Firebase token available for session creation')
67 : }
68 :
69 : return { Authorization: `Bearer ${firebaseToken}` }
70 : }
71 :
72 : /** Creates or refreshes the session cookie after login or token refresh. */
73 : const performCreateSession = async (
74 : expectedOwnerUid: string
75 : ): Promise<void> => {
76 : const authStore = useAuthStoreAccess()
77 : const authHeader = await getSessionHeaderOrThrow()
78 :
79 : if ((authStore.currentUser?.uid ?? null) !== expectedOwnerUid) {
80 : throw new Error('Session identity changed during creation')
81 : }
82 :
83 : const response = await createSessionWithHeader(authHeader)
84 :
85 : if (!response.ok) {
86 : throw await readSessionError(response)
87 : }
88 : }
89 :
90 : const establishSession = (
91 : ownerUid: string,
92 : forceRefresh: boolean
93 : ): Promise<void> => {
94 : if (
95 : !forceRefresh &&
96 : pendingSessionMutations === 0 &&
97 : confirmedSessionOwnerUid === ownerUid
98 : ) {
99 : return Promise.resolve()
100 : }
101 : if (inFlightCreateSession?.ownerUid === ownerUid) {
102 : return inFlightCreateSession.promise
103 : }
104 :
105 : pendingSessionMutations++
106 : const request: InFlightCreateSession = {
107 : ownerUid,
108 : promise: sessionMutationTail
109 : .then(async () => {
110 : if ((useAuthStoreAccess().currentUser?.uid ?? null) !== ownerUid) {
111 : throw new Error('Session identity changed before creation')
112 : }
113 : await performCreateSession(ownerUid)
114 : confirmedSessionOwnerUid = ownerUid
115 : if ((useAuthStoreAccess().currentUser?.uid ?? null) !== ownerUid) {
116 : throw new Error('Session identity changed during creation')
117 : }
118 : })
119 : .finally(() => {
120 : pendingSessionMutations--
121 : if (inFlightCreateSession === request) {
122 : inFlightCreateSession = null
123 : }
124 : })
125 : }
126 : inFlightCreateSession = request
127 : sessionMutationTail = request.promise.catch(() => {})
128 : return request.promise
129 : }
130 :
131 : const currentOwnerUidOrThrow = (): string => {
132 : const ownerUid = useAuthStoreAccess().currentUser?.uid
133 : if (!ownerUid) {
134 : throw new Error('No authenticated user available for session creation')
135 : }
136 : return ownerUid
137 : }
138 :
139 : const isApiKeyOnWebSession = () =>
140 : useFeatureFlags().flags.unifiedWebSessionEnabled &&
141 : useCurrentUserAccess().isApiKeyLogin.value
142 :
143 11 : const ensureSessionCookie = async (): Promise<void> => {
144 : if (!isCloud || isApiKeyOnWebSession()) return
145 : const webSession = useCloudWebSessionStore()
146 : if (webSession.start()) return webSession.whenReady()
147 : await establishSession(currentOwnerUidOrThrow(), false)
148 : }
149 :
150 11 : const createSession = async (): Promise<void> => {
151 : if (!isCloud || isApiKeyOnWebSession()) return
152 : if (useCloudWebSessionStore().start()) return
153 : try {
154 : await establishSession(currentOwnerUidOrThrow(), true)
155 : } catch (error) {
156 : if (error instanceof SessionRevokedError) return
157 : reportError(error, {
158 : surface: 'auth',
159 : errorType: 'session_cookie_creation_failure',
160 : level: 'warning'
161 : })
162 : }
163 : }
164 :
165 : /** After an interactive sign-in: whether ingest refused its session for SSO. */
166 11 : const sessionRequiresSso = async (): Promise<boolean> => {
167 0 : if (!isCloud || isApiKeyOnWebSession()) return false
168 : const webSession = useCloudWebSessionStore()
169 : if (webSession.start()) {
170 : return (await webSession.whenSessionCreated()) === 'SSO_REQUIRED'
171 : }
172 : try {
173 : await establishSession(currentOwnerUidOrThrow(), false)
174 : return false
175 : } catch (error) {
176 : return error instanceof SsoRequiredSessionError
177 : }
178 : }
179 :
180 11 : const createSessionOrThrow = async (): Promise<void> => {
181 : if (!isCloud) return
182 : const webSession = useCloudWebSessionStore()
183 : if (webSession.isActive()) return webSession.whenReady()
184 : await establishSession(currentOwnerUidOrThrow(), true)
185 : }
186 :
187 : /**
188 : * Deletes the session cookie.
189 : * Called on logout.
190 : */
191 11 : const deleteSession = async (): Promise<void> => {
192 : if (!isCloud) return
193 : if (useCloudWebSessionStore().isActive()) return
194 : confirmedSessionOwnerUid = null
195 : inFlightCreateSession = null
196 :
197 : try {
198 : pendingSessionMutations++
199 : const deleteRequest = sessionMutationTail
200 : .then(async () => {
201 : const response = await fetch(api.apiURL('/auth/session'), {
202 : method: 'DELETE',
203 : credentials: 'include'
204 : })
205 :
206 : if (!response.ok) {
207 : throw await readSessionError(response)
208 : }
209 : confirmedSessionOwnerUid = null
210 : })
211 : .finally(() => {
212 : pendingSessionMutations--
213 : })
214 : sessionMutationTail = deleteRequest.catch(() => {})
215 : await deleteRequest
216 : } catch {
217 : // Logout resolves regardless so the client-side sign-out completes, but
218 : // a failed DELETE leaves the server-side session cookie alive with no
219 : // other signal. The caught error carries the server's message, which can
220 : // name the user, so a fixed error is reported in its place.
221 : reportError(new Error('Session cookie deletion failed'), {
222 : surface: 'auth',
223 : errorType: 'auth_session_cookie_delete_failed',
224 : tags: {
225 : failure_kind: 'caught_unexpected',
226 : feature_area: 'auth',
227 : operation: 'auth',
228 : outcome: 'failed'
229 : },
230 : context: {
231 : had_pending_session_mutation: pendingSessionMutations > 0
232 : },
233 : level: 'error'
234 : })
235 : }
236 : }
237 :
238 11 : return {
239 : createSession,
240 : createSessionOrThrow,
241 : sessionRequiresSso,
242 : ensureSessionCookie,
243 : deleteSession
244 : }
245 : }
|