Line data Source code
1 : import type {
2 : CheckoutAssignmentStatus,
3 : CheckoutEntryFlow,
4 : CheckoutEntrySource,
5 : CheckoutJourneyArm,
6 : CheckoutJourneyContext,
7 : CheckoutUiMode
8 : } from '@comfyorg/account-core/billing'
9 : import {
10 : isBillingSource,
11 : isContractIdentifier
12 : } from '@comfyorg/billing-contract'
13 :
14 : import type { PaymentIntentSource } from '@comfyorg/telemetry/types'
15 : import { paymentIntentSourceForJourneyEntry } from '@/platform/telemetry/utils/paymentIntentSource'
16 :
17 : /**
18 : * One lifecycle owner for a checkout journey's frozen entry context and
19 : * durable resume metadata, shared by the subscription and top-up rails and
20 : * by both rollout arms. The journey identity and its server-assigned arm are
21 : * captured once at entry and preserved across reload; a later flag refresh
22 : * changes observed behaviour but never the frozen assignment. See
23 : * ADR-AUTH-BILLING-0014 for the rail-neutral attempt context this extends.
24 : */
25 :
26 2356 : const CHECKOUT_JOURNEY_MAX_AGE_MS = 24 * 60 * 60 * 1000
27 2356 : const CHECKOUT_JOURNEY_STORAGE_KEY = 'comfy.checkout.journey'
28 2356 : const EMBEDDED_CHECKOUT_FLAG_KEY = 'embedded_checked_enabled'
29 :
30 2356 : const ENTRY_FLOWS = {
31 : initial_subscription: true,
32 : paid_upgrade: true,
33 : topup: true,
34 : other: true,
35 : unknown: true
36 : } satisfies Record<CheckoutEntryFlow, true>
37 2356 : const ENTRY_SOURCES = {
38 : pricing: true,
39 : deep_link: true,
40 : recovery: true,
41 : settings_billing: true,
42 : other: true,
43 : unknown: true,
44 : agent_paywall: true
45 : } satisfies Record<CheckoutEntrySource, true>
46 :
47 0 : function isAllowlisted<T extends string>(
48 : allowlist: Record<T, true>,
49 : value: unknown
50 : ): value is T {
51 0 : return typeof value === 'string' && Object.hasOwn(allowlist, value)
52 : }
53 :
54 0 : function toEntryFlow(value: unknown): CheckoutEntryFlow {
55 0 : return isAllowlisted(ENTRY_FLOWS, value) ? value : 'unknown'
56 : }
57 :
58 0 : function toEntrySource(value: unknown): CheckoutEntrySource {
59 0 : return isAllowlisted(ENTRY_SOURCES, value) ? value : 'unknown'
60 : }
61 :
62 2356 : const PAYMENT_INTENT_ENTRY_SOURCES: Partial<
63 : Record<PaymentIntentSource, CheckoutEntrySource>
64 : > = {
65 : agent_paywall: 'agent_paywall'
66 : }
67 :
68 4 : function isMappedPaymentIntentSource(
69 : value: string
70 : ): value is keyof typeof PAYMENT_INTENT_ENTRY_SOURCES {
71 4 : return Object.hasOwn(PAYMENT_INTENT_ENTRY_SOURCES, value)
72 : }
73 :
74 : /**
75 : * Entry source for a journey opened with `paymentIntentSource`.
76 : *
77 : * Takes a `string` rather than a `PaymentIntentSource` because this function
78 : * owns the runtime hardening: its callers read the value from a Vue prop and a
79 : * composable argument, neither of which TypeScript enforces at runtime. Own-key
80 : * narrowing is what makes that safe — a bare lookup would resolve an inherited
81 : * `Object.prototype` member (`'constructor'`, `'toString'`) truthy, so
82 : * `?? fallback` would not fire and a non-`CheckoutEntrySource` value would
83 : * reach the record, storage and every downstream phase.
84 : */
85 4 : export function resolveEntrySource(
86 : paymentIntentSource: string | undefined,
87 : fallback: CheckoutEntrySource
88 : ): CheckoutEntrySource {
89 4 : if (paymentIntentSource === undefined) return fallback
90 4 : if (!isMappedPaymentIntentSource(paymentIntentSource)) return fallback
91 4 : return PAYMENT_INTENT_ENTRY_SOURCES[paymentIntentSource] ?? fallback
92 : }
93 :
94 : export interface CheckoutJourneyRecord {
95 : journey_id: string
96 : entered_at: string
97 : started_at_ms: number
98 : actor_uid: string
99 : workspace_id: string
100 : entry_flow: CheckoutEntryFlow
101 : entry_source: CheckoutEntrySource
102 : /**
103 : * The source the customer entered from, as the one source list names it.
104 : * Absent on a record written before it was kept, or opened with no source.
105 : */
106 : payment_intent_source?: PaymentIntentSource
107 : /**
108 : * Stable key for the intended purchase within the flow (e.g. tier:cycle).
109 : * A change of intent starts a new journey rather than resuming.
110 : */
111 : intent?: string
112 : assignment_status: CheckoutAssignmentStatus
113 : assigned_arm?: CheckoutJourneyArm
114 : ui_mode?: CheckoutUiMode
115 : billing_op_id?: string
116 : }
117 :
118 : export type CheckoutAssignment =
119 : | { status: 'resolved'; arm: CheckoutJourneyArm }
120 : | { status: 'unavailable' }
121 :
122 : interface CheckoutJourneyIdentity {
123 : actorUid: string
124 : workspaceId: string
125 : }
126 :
127 : export interface StartCheckoutJourneyInput extends CheckoutJourneyIdentity {
128 : entryFlow: CheckoutEntryFlow
129 : entrySource: CheckoutEntrySource
130 : paymentIntentSource?: PaymentIntentSource
131 : assignment: CheckoutAssignment
132 : /** Stable key for the intended purchase (e.g. tier:cycle); a change starts a new journey. */
133 : intent?: string
134 : /** Checkout UI the user actually sees, so a frozen arm can be reconciled against real experience. */
135 : uiMode?: CheckoutUiMode
136 : }
137 :
138 : export type ResolveCheckoutJourneyResult =
139 : | {
140 : status: 'active'
141 : record: CheckoutJourneyRecord
142 : /** True when an in-flight journey was recovered rather than newly created. */
143 : resumed: boolean
144 : }
145 : /**
146 : * Another rail owns the single journey slot with an operation still in
147 : * flight. This rail gets no journey at all rather than a foreign one: its
148 : * phases would otherwise be emitted under the other rail's `entry_flow`.
149 : */
150 : | { status: 'blocked' }
151 :
152 : /**
153 : * Freeze the rollout arm from the server feature response used at entry. An
154 : * absent flag is `unavailable`, never a fabricated `control`, so an unknown
155 : * assignment cannot masquerade as a resolved control arm downstream.
156 : */
157 4 : export function resolveCheckoutAssignment(
158 : serverFeatures: Record<string, unknown>
159 : ): CheckoutAssignment {
160 4 : if (!Object.hasOwn(serverFeatures, EMBEDDED_CHECKOUT_FLAG_KEY)) {
161 4 : return { status: 'unavailable' }
162 : }
163 :
164 4 : return {
165 : status: 'resolved',
166 : arm:
167 : serverFeatures[EMBEDDED_CHECKOUT_FLAG_KEY] === true
168 : ? 'treatment'
169 : : 'control'
170 : }
171 : }
172 :
173 4 : export function createCheckoutJourneyRecord(
174 : input: StartCheckoutJourneyInput,
175 : now: number
176 : ): CheckoutJourneyRecord {
177 4 : return {
178 : journey_id: createJourneyId(),
179 : entered_at: new Date(now).toISOString(),
180 : started_at_ms: now,
181 : actor_uid: input.actorUid,
182 : workspace_id: input.workspaceId,
183 : entry_flow: input.entryFlow,
184 : entry_source: input.entrySource,
185 : ...(input.paymentIntentSource !== undefined && {
186 : payment_intent_source: input.paymentIntentSource
187 : }),
188 : ...(input.intent !== undefined && { intent: input.intent }),
189 : assignment_status: input.assignment.status,
190 : ...(input.assignment.status === 'resolved' && {
191 : assigned_arm: input.assignment.arm
192 : }),
193 : ...(input.uiMode !== undefined && { ui_mode: input.uiMode })
194 : }
195 : }
196 :
197 0 : export function toCheckoutJourneyContext(
198 : record: CheckoutJourneyRecord
199 : ): CheckoutJourneyContext {
200 0 : const base = {
201 : checkout_journey_id: record.journey_id,
202 : checkout_entered_at: record.entered_at,
203 : entry_flow: record.entry_flow,
204 : entry_source: record.entry_source,
205 : ...(record.ui_mode !== undefined && { ui_mode: record.ui_mode }),
206 : ...(record.billing_op_id !== undefined && {
207 : billing_op_id: record.billing_op_id
208 : })
209 : }
210 :
211 0 : return record.assignment_status === 'resolved' &&
212 : record.assigned_arm !== undefined
213 : ? {
214 : ...base,
215 : assignment_status: 'resolved',
216 : assigned_arm: record.assigned_arm
217 : }
218 : : { ...base, assignment_status: 'unavailable' }
219 : }
220 :
221 0 : function isCheckoutJourneyExpired(
222 : record: CheckoutJourneyRecord,
223 : now: number
224 : ): boolean {
225 0 : return now - record.started_at_ms > CHECKOUT_JOURNEY_MAX_AGE_MS
226 : }
227 :
228 0 : function journeyMatchesIdentity(
229 : record: CheckoutJourneyRecord,
230 : identity: CheckoutJourneyIdentity
231 : ): boolean {
232 0 : return (
233 : record.actor_uid === identity.actorUid &&
234 : record.workspace_id === identity.workspaceId
235 : )
236 : }
237 :
238 : /**
239 : * Recover an in-flight journey for the same actor, workspace, and purchase
240 : * intent, or begin a new one. A changed actor/workspace or a different entry
241 : * flow never inherits the previous context: the stale record is discarded and
242 : * a fresh journey created.
243 : */
244 4 : export function resolveCheckoutJourney(
245 : input: StartCheckoutJourneyInput
246 : ): ResolveCheckoutJourneyResult {
247 4 : const now = Date.now()
248 4 : const existing = loadCheckoutJourney()
249 :
250 4 : const live = existing && !isCheckoutJourneyExpired(existing, now)
251 :
252 4 : if (
253 : live &&
254 : journeyMatchesIdentity(existing, input) &&
255 : existing.entry_flow === input.entryFlow &&
256 : existing.intent === input.intent
257 : ) {
258 0 : return { status: 'active', record: existing, resumed: true }
259 : }
260 :
261 4 : if (live && existing.billing_op_id !== undefined) {
262 0 : return { status: 'blocked' }
263 : }
264 :
265 4 : const record = createCheckoutJourneyRecord(input, now)
266 4 : saveCheckoutJourney(record)
267 4 : return { status: 'active', record, resumed: false }
268 : }
269 :
270 0 : export function getActiveCheckoutJourney(): CheckoutJourneyRecord | null {
271 0 : return loadCheckoutJourney()
272 : }
273 :
274 : /**
275 : * The source of the journey bound to `billingOpId`, for an operation event
276 : * emitted by a tab that did not start it (a poll recovered after reload).
277 : */
278 0 : export function getCheckoutJourneyPaymentIntentSource(
279 : billingOpId: string
280 : ): PaymentIntentSource | undefined {
281 0 : const journey = loadCheckoutJourney()
282 0 : if (journey?.billing_op_id !== billingOpId) return undefined
283 0 : return (
284 : journey.payment_intent_source ??
285 : paymentIntentSourceForJourneyEntry(journey.entry_source)
286 : )
287 : }
288 :
289 0 : export function bindOperationToCheckoutJourney(
290 : billingOpId: string
291 : ): CheckoutJourneyRecord | null {
292 0 : const existing = loadCheckoutJourney()
293 0 : if (!existing) {
294 0 : return null
295 : }
296 :
297 : // A journey binds to exactly one operation. If it is already bound (e.g. a
298 : // concurrent rail's operation is in flight), refuse to rebind so the first
299 : // operation keeps ownership of the terminal clear.
300 0 : if (existing.billing_op_id !== undefined) {
301 0 : return existing.billing_op_id === billingOpId ? existing : null
302 : }
303 :
304 0 : const updated: CheckoutJourneyRecord = {
305 : ...existing,
306 : billing_op_id: billingOpId
307 : }
308 0 : saveCheckoutJourney(updated)
309 0 : return updated
310 : }
311 :
312 0 : export function clearCheckoutJourney(): void {
313 0 : inMemoryJourney = null
314 0 : const storage = getStorage()
315 0 : if (!storage) {
316 0 : return
317 : }
318 :
319 0 : try {
320 0 : storage.removeItem(CHECKOUT_JOURNEY_STORAGE_KEY)
321 0 : persistedJourneyIsStale = false
322 : } catch {
323 0 : persistedJourneyIsStale = true
324 : }
325 : }
326 :
327 2356 : let fallbackJourneyIdCounter = 0
328 :
329 44 : export function createJourneyId(): string {
330 44 : if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
331 44 : return crypto.randomUUID()
332 : }
333 :
334 : // Monotonic suffix so journeys created within the same millisecond stay
335 : // distinct when randomUUID is unavailable.
336 0 : fallbackJourneyIdCounter += 1
337 0 : return `journey-${Date.now()}-${fallbackJourneyIdCounter}`
338 : }
339 :
340 : /**
341 : * Session-scoped mirror so the journey stays consistent even when
342 : * `sessionStorage` is unavailable (private mode, quota, disabled). Reload
343 : * resilience still requires storage, but within a session the active journey
344 : * never silently vanishes and `entered` is not re-emitted.
345 : */
346 2356 : let inMemoryJourney: CheckoutJourneyRecord | null = null
347 :
348 : /**
349 : * Set when a write to persistent storage failed, leaving a record there that no
350 : * longer reflects this session. Rehydrating it would resurrect a journey the
351 : * session already cleared, so persisted reads are suppressed until a write
352 : * succeeds.
353 : */
354 2356 : let persistedJourneyIsStale = false
355 :
356 : type CheckoutStorage = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
357 :
358 8 : function getStorage(): CheckoutStorage | null {
359 8 : let storage: unknown
360 :
361 8 : try {
362 8 : storage = globalThis.sessionStorage
363 : } catch {
364 0 : return null
365 : }
366 :
367 8 : return isCheckoutStorage(storage) ? storage : null
368 : }
369 :
370 8 : function isCheckoutStorage(value: unknown): value is CheckoutStorage {
371 8 : return (
372 : !!value &&
373 : typeof value === 'object' &&
374 : 'getItem' in value &&
375 : typeof value.getItem === 'function' &&
376 : 'setItem' in value &&
377 : typeof value.setItem === 'function' &&
378 : 'removeItem' in value &&
379 : typeof value.removeItem === 'function'
380 : )
381 : }
382 :
383 4 : function saveCheckoutJourney(record: CheckoutJourneyRecord): void {
384 4 : inMemoryJourney = record
385 4 : const storage = getStorage()
386 4 : if (!storage) {
387 0 : return
388 : }
389 :
390 4 : try {
391 4 : storage.setItem(CHECKOUT_JOURNEY_STORAGE_KEY, JSON.stringify(record))
392 4 : persistedJourneyIsStale = false
393 : } catch {
394 0 : persistedJourneyIsStale = true
395 : }
396 : }
397 :
398 4 : function loadCheckoutJourney(): CheckoutJourneyRecord | null {
399 : // The mirror is the source of truth within a session: it holds the latest
400 : // write even when persistence failed, so a stale persisted record can never
401 : // shadow it. Persisted storage is only consulted to rehydrate after reload.
402 4 : const record = inMemoryJourney ?? readPersistedJourney()
403 4 : if (!record) {
404 4 : return null
405 : }
406 :
407 0 : if (isCheckoutJourneyExpired(record, Date.now())) {
408 0 : clearCheckoutJourney()
409 0 : return null
410 : }
411 :
412 0 : inMemoryJourney = record
413 0 : return record
414 : }
415 :
416 4 : function readPersistedJourney(): CheckoutJourneyRecord | null {
417 4 : if (persistedJourneyIsStale) {
418 0 : return null
419 : }
420 :
421 4 : const storage = getStorage()
422 4 : if (!storage) {
423 0 : return null
424 : }
425 :
426 4 : let raw: string | null
427 4 : try {
428 4 : raw = storage.getItem(CHECKOUT_JOURNEY_STORAGE_KEY)
429 : } catch {
430 0 : return null
431 : }
432 :
433 4 : if (!raw) {
434 4 : return null
435 : }
436 :
437 0 : try {
438 0 : const record = normalizeRecord(JSON.parse(raw))
439 0 : if (!record) {
440 0 : clearCheckoutJourney()
441 0 : return null
442 : }
443 0 : return record
444 : } catch {
445 0 : clearCheckoutJourney()
446 0 : return null
447 : }
448 : }
449 :
450 2356 : const UI_MODES = {
451 : embedded: true,
452 : full_page: true,
453 : hosted: true,
454 : unknown: true
455 : } satisfies Record<CheckoutUiMode, true>
456 :
457 : type PersistedJourneyIdentity = Pick<
458 : CheckoutJourneyRecord,
459 : 'journey_id' | 'entered_at' | 'started_at_ms' | 'actor_uid' | 'workspace_id'
460 : >
461 :
462 0 : function readIdentity(
463 : candidate: Record<string, unknown>
464 : ): PersistedJourneyIdentity | null {
465 0 : const { journey_id, entered_at, started_at_ms, actor_uid, workspace_id } =
466 : candidate
467 : // A non-finite started_at_ms would make every expiry comparison false, so an
468 : // immortal journey could be persisted by hand; an unparseable entered_at
469 : // would reach telemetry as the journey's declared UTC entry time; a
470 : // journey_id the billing contract refuses would stop the hosted handoff.
471 0 : return typeof journey_id === 'string' &&
472 : isContractIdentifier(journey_id) &&
473 : typeof entered_at === 'string' &&
474 : !Number.isNaN(Date.parse(entered_at)) &&
475 : typeof started_at_ms === 'number' &&
476 : Number.isFinite(started_at_ms) &&
477 : typeof actor_uid === 'string' &&
478 : typeof workspace_id === 'string'
479 : ? { journey_id, entered_at, started_at_ms, actor_uid, workspace_id }
480 : : null
481 : }
482 :
483 : type PersistedAssignment = Pick<
484 : CheckoutJourneyRecord,
485 : 'assignment_status' | 'assigned_arm'
486 : >
487 :
488 : /**
489 : * Enforce the assignment invariant on persisted records: resolved must carry an
490 : * arm, unavailable must not. A contradictory record is rejected rather than
491 : * replayed as a fabricated assignment.
492 : */
493 0 : function readAssignment(
494 : candidate: Record<string, unknown>
495 : ): PersistedAssignment | null {
496 0 : const status = candidate.assignment_status
497 0 : const arm = candidate.assigned_arm
498 :
499 0 : if (status === 'unavailable') {
500 0 : return arm === undefined ? { assignment_status: 'unavailable' } : null
501 : }
502 0 : if (status !== 'resolved') {
503 0 : return null
504 : }
505 0 : return arm === 'control' || arm === 'treatment'
506 : ? { assignment_status: 'resolved', assigned_arm: arm }
507 : : null
508 : }
509 :
510 0 : function readOptionalFields(candidate: Record<string, unknown>) {
511 0 : const { intent, ui_mode, billing_op_id, payment_intent_source } = candidate
512 0 : return {
513 : ...(typeof payment_intent_source === 'string' &&
514 : isBillingSource(payment_intent_source) && { payment_intent_source }),
515 : ...(typeof intent === 'string' && { intent }),
516 : ...(isAllowlisted(UI_MODES, ui_mode) && { ui_mode }),
517 : ...(typeof billing_op_id === 'string' && { billing_op_id })
518 : }
519 : }
520 :
521 0 : function normalizeRecord(value: unknown): CheckoutJourneyRecord | null {
522 0 : if (!value || typeof value !== 'object') {
523 0 : return null
524 : }
525 :
526 0 : const candidate = value as Record<string, unknown>
527 0 : const identity = readIdentity(candidate)
528 0 : const assignment = readAssignment(candidate)
529 0 : if (!identity || !assignment) {
530 0 : return null
531 : }
532 :
533 0 : return {
534 : ...identity,
535 : entry_flow: toEntryFlow(candidate.entry_flow),
536 : entry_source: toEntrySource(candidate.entry_source),
537 : ...assignment,
538 : ...readOptionalFields(candidate)
539 : }
540 : }
|