From 8a6386cc34ee4f59cbd57d61c3962ab9bbcb93cd Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 15 Sep 2026 21:06:17 -0400 Subject: [PATCH 1/3] feat(billing-contract): route builder, entry parser and return_to registry --- .../workflows/ci-oss-assets-validation.yaml | 2 +- .github/workflows/ci-tests-unit.yaml | 4 +- eslint.config.ts | 1 + knip.config.ts | 3 + package.json | 7 +- packages/billing-contract/package.json | 23 +++ .../billing-contract/src/billingEntry.test.ts | 167 ++++++++++++++++++ packages/billing-contract/src/contract.ts | 73 ++++++++ packages/billing-contract/src/entryFields.ts | 36 ++++ packages/billing-contract/src/entryParser.ts | 111 ++++++++++++ packages/billing-contract/src/entryUrl.ts | 83 +++++++++ packages/billing-contract/src/identifiers.ts | 12 ++ packages/billing-contract/src/index.ts | 33 ++++ .../src/returnTargets.test.ts | 48 +++++ .../billing-contract/src/returnTargets.ts | 72 ++++++++ .../billing-contract/src/returnUrl.test.ts | 73 ++++++++ packages/billing-contract/src/returnUrl.ts | 66 +++++++ packages/billing-contract/src/url.ts | 20 +++ packages/billing-contract/tsconfig.json | 9 + packages/billing-contract/vitest.config.ts | 18 ++ pnpm-lock.yaml | 15 ++ 21 files changed, 870 insertions(+), 6 deletions(-) create mode 100644 packages/billing-contract/package.json create mode 100644 packages/billing-contract/src/billingEntry.test.ts create mode 100644 packages/billing-contract/src/contract.ts create mode 100644 packages/billing-contract/src/entryFields.ts create mode 100644 packages/billing-contract/src/entryParser.ts create mode 100644 packages/billing-contract/src/entryUrl.ts create mode 100644 packages/billing-contract/src/identifiers.ts create mode 100644 packages/billing-contract/src/index.ts create mode 100644 packages/billing-contract/src/returnTargets.test.ts create mode 100644 packages/billing-contract/src/returnTargets.ts create mode 100644 packages/billing-contract/src/returnUrl.test.ts create mode 100644 packages/billing-contract/src/returnUrl.ts create mode 100644 packages/billing-contract/src/url.ts create mode 100644 packages/billing-contract/tsconfig.json create mode 100644 packages/billing-contract/vitest.config.ts diff --git a/.github/workflows/ci-oss-assets-validation.yaml b/.github/workflows/ci-oss-assets-validation.yaml index b698526eb99..fcc0f566112 100644 --- a/.github/workflows/ci-oss-assets-validation.yaml +++ b/.github/workflows/ci-oss-assets-validation.yaml @@ -117,7 +117,7 @@ jobs: if pnpx license-checker-rseidelsohn@4 \ --production \ --summary \ - --excludePackages '@comfyorg/comfyui-frontend;@comfyorg/account;@comfyorg/account-ui;@comfyorg/design-system;@comfyorg/ingest-types;@comfyorg/registry-types;@comfyorg/shared-frontend-utils;@comfyorg/tailwind-utils;@comfyorg/comfyui-electron-types;@comfyorg/comfy-multi-player' \ + --excludePackages '@comfyorg/comfyui-frontend;@comfyorg/account;@comfyorg/account-ui;@comfyorg/billing-contract;@comfyorg/design-system;@comfyorg/ingest-types;@comfyorg/registry-types;@comfyorg/shared-frontend-utils;@comfyorg/tailwind-utils;@comfyorg/comfyui-electron-types;@comfyorg/comfy-multi-player' \ --clarificationsFile .github/license-clarifications.json \ --onlyAllow 'MIT;MIT*;Apache-2.0;BSD-2-Clause;BSD-3-Clause;ISC;0BSD;BlueOak-1.0.0;Python-2.0;CC0-1.0;Unlicense;(MIT OR Apache-2.0);(MIT OR GPL-3.0);(Apache-2.0 OR MIT);(MPL-2.0 OR Apache-2.0);MPL-2.0;CC-BY-4.0;CC-BY-3.0;GPL-3.0-only'; then echo '' diff --git a/.github/workflows/ci-tests-unit.yaml b/.github/workflows/ci-tests-unit.yaml index 71f3f1e4d66..dd5a11514c9 100644 --- a/.github/workflows/ci-tests-unit.yaml +++ b/.github/workflows/ci-tests-unit.yaml @@ -42,7 +42,7 @@ jobs: - name: Run package unit tests with coverage run: | rc=0 - for pkg in account account-ui object-info-parser shared-frontend-utils design-system; do + for pkg in account account-ui billing-contract object-info-parser shared-frontend-utils design-system; do pnpm --filter "@comfyorg/$pkg" exec vitest run --coverage || rc=1 done exit $rc @@ -60,7 +60,7 @@ jobs: if: always() uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: - files: coverage/lcov.info,packages/account/coverage/lcov.info,packages/account-ui/coverage/lcov.info,packages/object-info-parser/coverage/lcov.info,packages/shared-frontend-utils/coverage/lcov.info,packages/design-system/coverage/lcov.info + files: coverage/lcov.info,packages/account/coverage/lcov.info,packages/account-ui/coverage/lcov.info,packages/billing-contract/coverage/lcov.info,packages/object-info-parser/coverage/lcov.info,packages/shared-frontend-utils/coverage/lcov.info,packages/design-system/coverage/lcov.info flags: unit token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: false diff --git a/eslint.config.ts b/eslint.config.ts index da88da15497..2d887dfeeb0 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -204,6 +204,7 @@ export default defineConfig([ allowDefaultProject: [ 'packages/account/vitest.config.ts', 'packages/account-ui/vitest.config.ts', + 'packages/billing-contract/vitest.config.ts', 'packages/design-system/vitest.config.ts', 'packages/object-info-parser/vitest.config.ts', 'packages/shared-frontend-utils/vitest.config.ts', diff --git a/knip.config.ts b/knip.config.ts index f1f8e13ea9a..723f13f8da2 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -30,6 +30,9 @@ const config: KnipConfig = { 'packages/account-ui': { project: ['src/**/*.{js,ts,vue}'] }, + 'packages/billing-contract': { + project: ['src/**/*.ts'] + }, 'packages/design-system': { project: ['src/**/*.{css,js,ts}'] }, diff --git a/package.json b/package.json index 6cd3ec9a089..4911398cfc7 100644 --- a/package.json +++ b/package.json @@ -42,10 +42,10 @@ "knip": "knip --cache", "lint:fix:no-cache": "pnpm oxlint:main --fix && pnpm oxlint:audit && eslint src --fix && pnpm lint:website:fix", "lint:fix": "pnpm oxlint:main --fix && pnpm oxlint:audit && eslint src --cache --fix && pnpm lint:website:fix", - "lint:no-cache": "pnpm exec stylelint '{apps,packages,src}/**/*.{css,vue}' && pnpm oxlint && eslint src && pnpm lint:website && pnpm --filter @comfyorg/account lint && pnpm --filter @comfyorg/billing-web lint && pnpm --filter @comfyorg/account-ui lint", + "lint:no-cache": "pnpm exec stylelint '{apps,packages,src}/**/*.{css,vue}' && pnpm oxlint && eslint src && pnpm lint:website && pnpm --filter @comfyorg/account lint && pnpm --filter @comfyorg/billing-web lint && pnpm --filter @comfyorg/account-ui lint && pnpm --filter @comfyorg/billing-contract lint", "lint:unstaged:fix": "git diff --name-only --diff-filter=d -z HEAD -- '*.astro' '*.js' '*.ts' '*.vue' '*.mts' | xargs -0 -r eslint --cache --fix", "lint:unstaged": "git diff --name-only --diff-filter=d -z HEAD -- '*.astro' '*.js' '*.ts' '*.vue' '*.mts' | xargs -0 -r eslint --cache", - "lint": "pnpm stylelint && pnpm oxlint && eslint src --cache && pnpm lint:website && pnpm --filter @comfyorg/account lint && pnpm --filter @comfyorg/billing-web lint && pnpm --filter @comfyorg/account-ui lint", + "lint": "pnpm stylelint && pnpm oxlint && eslint src --cache && pnpm lint:website && pnpm --filter @comfyorg/account lint && pnpm --filter @comfyorg/billing-web lint && pnpm --filter @comfyorg/account-ui lint && pnpm --filter @comfyorg/billing-contract lint", "lint:website": "eslint \"apps/website/**/*.{astro,js,mjs,ts,tsx,mts,vue}\"", "lint:website:fix": "pnpm lint:website --fix", "locale": "tsx scripts/i18n/update-locales.ts", @@ -74,9 +74,10 @@ "test:custom-nodes:self-check": "pnpm test:custom-nodes:watch -g \"self-check\"", "test:coverage": "vitest run --coverage", "test:unit": "vitest run", - "typecheck": "vue-tsc --noEmit && pnpm typecheck:account && pnpm typecheck:billing-web && pnpm typecheck:account-ui", + "typecheck": "vue-tsc --noEmit && pnpm typecheck:account && pnpm typecheck:billing-web && pnpm typecheck:account-ui && pnpm typecheck:billing-contract", "typecheck:account": "pnpm --filter @comfyorg/account typecheck", "typecheck:account-ui": "pnpm --filter @comfyorg/account-ui typecheck", + "typecheck:billing-contract": "pnpm --filter @comfyorg/billing-contract typecheck", "typecheck:browser": "vue-tsc --project browser_tests/tsconfig.json", "typecheck:build": "vue-tsc --project build/tsconfig.json", "typecheck:billing-web": "pnpm --filter @comfyorg/billing-web run typecheck", diff --git a/packages/billing-contract/package.json b/packages/billing-contract/package.json new file mode 100644 index 00000000000..2f129c41f8c --- /dev/null +++ b/packages/billing-contract/package.json @@ -0,0 +1,23 @@ +{ + "name": "@comfyorg/billing-contract", + "version": "1.0.0-alpha.0", + "private": true, + "description": "The URL contract every Comfy product shares with the hosted billing app: the versioned route builder, the entry parser billing-web reads on arrival, and the closed return_to registry that keeps the trip back off open redirects", + "keywords": [], + "license": "MIT", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "lint": "oxlint src --type-aware && eslint src", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@types/node": "catalog:", + "@vitest/coverage-v8": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/billing-contract/src/billingEntry.test.ts b/packages/billing-contract/src/billingEntry.test.ts new file mode 100644 index 00000000000..68f1363c700 --- /dev/null +++ b/packages/billing-contract/src/billingEntry.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it } from 'vitest' + +import { BILLING_INTENTS, BILLING_PRODUCTS } from './contract' +import { parseBillingEntry } from './entryParser' +import type { BillingEntryInput, BillingEntryUrlErrorCode } from './entryUrl' +import { buildBillingEntryUrl } from './entryUrl' + +const BASE_INPUT: BillingEntryInput = { + billingOrigin: 'https://billing.comfy.org', + intent: 'checkout', + product: 'platform', + returnTo: 'platform_account' +} + +function entryUrl(input: BillingEntryInput): URL { + const result = buildBillingEntryUrl(input) + if (result.status === 'error') + throw new Error(`expected an entry URL, got ${result.code}`) + return result.url +} + +function errorCode(input: BillingEntryInput): BillingEntryUrlErrorCode | 'ok' { + const result = buildBillingEntryUrl(input) + return result.status === 'error' ? result.code : 'ok' +} + +describe('buildBillingEntryUrl', () => { + it('routes an intent under the contract version', () => { + expect(entryUrl({ ...BASE_INPUT, intent: 'invoices' }).pathname).toBe( + '/v1/invoices' + ) + }) + + it('keeps only the origin of a billing URL that carries a path', () => { + expect( + entryUrl({ + ...BASE_INPUT, + billingOrigin: 'https://billing.comfy.org/app' + }).href + ).toBe( + 'https://billing.comfy.org/v1/checkout?product=platform&return_to=platform_account' + ) + }) + + it('omits an absent optional identifier rather than writing it empty', () => { + expect(entryUrl(BASE_INPUT).search).toBe( + '?product=platform&return_to=platform_account' + ) + }) + + it.for([ + ['https://billing.comfy.org', 'ok'], + ['http://localhost:5174', 'ok'], + ['http://127.0.0.1:5174', 'ok'], + ['http://billing.comfy.org', 'INVALID_ORIGIN'], + ['https://user:secret@billing.comfy.org', 'INVALID_ORIGIN'], + ['ftp://billing.comfy.org', 'INVALID_ORIGIN'], + ['not a url', 'INVALID_ORIGIN'] + ] as const)('reports %s as %s', ([billingOrigin, expected]) => { + expect(errorCode({ ...BASE_INPUT, billingOrigin })).toBe(expected) + }) + + it.for([ + [{ returnTo: 'attacker_site' }, 'UNKNOWN_RETURN_TARGET'], + [{ plan: 'pro plan' }, 'INVALID_PLAN'], + [{ correlationId: '../escape' }, 'INVALID_CORRELATION_ID'], + [{ workspaceId: '' }, 'INVALID_WORKSPACE_ID'] + ] as const)('refuses %o with %s', ([overrides, expected]) => { + expect(errorCode({ ...BASE_INPUT, ...overrides })).toBe(expected) + }) +}) + +describe('parseBillingEntry', () => { + it.for(BILLING_INTENTS)('round-trips the %s intent', (intent) => { + const url = entryUrl({ + ...BASE_INPUT, + intent, + plan: 'pro_monthly', + correlationId: 'corr-1', + workspaceId: 'ws_1' + }) + + expect(parseBillingEntry(url)).toEqual({ + status: 'ok', + entry: { + version: 'v1', + intent, + product: 'platform', + returnTo: 'platform_account', + plan: 'pro_monthly', + correlationId: 'corr-1', + workspaceId: 'ws_1' + } + }) + }) + + it.for(BILLING_PRODUCTS)('round-trips the %s product', (product) => { + const url = entryUrl({ ...BASE_INPUT, product }) + + expect(parseBillingEntry(url)).toEqual({ + status: 'ok', + entry: { + version: 'v1', + intent: 'checkout', + product, + returnTo: 'platform_account' + } + }) + }) + + it('ignores a query parameter the contract does not name', () => { + expect( + parseBillingEntry( + '/v1/pricing?product=workshop&return_to=comfyui_credits&utm_source=email' + ) + ).toEqual({ + status: 'ok', + entry: { + version: 'v1', + intent: 'pricing', + product: 'workshop', + returnTo: 'comfyui_credits' + } + }) + }) + + it.for([ + [ + '/v2/checkout?product=platform&return_to=platform_account', + 'UNSUPPORTED_VERSION' + ], + ['nonsense', 'UNSUPPORTED_VERSION'], + ['http://[', 'UNSUPPORTED_VERSION'], + [ + '/v1/refunds?product=platform&return_to=platform_account', + 'UNKNOWN_INTENT' + ], + [ + '/v1/checkout/extra?product=platform&return_to=platform_account', + 'UNKNOWN_INTENT' + ], + ['/v1/checkout?return_to=platform_account', 'UNKNOWN_PRODUCT'], + [ + '/v1/checkout?product=desktop&return_to=platform_account', + 'UNKNOWN_PRODUCT' + ], + ['/v1/checkout?product=platform', 'UNKNOWN_RETURN_TARGET'], + [ + '/v1/checkout?product=platform&return_to=https://attacker.example', + 'UNKNOWN_RETURN_TARGET' + ], + [ + '/v1/checkout?product=platform&return_to=platform_account&plan=pro%20plan', + 'INVALID_PLAN' + ], + [ + '/v1/checkout?product=platform&return_to=platform_account&correlation_id=a/b', + 'INVALID_CORRELATION_ID' + ], + [ + '/v1/checkout?product=platform&return_to=platform_account&workspace_id=', + 'INVALID_WORKSPACE_ID' + ] + ] as const)('refuses %s with %s', ([url, expected]) => { + expect(parseBillingEntry(url)).toEqual({ status: 'error', code: expected }) + }) +}) diff --git a/packages/billing-contract/src/contract.ts b/packages/billing-contract/src/contract.ts new file mode 100644 index 00000000000..11fb1b91830 --- /dev/null +++ b/packages/billing-contract/src/contract.ts @@ -0,0 +1,73 @@ +/** + * The versioned URL contract every Comfy product uses to hand a customer to + * the hosted billing app, and that the app reads back on arrival. + * + * The entry URL is routing input and nothing more. It never carries a token, + * a JWT, a payment-provider secret, an authoritative price, or a caller-chosen + * return URL: a product states which billing screen it wants, which product is + * asking, and which registered destination the customer should land on + * afterwards. Billing resolves everything else against its own environment and + * the signed-in session, so a workspace id here is a requested scope and never + * an authorization. + * + * Route and parameter names are provisional while the hosted app is behind a + * flag. `BILLING_CONTRACT_VERSION` is what lets them change without stranding + * a product that is already deployed against the older shape. + * + * Whether a payment renders embedded or hosted is not decided here — that is + * the SDK core's `hostedDestination` port. This package stays dependency-free + * and framework-free so a product, the billing app, and a future non-Vue host + * can share exactly one definition of the route surface. + */ +export const BILLING_CONTRACT_VERSION = 'v1' + +export const BILLING_INTENTS = [ + 'pricing', + 'checkout', + 'subscription', + 'payment-methods', + 'invoices', + 'result' +] as const + +export type BillingIntent = (typeof BILLING_INTENTS)[number] + +export function isBillingIntent( + value: string | null | undefined +): value is BillingIntent { + return BILLING_INTENTS.some((intent) => intent === value) +} + +/** The route an intent occupies, e.g. `/v1/checkout`. */ +export function billingIntentPath(intent: BillingIntent): string { + return `/${BILLING_CONTRACT_VERSION}/${intent}` +} + +/** The surfaces allowed to originate a billing trip. */ +export const BILLING_PRODUCTS = [ + 'comfyui', + 'platform', + 'workshop', + 'models' +] as const + +export type BillingProduct = (typeof BILLING_PRODUCTS)[number] + +export function isBillingProduct( + value: string | null | undefined +): value is BillingProduct { + return BILLING_PRODUCTS.some((product) => product === value) +} + +/** + * Which deployment family a return destination belongs to. The backends run + * three of them, not two, and pair each origin with exactly one family, so a + * product resolves its return target in the same family its session was + * minted against. + * + * A host picks its family by origin, never by the label on its own build: the + * cloud app's "staging" distribution points at `testcloud.comfy.org` + * (`STAGING_CLOUD_BASE_URL` in `src/config/comfyApi.ts`) and therefore maps to + * `test` here, while `staging` means `stagingcloud.comfy.org`. + */ +export type BillingEnvironment = 'production' | 'staging' | 'test' diff --git a/packages/billing-contract/src/entryFields.ts b/packages/billing-contract/src/entryFields.ts new file mode 100644 index 00000000000..7ea6b2c5353 --- /dev/null +++ b/packages/billing-contract/src/entryFields.ts @@ -0,0 +1,36 @@ +/** + * The query shape of an entry URL, in one table so the builder and the parser + * cannot drift apart: a field is written and read under the same name, and a + * value that fails the shared charset reports the same code on both sides. + */ + +/** Names are provisional; see `contract.ts`. */ +export const ENTRY_PARAM_PRODUCT = 'product' +export const ENTRY_PARAM_RETURN_TO = 'return_to' + +export type OptionalEntryKey = 'plan' | 'correlationId' | 'workspaceId' + +export type InvalidIdentifierCode = + | 'INVALID_PLAN' + | 'INVALID_CORRELATION_ID' + | 'INVALID_WORKSPACE_ID' + +interface OptionalEntryField { + readonly key: OptionalEntryKey + readonly param: string + readonly code: InvalidIdentifierCode +} + +export const OPTIONAL_ENTRY_FIELDS: readonly OptionalEntryField[] = [ + { key: 'plan', param: 'plan', code: 'INVALID_PLAN' }, + { + key: 'correlationId', + param: 'correlation_id', + code: 'INVALID_CORRELATION_ID' + }, + { key: 'workspaceId', param: 'workspace_id', code: 'INVALID_WORKSPACE_ID' } +] + +export type OptionalEntryValues = { + readonly [K in OptionalEntryKey]?: string +} diff --git a/packages/billing-contract/src/entryParser.ts b/packages/billing-contract/src/entryParser.ts new file mode 100644 index 00000000000..eff356ccaa2 --- /dev/null +++ b/packages/billing-contract/src/entryParser.ts @@ -0,0 +1,111 @@ +/** + * The billing-web side of the contract: read an arriving URL back into the + * request a product meant to make. Unknown query parameters are ignored, so a + * product may add analytics noise without breaking the app; everything the + * contract names is validated, because this is untrusted input. + */ +import type { BillingIntent, BillingProduct } from './contract' +import { + BILLING_CONTRACT_VERSION, + isBillingIntent, + isBillingProduct +} from './contract' +import type { + InvalidIdentifierCode, + OptionalEntryKey, + OptionalEntryValues +} from './entryFields' +import { + ENTRY_PARAM_PRODUCT, + ENTRY_PARAM_RETURN_TO, + OPTIONAL_ENTRY_FIELDS +} from './entryFields' +import { isContractIdentifier } from './identifiers' +import type { ReturnTarget } from './returnTargets' +import { isReturnTarget } from './returnTargets' +import { CONTRACT_PARSE_BASE, parseUrl } from './url' + +export interface BillingEntry extends OptionalEntryValues { + readonly version: typeof BILLING_CONTRACT_VERSION + readonly intent: BillingIntent + readonly product: BillingProduct + readonly returnTo: ReturnTarget +} + +export type BillingEntryErrorCode = + | 'UNSUPPORTED_VERSION' + | 'UNKNOWN_INTENT' + | 'UNKNOWN_PRODUCT' + | 'UNKNOWN_RETURN_TARGET' + | InvalidIdentifierCode + +export type BillingEntryResult = + | { readonly status: 'ok'; readonly entry: BillingEntry } + | { readonly status: 'error'; readonly code: BillingEntryErrorCode } + +type RouteResult = + | { readonly status: 'ok'; readonly intent: BillingIntent } + | { + readonly status: 'error' + readonly code: 'UNSUPPORTED_VERSION' | 'UNKNOWN_INTENT' + } + +function parseRoute(pathname: string): RouteResult { + const [version, intent, ...rest] = pathname.split('/').filter(Boolean) + if (version !== BILLING_CONTRACT_VERSION) + return { status: 'error', code: 'UNSUPPORTED_VERSION' } + if (rest.length > 0 || !isBillingIntent(intent)) + return { status: 'error', code: 'UNKNOWN_INTENT' } + return { status: 'ok', intent } +} + +type OptionalFieldsResult = + | { readonly status: 'ok'; readonly values: OptionalEntryValues } + | { readonly status: 'error'; readonly code: InvalidIdentifierCode } + +function parseOptionalFields(params: URLSearchParams): OptionalFieldsResult { + const values: Partial> = {} + for (const field of OPTIONAL_ENTRY_FIELDS) { + const raw = params.get(field.param) + if (raw === null) continue + if (!isContractIdentifier(raw)) return { status: 'error', code: field.code } + values[field.key] = raw + } + return { status: 'ok', values } +} + +/** + * Accepts a full href or the path-and-query form a router hands over. Input + * that is not a `/v1` billing route at all — a malformed string included — + * reports `UNSUPPORTED_VERSION`, because from the app's side it is a URL the + * contract does not describe. + */ +export function parseBillingEntry(url: string | URL): BillingEntryResult { + const parsed = parseUrl(url, CONTRACT_PARSE_BASE) + if (!parsed) return { status: 'error', code: 'UNSUPPORTED_VERSION' } + + const route = parseRoute(parsed.pathname) + if (route.status === 'error') return route + + const product = parsed.searchParams.get(ENTRY_PARAM_PRODUCT) + if (!isBillingProduct(product)) + return { status: 'error', code: 'UNKNOWN_PRODUCT' } + + const returnTo = parsed.searchParams.get(ENTRY_PARAM_RETURN_TO) + if (returnTo === null || !isReturnTarget(returnTo)) + return { status: 'error', code: 'UNKNOWN_RETURN_TARGET' } + + const optional = parseOptionalFields(parsed.searchParams) + if (optional.status === 'error') return optional + + return { + status: 'ok', + entry: { + version: BILLING_CONTRACT_VERSION, + intent: route.intent, + product, + returnTo, + ...optional.values + } + } +} diff --git a/packages/billing-contract/src/entryUrl.ts b/packages/billing-contract/src/entryUrl.ts new file mode 100644 index 00000000000..b0a27587904 --- /dev/null +++ b/packages/billing-contract/src/entryUrl.ts @@ -0,0 +1,83 @@ +/** + * The product side of the contract: turn a billing request into the URL to + * navigate to. Failures are coded results in the style of the billing core's + * `BillingResult` — the builder never throws, and a code carries no server or + * caller text a host could render by accident. + */ +import type { BillingIntent, BillingProduct } from './contract' +import { billingIntentPath } from './contract' +import type { InvalidIdentifierCode, OptionalEntryValues } from './entryFields' +import { + ENTRY_PARAM_PRODUCT, + ENTRY_PARAM_RETURN_TO, + OPTIONAL_ENTRY_FIELDS +} from './entryFields' +import { isContractIdentifier } from './identifiers' +import { isReturnTarget } from './returnTargets' +import { parseUrl } from './url' + +export interface BillingEntryInput extends OptionalEntryValues { + /** Only the origin is used; any path or query on it is discarded. */ + readonly billingOrigin: string | URL + readonly intent: BillingIntent + readonly product: BillingProduct + /** + * A `ReturnTarget`. Typed wide because the registry lookup is the real gate: + * a JavaScript host, or a generic that widened the literal, still has to + * name a registered target. + */ + readonly returnTo: string +} + +export type BillingEntryUrlErrorCode = + | 'INVALID_ORIGIN' + | 'UNKNOWN_RETURN_TARGET' + | InvalidIdentifierCode + +export type BillingEntryUrlResult = + | { readonly status: 'ok'; readonly url: URL } + | { readonly status: 'error'; readonly code: BillingEntryUrlErrorCode } + +const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']) + +function billingOriginHref(origin: string | URL): string | undefined { + const url = parseUrl(origin) + if (!url || url.username || url.password) return undefined + if (url.protocol === 'https:') return url.origin + if (url.protocol === 'http:' && LOCAL_HOSTNAMES.has(url.hostname)) + return url.origin + return undefined +} + +function invalidIdentifierCode( + values: OptionalEntryValues +): InvalidIdentifierCode | undefined { + for (const field of OPTIONAL_ENTRY_FIELDS) { + const value = values[field.key] + if (value !== undefined && !isContractIdentifier(value)) return field.code + } + return undefined +} + +export function buildBillingEntryUrl( + input: BillingEntryInput +): BillingEntryUrlResult { + const origin = billingOriginHref(input.billingOrigin) + if (origin === undefined) return { status: 'error', code: 'INVALID_ORIGIN' } + + if (!isReturnTarget(input.returnTo)) + return { status: 'error', code: 'UNKNOWN_RETURN_TARGET' } + + const invalid = invalidIdentifierCode(input) + if (invalid !== undefined) return { status: 'error', code: invalid } + + const url = new URL(billingIntentPath(input.intent), origin) + url.searchParams.set(ENTRY_PARAM_PRODUCT, input.product) + url.searchParams.set(ENTRY_PARAM_RETURN_TO, input.returnTo) + for (const field of OPTIONAL_ENTRY_FIELDS) { + const value = input[field.key] + if (value !== undefined) url.searchParams.set(field.param, value) + } + + return { status: 'ok', url } +} diff --git a/packages/billing-contract/src/identifiers.ts b/packages/billing-contract/src/identifiers.ts new file mode 100644 index 00000000000..1c006e9161c --- /dev/null +++ b/packages/billing-contract/src/identifiers.ts @@ -0,0 +1,12 @@ +/** + * The charset every free-form identifier in the contract shares: plan slugs, + * correlation ids, workspace ids, and the reference billing hands back. It is + * deliberately narrower than what a URL permits, so nothing that survives it + * can carry a path separator, a query delimiter, or a percent escape into a + * downstream URL. + */ +const CONTRACT_IDENTIFIER = /^[A-Za-z0-9_-]{1,128}$/ + +export function isContractIdentifier(value: string): boolean { + return CONTRACT_IDENTIFIER.test(value) +} diff --git a/packages/billing-contract/src/index.ts b/packages/billing-contract/src/index.ts new file mode 100644 index 00000000000..71b58f7bd89 --- /dev/null +++ b/packages/billing-contract/src/index.ts @@ -0,0 +1,33 @@ +export type { + BillingEnvironment, + BillingIntent, + BillingProduct +} from './contract' +export { + BILLING_CONTRACT_VERSION, + BILLING_INTENTS, + BILLING_PRODUCTS, + billingIntentPath, + isBillingIntent, + isBillingProduct +} from './contract' +export type { + BillingEntry, + BillingEntryErrorCode, + BillingEntryResult +} from './entryParser' +export { parseBillingEntry } from './entryParser' +export type { + BillingEntryInput, + BillingEntryUrlErrorCode, + BillingEntryUrlResult +} from './entryUrl' +export { buildBillingEntryUrl } from './entryUrl' +export type { ReturnTarget } from './returnTargets' +export { + RETURN_TARGETS, + isReturnTarget, + resolveReturnTarget +} from './returnTargets' +export type { BillingOutcome, BillingReturn, ReturnUrlInput } from './returnUrl' +export { buildReturnUrl, parseReturnResult } from './returnUrl' diff --git a/packages/billing-contract/src/returnTargets.test.ts b/packages/billing-contract/src/returnTargets.test.ts new file mode 100644 index 00000000000..3073d0df39e --- /dev/null +++ b/packages/billing-contract/src/returnTargets.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' + +import { resolveReturnTarget } from './returnTargets' + +describe('resolveReturnTarget', () => { + it.for([ + ['comfyui_workspace', 'production', 'https://cloud.comfy.org/'], + ['comfyui_workspace', 'staging', 'https://stagingcloud.comfy.org/'], + ['comfyui_workspace', 'test', 'https://testcloud.comfy.org/'], + [ + 'comfyui_credits', + 'production', + 'https://cloud.comfy.org/?settings=plan-credits' + ], + [ + 'comfyui_credits', + 'staging', + 'https://stagingcloud.comfy.org/?settings=plan-credits' + ], + [ + 'comfyui_credits', + 'test', + 'https://testcloud.comfy.org/?settings=plan-credits' + ], + ['platform_account', 'production', 'https://platform.comfy.org/'], + ['platform_account', 'staging', 'https://stagingplatform.comfy.org/'] + ] as const)('resolves %s in %s', ([target, environment, expected]) => { + expect(resolveReturnTarget(target, environment)?.href).toBe(expected) + }) + + it.for([ + ['platform_account', 'test'], + ['workshop_credits', 'production'], + ['attacker_site', 'production'], + ['https://attacker.example', 'production'] + ] as const)('leaves %s in %s unresolved', ([target, environment]) => { + expect(resolveReturnTarget(target, environment)).toBeUndefined() + }) + + it('hands back a URL the caller may append to without editing the registry', () => { + const first = resolveReturnTarget('comfyui_workspace', 'production') + first?.searchParams.set('billing_result', 'success') + + expect(resolveReturnTarget('comfyui_workspace', 'production')?.href).toBe( + 'https://cloud.comfy.org/' + ) + }) +}) diff --git a/packages/billing-contract/src/returnTargets.ts b/packages/billing-contract/src/returnTargets.ts new file mode 100644 index 00000000000..c6ab3936d83 --- /dev/null +++ b/packages/billing-contract/src/returnTargets.ts @@ -0,0 +1,72 @@ +/** + * Where billing is allowed to send a customer back to. A closed registry, not + * a caller-supplied URL: `return_to=` names a target, and the + * absolute destination is chosen here per environment, so a crafted entry URL + * cannot turn the hosted app into an open redirect. + * + * Every destination below is one this repository already states. A family a + * target has no confirmed origin for stays absent rather than being derived + * from a sibling's hostname, because an unresolvable target fails closed while + * a guessed one sends a customer somewhere nobody serves. + * + * Localhost and desktop return targets are out of scope: a developer running a + * product locally returns to the deployed destination of whichever environment + * their backend belongs to. + */ +import type { BillingEnvironment } from './contract' +import { parseUrl } from './url' + +export const RETURN_TARGETS = [ + 'comfyui_workspace', + 'comfyui_credits', + 'platform_account' +] as const + +export type ReturnTarget = (typeof RETURN_TARGETS)[number] + +type ReturnTargetDestinations = Readonly< + Partial> +> + +const RETURN_TARGET_DESTINATIONS: Readonly< + Record +> = { + comfyui_workspace: { + production: 'https://cloud.comfy.org/', + staging: 'https://stagingcloud.comfy.org/', + test: 'https://testcloud.comfy.org/' + }, + // The cloud app's credits settings page, the same URL the Workshop builds as + // `WORKSHOP_CREDITS_URL`. + comfyui_credits: { + production: 'https://cloud.comfy.org/?settings=plan-credits', + staging: 'https://stagingcloud.comfy.org/?settings=plan-credits', + test: 'https://testcloud.comfy.org/?settings=plan-credits' + }, + // Platform lives in its own repository and names no account route here, so + // its origin root is the destination until that app names one. + platform_account: { + production: 'https://platform.comfy.org/', + staging: 'https://stagingplatform.comfy.org/' + } +} + +export function isReturnTarget(value: string): value is ReturnTarget { + return RETURN_TARGETS.some((target) => target === value) +} + +/** + * Undefined for an identifier outside the registry, and for a registered + * target that has no destination in the requested environment. Each call + * returns a fresh `URL` so a caller can append to it without editing the + * registry. + */ +export function resolveReturnTarget( + target: string, + environment: BillingEnvironment +): URL | undefined { + if (!isReturnTarget(target)) return undefined + + const destination = RETURN_TARGET_DESTINATIONS[target][environment] + return destination === undefined ? undefined : parseUrl(destination) +} diff --git a/packages/billing-contract/src/returnUrl.test.ts b/packages/billing-contract/src/returnUrl.test.ts new file mode 100644 index 00000000000..852b81ae67e --- /dev/null +++ b/packages/billing-contract/src/returnUrl.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' + +import { buildReturnUrl, parseReturnResult } from './returnUrl' + +describe('buildReturnUrl', () => { + it.for(['success', 'cancelled', 'pending'] as const)( + 'round-trips the %s outcome with its reference', + (result) => { + const url = buildReturnUrl({ + target: 'comfyui_workspace', + environment: 'production', + result, + reference: 'op_42' + }) + + expect(parseReturnResult(url?.href ?? '')).toEqual({ + result, + reference: 'op_42' + }) + } + ) + + it('keeps the query the destination already carries', () => { + expect( + buildReturnUrl({ + target: 'comfyui_credits', + environment: 'staging', + result: 'success' + })?.href + ).toBe( + 'https://stagingcloud.comfy.org/?settings=plan-credits&billing_result=success' + ) + }) + + it('drops a reference that is not opaque', () => { + const url = buildReturnUrl({ + target: 'comfyui_workspace', + environment: 'production', + result: 'success', + reference: 'op 42/../' + }) + + expect(parseReturnResult(url?.href ?? '')).toEqual({ result: 'success' }) + }) + + it('omits the outcome when billing has none to report', () => { + const url = buildReturnUrl({ + target: 'comfyui_workspace', + environment: 'production', + reference: 'op_42' + }) + + expect(parseReturnResult(url?.href ?? '')).toEqual({ reference: 'op_42' }) + }) + + it('returns nothing for a target the environment cannot resolve', () => { + expect( + buildReturnUrl({ target: 'platform_account', environment: 'test' }) + ).toBeUndefined() + }) +}) + +describe('parseReturnResult', () => { + it.for([ + 'https://cloud.comfy.org/', + 'https://cloud.comfy.org/?billing_result=partially_refunded', + 'https://cloud.comfy.org/?billing_ref=op%2042', + 'not a url', + 'http://[' + ])('reads nothing usable out of %s', (url) => { + expect(parseReturnResult(url)).toEqual({}) + }) +}) diff --git a/packages/billing-contract/src/returnUrl.ts b/packages/billing-contract/src/returnUrl.ts new file mode 100644 index 00000000000..93d7fc1335c --- /dev/null +++ b/packages/billing-contract/src/returnUrl.ts @@ -0,0 +1,66 @@ +/** + * The trip back. Billing resolves a registered target to its environment's + * destination and may append a coarse outcome plus an opaque reference; a + * consumer reads both back and must work when neither is there, because a + * customer can close the tab or arrive by bookmark at any point. + */ +import type { BillingEnvironment } from './contract' +import { isContractIdentifier } from './identifiers' +import { resolveReturnTarget } from './returnTargets' +import { CONTRACT_PARSE_BASE, parseUrl } from './url' + +/** Names are provisional; see `contract.ts`. */ +const RETURN_PARAM_OUTCOME = 'billing_result' +const RETURN_PARAM_REFERENCE = 'billing_ref' + +const BILLING_OUTCOMES = ['success', 'cancelled', 'pending'] as const + +/** + * Deliberately coarse. A consumer routes on it; the authoritative state of a + * subscription is whatever the consumer's own next read of billing says. + */ +export type BillingOutcome = (typeof BILLING_OUTCOMES)[number] + +function isBillingOutcome(value: string | null): value is BillingOutcome { + return BILLING_OUTCOMES.some((outcome) => outcome === value) +} + +export interface ReturnUrlInput { + /** A `ReturnTarget`; see `BillingEntryInput.returnTo` for why it is wide. */ + readonly target: string + readonly environment: BillingEnvironment + readonly result?: BillingOutcome + /** An operation or correlation reference. Dropped when it is not opaque. */ + readonly reference?: string +} + +export function buildReturnUrl(input: ReturnUrlInput): URL | undefined { + const url = resolveReturnTarget(input.target, input.environment) + if (!url) return undefined + + if (input.result !== undefined) + url.searchParams.set(RETURN_PARAM_OUTCOME, input.result) + if (input.reference !== undefined && isContractIdentifier(input.reference)) + url.searchParams.set(RETURN_PARAM_REFERENCE, input.reference) + + return url +} + +export interface BillingReturn { + readonly result?: BillingOutcome + readonly reference?: string +} + +export function parseReturnResult(url: string | URL): BillingReturn { + const params = parseUrl(url, CONTRACT_PARSE_BASE)?.searchParams + if (!params) return {} + + const result = params.get(RETURN_PARAM_OUTCOME) + const reference = params.get(RETURN_PARAM_REFERENCE) + return { + ...(isBillingOutcome(result) ? { result } : {}), + ...(reference !== null && isContractIdentifier(reference) + ? { reference } + : {}) + } +} diff --git a/packages/billing-contract/src/url.ts b/packages/billing-contract/src/url.ts new file mode 100644 index 00000000000..598a9595ff7 --- /dev/null +++ b/packages/billing-contract/src/url.ts @@ -0,0 +1,20 @@ +/** + * The one place a string becomes a `URL` in this package. Every entry point + * here takes input that arrived over a URL bar, so a parse failure is a value + * to branch on rather than an exception each caller has to remember to catch. + */ +export function parseUrl(value: string | URL, base?: string): URL | undefined { + try { + return new URL(value instanceof URL ? value.href : value, base) + } catch { + return undefined + } +} + +/** + * Lets the parsers accept the path-and-query form a router hands them + * (`/v1/checkout?...`) as readily as a full href. It is never read back: only + * the pathname and the query survive parsing, and `.invalid` is reserved by + * RFC 2606 so a bug that leaked it could not reach a real host. + */ +export const CONTRACT_PARSE_BASE = 'https://billing.invalid/' diff --git a/packages/billing-contract/tsconfig.json b/packages/billing-contract/tsconfig.json new file mode 100644 index 00000000000..bf0260b57e0 --- /dev/null +++ b/packages/billing-contract/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "types": ["node"] + }, + "include": ["src/**/*"] +} diff --git a/packages/billing-contract/vitest.config.ts b/packages/billing-contract/vitest.config.ts new file mode 100644 index 00000000000..b463d3455e1 --- /dev/null +++ b/packages/billing-contract/vitest.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + name: 'billing-contract', + environment: 'node', + include: ['src/**/*.{test,spec}.ts'], + mockReset: true, + restoreMocks: true, + unstubEnvs: true, + unstubGlobals: true, + coverage: { + provider: 'v8', + reporter: ['text', 'lcov'], + include: ['src/**'] + } + } +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 980b21aec2b..98173145eb3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1276,6 +1276,21 @@ importers: specifier: 'catalog:' version: 3.3.11(typescript@6.0.3) + packages/billing-contract: + devDependencies: + '@types/node': + specifier: 'catalog:' + version: 25.9.5 + '@vitest/coverage-v8': + specifier: 'catalog:' + version: 4.1.11(vitest@4.1.11) + typescript: + specifier: 'catalog:' + version: 6.0.3 + vitest: + specifier: 'catalog:' + version: 4.1.11(@types/node@25.9.5)(@vitest/coverage-v8@4.1.11)(@vitest/ui@4.1.11)(happy-dom@20.10.6)(jsdom@29.1.1)(vite@8.2.2(@types/node@25.9.5)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.23.1)(yaml@2.9.0)) + packages/design-system: dependencies: '@iconify-json/lucide': From 947c9778623febf5dc31d0629cf05daea2177bbf Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 15 Sep 2026 23:17:46 -0400 Subject: [PATCH 2/3] feat(billing-web): v1 entry routing, subscription and payment-method surfaces --- apps/billing-web/package.json | 1 + apps/billing-web/src/App.test.ts | 20 -- apps/billing-web/src/App.vue | 7 +- .../src/components/HostedSurface.test.ts | 49 ++++ .../src/components/HostedSurface.vue | 66 ++++++ .../src/components/PaymentMethodsPanel.vue | 122 ++++++++++ apps/billing-web/src/components/PlanCard.vue | 53 +++++ .../src/components/SubscriptionPanel.vue | 93 ++++++++ .../src/components/SubscriptionQuote.vue | 103 +++++++++ .../src/composables/useHostedCopy.ts | 27 +++ apps/billing-web/src/config/env.ts | 5 +- apps/billing-web/src/entry/billingEntry.ts | 34 +++ apps/billing-web/src/i18n.ts | 27 ++- apps/billing-web/src/locales/en/main.json | 109 +++++++++ apps/billing-web/src/router.test.ts | 140 +++++++++++- apps/billing-web/src/router.ts | 50 ++++- .../billing-web/src/test/fakeBillingClient.ts | 210 ++++++++++++++++++ apps/billing-web/src/views/ComingSoonView.vue | 16 ++ apps/billing-web/src/views/EntryErrorView.vue | 7 + .../src/views/PaymentMethodsView.test.ts | 95 ++++++++ .../src/views/PaymentMethodsView.vue | 10 + .../src/views/SubscriptionView.test.ts | 134 +++++++++++ .../src/views/SubscriptionView.vue | 10 + apps/billing-web/vitest.config.ts | 4 + pnpm-lock.yaml | 3 + 25 files changed, 1367 insertions(+), 28 deletions(-) create mode 100644 apps/billing-web/src/components/HostedSurface.test.ts create mode 100644 apps/billing-web/src/components/HostedSurface.vue create mode 100644 apps/billing-web/src/components/PaymentMethodsPanel.vue create mode 100644 apps/billing-web/src/components/PlanCard.vue create mode 100644 apps/billing-web/src/components/SubscriptionPanel.vue create mode 100644 apps/billing-web/src/components/SubscriptionQuote.vue create mode 100644 apps/billing-web/src/composables/useHostedCopy.ts create mode 100644 apps/billing-web/src/entry/billingEntry.ts create mode 100644 apps/billing-web/src/test/fakeBillingClient.ts create mode 100644 apps/billing-web/src/views/ComingSoonView.vue create mode 100644 apps/billing-web/src/views/EntryErrorView.vue create mode 100644 apps/billing-web/src/views/PaymentMethodsView.test.ts create mode 100644 apps/billing-web/src/views/PaymentMethodsView.vue create mode 100644 apps/billing-web/src/views/SubscriptionView.test.ts create mode 100644 apps/billing-web/src/views/SubscriptionView.vue diff --git a/apps/billing-web/package.json b/apps/billing-web/package.json index d6e775ff0e3..44befdaccd9 100644 --- a/apps/billing-web/package.json +++ b/apps/billing-web/package.json @@ -15,6 +15,7 @@ "dependencies": { "@comfyorg/account": "workspace:*", "@comfyorg/account-ui": "workspace:*", + "@comfyorg/billing-contract": "workspace:*", "@comfyorg/design-system": "workspace:*", "@comfyorg/tailwind-utils": "workspace:*", "@vueuse/core": "catalog:", diff --git a/apps/billing-web/src/App.test.ts b/apps/billing-web/src/App.test.ts index ede45127c8e..342616804a9 100644 --- a/apps/billing-web/src/App.test.ts +++ b/apps/billing-web/src/App.test.ts @@ -28,24 +28,4 @@ describe('billing app', () => { screen.getByRole('button', { name: 'Pay and subscribe' }) ).toBeDisabled() }) - - it('recovers unknown static-host paths to the app entry route', async () => { - const router = createBillingRouter( - createMemoryHistory(), - () => 'authenticated' - ) - - await router.push('/unknown-path') - await router.isReady() - - render(App, { - global: { - plugins: [createBillingI18n(), router] - } - }) - - expect( - await screen.findByRole('heading', { name: 'Confirm your payment' }) - ).toBeInTheDocument() - }) }) diff --git a/apps/billing-web/src/App.vue b/apps/billing-web/src/App.vue index 6cabb914036..a256856ba7a 100644 --- a/apps/billing-web/src/App.vue +++ b/apps/billing-web/src/App.vue @@ -2,8 +2,11 @@ import { computed } from 'vue' import BillingShell from '@/components/BillingShell.vue' +import { useBillingEntry } from '@/entry/billingEntry' import { useBillingWebSession } from '@/session/billingWebSession' +import EntryErrorView from '@/views/EntryErrorView.vue' +const { error } = useBillingEntry() const { session } = useBillingWebSession() /** A new key is a new scope, so the shell remounts with a fresh client. */ @@ -15,7 +18,9 @@ const scopeKey = computed(() =>