Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/account/src/core/billing/billingContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
*/

/**
Expand Down Expand Up @@ -35,6 +38,13 @@ 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. Never render it; the contract does not
* bound its shape, so it is a value to match, not to show.
*/
readonly serverCode?: string
}

export type BillingResult<T> =
Expand Down
11 changes: 11 additions & 0 deletions packages/account/src/core/billing/billingErrorBody.ts
Original file line number Diff line number Diff line change
@@ -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
}
90 changes: 90 additions & 0 deletions packages/account/src/core/billing/challengeDriver.test.ts
Original file line number Diff line number Diff line change
@@ -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<Extract<BillingOperationState, { phase: 'pending' }>> = {}
): 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()
})
})
77 changes: 77 additions & 0 deletions packages/account/src/core/billing/challengeDriver.ts
Original file line number Diff line number Diff line change
@@ -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<string> = 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<EmbeddedChallengeOutcome> {
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'
}
}
6 changes: 6 additions & 0 deletions packages/account/src/core/billing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
55 changes: 55 additions & 0 deletions packages/account/src/core/billing/sharedRead.test.ts
Original file line number Diff line number Diff line change
@@ -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<BillingHttpResponse> = {
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
})
})
})
5 changes: 4 additions & 1 deletion packages/account/src/core/billing/sharedRead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

/**
Expand Down Expand Up @@ -62,10 +63,12 @@ export async function readValidatedBillingResponse<T>(

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 })
}
}

Expand Down
Loading