Line data Source code
1 : import type {
2 : AxiosError,
3 : AxiosInstance,
4 : InternalAxiosRequestConfig
5 : } from 'axios'
6 : import axios, { AxiosHeaders } from 'axios'
7 :
8 : import type { RetrySignalLifecycle } from '@comfyorg/api-client/apiAuthProvider'
9 : import {
10 : presentForRefusal,
11 : presentForResponse
12 : } from '@/platform/auth/sso/ssoRequired'
13 : import { isCloud } from '@/platform/distribution/types'
14 : import { useTelemetry } from '@comfyorg/telemetry'
15 : import { reportError } from '@comfyorg/telemetry/reportError'
16 : import type {
17 : UnifiedAuthRetryFailureReason,
18 : UnifiedAuthRetryMetadata
19 : } from '@comfyorg/telemetry/types'
20 : import { fetchWithRetry } from '@comfyorg/api-client/fetchWithRetry'
21 : import type { RetryPolicy } from '@comfyorg/api-client/retryPolicy'
22 : import { withSignInRefusalRetry } from '@comfyorg/api-client/retryPolicy'
23 :
24 : type UnifiedRemint = (expectedToken: string) => Promise<string | null>
25 :
26 2356 : let remintUnified: UnifiedRemint | undefined
27 :
28 : /** Installed by `workspaceAuthStore`; importing it here cycles through `authStore`. */
29 2356 : export function provideUnifiedRemint(remint: UnifiedRemint): void {
30 2356 : remintUnified = remint
31 : }
32 :
33 : /** Single gate for the reactive 401 guard, reused at every cloud request seam: true on Cloud. */
34 0 : export async function shouldRemintCloudRequest(): Promise<boolean> {
35 0 : return isCloud
36 : }
37 :
38 : /** `policy`, also sending a write the sign-in check refused once more on cloud. */
39 2356 : export function cloudRetryPolicy(
40 : policy?: RetryPolicy
41 : ): RetryPolicy | undefined {
42 2356 : return isCloud ? withSignInRefusalRetry(policy) : policy
43 : }
44 :
45 : /**
46 : * Re-mints the unified Cloud JWT once from the current Firebase identity and
47 : * returns the fresh token, or `null` when there is nothing to retry with: no
48 : * active unified session, or the re-mint failed. A permanent auth failure is
49 : * surfaced + torn down inside `remintUnifiedOnce` (error toast + session clear,
50 : * matching the proactive refresh path); the `catch` here only guards an
51 : * unexpected throw (e.g. no active Pinia), which it
52 : * reports as `auth_unified_remint_unexpected`. Either way `null` makes the
53 : * caller surface its original 401 unchanged.
54 : */
55 0 : async function tryRemintToken(expectedToken: string): Promise<string | null> {
56 0 : try {
57 0 : return (await remintUnified?.(expectedToken)) ?? null
58 : } catch (err) {
59 0 : reportError(err, {
60 : surface: 'auth',
61 : errorType: 'auth_unified_remint_unexpected',
62 : tags: {
63 : failure_kind: 'caught_unexpected',
64 : feature_area: 'auth',
65 : operation: 'auth',
66 : outcome: 'failed'
67 : },
68 : level: 'error'
69 : })
70 0 : return null
71 : }
72 : }
73 :
74 0 : function trackRetry(
75 : transport: UnifiedAuthRetryMetadata['transport'],
76 : outcome: UnifiedAuthRetryMetadata['outcome'],
77 : finalStatus?: number,
78 : failureReason?: UnifiedAuthRetryFailureReason
79 : ): void {
80 0 : useTelemetry()?.trackUnifiedAuthRetry({
81 : transport,
82 : outcome,
83 : ...(finalStatus !== undefined && { final_status: finalStatus }),
84 : ...(failureReason !== undefined && { failure_reason: failureReason })
85 : })
86 : }
87 :
88 0 : function trackRetryResponse(
89 : transport: UnifiedAuthRetryMetadata['transport'],
90 : status: number
91 : ): void {
92 0 : trackRetry(
93 : transport,
94 : status < 400 ? 'succeeded' : 'failed',
95 : status,
96 : status < 400 ? undefined : 'retry_rejected'
97 : )
98 : }
99 :
100 0 : function bearerToken(authorization: unknown): string | undefined {
101 0 : if (typeof authorization !== 'string') return
102 0 : return authorization.startsWith('Bearer ')
103 : ? authorization.slice('Bearer '.length)
104 : : undefined
105 : }
106 :
107 0 : function fetchRequestHeaders(
108 : input: RequestInfo | URL,
109 : init: RequestInit
110 : ): Headers {
111 0 : if (init.headers !== undefined) return new Headers(init.headers)
112 0 : return input instanceof Request ? new Headers(input.headers) : new Headers()
113 : }
114 :
115 : /** Best-effort: the SSO screen never replaces the 403 the caller is owed. */
116 : async function presentSsoRequired(present: () => unknown): Promise<void> {
117 : try {
118 : await present()
119 : } catch (error) {
120 : reportError(error, {
121 : surface: 'auth',
122 : errorType: 'failure_presenting_sso_required'
123 : })
124 : }
125 : }
126 :
127 : /**
128 : * Issues a `fetch` and, on a `401`, re-mints the unified Cloud JWT once and
129 : * retries the request exactly once with the fresh token. A persistent `401`
130 : * (or a `null` re-mint) surfaces the original Response unchanged — no retry
131 : * loop. Requires a replayable body: a one-shot `ReadableStream` body cannot be
132 : * replayed, so such a request surfaces its original `401` without a retry (no
133 : * current cloud caller sends one).
134 : *
135 : * `shouldRetryOn401` is the caller's gate (see {@link shouldRemintCloudRequest}).
136 : *
137 : * `retrySignalLifecycle`, when supplied, ends the initial fetch's timeout
138 : * before re-minting and creates a fresh signal immediately before the retry.
139 : */
140 1 : export async function fetchWithUnifiedRemint(
141 : input: RequestInfo | URL,
142 : init: RequestInit,
143 : shouldRetryOn401: boolean,
144 : retrySignalLifecycle?: RetrySignalLifecycle,
145 : retryPolicy?: RetryPolicy
146 : ): Promise<Response> {
147 1 : const policy = cloudRetryPolicy(retryPolicy)
148 1 : const retryInput =
149 : shouldRetryOn401 && input instanceof Request && input.body !== null
150 : ? input.clone()
151 : : input
152 1 : const response = await fetchWithRetry(input, init, { policy })
153 1 : if (response.status === 403 && isCloud) {
154 : await presentSsoRequired(() => presentForResponse(response))
155 : }
156 1 : if (!shouldRetryOn401 || response.status !== 401) {
157 1 : return response
158 : }
159 :
160 0 : if (init.body instanceof ReadableStream) {
161 0 : console.warn(
162 : 'fetchWithUnifiedRemint: a ReadableStream body is not replayable; surfacing the original 401'
163 : )
164 0 : trackRetry('fetch', 'failed', response.status, 'non_replayable_body')
165 0 : return response
166 : }
167 :
168 0 : const requestHeaders = fetchRequestHeaders(input, init)
169 0 : const expectedToken = bearerToken(requestHeaders.get('Authorization'))
170 0 : if (!expectedToken) {
171 0 : trackRetry('fetch', 'failed', response.status, 'missing_bearer')
172 0 : return response
173 : }
174 :
175 1 : retrySignalLifecycle?.clearInitialTimeout()
176 1 : const token = await tryRemintToken(expectedToken)
177 0 : if (!token) {
178 0 : trackRetry('fetch', 'failed', response.status, 'remint_failed')
179 0 : return response
180 : }
181 :
182 0 : const headers = requestHeaders
183 0 : headers.set('Authorization', `Bearer ${token}`)
184 1 : const retryInit = retrySignalLifecycle
185 : ? { ...init, headers, signal: retrySignalLifecycle.createSignal() }
186 : : { ...init, headers }
187 1 : try {
188 1 : const retryResponse = await fetchWithRetry(retryInput, retryInit, {
189 : policy
190 : })
191 0 : trackRetryResponse('fetch', retryResponse.status)
192 0 : return retryResponse
193 : } catch (error) {
194 0 : trackRetry('fetch', 'failed', undefined, 'retry_request_failed')
195 0 : throw error
196 : }
197 : }
198 :
199 0 : function isRetriableUnauthorized(
200 : error: unknown
201 : ): error is AxiosError & { config: InternalAxiosRequestConfig } {
202 0 : if (!axios.isAxiosError(error)) return false
203 0 : const config = error.config
204 0 : if (!config || config.__unifiedRetried || config.__skipUnifiedRemint) {
205 0 : return false
206 : }
207 0 : return error.response?.status === 401
208 : }
209 :
210 0 : async function presentSsoRefusal(error: unknown): Promise<void> {
211 : if (!isCloud || !axios.isAxiosError(error)) return
212 : const response = error.response
213 : if (response?.status !== 403) return
214 : await presentSsoRequired(() =>
215 : presentForRefusal(response.status, response.data)
216 : )
217 : }
218 :
219 : /**
220 : * Installs a response interceptor that gives a cloud axios client the same
221 : * reactive 401 guard as {@link fetchWithUnifiedRemint}: a single re-mint + a
222 : * single retry on `401`, surfacing a persistent `401` unchanged. A no-op off
223 : * Cloud: the original error rejects unchanged.
224 : */
225 2355 : export function attachUnifiedRemintInterceptor(client: AxiosInstance): void {
226 2355 : client.interceptors.response.use(
227 : (response) => response,
228 : async (error: unknown) => {
229 0 : await presentSsoRefusal(error)
230 0 : if (
231 : !isRetriableUnauthorized(error) ||
232 : !(await shouldRemintCloudRequest())
233 : ) {
234 0 : throw error
235 : }
236 :
237 0 : const expectedToken = bearerToken(
238 : new AxiosHeaders(error.config.headers).get('Authorization')
239 : )
240 0 : if (!expectedToken) {
241 0 : trackRetry('axios', 'failed', 401, 'missing_bearer')
242 0 : throw error
243 : }
244 :
245 0 : const token = await tryRemintToken(expectedToken)
246 0 : if (!token) {
247 0 : trackRetry('axios', 'failed', 401, 'remint_failed')
248 0 : throw error
249 : }
250 :
251 : // Clone (don't mutate) the caller's config so the re-minted Bearer never
252 : // leaks into a caller-retained reference, matching fetchWithUnifiedRemint.
253 0 : const { config } = error
254 0 : const headers = new AxiosHeaders(config.headers)
255 0 : headers.set('Authorization', `Bearer ${token}`)
256 0 : try {
257 0 : const retryResponse = await client.request({
258 : ...config,
259 : headers,
260 : __unifiedRetried: true
261 : })
262 0 : trackRetryResponse('axios', retryResponse.status)
263 0 : return retryResponse
264 : } catch (retryError) {
265 0 : const finalStatus = axios.isAxiosError(retryError)
266 : ? retryError.response?.status
267 : : undefined
268 0 : trackRetry(
269 : 'axios',
270 : 'failed',
271 : finalStatus,
272 : finalStatus !== undefined ? 'retry_rejected' : 'retry_request_failed'
273 : )
274 0 : throw retryError
275 : }
276 : }
277 : )
278 : }
|