Line data Source code
1 : import { useEventListener } from '@vueuse/core'
2 : import { defineStore } from 'pinia'
3 : import { computed, nextTick, ref, watch } from 'vue'
4 :
5 : import { useErrorHandling } from '@/composables/useErrorHandling'
6 : import { t } from '@/i18n'
7 : import { useToast } from '@/components/ui/toast/toastStore'
8 : import { useAuthStoreAccess } from '@/platform/auth/authStoreAccess'
9 : import { reportError as reportTelemetryError } from '@comfyorg/telemetry/reportError'
10 : import type { ApiKeyAuthHeader } from '@comfyorg/api-client/authTypes'
11 : import type { operations } from '@/types/comfyRegistryTypes'
12 :
13 : type ComfyApiUser =
14 : operations['createCustomer']['responses']['201']['content']['application/json']
15 :
16 2356 : const STORAGE_KEY = 'comfy_api_key'
17 :
18 2356 : const SAVE_FAILURE_DETAIL = {
19 : gone: 'auth.apiKey.storedForSessionDetail',
20 : kept: 'auth.apiKey.storedForSessionPreviousKeptDetail',
21 : unreadable: 'auth.apiKey.storedForSessionBlockedDetail'
22 : } as const
23 :
24 2356 : export const useApiKeyAuthStore = defineStore('apiKeyAuth', () => {
25 2355 : const authStore = useAuthStoreAccess()
26 2355 : let storageFailureReported = false
27 2355 : const reportStorageFailure = (error: unknown) => {
28 : // Some embedded or privacy-restricted browser contexts expose Storage but
29 : // throw SecurityError when it is read. The store already degrades to an
30 : // in-memory key and tells the user, so this expected restriction is not an
31 : // actionable application error.
32 0 : if (error instanceof DOMException && error.name === 'SecurityError') return
33 0 : if (storageFailureReported) return
34 0 : storageFailureReported = true
35 0 : reportTelemetryError(error, {
36 : surface: 'auth',
37 : errorType: 'api_key_storage_failed',
38 : level: 'warning'
39 : })
40 : }
41 :
42 2355 : const readPersistedKey = (): string | null => {
43 2355 : try {
44 2355 : return localStorage.getItem(STORAGE_KEY)
45 : } catch (error) {
46 0 : reportStorageFailure(error)
47 0 : return null
48 : }
49 : }
50 :
51 2355 : const apiKey = ref<string | null>(readPersistedKey())
52 :
53 2355 : useEventListener(window, 'storage', (event: StorageEvent) => {
54 2617 : if (event.key !== null && event.key !== STORAGE_KEY) return
55 2617 : try {
56 0 : if (event.storageArea !== localStorage) return
57 : } catch {
58 0 : return
59 : }
60 0 : apiKey.value = event.newValue
61 : })
62 :
63 2355 : const persistKey = (key: string): boolean => {
64 0 : try {
65 0 : localStorage.setItem(STORAGE_KEY, key)
66 0 : return true
67 : } catch (error) {
68 0 : reportStorageFailure(error)
69 0 : return false
70 : }
71 : }
72 :
73 2355 : const forgetPersistedKey = (): 'gone' | 'kept' | 'unreadable' => {
74 0 : let stored: string | null
75 0 : try {
76 0 : stored = localStorage.getItem(STORAGE_KEY)
77 : } catch (error) {
78 0 : reportStorageFailure(error)
79 0 : return 'unreadable'
80 : }
81 0 : if (stored === null) return 'gone'
82 0 : try {
83 0 : localStorage.removeItem(STORAGE_KEY)
84 0 : return 'gone'
85 : } catch (error) {
86 0 : reportStorageFailure(error)
87 0 : return 'kept'
88 : }
89 : }
90 2355 : const toast = useToast()
91 2355 : const { wrapWithErrorHandlingAsync, toastErrorHandler } = useErrorHandling()
92 :
93 2355 : const currentUser = ref<ComfyApiUser | null>(null)
94 2355 : const isAuthenticated = computed(() => !!currentUser.value)
95 :
96 2355 : const initializeUserFromApiKey = async (watchedApiKey: string) => {
97 0 : const createCustomerResponse = await authStore
98 : .createCustomer()
99 : .catch((err) => {
100 0 : console.error(err)
101 : return
102 : })
103 0 : if (apiKey.value !== watchedApiKey) return
104 0 : if (!createCustomerResponse) {
105 0 : forgetPersistedKey()
106 0 : apiKey.value = null
107 0 : throw new Error(t('auth.login.noAssociatedUser'))
108 : }
109 0 : currentUser.value = createCustomerResponse
110 : }
111 :
112 : // The stored key and its validated user form one session value: replacing
113 : // the key ends the previous user's session immediately instead of exposing
114 : // the old user while the new key validates.
115 2355 : watch(
116 : apiKey,
117 : async (watchedApiKey) => {
118 2355 : currentUser.value = null
119 2355 : if (watchedApiKey) {
120 0 : await nextTick()
121 0 : if (apiKey.value !== watchedApiKey) return
122 0 : void initializeUserFromApiKey(watchedApiKey)
123 : }
124 : },
125 : { immediate: true }
126 : )
127 :
128 2355 : const reportError = (error: unknown) => {
129 0 : if (error instanceof Error && error.message === 'STORAGE_FAILED') {
130 0 : toast.error(t('auth.apiKey.storageFailed'), {
131 : description: t('auth.apiKey.storageFailedDetail')
132 : })
133 : } else {
134 0 : toastErrorHandler(error)
135 : }
136 : }
137 :
138 2355 : const storeApiKey = wrapWithErrorHandlingAsync(async (newApiKey: string) => {
139 0 : const persisted = persistKey(newApiKey)
140 0 : apiKey.value = newApiKey
141 0 : if (!persisted) {
142 0 : toast.warning(t('auth.apiKey.storedForSession'), {
143 : description: t(SAVE_FAILURE_DETAIL[forgetPersistedKey()]),
144 : duration: 8000
145 : })
146 0 : return true
147 : }
148 0 : toast.success(t('auth.apiKey.stored'), {
149 : description: t('auth.apiKey.storedDetail'),
150 : duration: 5000
151 : })
152 0 : return true
153 : }, reportError)
154 :
155 2355 : const clearStoredApiKey = wrapWithErrorHandlingAsync(async () => {
156 0 : const removal = forgetPersistedKey()
157 0 : apiKey.value = null
158 0 : if (removal !== 'gone') {
159 0 : toast.warning(t('auth.apiKey.clearedForSession'), {
160 : description: t(
161 : removal === 'kept'
162 : ? 'auth.apiKey.clearedForSessionDetail'
163 : : 'auth.apiKey.clearedForSessionBlockedDetail'
164 : ),
165 : duration: 8000
166 : })
167 0 : return true
168 : }
169 0 : toast.success(t('auth.apiKey.cleared'), {
170 : description: t('auth.apiKey.clearedDetail'),
171 : duration: 5000
172 : })
173 0 : return true
174 : }, reportError)
175 :
176 2355 : const getApiKey = () => apiKey.value
177 :
178 : /**
179 : * Retrieves the appropriate authentication header for API requests if an
180 : * API key is available, otherwise returns null.
181 : */
182 2355 : const getAuthHeader = (): ApiKeyAuthHeader | null => {
183 0 : const comfyOrgApiKey = getApiKey()
184 0 : if (comfyOrgApiKey) {
185 0 : return {
186 : 'X-API-KEY': comfyOrgApiKey
187 : }
188 : }
189 0 : return null
190 : }
191 :
192 2355 : return {
193 : // State
194 : currentUser,
195 : isAuthenticated,
196 :
197 : // Actions
198 : storeApiKey,
199 : clearStoredApiKey,
200 : getAuthHeader,
201 : getApiKey
202 : }
203 : })
|