diff --git a/CODEOWNERS b/CODEOWNERS index db9ccf109ac..5d485c90b54 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -69,6 +69,9 @@ # Model-to-node mappings (cloud team) /src/platform/assets/mappings/ @deepme987 @Comfy-Org/comfy_frontend_devs +# Account layer (auth, billing, subscriptions, credits) - owned by the billing codeowners; individual handles to be confirmed by the billing team (decision D-044 in the account-layer PoC run) +/packages/account/ @Comfy-Org/comfy_frontend_devs + # Translations - native-language reviewers # NOTE: GitHub only honors a code owner that has WRITE access to this repo. # Owners without write access are silently ignored: they are never auto-requested diff --git a/eslint.config.ts b/eslint.config.ts index 9a90eb63699..04ee58dfdfb 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -125,6 +125,7 @@ export default defineConfig([ 'components.d.ts', 'coverage/*', 'dist/*', + 'packages/*/dist/**', 'packages/registry-types/src/comfyRegistryTypes.ts', 'playwright-report/*', 'scripts/registry-census/detection-proof/**', @@ -543,6 +544,25 @@ export default defineConfig([ } }, + { + files: ['packages/account/**/*.{ts,vue}'], + rules: { + 'import-x/no-restricted-paths': [ + 'error', + { + zones: [ + { + target: './packages/account/**', + from: './src/**', + message: + 'packages/account cannot import producer application code; inject host behavior through public account contracts' + } + ] + } + ] + } + }, + // src/lib/ holds vendored leaf libraries (litegraph). They may import from // src/lib/ and from the shared base utilities, but never from an app layer — // a vendored library depending on the app that vendors it is a dependency diff --git a/knip.config.ts b/knip.config.ts index 7be9272e7fa..c2f40873c40 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -39,6 +39,10 @@ const config: KnipConfig = { 'packages/ingest-types': { project: ['src/**/*.{js,ts}'] }, + 'packages/account': { + entry: ['src/core/index.ts', 'src/vue/index.ts'], + project: ['src/**/*.{js,ts}'] + }, 'apps/website': { entry: ['src/scripts/**/*.ts'] }, diff --git a/packages/account/docs/billing-command-eligibility.md b/packages/account/docs/billing-command-eligibility.md new file mode 100644 index 00000000000..65eacdd3484 --- /dev/null +++ b/packages/account/docs/billing-command-eligibility.md @@ -0,0 +1,7 @@ +# Billing command eligibility + +| Current status | Command behavior | +| --------------- | -------------------------------------------------------------------------------------------------------------------- | +| `FREE` | Subscribe creates a subscription checkout. Cancel may return `NO_ACTIVE_SUBSCRIPTION`. | +| `PRO`, active | Subscribe is a no-op; the payment portal remains available. Resubscribe may return `NOT_SCHEDULED_FOR_CANCELLATION`. | +| `PRO`, canceled | Subscribe uses the resubscribe endpoint. | diff --git a/packages/account/package.json b/packages/account/package.json new file mode 100644 index 00000000000..8b3de306f8c --- /dev/null +++ b/packages/account/package.json @@ -0,0 +1,49 @@ +{ + "name": "@comfyorg/account", + "version": "0.0.0-poc", + "files": [ + "dist" + ], + "type": "module", + "exports": { + "./core": { + "types": "./dist/core/index.d.ts", + "import": "./dist/core/index.js" + }, + "./firebase": { + "types": "./dist/firebase/index.d.ts", + "import": "./dist/firebase/index.js" + }, + "./vue": { + "types": "./dist/vue/index.d.ts", + "import": "./dist/vue/index.js" + } + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "guard": "bash scripts/verify-import-guard.sh", + "typecheck": "tsc --noEmit", + "test": "vitest run --root ../.. packages/account/src" + }, + "devDependencies": { + "firebase": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:", + "vue": "catalog:" + }, + "peerDependencies": { + "firebase": ">=11 <13", + "vue": ">=3.5 <4" + }, + "peerDependenciesMeta": { + "firebase": { + "optional": true + }, + "vue": { + "optional": true + } + } +} diff --git a/packages/account/scripts/verify-import-guard.sh b/packages/account/scripts/verify-import-guard.sh new file mode 100644 index 00000000000..9cc780c2ded --- /dev/null +++ b/packages/account/scripts/verify-import-guard.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root=$(git rev-parse --show-toplevel) +seed="$repo_root/packages/account/import-guard-seed.ts" +trap 'rm -f "$seed"' EXIT + +for forbidden in "@/stores/authStore" "../../src/stores/authStore"; do + printf "import '%s'\n" "$forbidden" > "$seed" + if "$repo_root/node_modules/.bin/eslint" "$seed" >/dev/null 2>&1; then + echo "guard accepted forbidden import: $forbidden" >&2 + exit 1 + fi +done + +if rg -n "from ['\"](vue|pinia|nuxt|astro|firebase)|\b(window|document|localStorage|sessionStorage)\b" "$repo_root/packages/account/src/core" --glob '*.ts'; then + echo 'core contains a forbidden framework, SDK, or browser-global dependency' >&2 + exit 1 +fi + +echo 'guard rejected alias and relative src imports' diff --git a/packages/account/src/core/account.test.ts b/packages/account/src/core/account.test.ts new file mode 100644 index 00000000000..a9d27a33a5e --- /dev/null +++ b/packages/account/src/core/account.test.ts @@ -0,0 +1,370 @@ +import { describe, expect, it, vi } from 'vitest' +import { + AccountError, + MalformedResponseError, + createBillingClient, + createSessionClient +} from './index' +import type { + AccountHostAdapter, + SchedulerPort, + TransportRequest, + WorkspaceCredential +} from './index' +import { createFakeIdentity } from './testing/identity' + +class FakeScheduler implements SchedulerPort { + time = 0 + next = 1 + jobs = new Map void }>() + now = () => this.time + schedule(fn: () => void, delayMs: number) { + const id = this.next++ + this.jobs.set(id, { at: this.time + delayMs, fn }) + return id + } + cancel(handle: unknown) { + if (typeof handle === 'number') this.jobs.delete(handle) + } + advance(ms: number) { + this.time += ms + const due = [...this.jobs].filter(([, job]) => job.at <= this.time) + for (const [id, job] of due) { + this.jobs.delete(id) + job.fn() + } + } +} + +function credential( + workspaceId: string, + expiresAt = 600_000 +): WorkspaceCredential { + return { token: `token-${workspaceId}`, workspaceId, expiresAt } +} + +function adapter(kind: 'map' | 'json' = 'map') { + const scheduler = new FakeScheduler() + const records = new Map() + const trace: TransportRequest[] = [] + let workspace = 'A' + let exchangeBody: unknown = credential('A') + let balanceBody: unknown = { balance: 7 } + let balanceStatus = 200 + let clearFails = false + const identity = createFakeIdentity({ userId: 'user', token: 'identity' }) + const key = (value: { + namespace: string + userId: string + workspaceId: string + }) => + kind === 'map' + ? `${value.namespace}:${value.userId}:${value.workspaceId}` + : JSON.stringify(value) + const host: AccountHostAdapter = { + namespace: `fake-${kind}`, + scheduler, + getActiveWorkspace: () => workspace, + storage: { + read: async (value) => records.get(key(value)) ?? null, + write: async (value, record) => void records.set(key(value), record), + clear: async (value) => { + if (clearFails) throw new Error('disk') + records.delete(key(value)) + } + }, + operations: { + exchange: { + idempotent: true, + makeRequest: ({ identity, workspaceId }, signal) => ({ + method: 'POST', + path: '/auth/token', + headers: {}, + body: { identityToken: identity.token, workspaceId }, + signal + }), + response: { decode: (value) => decodeCredential(value) }, + mapError: (status) => new AccountError(`exchange ${status}`, status) + }, + balance: { + idempotent: true, + makeRequest: (_input, signal) => ({ + method: 'GET', + path: '/billing/balance', + headers: {}, + signal + }), + response: { decode: (value) => decodeBalance(value) }, + mapError: (status) => new AccountError(`balance ${status}`, status) + } + }, + transport: async (request) => { + trace.push(request) + return { + status: request.path.includes('balance') ? balanceStatus : 200, + body: request.path.includes('balance') ? balanceBody : exchangeBody + } + } + } + return { + host, + identity, + scheduler, + records, + trace, + setWorkspace: (value: string) => (workspace = value), + setExchange: (value: unknown) => (exchangeBody = value), + setBalance: (value: unknown, status = 200) => { + balanceBody = value + balanceStatus = status + }, + failClear: () => (clearFails = true) + } +} + +function decodeCredential(value: unknown): WorkspaceCredential { + if ( + !value || + typeof value !== 'object' || + !('token' in value) || + !('workspaceId' in value) || + !('expiresAt' in value) + ) + throw new MalformedResponseError() + const item = value as Record + if ( + typeof item.token !== 'string' || + typeof item.workspaceId !== 'string' || + typeof item.expiresAt !== 'number' + ) + throw new MalformedResponseError() + return { + token: item.token, + workspaceId: item.workspaceId, + expiresAt: item.expiresAt + } +} + +function decodeBalance(value: unknown): { balance: number } { + if ( + !value || + typeof value !== 'object' || + !('balance' in value) || + typeof (value as Record).balance !== 'number' + ) + throw new MalformedResponseError() + return { balance: (value as { balance: number }).balance } +} + +describe.for(['map', 'json'] as const)( + 'TP-3a adapter %s conformance', + (kind) => { + it('TP-1a: restores, exchanges, persists, reads balance, and clears', async () => { + const fake = adapter(kind) + const first = createSessionClient(fake.host, fake.identity) + await first.establishSession() + const second = createSessionClient(fake.host, fake.identity) + await second.bootstrap() + expect(second.getState().phase).toBe('authenticated') + const billing = createBillingClient(second, fake.host) + await billing.refreshCredits() + expect(billing.getCreditsState()).toEqual({ + phase: 'value', + value: { balance: 7 } + }) + expect((await second.clearSession()).ok).toBe(true) + }) + + it('TP-3a PM-3: corrupt and mismatched records fail closed', async () => { + const fake = adapter(kind) + fake.records.set( + kind === 'map' + ? 'fake-map:user:A' + : JSON.stringify({ + namespace: 'fake-json', + userId: 'user', + workspaceId: 'A' + }), + { bad: true } + ) + const client = createSessionClient(fake.host, fake.identity) + await client.bootstrap() + expect(client.getState().phase).toBe('signed-out') + }) + } +) + +it('TP-2a PM-4: refresh fires at expiry minus five minutes, not one ms earlier', async () => { + const fake = adapter() + const client = createSessionClient(fake.host, fake.identity) + await client.establishSession() + expect(fake.trace).toHaveLength(1) + fake.scheduler.advance(299_999) + expect(fake.trace).toHaveLength(1) + fake.scheduler.advance(1) + await vi.waitFor(() => expect(fake.trace).toHaveLength(2)) +}) + +it('TP-2a S146: transient refresh retains credential and caps retry', async () => { + const fake = adapter() + const client = createSessionClient(fake.host, fake.identity) + await client.establishSession() + fake.host.transport = async () => { + throw new AccountError('offline') + } + await expect(client.refresh()).rejects.toThrow('offline') + const state = client.getState() + expect(state.phase).toBe('authenticated') + if (state.phase === 'authenticated') + expect(state.refreshError?.message).toBe('offline') + expect( + [...fake.scheduler.jobs.values()].every( + (job) => job.at - fake.scheduler.time <= 300_000 + ) + ).toBe(true) +}) + +it('TP-2b: idempotent 401 replays once; unsafe and second 401 do not loop', async () => { + const fake = adapter() + let calls = 0 + fake.host.transport = async () => ({ + status: ++calls <= 2 ? 401 : 200, + body: {} + }) + const client = createSessionClient(fake.host, fake.identity) + await expect(client.establishSession()).rejects.toThrow('exchange 401') + expect(calls).toBe(2) + fake.host.operations.exchange.idempotent = false + calls = 0 + await expect(client.establishSession()).rejects.toThrow('exchange 401') + expect(calls).toBe(1) +}) + +it('regression: balance 401 refreshes the session and replays with the new credential', async () => { + const fake = adapter() + let exchanges = 0 + let balanceCalls = 0 + fake.host.operations.balance.makeRequest = ({ credential }, signal) => ({ + method: 'GET', + path: '/billing/balance', + headers: { authorization: credential.token }, + signal + }) + fake.host.transport = async (request) => { + fake.trace.push(request) + if (request.path.includes('auth')) { + exchanges++ + return { + status: 200, + body: { + ...credential('A', 600_000 + exchanges), + token: `token-${exchanges}` + } + } + } + balanceCalls++ + return balanceCalls === 1 + ? { status: 401, body: {} } + : { status: 200, body: { balance: 7 } } + } + const session = createSessionClient(fake.host, fake.identity) + await session.establishSession() + const billing = createBillingClient(session, fake.host) + + await billing.refreshCredits() + + expect(balanceCalls).toBe(2) + expect(exchanges).toBe(2) + expect(fake.trace.at(-1)?.headers.authorization).toBe('token-2') + expect(billing.getCreditsState()).toEqual({ + phase: 'value', + value: { balance: 7 } + }) +}) + +it('TP-4 PM-3: credits preserve 7, 0, -2 and reject malformed payloads', async () => { + const fake = adapter() + const session = createSessionClient(fake.host, fake.identity) + await session.establishSession() + const billing = createBillingClient(session, fake.host) + for (const balance of [7, 0, -2]) { + fake.setBalance({ balance }) + await billing.refreshCredits() + expect(billing.getCreditsState()).toEqual({ + phase: 'value', + value: { balance } + }) + } + fake.setBalance({ balance: 'bad' }) + const observed: string[] = [] + billing.subscribeCredits((state) => observed.push(state.phase)) + await billing.refreshCredits() + expect(billing.getCreditsState().phase).toBe('error') + expect(observed).toEqual(['loading', 'error']) + fake.setBalance({ message: 'boom' }, 500) + await billing.refreshCredits() + expect(billing.getCreditsState().phase).toBe('error') +}) + +it('TP-4 PM-2: a late workspace A balance cannot replace B', async () => { + const fake = adapter() + const session = createSessionClient(fake.host, fake.identity) + await session.establishSession() + const billing = createBillingClient(session, fake.host) + let release: ((value: { status: number; body: unknown }) => void) | undefined + fake.host.transport = (request) => + request.path.includes('balance') + ? new Promise((resolve) => (release = resolve)) + : Promise.resolve({ status: 200, body: credential('B') }) + const pending = billing.refreshCredits() + fake.setWorkspace('B') + await session.switchWorkspace('B') + release?.({ status: 200, body: { balance: 99 } }) + await pending + expect(billing.getCreditsState().phase).toBe('idle') +}) + +it('does not restore a cleared session after an in-flight refresh fails', async () => { + const fake = adapter() + const client = createSessionClient(fake.host, fake.identity) + await client.establishSession() + let rejectRefresh: ((error: Error) => void) | undefined + fake.host.transport = () => + new Promise((_resolve, reject) => { + rejectRefresh = reject + }) + + const pending = client.refresh() + await client.clearSession() + rejectRefresh?.(new AccountError('offline')) + + await expect(pending).rejects.toThrow('offline') + expect(client.getState().phase).toBe('signed-out') + expect(fake.scheduler.jobs.size).toBe(0) +}) + +it('billing dispose unsubscribes from the session and clears listeners', async () => { + const fake = adapter() + const session = createSessionClient(fake.host, fake.identity) + await session.establishSession() + const billing = createBillingClient(session, fake.host) + const listener = vi.fn() + billing.subscribeCredits(listener) + await billing.refreshCredits() + listener.mockClear() + + billing.dispose() + await session.clearSession() + + expect(listener).not.toHaveBeenCalled() + expect(billing.getCreditsState().phase).toBe('value') +}) + +it('TP-3a: clear failure reports failure while remaining signed out', async () => { + const fake = adapter() + const client = createSessionClient(fake.host, fake.identity) + await client.establishSession() + fake.failClear() + expect((await client.clearSession()).ok).toBe(false) + expect(client.getState().phase).toBe('signed-out') +}) diff --git a/packages/account/src/core/adapters/stripe.test.ts b/packages/account/src/core/adapters/stripe.test.ts new file mode 100644 index 00000000000..6417b07f3cf --- /dev/null +++ b/packages/account/src/core/adapters/stripe.test.ts @@ -0,0 +1,12 @@ +import { expect, it } from 'vitest' +import { isTestCheckoutUrl } from './stripe.js' + +it('TP-6 EC-P-1: accepts only URLs containing a Stripe test checkout session', () => { + expect( + isTestCheckoutUrl('https://checkout.stripe.com/c/pay/cs_test_abc123') + ).toBe(true) + expect( + isTestCheckoutUrl('https://checkout.stripe.com/c/pay/cs_live_abc123') + ).toBe(false) + expect(isTestCheckoutUrl('not a url cs_test_fake')).toBe(false) +}) diff --git a/packages/account/src/core/adapters/stripe.ts b/packages/account/src/core/adapters/stripe.ts new file mode 100644 index 00000000000..0e9a97be814 --- /dev/null +++ b/packages/account/src/core/adapters/stripe.ts @@ -0,0 +1,10 @@ +export function isTestCheckoutUrl(url: string): boolean { + try { + const value = new URL(url) + return /(?:^|[^A-Za-z0-9])cs_test_[A-Za-z0-9_]+/.test( + `${value.pathname}${value.search}` + ) + } catch { + return false + } +} diff --git a/packages/account/src/core/billing/billing.test.ts b/packages/account/src/core/billing/billing.test.ts new file mode 100644 index 00000000000..640650d9b22 --- /dev/null +++ b/packages/account/src/core/billing/billing.test.ts @@ -0,0 +1,865 @@ +import { describe, expect, it, vi } from 'vitest' +import { + billingCopyKeys, + createBillingCopy, + defaultBillingCopy +} from './copy.js' +import { createBillingApiClient } from './client.js' +import { createBillingCommands } from './commands.js' +import { billingPollTiming, createBillingPoller } from './poller.js' +import { resolveBillingReason } from './reasons.js' +import { initialBillingState, reduceBilling } from './reducer.js' +import { createSingleFlight } from './singleFlight.js' +import type { + BillingClock, + BillingOperationStore, + BillingState, + BillingStep +} from './types.js' + +describe('payments claims', () => { + it('preserves the HTTP status and response body on billing failures', async () => { + const body = { + code: 'SUBSCRIPTION_NOT_CANCELING', + message: 'Already active' + } + const client = createBillingApiClient({ + transport: vi.fn(async () => ({ status: 400, body })) + }) + + await expect(client.resubscribe({}, 'attempt')).rejects.toEqual( + expect.objectContaining({ status: 400, body }) + ) + }) + + it('reads server-resolved billing capabilities', async () => { + const body = { + capabilities: { + can_cancel: true, + can_change_seats: false, + can_downgrade_to_personal: false, + can_invite_members: true, + can_reactivate: false, + can_subscribe_self_serve: true, + can_top_up: true + }, + expires_at: '2026-09-06T12:00:00Z', + resolved_for: { workspace_id: 'workspace-1' }, + revision: 1, + rollout_defaults_applied: { + can_downgrade_to_personal: false, + can_subscribe_self_serve: false, + can_top_up: false + } + } + const transport = vi.fn(async () => ({ status: 200, body })) + const client = createBillingApiClient({ transport }) + + await expect(client.getCapabilities!()).resolves.toEqual(body) + expect(transport).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'GET', + path: '/api/billing/capabilities', + headers: {} + }) + ) + }) + + it('TP-6 PM-8 PM-10 EC-P-1: sends the production subscribe body without an idempotency header', async () => { + const transport = vi.fn(async () => ({ + status: 200, + body: { billing_op_id: 'op', status: 'pending_payment' } + })) + const client = createBillingApiClient({ transport }) + await client.subscribe({ + plan_slug: 'pro', + return_url: 'https://host/ok', + cancel_url: 'https://host/no' + }) + expect(transport).toHaveBeenCalledWith( + expect.objectContaining({ + path: '/api/billing/subscribe', + headers: {}, + body: { + plan_slug: 'pro', + return_url: 'https://host/ok', + cancel_url: 'https://host/no' + } + }) + ) + }) + it.for<[string, BillingState, BillingStep]>([ + ['select', initialBillingState, 'select'], + [ + 'preview', + reduceBilling(initialBillingState, { type: 'started', operationId: '1' }), + 'preview' + ], + [ + 'verifying', + reduceBilling(initialBillingState, { + type: 'urlReceived', + url: 'https://verify' + }), + 'verifying' + ], + [ + 'canceled', + reduceBilling(initialBillingState, { + type: 'opStatus', + status: 'canceled', + no_charge_confirmed: true + }), + 'canceled' + ], + [ + 'declined', + reduceBilling(initialBillingState, { + type: 'opStatus', + status: 'failed', + reason_code: 'card_declined' + }), + 'declined' + ], + [ + 'processing_error', + reduceBilling(initialBillingState, { + type: 'opStatus', + status: 'timeout' + }), + 'processing_error' + ], + [ + 'payment_received_hold', + reduceBilling(initialBillingState, { + type: 'opStatus', + status: 'payment_received_hold' + }), + 'payment_received_hold' + ], + [ + 'success', + reduceBilling(initialBillingState, { + type: 'opStatus', + status: 'succeeded' + }), + 'success' + ] + ])('TP-10 PM-6: reduces %s', ([_name, state, step]) => + expect(state.step).toBe(step) + ) + it('TP-11 EC-P-6: fuzzed raw text never survives reason mapping', () => { + for (let index = 0; index < 200; index++) { + const raw = `${crypto.randomUUID()}