From 8c24dbcd915a1aaa0eb46f1bff1f84d78fe623f3 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 14 Sep 2026 12:40:12 -0400 Subject: [PATCH 1/2] feat(account): coded billing error bodies and an embedded challenge driver (FE-2227) --- .../src/core/billing/billingContracts.ts | 6 ++ .../src/core/billing/billingErrorBody.ts | 11 +++ .../src/core/billing/challengeDriver.test.ts | 90 +++++++++++++++++++ .../src/core/billing/challengeDriver.ts | 77 ++++++++++++++++ packages/account/src/core/billing/index.ts | 6 ++ .../src/core/billing/sharedRead.test.ts | 55 ++++++++++++ .../account/src/core/billing/sharedRead.ts | 5 +- 7 files changed, 249 insertions(+), 1 deletion(-) create mode 100644 packages/account/src/core/billing/billingErrorBody.ts create mode 100644 packages/account/src/core/billing/challengeDriver.test.ts create mode 100644 packages/account/src/core/billing/challengeDriver.ts create mode 100644 packages/account/src/core/billing/sharedRead.test.ts diff --git a/packages/account/src/core/billing/billingContracts.ts b/packages/account/src/core/billing/billingContracts.ts index dbaf55ecaa4..aaa31221315 100644 --- a/packages/account/src/core/billing/billingContracts.ts +++ b/packages/account/src/core/billing/billingContracts.ts @@ -35,6 +35,12 @@ export type BillingFailure = { readonly code: BillingErrorCode /** Set only when the failure came from an HTTP response. */ readonly httpStatus?: number + /** + * The coded `code` of a generated `ErrorResponse` body, when the server + * sent one. Its `message` is dropped on purpose: a command acts on codes + * it names, never on server text. + */ + readonly serverCode?: string } export type BillingResult = diff --git a/packages/account/src/core/billing/billingErrorBody.ts b/packages/account/src/core/billing/billingErrorBody.ts new file mode 100644 index 00000000000..63137713235 --- /dev/null +++ b/packages/account/src/core/billing/billingErrorBody.ts @@ -0,0 +1,11 @@ +import { zErrorResponse } from '@comfyorg/ingest-types/zod' + +/** + * The `code` of a generated `ErrorResponse` body, or nothing. The body's + * `message` is read by the schema and discarded here, so it cannot travel + * further into the SDK. + */ +export function readBillingErrorCode(body: unknown): string | undefined { + const parsed = zErrorResponse.safeParse(body) + return parsed.success ? parsed.data.code : undefined +} diff --git a/packages/account/src/core/billing/challengeDriver.test.ts b/packages/account/src/core/billing/challengeDriver.test.ts new file mode 100644 index 00000000000..c91771dad94 --- /dev/null +++ b/packages/account/src/core/billing/challengeDriver.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it, vi } from 'vitest' + +import { driveEmbeddedChallenge } from './challengeDriver.js' +import type { BillingOperationState } from './operationState.js' + +const SCOPE = { userId: 'uid-1', workspaceId: 'ws-1', role: 'owner' } as const + +function challenged( + overrides: Partial> = {} +): BillingOperationState { + return { + id: 'op-1', + kind: 'topup', + scope: SCOPE, + presentation: 'embedded', + observedAt: 0, + attemptStartedAt: 0, + phase: 'pending', + challenge: { clientSecret: 'pi_secret', status: 'required' }, + customerActionSeen: true, + ...overrides + } +} + +function fakeLifecycle(state: BillingOperationState | undefined) { + return { + get: vi.fn(() => state), + reportChallengeStarted: vi.fn(), + reportChallengeSettled: vi.fn() + } +} + +describe('driveEmbeddedChallenge', () => { + it('reports a moved intent as completed', async () => { + const lifecycle = fakeLifecycle(challenged()) + const handleNextAction = vi.fn(async () => ({ + paymentIntent: { status: 'processing' } + })) + + const outcome = await driveEmbeddedChallenge(lifecycle, 'op-1', { + handleNextAction + }) + + expect(outcome).toBe('completed') + expect(handleNextAction).toHaveBeenCalledWith('pi_secret') + expect(lifecycle.reportChallengeStarted).toHaveBeenCalledWith('op-1') + expect(lifecycle.reportChallengeSettled).toHaveBeenCalledWith( + 'op-1', + 'completed' + ) + }) + + it('reports an error, an unmoved intent, or a throw as failed', async () => { + for (const handleNextAction of [ + async () => ({ error: { code: 'card_declined' } }), + async () => ({ paymentIntent: { status: 'requires_action' } }), + async () => { + throw new Error('network') + } + ]) { + const lifecycle = fakeLifecycle(challenged()) + await expect( + driveEmbeddedChallenge(lifecycle, 'op-1', { handleNextAction }) + ).resolves.toBe('failed') + expect(lifecycle.reportChallengeSettled).toHaveBeenCalledWith( + 'op-1', + 'failed' + ) + } + }) + + it('does nothing without a required challenge on an embedded pending operation', async () => { + const handleNextAction = vi.fn(async () => ({})) + for (const state of [ + undefined, + challenged({ presentation: 'hosted' }), + challenged({ challenge: undefined }), + challenged({ + challenge: { clientSecret: 'pi_secret', status: 'in_progress' } + }) + ]) { + const lifecycle = fakeLifecycle(state) + await expect( + driveEmbeddedChallenge(lifecycle, 'op-1', { handleNextAction }) + ).resolves.toBe('not_required') + expect(lifecycle.reportChallengeStarted).not.toHaveBeenCalled() + } + expect(handleNextAction).not.toHaveBeenCalled() + }) +}) diff --git a/packages/account/src/core/billing/challengeDriver.ts b/packages/account/src/core/billing/challengeDriver.ts new file mode 100644 index 00000000000..60d10928013 --- /dev/null +++ b/packages/account/src/core/billing/challengeDriver.ts @@ -0,0 +1,77 @@ +/** + * Drives one embedded challenge through the host's payment-provider port and + * reports the verdict back to the lifecycle. The provider object stays on the + * host side: the core sees only `handleNextAction`, so no provider SDK is + * imported here and a test can hand in a plain function. + */ +import type { BillingOperationLifecycle } from './operationLifecycle.js' + +export interface EmbeddedChallengePort { + /** Stripe's `handleNextAction` shape: resolve the challenge for one client secret. */ + handleNextAction: (clientSecret: string) => Promise<{ + readonly error?: unknown + readonly paymentIntent?: { readonly status: string } + }> +} + +/** + * Statuses that mean the resumed challenge left the intent exactly where it + * started, so the attempt needs a fresh start rather than a poll. A denylist + * fails toward the server: an unlisted or future status reports optimistically + * as completed, and the next poll's own `authentication_state` corrects it. + */ +const UNMOVED_INTENT_STATUSES: ReadonlySet = new Set([ + 'requires_payment_method', + 'requires_action', + 'canceled' +]) + +export type EmbeddedChallengeOutcome = + | 'completed' + | 'failed' + /** No required challenge on an embedded, pending operation with that id. */ + | 'not_required' + +type ChallengeLifecycle = Pick< + BillingOperationLifecycle, + 'get' | 'reportChallengeStarted' | 'reportChallengeSettled' +> + +export async function driveEmbeddedChallenge( + lifecycle: ChallengeLifecycle, + operationId: string, + port: EmbeddedChallengePort +): Promise { + const state = lifecycle.get(operationId) + if ( + state?.phase !== 'pending' || + state.presentation !== 'embedded' || + state.challenge?.status !== 'required' + ) { + return 'not_required' + } + + lifecycle.reportChallengeStarted(operationId) + const outcome = await settle(port, state.challenge.clientSecret) + lifecycle.reportChallengeSettled(operationId, outcome) + return outcome +} + +async function settle( + port: EmbeddedChallengePort, + clientSecret: string +): Promise<'completed' | 'failed'> { + try { + const result = await port.handleNextAction(clientSecret) + if (result.error !== undefined) return 'failed' + if ( + result.paymentIntent !== undefined && + UNMOVED_INTENT_STATUSES.has(result.paymentIntent.status) + ) { + return 'failed' + } + return 'completed' + } catch { + return 'failed' + } +} diff --git a/packages/account/src/core/billing/index.ts b/packages/account/src/core/billing/index.ts index 10ac47277a5..30311069d39 100644 --- a/packages/account/src/core/billing/index.ts +++ b/packages/account/src/core/billing/index.ts @@ -109,3 +109,9 @@ export { operationRoute } from './operationLifecycle.js' export { BILLING_OPERATION_TELEMETRY_EVENT } from '../../telemetry.js' +export type { + EmbeddedChallengeOutcome, + EmbeddedChallengePort +} from './challengeDriver.js' +export { driveEmbeddedChallenge } from './challengeDriver.js' +export { readBillingErrorCode } from './billingErrorBody.js' diff --git a/packages/account/src/core/billing/sharedRead.test.ts b/packages/account/src/core/billing/sharedRead.test.ts new file mode 100644 index 00000000000..66766b3f689 --- /dev/null +++ b/packages/account/src/core/billing/sharedRead.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { z } from 'zod' + +import type { + BillingHttpResponse, + BillingResult, + BillingTransport +} from './billingContracts.js' +import { readValidatedBillingResponse } from './sharedRead.js' + +const REQUEST = { method: 'GET', route: '/billing/topup' } as const +const Body = z.object({ ok: z.literal(true) }) + +function answering(httpStatus: number, body: unknown): BillingTransport { + const answer: BillingResult = { + status: 'ok', + value: { httpStatus, body, header: () => null } + } + return async () => answer +} + +describe('readValidatedBillingResponse', () => { + it('carries the coded server error and never its message', async () => { + const result = await readValidatedBillingResponse( + answering(400, { + code: 'NO_PAYMENT_METHOD', + message: 'Stripe: no default payment method on customer cus_123' + }), + REQUEST, + (body) => Body.safeParse(body) + ) + + expect(result).toEqual({ + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 400, + serverCode: 'NO_PAYMENT_METHOD' + }) + expect(JSON.stringify(result)).not.toContain('Stripe') + }) + + it('omits the server code when the error body is not the generated contract', async () => { + const result = await readValidatedBillingResponse( + answering(404, { error: 'not found' }), + REQUEST, + (body) => Body.safeParse(body) + ) + + expect(result).toEqual({ + status: 'error', + code: 'NOT_FOUND', + httpStatus: 404 + }) + }) +}) diff --git a/packages/account/src/core/billing/sharedRead.ts b/packages/account/src/core/billing/sharedRead.ts index 2093dd03509..f6a44748a35 100644 --- a/packages/account/src/core/billing/sharedRead.ts +++ b/packages/account/src/core/billing/sharedRead.ts @@ -20,6 +20,7 @@ import type { } from './billingContracts.js' import type { BillingScopeContext } from './billingScope.js' import { sameBillingScope } from './billingScope.js' +import { readBillingErrorCode } from './billingErrorBody.js' import { codeForHttpStatus } from './httpStatus.js' /** @@ -62,10 +63,12 @@ export async function readValidatedBillingResponse( const { httpStatus, body } = response.value if (httpStatus < 200 || httpStatus >= 300) { + const serverCode = readBillingErrorCode(body) return { status: 'error', code: codeForHttpStatus(httpStatus), - httpStatus + httpStatus, + ...(serverCode === undefined ? {} : { serverCode }) } } From 55c4192a0f50fc8b43a7197c536688389f6f64ee Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 15 Sep 2026 07:46:42 -0400 Subject: [PATCH 2/2] docs(account): name serverCode as the one server value that crosses the billing boundary (FE-2227) --- packages/account/src/core/billing/billingContracts.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/account/src/core/billing/billingContracts.ts b/packages/account/src/core/billing/billingContracts.ts index aaa31221315..8f08cbc6a30 100644 --- a/packages/account/src/core/billing/billingContracts.ts +++ b/packages/account/src/core/billing/billingContracts.ts @@ -6,7 +6,10 @@ * Billing reports failures as coded results rather than thrown errors, so a * caller cannot accidentally surface a server or payment-provider string to a * user. The codes carry no server text; the copy that belongs to each code is - * owned by the billing core and localized by the host. + * owned by the billing core and localized by the host. The one server value + * that crosses this boundary is `serverCode`, a machine identifier and never + * copy: a command matches it against its own closed set, and a host stores it + * where it already keeps `WorkspaceApiError.code`. */ /** @@ -38,7 +41,8 @@ export type BillingFailure = { /** * The coded `code` of a generated `ErrorResponse` body, when the server * sent one. Its `message` is dropped on purpose: a command acts on codes - * it names, never on server text. + * it names, never on server text. Never render it; the contract does not + * bound its shape, so it is a value to match, not to show. */ readonly serverCode?: string }