Line data Source code
1 : import { combineAbortSignals } from '@comfyorg/api-client/abortSignal'
2 : import type { BillingHandoffCreateRequest } from '@comfyorg/ingest-types'
3 : import {
4 : zBillingHandoffCreateResponse,
5 : zErrorResponse
6 : } from '@comfyorg/ingest-types/zod'
7 : import { parseUrl } from '@comfyorg/shared-frontend-utils/urlSafety'
8 : import { useTelemetry } from '@comfyorg/telemetry'
9 : import { watch } from 'vue'
10 :
11 : import { useToast } from '@/components/ui/toast/toastStore'
12 : import { useAuthDialogs } from '@/composables/auth/useAuthDialogs'
13 : import { getComfyCloudBaseUrl } from '@/config/comfyApi'
14 : import { i18n, t } from '@/i18n'
15 : import {
16 : desktopHostUser,
17 : issueDesktopHostBillingHandoff
18 : } from '@/platform/auth/desktopHost/desktopHostSession'
19 : import { refreshBillingAccount } from '@/platform/billing/billingAccountRefresh'
20 : import type { BillingTab } from '@/platform/billing/billingTab'
21 : import { reserveBillingTab } from '@/platform/billing/billingTab'
22 : import { localSurface } from '@/platform/billing/localBillingWebEnabled'
23 : import { registerRefreshOnReturn } from '@/platform/billing/refreshOnReturn'
24 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
25 : import { useAuthStore } from '@/stores/authStore'
26 :
27 2356 : const ISSUE_TIMEOUT_MS = 15_000
28 :
29 : /** The billing flow billing-web opens after the exchange, or Platform's billing page, which takes none. */
30 : export type BillingHandoffRequest =
31 : | { readonly intent: 'top-up'; readonly amountCents: number }
32 : | { readonly intent: 'subscription' }
33 : | { readonly receiver: 'platform' }
34 :
35 : type HandoffIssue =
36 : | { readonly kind: 'issued'; readonly entryUrl: string }
37 : | { readonly kind: 'sign_in_again' }
38 : | {
39 : readonly kind: 'refused'
40 : readonly message: string | undefined
41 : readonly code: string | undefined
42 : }
43 :
44 : export type BillingHandoffResult =
45 : | { readonly status: 'ok'; readonly url: string }
46 : | { readonly status: 'error'; readonly message: string | undefined }
47 :
48 : interface HandoffScope {
49 : readonly userId: string
50 : readonly workspaceId: string
51 : readonly cloudBaseUrl: string
52 : }
53 :
54 2356 : const UNEXPLAINED_REFUSAL: HandoffIssue = {
55 : kind: 'refused',
56 : message: undefined,
57 : code: undefined
58 : }
59 :
60 2 : async function refusal(response: Response): Promise<HandoffIssue> {
61 2 : const body = zErrorResponse.safeParse(await response.json().catch(() => null))
62 2 : return body.success
63 : ? { kind: 'refused', message: body.data.message, code: body.data.code }
64 : : UNEXPLAINED_REFUSAL
65 : }
66 :
67 5 : function issueBody(
68 : workspaceId: string,
69 : request: BillingHandoffRequest
70 : ): BillingHandoffCreateRequest {
71 5 : return {
72 : workspace_id: workspaceId,
73 : surface: 'local_web',
74 : ...('receiver' in request
75 : ? { receiver: request.receiver }
76 : : { receiver: 'billing_web', intent: request.intent }),
77 : ...('amountCents' in request ? { amount_cents: request.amountCents } : {}),
78 : client_version: __COMFYUI_FRONTEND_VERSION__.slice(0, 64)
79 : }
80 : }
81 :
82 5 : async function issueBillingHandoff(
83 : token: string,
84 : workspaceId: string,
85 : cloudBaseUrl: string,
86 : request: BillingHandoffRequest,
87 : signal: AbortSignal
88 : ): Promise<HandoffIssue> {
89 5 : try {
90 5 : const response = await fetch(new URL('/api/auth/handoffs', cloudBaseUrl), {
91 : method: 'POST',
92 : cache: 'no-store',
93 : headers: {
94 : Authorization: `Bearer ${token}`,
95 : 'Content-Type': 'application/json'
96 : },
97 : body: JSON.stringify(issueBody(workspaceId, request)),
98 : signal
99 : })
100 5 : if (response.status === 401) return { kind: 'sign_in_again' }
101 5 : if (!response.ok) return refusal(response)
102 3 : const issued = zBillingHandoffCreateResponse.safeParse(
103 : await response.json()
104 : )
105 5 : return issued.success
106 : ? { kind: 'issued', entryUrl: issued.data.entry_url }
107 : : UNEXPLAINED_REFUSAL
108 : } catch {
109 0 : return UNEXPLAINED_REFUSAL
110 : }
111 : }
112 :
113 15 : function currentScope(): HandoffScope | undefined {
114 15 : const userId = useAuthStore().userId
115 15 : const workspaceId =
116 : useWorkspaceIdentity().activeWorkspaceId ??
117 : desktopHostUser.value?.workspaceId
118 15 : if (!userId || !workspaceId) return undefined
119 15 : return { userId, workspaceId, cloudBaseUrl: getComfyCloudBaseUrl() }
120 : }
121 :
122 2356 : const SIGN_IN_AGAIN: HandoffIssue = { kind: 'sign_in_again' }
123 :
124 2356 : const DISCARDED: BillingHandoffResult = { status: 'error', message: undefined }
125 :
126 10 : function scopeKey(scope: HandoffScope | undefined): string {
127 10 : return scope
128 : ? `${scope.userId} ${scope.workspaceId} ${scope.cloudBaseUrl}`
129 : : ''
130 : }
131 :
132 : interface ScopeWatch {
133 : readonly changed: () => boolean
134 : readonly replaced: () => boolean
135 : readonly stop: () => void
136 : }
137 :
138 5 : function watchScopeChange(): ScopeWatch {
139 5 : const started = scopeKey(currentScope())
140 5 : let signedOut = false
141 5 : let replaced = false
142 : const stop = watch(
143 : () => scopeKey(currentScope()),
144 : (key) => {
145 0 : if (key === '') signedOut = true
146 0 : else if (key !== started || signedOut) replaced = true
147 : },
148 : { flush: 'sync' }
149 : )
150 5 : return {
151 : changed: () => signedOut || replaced,
152 : replaced: () => replaced,
153 : stop
154 : }
155 : }
156 :
157 2356 : let inFlight = false
158 2356 : let stopReturnRefresh: (() => void) | null = null
159 :
160 3 : function armReturnRefresh(): void {
161 3 : stopReturnRefresh?.()
162 3 : stopReturnRefresh = registerRefreshOnReturn(refreshBillingAccount)
163 : }
164 :
165 0 : async function issueThroughDesktop(
166 : workspaceId: string,
167 : request: BillingHandoffRequest
168 : ): Promise<HandoffIssue> {
169 0 : const answer =
170 : 'receiver' in request
171 : ? await issueDesktopHostBillingHandoff(workspaceId, request.receiver)
172 : : await issueDesktopHostBillingHandoff(
173 : workspaceId,
174 : 'billing_web',
175 : request.intent,
176 : 'amountCents' in request ? request.amountCents : undefined
177 : )
178 0 : switch (answer.status) {
179 : case 'issued':
180 0 : return { kind: 'issued', entryUrl: answer.entryUrl }
181 : case 'sign_in_again':
182 0 : return SIGN_IN_AGAIN
183 : case 'refused':
184 0 : return { kind: 'refused', message: answer.message, code: answer.code }
185 : case 'disabled':
186 0 : return UNEXPLAINED_REFUSAL
187 : }
188 : }
189 :
190 5 : function refusedOnAbort(signal: AbortSignal): {
191 : refusal: Promise<HandoffIssue>
192 : stop: () => void
193 : } {
194 5 : let refuse = () => {}
195 5 : const refusal = new Promise<HandoffIssue>((resolve) => {
196 5 : refuse = () => resolve(UNEXPLAINED_REFUSAL)
197 : })
198 5 : signal.addEventListener('abort', refuse, { once: true })
199 5 : return { refusal, stop: () => signal.removeEventListener('abort', refuse) }
200 : }
201 :
202 5 : async function unlessAbandoned(
203 : issue: () => Promise<HandoffIssue>,
204 : signal: AbortSignal
205 : ): Promise<HandoffIssue> {
206 5 : if (signal.aborted) return UNEXPLAINED_REFUSAL
207 5 : const abandoned = refusedOnAbort(signal)
208 5 : return Promise.race([issue(), abandoned.refusal]).finally(abandoned.stop)
209 : }
210 :
211 5 : async function issueWithFreshToken(
212 : scope: HandoffScope,
213 : request: BillingHandoffRequest,
214 : signal: AbortSignal
215 : ): Promise<HandoffIssue> {
216 5 : const token = await useAuthStore().getFreshIdToken()
217 5 : if (signal.aborted) return UNEXPLAINED_REFUSAL
218 5 : if (!token) return SIGN_IN_AGAIN
219 5 : return issueBillingHandoff(
220 : token,
221 : scope.workspaceId,
222 : scope.cloudBaseUrl,
223 : request,
224 : signal
225 : )
226 : }
227 :
228 5 : function issueForScope(
229 : scope: HandoffScope,
230 : request: BillingHandoffRequest,
231 : signal: AbortSignal
232 : ): Promise<HandoffIssue> {
233 5 : if (localSurface() === 'desktop')
234 0 : return unlessAbandoned(
235 : () => issueThroughDesktop(scope.workspaceId, request),
236 : signal
237 : )
238 5 : const abandonedOrOverdue = combineAbortSignals([
239 : signal,
240 : AbortSignal.timeout(ISSUE_TIMEOUT_MS)
241 : ])
242 5 : return unlessAbandoned(
243 : () => issueWithFreshToken(scope, request, abandonedOrOverdue),
244 : abandonedOrOverdue
245 : )
246 : }
247 :
248 5 : function settle(
249 : issue: HandoffIssue,
250 : scopeChanged: boolean
251 : ): BillingHandoffResult {
252 5 : if (scopeChanged)
253 0 : return { status: 'error', message: t('billingHandoff.superseded') }
254 5 : if (issue.kind === 'issued') {
255 3 : armReturnRefresh()
256 3 : return { status: 'ok', url: issue.entryUrl }
257 : }
258 2 : if (issue.kind === 'refused')
259 2 : return { status: 'error', message: issue.message }
260 0 : void useAuthDialogs().showSignInDialog()
261 0 : return { status: 'error', message: t('billingHandoff.signInAgain') }
262 : }
263 :
264 5 : function supersededDuring(issue: HandoffIssue, scopeWatch: ScopeWatch) {
265 5 : if (scopeWatch.replaced()) return true
266 5 : const endedBySignOut =
267 : issue.kind === 'sign_in_again' && currentScope() === undefined
268 5 : return scopeWatch.changed() && !endedBySignOut
269 : }
270 :
271 5 : function trackIssue(issue: HandoffIssue, scopeChanged: boolean): void {
272 5 : const result = scopeChanged
273 : ? 'superseded'
274 : : issue.kind === 'issued'
275 : ? 'opened'
276 : : issue.kind
277 5 : useTelemetry()?.trackBillingEvent({
278 : operation: 'local_handoff',
279 : stage: 'launched',
280 : outcome: result === 'opened' ? 'pending' : 'failed',
281 : surface: localSurface(),
282 : result,
283 : ...(issue.kind === 'refused' && issue.code && { error_code: issue.code })
284 : })
285 : }
286 :
287 : /** The tab a handoff opens in, reserved during the click and showing that checkout is opening. */
288 5 : export function reserveBillingHandoffTab(): BillingTab | null {
289 5 : return reserveBillingTab({
290 : lang: i18n.global.locale.value,
291 : tabTitle: t('billingHandoff.openingTabTitle'),
292 : title: t('billingHandoff.opening'),
293 : detail: t('billingHandoff.openingDetail')
294 : })
295 : }
296 :
297 : /** Issues a one-time billing handoff for the signed-in local account, through Desktop's bridge on Desktop; the URL works once and is never shown. */
298 5 : export async function issueLocalBillingHandoff(
299 : request: BillingHandoffRequest,
300 : signal: AbortSignal
301 : ): Promise<BillingHandoffResult> {
302 5 : if (inFlight) return DISCARDED
303 5 : const scope = currentScope()
304 5 : const scopeWatch = watchScopeChange()
305 5 : inFlight = true
306 5 : try {
307 5 : const issue = scope
308 : ? await issueForScope(scope, request, signal)
309 : : SIGN_IN_AGAIN
310 5 : if (signal.aborted) return DISCARDED
311 5 : const scopeChanged = supersededDuring(issue, scopeWatch)
312 5 : trackIssue(issue, scopeChanged)
313 5 : return settle(issue, scopeChanged)
314 : } finally {
315 5 : scopeWatch.stop()
316 5 : inFlight = false
317 : }
318 : }
319 :
320 : /** A Platform page a handoff opens instead of its billing page; Platform reads it from the entry URL's query. */
321 : export type PlatformHandoffView = 'plans'
322 :
323 2 : function withPlatformView(
324 : entryUrl: string,
325 : view: PlatformHandoffView | undefined
326 : ): string | undefined {
327 2 : if (view === undefined) return entryUrl
328 1 : const url = parseUrl(entryUrl)
329 1 : if (!url) return undefined
330 1 : url.searchParams.set('view', view)
331 1 : return url.href
332 : }
333 :
334 : /** Opens Platform billing, or the page `view` names, through a one-time handoff, in a tab reserved during the click; a refusal closes the tab and is shown as a toast. */
335 3 : export async function openPlatformBillingHandoff(
336 : view?: PlatformHandoffView
337 : ): Promise<void> {
338 3 : if (inFlight) return
339 3 : const tab = reserveBillingHandoffTab()
340 3 : if (!tab) {
341 0 : useToast().error(t('subscription.billingTabBlocked'))
342 0 : return
343 : }
344 3 : const issued = await issueLocalBillingHandoff(
345 : { receiver: 'platform' },
346 : new AbortController().signal
347 : )
348 3 : const target =
349 : issued.status === 'ok' ? withPlatformView(issued.url, view) : undefined
350 3 : if (target !== undefined) return tab.navigate(target)
351 1 : tab.close()
352 3 : useToast().error(
353 : (issued.status === 'error' && issued.message) ||
354 : t('subscription.billingPortalUnavailable')
355 : )
356 : }
|