From eb42a643d38196792043a5f562cb8e95840f5202 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:05:39 -0700 Subject: [PATCH 01/26] test: add failing account package skeleton --- packages/account/package.json | 19 +++++++++++++++++++ packages/account/src/core/walking.test.ts | 8 ++++++++ packages/account/tsconfig.build.json | 6 ++++++ packages/account/tsconfig.json | 5 +++++ 4 files changed, 38 insertions(+) create mode 100644 packages/account/package.json create mode 100644 packages/account/src/core/walking.test.ts create mode 100644 packages/account/tsconfig.build.json create mode 100644 packages/account/tsconfig.json diff --git a/packages/account/package.json b/packages/account/package.json new file mode 100644 index 00000000000..096ee5534f3 --- /dev/null +++ b/packages/account/package.json @@ -0,0 +1,19 @@ +{ + "name": "@comfyorg/account", + "version": "0.0.0-poc", + "type": "module", + "files": ["dist"], + "exports": { + "./core": { "types": "./dist/core/index.d.ts", "import": "./dist/core/index.js" }, + "./vue": { "types": "./dist/vue/index.d.ts", "import": "./dist/vue/index.js" } + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "peerDependencies": { "vue": ">=3.5 <4" }, + "peerDependenciesMeta": { "vue": { "optional": true } }, + "devDependencies": { "typescript": "catalog:", "vitest": "catalog:", "vue": "catalog:" }, + "publishConfig": { "access": "public" } +} diff --git a/packages/account/src/core/walking.test.ts b/packages/account/src/core/walking.test.ts new file mode 100644 index 00000000000..0e5224383be --- /dev/null +++ b/packages/account/src/core/walking.test.ts @@ -0,0 +1,8 @@ +import { describe, expect, it } from 'vitest' +import { accountPackageId } from './index' + +describe('walking skeleton', () => { + it('TP-5-build: exposes one core function', () => { + expect(accountPackageId()).toBe('@comfyorg/account') + }) +}) diff --git a/packages/account/tsconfig.build.json b/packages/account/tsconfig.build.json new file mode 100644 index 00000000000..765d6891c56 --- /dev/null +++ b/packages/account/tsconfig.build.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "rootDir": "src", "declaration": true, "emitDeclarationOnly": false }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/account/tsconfig.json b/packages/account/tsconfig.json new file mode 100644 index 00000000000..0bfc6b5ec2d --- /dev/null +++ b/packages/account/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { "rootDir": ".", "outDir": "dist", "composite": false }, + "include": ["src/**/*.ts", "examples/**/*.ts"] +} From cebd125bfa90f6fb0a3aea610b63d286b045135f Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:06:16 -0700 Subject: [PATCH 02/26] feat: add publishable account package skeleton --- packages/account/examples/packed-consumer.ts | 4 ++++ packages/account/src/core/index.ts | 3 +++ packages/account/src/vue/index.ts | 1 + 3 files changed, 8 insertions(+) create mode 100644 packages/account/examples/packed-consumer.ts create mode 100644 packages/account/src/core/index.ts create mode 100644 packages/account/src/vue/index.ts diff --git a/packages/account/examples/packed-consumer.ts b/packages/account/examples/packed-consumer.ts new file mode 100644 index 00000000000..e59fca2b7d7 --- /dev/null +++ b/packages/account/examples/packed-consumer.ts @@ -0,0 +1,4 @@ +import { accountPackageId } from '../src/core/index' + +if (accountPackageId() !== '@comfyorg/account') + throw new Error('invalid package') diff --git a/packages/account/src/core/index.ts b/packages/account/src/core/index.ts new file mode 100644 index 00000000000..78b290cdbfa --- /dev/null +++ b/packages/account/src/core/index.ts @@ -0,0 +1,3 @@ +export function accountPackageId(): string { + return '@comfyorg/account' +} diff --git a/packages/account/src/vue/index.ts b/packages/account/src/vue/index.ts new file mode 100644 index 00000000000..612775a8b20 --- /dev/null +++ b/packages/account/src/vue/index.ts @@ -0,0 +1 @@ +export { accountPackageId } from '../core/index' From 897801155b70a0d76f042c9a5a194bb60a59bbd6 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:07:59 -0700 Subject: [PATCH 03/26] test: add failing account core claims --- packages/account/src/core/account.test.ts | 281 ++++++++++++++++++++++ 1 file changed, 281 insertions(+) create mode 100644 packages/account/src/core/account.test.ts diff --git a/packages/account/src/core/account.test.ts b/packages/account/src/core/account.test.ts new file mode 100644 index 00000000000..731892910aa --- /dev/null +++ b/packages/account/src/core/account.test.ts @@ -0,0 +1,281 @@ +import { describe, expect, it } from 'vitest' +import { + AccountError, + MalformedResponseError, + createBillingClient, + createSessionClient +} from './index' +import type { + AccountHostAdapter, + SchedulerPort, + TransportRequest, + WorkspaceCredential +} from './index' + +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 clearFails = false + 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, + acquireIdentity: async () => ({ userId: 'user', token: 'identity' }), + 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: (input, signal) => ({ + method: 'POST', + path: '/auth/token', + headers: {}, + body: input, + 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: 200, + body: request.path.includes('balance') ? balanceBody : exchangeBody + } + } + } + return { + host, + scheduler, + records, + trace, + setWorkspace: (value: string) => (workspace = value), + setExchange: (value: unknown) => (exchangeBody = value), + setBalance: (value: unknown) => (balanceBody = value), + 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) + await first.establishSession() + const second = createSessionClient(fake.host) + 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) + 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) + await client.establishSession() + expect(fake.trace).toHaveLength(1) + fake.scheduler.advance(299_999) + expect(fake.trace).toHaveLength(1) + fake.scheduler.advance(1) + await Promise.resolve() + 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) + 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) + 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('TP-4 PM-3: credits preserve 7, 0, -2 and reject malformed payloads', async () => { + const fake = adapter() + const session = createSessionClient(fake.host) + 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' }) + 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) + 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).not.toBe('value') +}) + +it('TP-3a: clear failure reports failure while remaining signed out', async () => { + const fake = adapter() + const client = createSessionClient(fake.host) + await client.establishSession() + fake.failClear() + expect((await client.clearSession()).ok).toBe(false) + expect(client.getState().phase).toBe('signed-out') +}) From 5292850c565202de803d2b8eaf4605b126e88430 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:11:11 -0700 Subject: [PATCH 04/26] feat: prove account core and Vue contracts --- eslint.config.ts | 19 + packages/account/package.json | 35 +- .../account/scripts/verify-import-guard.sh | 21 + packages/account/src/core/account.test.ts | 6 +- packages/account/src/core/index.ts | 381 ++++++++++++++++++ packages/account/src/vue/accountVue.test.ts | 67 +++ packages/account/src/vue/index.ts | 66 +++ 7 files changed, 586 insertions(+), 9 deletions(-) create mode 100644 packages/account/scripts/verify-import-guard.sh create mode 100644 packages/account/src/vue/accountVue.test.ts diff --git a/eslint.config.ts b/eslint.config.ts index 9a90eb63699..45e3d8a8375 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -543,6 +543,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/packages/account/package.json b/packages/account/package.json index 096ee5534f3..8deb5a7ae2f 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -1,19 +1,40 @@ { "name": "@comfyorg/account", "version": "0.0.0-poc", + "files": [ + "dist" + ], "type": "module", - "files": ["dist"], "exports": { - "./core": { "types": "./dist/core/index.d.ts", "import": "./dist/core/index.js" }, - "./vue": { "types": "./dist/vue/index.d.ts", "import": "./dist/vue/index.js" } + "./core": { + "types": "./dist/core/index.d.ts", + "import": "./dist/core/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" }, - "peerDependencies": { "vue": ">=3.5 <4" }, - "peerDependenciesMeta": { "vue": { "optional": true } }, - "devDependencies": { "typescript": "catalog:", "vitest": "catalog:", "vue": "catalog:" }, - "publishConfig": { "access": "public" } + "devDependencies": { + "typescript": "catalog:", + "vitest": "catalog:", + "vue": "catalog:" + }, + "peerDependencies": { + "vue": ">=3.5 <4" + }, + "peerDependenciesMeta": { + "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..0478ae2b178 --- /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 ['\"](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 index 731892910aa..77319be8ef5 100644 --- a/packages/account/src/core/account.test.ts +++ b/packages/account/src/core/account.test.ts @@ -74,11 +74,11 @@ function adapter(kind: 'map' | 'json' = 'map') { operations: { exchange: { idempotent: true, - makeRequest: (input, signal) => ({ + makeRequest: ({ identity, workspaceId }, signal) => ({ method: 'POST', path: '/auth/token', headers: {}, - body: input, + body: { identityToken: identity.token, workspaceId }, signal }), response: { decode: (value) => decodeCredential(value) }, @@ -197,6 +197,8 @@ it('TP-2a PM-4: refresh fires at expiry minus five minutes, not one ms earlier', expect(fake.trace).toHaveLength(1) fake.scheduler.advance(1) await Promise.resolve() + await Promise.resolve() + await Promise.resolve() expect(fake.trace).toHaveLength(2) }) diff --git a/packages/account/src/core/index.ts b/packages/account/src/core/index.ts index 78b290cdbfa..6b3360dfaa2 100644 --- a/packages/account/src/core/index.ts +++ b/packages/account/src/core/index.ts @@ -1,3 +1,384 @@ +export type UserId = string +export type WorkspaceId = string +export type Namespace = string +export type ScheduleHandle = unknown + +export interface IdentitySnapshot { + userId: UserId + token: string +} +export interface WorkspaceCredential { + token: string + workspaceId: WorkspaceId + expiresAt: number +} +export interface BillingBalanceResponse { + balance: number +} +export interface AccountAbortSignal { + readonly aborted: boolean +} + +export class AccountError extends Error { + constructor( + message: string, + readonly status?: number + ) { + super(message) + } +} +export class MalformedResponseError extends AccountError { + constructor() { + super('Malformed response') + } +} +export class StorageClearError extends AccountError { + constructor() { + super('Could not clear account storage') + } +} + +export interface SchedulerPort { + now(): number + schedule(fn: () => void, delayMs: number): ScheduleHandle + cancel(handle: ScheduleHandle): void +} +export interface StorageKey { + namespace: Namespace + userId: UserId + workspaceId: WorkspaceId +} +export interface StoredCredentialRecord { + version: 1 + key: StorageKey + credential: WorkspaceCredential +} +export interface Decoder { + decode(input: unknown): T +} +export interface TransportRequest { + method: 'POST' | 'GET' + path: string + headers: Readonly> + body?: TBody + signal: AccountAbortSignal +} +export interface TransportOperation { + idempotent: boolean + makeRequest( + input: TInput, + signal: AccountAbortSignal + ): TransportRequest + response: Decoder + mapError(status: number, body: unknown): AccountError +} +export interface AccountOperations { + exchange: TransportOperation< + { identity: IdentitySnapshot; workspaceId: WorkspaceId }, + { identityToken: string; workspaceId: WorkspaceId }, + WorkspaceCredential + > + balance: TransportOperation< + { credential: WorkspaceCredential }, + never, + BillingBalanceResponse + > +} +export interface AccountHostAdapter { + namespace: Namespace + scheduler: SchedulerPort + acquireIdentity(options?: { + forceRefresh?: boolean + }): Promise + getActiveWorkspace(): WorkspaceId | null + storage: { + read(key: StorageKey): Promise + write(key: StorageKey, value: StoredCredentialRecord): Promise + clear(key: StorageKey): Promise + } + operations: AccountOperations + transport( + request: TransportRequest + ): Promise<{ status: number; body: unknown }> +} +export type SessionState = + | { phase: 'idle' } + | { phase: 'restoring' } + | { + phase: 'authenticated' + credential: WorkspaceCredential + generation: number + refreshError?: AccountError + } + | { phase: 'refreshing'; credential: WorkspaceCredential; generation: number } + | { phase: 'signed-out'; error?: AccountError } +export type Loadable = + | { phase: 'idle' | 'loading' } + | { phase: 'value'; value: T } + | { phase: 'empty' } + | { phase: 'error'; error: AccountError } + +export interface SessionClient { + bootstrap(): Promise + getState(): SessionState + getGeneration(): number + subscribe(listener: (state: SessionState) => void): () => void + establishSession(workspaceId?: WorkspaceId): Promise + switchWorkspace(workspaceId: WorkspaceId): Promise + refresh(options?: { + forceIdentityRefresh?: boolean + }): Promise + clearSession(): Promise< + { ok: true } | { ok: false; error: StorageClearError } + > +} +export interface BillingClient { + getCreditsState(): Loadable + subscribeCredits( + listener: (state: Loadable) => void + ): () => void + refreshCredits(signal?: AccountAbortSignal): Promise +} + +const REFRESH_BUFFER_MS = 300_000 +const aliveSignal: AccountAbortSignal = { aborted: false } + +async function runOperation( + adapter: AccountHostAdapter, + operation: TransportOperation, + input: I, + signal: AccountAbortSignal +): Promise { + const request = operation.makeRequest(input, signal) + for (let attempt = 0; attempt < 2; attempt++) { + const response = await adapter.transport(request) + if (response.status >= 200 && response.status < 300) + return operation.response.decode(response.body) + if (response.status !== 401 || !operation.idempotent || attempt === 1) + throw operation.mapError(response.status, response.body) + } + throw new AccountError('Unreachable operation state') +} + +function isRecord( + value: unknown, + key: StorageKey +): value is StoredCredentialRecord { + if (!value || typeof value !== 'object') return false + const item = value as Partial + return ( + item.version === 1 && + item.key?.namespace === key.namespace && + item.key.userId === key.userId && + item.key.workspaceId === key.workspaceId && + typeof item.credential?.token === 'string' && + item.credential.workspaceId === key.workspaceId && + typeof item.credential.expiresAt === 'number' + ) +} + +export function createSessionClient( + adapter: AccountHostAdapter +): SessionClient { + let state: SessionState = { phase: 'idle' } + let generation = 0 + let timer: ScheduleHandle | undefined + let retry = 1_000 + let lastKey: StorageKey | undefined + const listeners = new Set<(state: SessionState) => void>() + function publish(next: SessionState) { + state = next + listeners.forEach((listener) => listener(state)) + } + function cancelTimer() { + if (timer !== undefined) adapter.scheduler.cancel(timer) + timer = undefined + } + function schedule(credential: WorkspaceCredential) { + cancelTimer() + const delay = Math.max( + 0, + credential.expiresAt - REFRESH_BUFFER_MS - adapter.scheduler.now() + ) + timer = adapter.scheduler.schedule(() => { + void refresh().catch(() => undefined) + }, delay) + } + async function identityAndKey(workspaceId?: string) { + const identity = await adapter.acquireIdentity() + const workspace = workspaceId ?? adapter.getActiveWorkspace() + if (!identity || !workspace) throw new AccountError('No active account') + return { + identity, + key: { + namespace: adapter.namespace, + userId: identity.userId, + workspaceId: workspace + } + } + } + async function establishSession( + workspaceId?: string + ): Promise { + const ownGeneration = generation + const { identity, key } = await identityAndKey(workspaceId) + const credential = await runOperation( + adapter, + adapter.operations.exchange, + { identity, workspaceId: key.workspaceId }, + aliveSignal + ) + if ( + generation !== ownGeneration || + adapter.getActiveWorkspace() !== key.workspaceId + ) + throw new AccountError('Stale session result') + await adapter.storage.write(key, { version: 1, key, credential }) + lastKey = key + retry = 1_000 + publish({ phase: 'authenticated', credential, generation }) + schedule(credential) + return credential + } + async function refresh(): Promise { + const previous = + state.phase === 'authenticated' || state.phase === 'refreshing' + ? state.credential + : undefined + if (!previous) throw new AccountError('Not authenticated') + publish({ phase: 'refreshing', credential: previous, generation }) + try { + return await establishSession(previous.workspaceId) + } catch (error) { + const accountError = + error instanceof AccountError + ? error + : new AccountError('Refresh failed') + publish({ + phase: 'authenticated', + credential: previous, + generation, + refreshError: accountError + }) + timer = adapter.scheduler.schedule( + () => { + void refresh().catch(() => undefined) + }, + Math.min(retry, REFRESH_BUFFER_MS) + ) + retry = Math.min(retry * 2, REFRESH_BUFFER_MS) + throw accountError + } + } + return { + async bootstrap() { + publish({ phase: 'restoring' }) + try { + const { key } = await identityAndKey() + const value = await adapter.storage.read(key) + if (!isRecord(value, key)) { + await adapter.storage.clear(key) + publish({ phase: 'signed-out' }) + return + } + lastKey = key + publish({ + phase: 'authenticated', + credential: value.credential, + generation + }) + schedule(value.credential) + } catch (error) { + publish({ + phase: 'signed-out', + error: + error instanceof AccountError + ? error + : new AccountError('Restore failed') + }) + } + }, + getState: () => state, + getGeneration: () => generation, + subscribe(listener) { + listeners.add(listener) + return () => listeners.delete(listener) + }, + establishSession, + async switchWorkspace(workspaceId) { + generation++ + cancelTimer() + return establishSession(workspaceId) + }, + refresh, + async clearSession() { + generation++ + cancelTimer() + publish({ phase: 'signed-out' }) + if (!lastKey) return { ok: true } + try { + await adapter.storage.clear(lastKey) + return { ok: true } + } catch { + const error = new StorageClearError() + publish({ phase: 'signed-out', error }) + return { ok: false, error } + } + } + } +} + +export function createBillingClient( + session: SessionClient, + adapter: AccountHostAdapter +): BillingClient { + let state: Loadable = { phase: 'idle' } + const listeners = new Set<(state: Loadable) => void>() + function publish(next: Loadable) { + state = next + listeners.forEach((listener) => listener(state)) + } + session.subscribe((next) => { + if (next.phase !== 'authenticated' && next.phase !== 'refreshing') + publish({ phase: 'idle' }) + }) + return { + getCreditsState: () => state, + subscribeCredits(listener) { + listeners.add(listener) + return () => listeners.delete(listener) + }, + async refreshCredits(signal = aliveSignal) { + const startGeneration = session.getGeneration() + const current = session.getState() + if (current.phase !== 'authenticated' && current.phase !== 'refreshing') { + publish({ phase: 'empty' }) + return + } + publish({ phase: 'loading' }) + try { + const value = await runOperation( + adapter, + adapter.operations.balance, + { credential: current.credential }, + signal + ) + if (!signal.aborted && startGeneration === session.getGeneration()) + publish({ phase: 'value', value }) + } catch (error) { + if (!signal.aborted && startGeneration === session.getGeneration()) + publish({ + phase: 'error', + error: + error instanceof AccountError + ? error + : new AccountError('Balance failed') + }) + } + } + } +} + export function accountPackageId(): string { return '@comfyorg/account' } diff --git a/packages/account/src/vue/accountVue.test.ts b/packages/account/src/vue/accountVue.test.ts new file mode 100644 index 00000000000..00744cbf858 --- /dev/null +++ b/packages/account/src/vue/accountVue.test.ts @@ -0,0 +1,67 @@ +import { render, screen } from '@testing-library/vue' +import { defineComponent, h, provide } from 'vue' +import { describe, expect, it, vi } from 'vitest' +import type { + BillingClient, + Loadable, + BillingBalanceResponse +} from '../core/index' +import { + CreditsDisplay, + MissingAccountProviderError, + billingClientKey, + useCredits +} from './index' + +function billing( + state: Loadable +): BillingClient & { unsubscribe: ReturnType } { + const unsubscribe = vi.fn() + return { + unsubscribe, + getCreditsState: () => state, + subscribeCredits: () => unsubscribe, + refreshCredits: async () => undefined + } +} + +describe('TP-4 Vue contract', () => { + it.for([7, 0, -2])( + 'TP-4: CreditsDisplay preserves numeric balance %s', + (balance) => { + render(CreditsDisplay, { + props: { + source: 'props', + state: { phase: 'value', value: { balance } } + } + }) + expect(screen.getByText(String(balance))).toBeTruthy() + } + ) + + it('TP-4: missing provider throws MissingAccountProviderError', () => { + expect(() => + render(CreditsDisplay, { props: { source: 'provider' } }) + ).toThrow(MissingAccountProviderError) + }) + + it('TP-4: useCredits returns readonly ref and disposes subscription', () => { + const client = billing({ phase: 'value', value: { balance: 7 } }) + const Child = defineComponent({ + setup() { + const credits = useCredits() + expect(credits.value.phase).toBe('value') + return () => h('span') + } + }) + const Host = defineComponent({ + setup() { + provide(billingClientKey, client) + return () => h(Child) + } + }) + const result = render(Host) + result.unmount() + expect(client.unsubscribe).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/account/src/vue/index.ts b/packages/account/src/vue/index.ts index 612775a8b20..43d78d94b01 100644 --- a/packages/account/src/vue/index.ts +++ b/packages/account/src/vue/index.ts @@ -1 +1,67 @@ +import { defineComponent, h, inject, onScopeDispose, readonly, ref } from 'vue' +import type { InjectionKey, PropType, Ref } from 'vue' +import { AccountError } from '../core/index' +import type { + BillingBalanceResponse, + BillingClient, + Loadable +} from '../core/index' + +export const billingClientKey: InjectionKey = + Symbol('billingClient') + +export class MissingAccountProviderError extends AccountError { + constructor() { + super('No account billing provider is available') + } +} + +export function useCredits( + explicit?: BillingClient +): Readonly>> { + const client = explicit ?? inject(billingClientKey) + if (!client) throw new MissingAccountProviderError() + const state = ref(client.getCreditsState()) + const unsubscribe = client.subscribeCredits((next) => { + state.value = next + }) + onScopeDispose(unsubscribe) + return readonly(state) +} + +export type CreditsDisplayProps = + | { + source: 'props' + state: Loadable + provider?: never + } + | { source: 'provider'; state?: never; provider?: BillingClient } + +function renderState(state: Loadable) { + if (state.phase === 'value') return String(state.value.balance) + if (state.phase === 'error') return 'Error' + if (state.phase === 'empty') return 'Empty' + return 'Loading' +} + +export const CreditsDisplay = defineComponent({ + name: 'CreditsDisplay', + props: { + source: { type: String as PropType<'props' | 'provider'>, required: true }, + state: { + type: Object as PropType>, + required: false + }, + provider: { type: Object as PropType, required: false } + }, + setup(props) { + if (props.source === 'props') { + if (!props.state) throw new MissingAccountProviderError() + return () => h('span', renderState(props.state ?? { phase: 'empty' })) + } + const state = useCredits(props.provider) + return () => h('span', renderState(state.value)) + } +}) + export { accountPackageId } from '../core/index' From 7465cafbce48e5312adcc7d443bec3e21c08330a Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:12:07 -0700 Subject: [PATCH 05/26] build: emit account package artifacts --- packages/account/tsconfig.build.json | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/account/tsconfig.build.json b/packages/account/tsconfig.build.json index 765d6891c56..0106f79d79b 100644 --- a/packages/account/tsconfig.build.json +++ b/packages/account/tsconfig.build.json @@ -1,6 +1,13 @@ { "extends": "./tsconfig.json", - "compilerOptions": { "rootDir": "src", "declaration": true, "emitDeclarationOnly": false }, + "compilerOptions": { + "rootDir": "src", + "declaration": true, + "emitDeclarationOnly": false, + "noEmit": false, + "incremental": false, + "allowImportingTsExtensions": false + }, "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts"] } From 7c6d9491dc2589ad65a07a24495fd455d3370fa0 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:13:43 -0700 Subject: [PATCH 06/26] chore: register account workspace package --- eslint.config.ts | 1 + pnpm-lock.yaml | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/eslint.config.ts b/eslint.config.ts index 45e3d8a8375..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/**', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a4aeab56f0..7d9eb8eb333 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1048,6 +1048,18 @@ importers: specifier: 'catalog:' version: 3.3.9(typescript@6.0.3) + packages/account: + devDependencies: + typescript: + specifier: 'catalog:' + version: 6.0.3 + vitest: + specifier: 'catalog:' + version: 4.1.10(@types/node@25.9.5)(@vitest/coverage-v8@4.1.10)(@vitest/ui@4.1.10)(happy-dom@20.10.6)(jsdom@29.1.1)(vite@8.2.1(@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)) + vue: + specifier: 'catalog:' + version: 3.5.41(typescript@6.0.3) + packages/design-system: dependencies: '@iconify-json/lucide': From c6ee121b9c86b3346df621aea916f6700f422299 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 01:23:11 -0700 Subject: [PATCH 07/26] fix: emit resolvable account package imports --- packages/account/src/packedTarball.test.ts | 97 ++++++++++++++++++++++ packages/account/src/vue/index.ts | 6 +- packages/account/tsconfig.json | 7 +- 3 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 packages/account/src/packedTarball.test.ts diff --git a/packages/account/src/packedTarball.test.ts b/packages/account/src/packedTarball.test.ts new file mode 100644 index 00000000000..4de8837ffbc --- /dev/null +++ b/packages/account/src/packedTarball.test.ts @@ -0,0 +1,97 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { afterAll, describe, expect, it } from 'vitest' + +const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const tempRoot = mkdtempSync(join(tmpdir(), 'comfy-account-pack-')) + +afterAll(() => rmSync(tempRoot, { force: true, recursive: true })) + +function run(command: string, args: string[], cwd: string) { + return execFileSync(command, args, { + cwd, + encoding: 'utf8', + env: { ...process.env, npm_config_cache: join(tempRoot, 'npm-cache') } + }) +} + +describe('packed package', () => { + it('TP-5: packed tarball resolves ./core and ./vue under Node ESM and TS nodenext/bundler', () => { + run('pnpm', ['build'], packageRoot) + const packOutput: unknown = JSON.parse( + run( + 'npm', + ['pack', '--json', '--pack-destination', tempRoot], + packageRoot + ) + ) + const tarballName = + Array.isArray(packOutput) && + typeof packOutput[0] === 'object' && + packOutput[0] !== null && + 'filename' in packOutput[0] && + typeof packOutput[0].filename === 'string' + ? packOutput[0].filename + : undefined + expect(tarballName).toBeTruthy() + if (!tarballName) throw new Error('npm pack did not return a filename') + + const consumerRoot = join(tempRoot, 'consumer') + mkdirSync(consumerRoot) + writeFileSync( + join(consumerRoot, 'package.json'), + JSON.stringify({ private: true, type: 'module' }) + ) + run( + 'npm', + [ + 'install', + '--ignore-scripts', + join(tempRoot, tarballName), + 'typescript@5.9.2', + 'vue@3.5.21' + ], + consumerRoot + ) + + const nodeOutput = run( + 'node', + [ + '--input-type=module', + '-e', + "await import('@comfyorg/account/core'); await import('@comfyorg/account/vue'); console.log('node-esm-ok')" + ], + consumerRoot + ) + expect(nodeOutput).toContain('node-esm-ok') + + writeFileSync( + join(consumerRoot, 'consumer.ts'), + "import '@comfyorg/account/core'\nimport '@comfyorg/account/vue'\n" + ) + for (const [module, moduleResolution] of [ + ['NodeNext', 'NodeNext'], + ['ESNext', 'Bundler'] + ]) { + run( + 'node', + [ + 'node_modules/typescript/bin/tsc', + '--noEmit', + '--strict', + '--skipLibCheck', + '--module', + module, + '--moduleResolution', + moduleResolution, + 'consumer.ts' + ], + consumerRoot + ) + } + }, 120_000) +}) diff --git a/packages/account/src/vue/index.ts b/packages/account/src/vue/index.ts index 43d78d94b01..c6089d918ad 100644 --- a/packages/account/src/vue/index.ts +++ b/packages/account/src/vue/index.ts @@ -1,11 +1,11 @@ import { defineComponent, h, inject, onScopeDispose, readonly, ref } from 'vue' import type { InjectionKey, PropType, Ref } from 'vue' -import { AccountError } from '../core/index' +import { AccountError } from '../core/index.js' import type { BillingBalanceResponse, BillingClient, Loadable -} from '../core/index' +} from '../core/index.js' export const billingClientKey: InjectionKey = Symbol('billingClient') @@ -64,4 +64,4 @@ export const CreditsDisplay = defineComponent({ } }) -export { accountPackageId } from '../core/index' +export { accountPackageId } from '../core/index.js' diff --git a/packages/account/tsconfig.json b/packages/account/tsconfig.json index 0bfc6b5ec2d..cf23a5a4446 100644 --- a/packages/account/tsconfig.json +++ b/packages/account/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.json", - "compilerOptions": { "rootDir": ".", "outDir": "dist", "composite": false }, + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "composite": false, + "types": ["node", "vitest/globals"] + }, "include": ["src/**/*.ts", "examples/**/*.ts"] } From b7a6510351a2b1af83099008e5a32f02de99c252 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 2 Sep 2026 04:38:16 -0700 Subject: [PATCH 08/26] fix(account): declare package entry points for knip --- knip.config.ts | 4 ++++ packages/account/examples/packed-consumer.ts | 4 ---- 2 files changed, 4 insertions(+), 4 deletions(-) delete mode 100644 packages/account/examples/packed-consumer.ts 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/examples/packed-consumer.ts b/packages/account/examples/packed-consumer.ts deleted file mode 100644 index e59fca2b7d7..00000000000 --- a/packages/account/examples/packed-consumer.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { accountPackageId } from '../src/core/index' - -if (accountPackageId() !== '@comfyorg/account') - throw new Error('invalid package') From b88c80acdea054c070edb19a2abdff400101d715 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 04:29:42 -0700 Subject: [PATCH 09/26] fix: re-mint credentials before replaying balance requests --- packages/account/src/core/account.test.ts | 45 +++++++++++++++++++++ packages/account/src/core/index.ts | 33 ++++++++++----- packages/account/src/vue/accountVue.test.ts | 10 +++++ packages/account/src/vue/index.ts | 12 +++++- 4 files changed, 89 insertions(+), 11 deletions(-) diff --git a/packages/account/src/core/account.test.ts b/packages/account/src/core/account.test.ts index 77319be8ef5..3bef6190006 100644 --- a/packages/account/src/core/account.test.ts +++ b/packages/account/src/core/account.test.ts @@ -237,6 +237,48 @@ it('TP-2b: idempotent 401 replays once; unsafe and second 401 do not loop', asyn 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) + 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) @@ -251,8 +293,11 @@ it('TP-4 PM-3: credits preserve 7, 0, -2 and reject malformed payloads', async ( }) } 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']) }) it('TP-4 PM-2: a late workspace A balance cannot replace B', async () => { diff --git a/packages/account/src/core/index.ts b/packages/account/src/core/index.ts index 6b3360dfaa2..7ef9b84c8f2 100644 --- a/packages/account/src/core/index.ts +++ b/packages/account/src/core/index.ts @@ -147,15 +147,18 @@ async function runOperation( adapter: AccountHostAdapter, operation: TransportOperation, input: I, - signal: AccountAbortSignal + signal: AccountAbortSignal, + remint?: () => Promise ): Promise { - const request = operation.makeRequest(input, signal) + let currentInput = input for (let attempt = 0; attempt < 2; attempt++) { + const request = operation.makeRequest(currentInput, signal) const response = await adapter.transport(request) if (response.status >= 200 && response.status < 300) return operation.response.decode(response.body) if (response.status !== 401 || !operation.idempotent || attempt === 1) throw operation.mapError(response.status, response.body) + if (remint) currentInput = await remint() } throw new AccountError('Unreachable operation state') } @@ -204,8 +207,8 @@ export function createSessionClient( void refresh().catch(() => undefined) }, delay) } - async function identityAndKey(workspaceId?: string) { - const identity = await adapter.acquireIdentity() + async function identityAndKey(workspaceId?: string, forceRefresh = false) { + const identity = await adapter.acquireIdentity({ forceRefresh }) const workspace = workspaceId ?? adapter.getActiveWorkspace() if (!identity || !workspace) throw new AccountError('No active account') return { @@ -218,10 +221,14 @@ export function createSessionClient( } } async function establishSession( - workspaceId?: string + workspaceId?: string, + forceIdentityRefresh = false ): Promise { const ownGeneration = generation - const { identity, key } = await identityAndKey(workspaceId) + const { identity, key } = await identityAndKey( + workspaceId, + forceIdentityRefresh + ) const credential = await runOperation( adapter, adapter.operations.exchange, @@ -240,7 +247,9 @@ export function createSessionClient( schedule(credential) return credential } - async function refresh(): Promise { + async function refresh(options?: { + forceIdentityRefresh?: boolean + }): Promise { const previous = state.phase === 'authenticated' || state.phase === 'refreshing' ? state.credential @@ -248,7 +257,10 @@ export function createSessionClient( if (!previous) throw new AccountError('Not authenticated') publish({ phase: 'refreshing', credential: previous, generation }) try { - return await establishSession(previous.workspaceId) + return await establishSession( + previous.workspaceId, + options?.forceIdentityRefresh + ) } catch (error) { const accountError = error instanceof AccountError @@ -361,7 +373,10 @@ export function createBillingClient( adapter, adapter.operations.balance, { credential: current.credential }, - signal + signal, + async () => ({ + credential: await session.refresh({ forceIdentityRefresh: true }) + }) ) if (!signal.aborted && startGeneration === session.getGeneration()) publish({ phase: 'value', value }) diff --git a/packages/account/src/vue/accountVue.test.ts b/packages/account/src/vue/accountVue.test.ts index 00744cbf858..a5dc1c34520 100644 --- a/packages/account/src/vue/accountVue.test.ts +++ b/packages/account/src/vue/accountVue.test.ts @@ -45,6 +45,16 @@ describe('TP-4 Vue contract', () => { ).toThrow(MissingAccountProviderError) }) + it('regression: CreditsDisplay marks errors as alerts', () => { + render(CreditsDisplay, { + props: { + source: 'props', + state: { phase: 'error', error: new Error('offline') } + } + }) + expect(screen.getByRole('alert').textContent).toBe('Error') + }) + it('TP-4: useCredits returns readonly ref and disposes subscription', () => { const client = billing({ phase: 'value', value: { balance: 7 } }) const Child = defineComponent({ diff --git a/packages/account/src/vue/index.ts b/packages/account/src/vue/index.ts index c6089d918ad..f345ede3e18 100644 --- a/packages/account/src/vue/index.ts +++ b/packages/account/src/vue/index.ts @@ -44,6 +44,10 @@ function renderState(state: Loadable) { return 'Loading' } +function stateAttributes(state: Loadable) { + return state.phase === 'error' ? { role: 'alert' } : undefined +} + export const CreditsDisplay = defineComponent({ name: 'CreditsDisplay', props: { @@ -57,10 +61,14 @@ export const CreditsDisplay = defineComponent({ setup(props) { if (props.source === 'props') { if (!props.state) throw new MissingAccountProviderError() - return () => h('span', renderState(props.state ?? { phase: 'empty' })) + return () => { + const state = props.state ?? { phase: 'empty' } + return h('span', stateAttributes(state), renderState(state)) + } } const state = useCredits(props.provider) - return () => h('span', renderState(state.value)) + return () => + h('span', stateAttributes(state.value), renderState(state.value)) } }) From 8930262e98780714f7d0002bf6977392ec1008ef Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 05:25:04 -0700 Subject: [PATCH 10/26] chore(account): add CODEOWNERS entry for packages/account --- CODEOWNERS | 3 +++ 1 file changed, 3 insertions(+) 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 From ed428aa41c3d22a0adc34c49db5011ba9b29b0f5 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 3 Sep 2026 16:52:59 +0000 Subject: [PATCH 11/26] fix(account): address lifecycle review findings --- .../account/scripts/verify-import-guard.sh | 2 +- packages/account/src/core/account.test.ts | 56 ++++++++++++++++--- packages/account/src/core/index.ts | 36 ++++++++---- packages/account/src/vue/accountVue.test.ts | 34 ++++++++--- packages/account/src/vue/index.ts | 27 ++++----- 5 files changed, 114 insertions(+), 41 deletions(-) diff --git a/packages/account/scripts/verify-import-guard.sh b/packages/account/scripts/verify-import-guard.sh index 0478ae2b178..9cc780c2ded 100644 --- a/packages/account/scripts/verify-import-guard.sh +++ b/packages/account/scripts/verify-import-guard.sh @@ -13,7 +13,7 @@ for forbidden in "@/stores/authStore" "../../src/stores/authStore"; do fi done -if rg -n "from ['\"](pinia|nuxt|astro|firebase)|\b(window|document|localStorage|sessionStorage)\b" "$repo_root/packages/account/src/core" --glob '*.ts'; then +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 diff --git a/packages/account/src/core/account.test.ts b/packages/account/src/core/account.test.ts index 3bef6190006..c1142adfb21 100644 --- a/packages/account/src/core/account.test.ts +++ b/packages/account/src/core/account.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { AccountError, MalformedResponseError, @@ -49,6 +49,7 @@ function adapter(kind: 'map' | 'json' = 'map') { let workspace = 'A' let exchangeBody: unknown = credential('A') let balanceBody: unknown = { balance: 7 } + let balanceStatus = 200 let clearFails = false const key = (value: { namespace: string @@ -99,7 +100,7 @@ function adapter(kind: 'map' | 'json' = 'map') { transport: async (request) => { trace.push(request) return { - status: 200, + status: request.path.includes('balance') ? balanceStatus : 200, body: request.path.includes('balance') ? balanceBody : exchangeBody } } @@ -111,7 +112,10 @@ function adapter(kind: 'map' | 'json' = 'map') { trace, setWorkspace: (value: string) => (workspace = value), setExchange: (value: unknown) => (exchangeBody = value), - setBalance: (value: unknown) => (balanceBody = value), + setBalance: (value: unknown, status = 200) => { + balanceBody = value + balanceStatus = status + }, failClear: () => (clearFails = true) } } @@ -196,10 +200,7 @@ it('TP-2a PM-4: refresh fires at expiry minus five minutes, not one ms earlier', fake.scheduler.advance(299_999) expect(fake.trace).toHaveLength(1) fake.scheduler.advance(1) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() - expect(fake.trace).toHaveLength(2) + await vi.waitFor(() => expect(fake.trace).toHaveLength(2)) }) it('TP-2a S146: transient refresh retains credential and caps retry', async () => { @@ -298,6 +299,9 @@ it('TP-4 PM-3: credits preserve 7, 0, -2 and reject malformed payloads', async ( 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 () => { @@ -315,7 +319,43 @@ it('TP-4 PM-2: a late workspace A balance cannot replace B', async () => { await session.switchWorkspace('B') release?.({ status: 200, body: { balance: 99 } }) await pending - expect(billing.getCreditsState().phase).not.toBe('value') + 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) + 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) + 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 () => { diff --git a/packages/account/src/core/index.ts b/packages/account/src/core/index.ts index 7ef9b84c8f2..23ececd4509 100644 --- a/packages/account/src/core/index.ts +++ b/packages/account/src/core/index.ts @@ -138,6 +138,7 @@ export interface BillingClient { listener: (state: Loadable) => void ): () => void refreshCredits(signal?: AccountAbortSignal): Promise + dispose(): void } const REFRESH_BUFFER_MS = 300_000 @@ -250,6 +251,7 @@ export function createSessionClient( async function refresh(options?: { forceIdentityRefresh?: boolean }): Promise { + const ownGeneration = generation const previous = state.phase === 'authenticated' || state.phase === 'refreshing' ? state.credential @@ -266,12 +268,14 @@ export function createSessionClient( error instanceof AccountError ? error : new AccountError('Refresh failed') + if (generation !== ownGeneration) throw accountError publish({ phase: 'authenticated', credential: previous, generation, refreshError: accountError }) + cancelTimer() timer = adapter.scheduler.schedule( () => { void refresh().catch(() => undefined) @@ -350,11 +354,15 @@ export function createBillingClient( state = next listeners.forEach((listener) => listener(state)) } - session.subscribe((next) => { + const unsubscribeSession = session.subscribe((next) => { if (next.phase !== 'authenticated' && next.phase !== 'refreshing') publish({ phase: 'idle' }) }) return { + dispose() { + unsubscribeSession() + listeners.clear() + }, getCreditsState: () => state, subscribeCredits(listener) { listeners.add(listener) @@ -378,17 +386,23 @@ export function createBillingClient( credential: await session.refresh({ forceIdentityRefresh: true }) }) ) - if (!signal.aborted && startGeneration === session.getGeneration()) - publish({ phase: 'value', value }) + if (signal.aborted || startGeneration !== session.getGeneration()) { + publish({ phase: 'idle' }) + return + } + publish({ phase: 'value', value }) } catch (error) { - if (!signal.aborted && startGeneration === session.getGeneration()) - publish({ - phase: 'error', - error: - error instanceof AccountError - ? error - : new AccountError('Balance failed') - }) + if (signal.aborted || startGeneration !== session.getGeneration()) { + publish({ phase: 'idle' }) + return + } + publish({ + phase: 'error', + error: + error instanceof AccountError + ? error + : new AccountError('Balance failed') + }) } } } diff --git a/packages/account/src/vue/accountVue.test.ts b/packages/account/src/vue/accountVue.test.ts index a5dc1c34520..fa7b9cc806e 100644 --- a/packages/account/src/vue/accountVue.test.ts +++ b/packages/account/src/vue/accountVue.test.ts @@ -1,5 +1,5 @@ import { render, screen } from '@testing-library/vue' -import { defineComponent, h, provide } from 'vue' +import { defineComponent, h, nextTick, provide } from 'vue' import { describe, expect, it, vi } from 'vitest' import type { BillingClient, @@ -13,15 +13,22 @@ import { useCredits } from './index' -function billing( - state: Loadable -): BillingClient & { unsubscribe: ReturnType } { +function billing(state: Loadable): BillingClient & { + publish(state: Loadable): void + unsubscribe: ReturnType +} { const unsubscribe = vi.fn() + let listener: ((state: Loadable) => void) | undefined return { unsubscribe, + dispose: vi.fn(), getCreditsState: () => state, - subscribeCredits: () => unsubscribe, - refreshCredits: async () => undefined + subscribeCredits: (next) => { + listener = next + return unsubscribe + }, + refreshCredits: async () => undefined, + publish: (next) => listener?.(next) } } @@ -55,13 +62,13 @@ describe('TP-4 Vue contract', () => { expect(screen.getByRole('alert').textContent).toBe('Error') }) - it('TP-4: useCredits returns readonly ref and disposes subscription', () => { + it('TP-4: useCredits reflects updates and disposes subscription', async () => { const client = billing({ phase: 'value', value: { balance: 7 } }) const Child = defineComponent({ setup() { const credits = useCredits() expect(credits.value.phase).toBe('value') - return () => h('span') + return () => h('span', renderCredits(credits.value)) } }) const Host = defineComponent({ @@ -71,7 +78,18 @@ describe('TP-4 Vue contract', () => { } }) const result = render(Host) + client.publish({ phase: 'value', value: { balance: 0 } }) + await nextTick() + expect(screen.getByText('0')).toBeTruthy() + client.publish({ phase: 'error', error: new Error('offline') }) + await nextTick() + expect(screen.getByText('error')).toBeTruthy() result.unmount() expect(client.unsubscribe).toHaveBeenCalledOnce() }) }) + +function renderCredits(state: Loadable) { + if (state.phase === 'value') return String(state.value.balance) + return state.phase +} diff --git a/packages/account/src/vue/index.ts b/packages/account/src/vue/index.ts index f345ede3e18..16bccc1c589 100644 --- a/packages/account/src/vue/index.ts +++ b/packages/account/src/vue/index.ts @@ -1,5 +1,5 @@ import { defineComponent, h, inject, onScopeDispose, readonly, ref } from 'vue' -import type { InjectionKey, PropType, Ref } from 'vue' +import type { InjectionKey, Ref } from 'vue' import { AccountError } from '../core/index.js' import type { BillingBalanceResponse, @@ -48,17 +48,14 @@ function stateAttributes(state: Loadable) { return state.phase === 'error' ? { role: 'alert' } : undefined } -export const CreditsDisplay = defineComponent({ - name: 'CreditsDisplay', - props: { - source: { type: String as PropType<'props' | 'provider'>, required: true }, - state: { - type: Object as PropType>, - required: false - }, - provider: { type: Object as PropType, required: false } - }, - setup(props) { +const creditsDisplayRuntimeProps: ('source' | 'state' | 'provider')[] = [ + 'source', + 'state', + 'provider' +] + +export const CreditsDisplay = defineComponent( + (props: CreditsDisplayProps) => { if (props.source === 'props') { if (!props.state) throw new MissingAccountProviderError() return () => { @@ -69,7 +66,11 @@ export const CreditsDisplay = defineComponent({ const state = useCredits(props.provider) return () => h('span', stateAttributes(state.value), renderState(state.value)) + }, + { + name: 'CreditsDisplay', + props: creditsDisplayRuntimeProps } -}) +) export { accountPackageId } from '../core/index.js' From 500048cab140a3de16183e06d1130874c576a29c Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 3 Sep 2026 02:01:10 -0700 Subject: [PATCH 12/26] feat(account): add billing proof of concept [PoC do not merge] Adds provider-neutral billing clients, state, polling, safety copy, Vue projection, and evidence tests. --- .../account/src/core/adapters/stripe.test.ts | 12 ++ packages/account/src/core/adapters/stripe.ts | 10 + .../account/src/core/billing/billing.test.ts | 180 ++++++++++++++++++ packages/account/src/core/billing/client.ts | 125 ++++++++++++ packages/account/src/core/billing/commands.ts | 112 +++++++++++ packages/account/src/core/billing/copy.ts | 55 ++++++ packages/account/src/core/billing/index.ts | 8 + packages/account/src/core/billing/poller.ts | 94 +++++++++ packages/account/src/core/billing/reasons.ts | 20 ++ packages/account/src/core/billing/reducer.ts | 77 ++++++++ .../account/src/core/billing/singleFlight.ts | 13 ++ packages/account/src/core/billing/types.ts | 148 ++++++++++++++ packages/account/src/core/index.ts | 1 + packages/account/src/packedTarball.test.ts | 4 +- .../account/src/vue/CheckoutSteps.test.ts | 31 +++ packages/account/src/vue/CheckoutSteps.ts | 52 +++++ packages/account/src/vue/billing.ts | 57 ++++++ packages/account/src/vue/index.ts | 4 + .../vue/localStorageBillingOperationStore.ts | 25 +++ 19 files changed, 1026 insertions(+), 2 deletions(-) create mode 100644 packages/account/src/core/adapters/stripe.test.ts create mode 100644 packages/account/src/core/adapters/stripe.ts create mode 100644 packages/account/src/core/billing/billing.test.ts create mode 100644 packages/account/src/core/billing/client.ts create mode 100644 packages/account/src/core/billing/commands.ts create mode 100644 packages/account/src/core/billing/copy.ts create mode 100644 packages/account/src/core/billing/index.ts create mode 100644 packages/account/src/core/billing/poller.ts create mode 100644 packages/account/src/core/billing/reasons.ts create mode 100644 packages/account/src/core/billing/reducer.ts create mode 100644 packages/account/src/core/billing/singleFlight.ts create mode 100644 packages/account/src/core/billing/types.ts create mode 100644 packages/account/src/vue/CheckoutSteps.test.ts create mode 100644 packages/account/src/vue/CheckoutSteps.ts create mode 100644 packages/account/src/vue/billing.ts create mode 100644 packages/account/src/vue/localStorageBillingOperationStore.ts 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..15e3b5a52ac --- /dev/null +++ b/packages/account/src/core/billing/billing.test.ts @@ -0,0 +1,180 @@ +import { describe, expect, it, vi } from 'vitest' +import { + billingCopyKeys, + createBillingCopy, + defaultBillingCopy +} from './copy.js' +import { createBillingApiClient } from './client.js' +import { 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('TP-6 PM-8 PM-10 EC-P-1: routes subscribe through the transport with an idempotency header', async () => { + const transport = vi.fn(async () => ({ + status: 200, + body: { billing_op_id: 'op' } + })) + const client = createBillingApiClient({ transport }) + await client.subscribe( + { + plan_slug: 'pro', + return_url: 'https://host/ok', + cancel_url: 'https://host/no' + }, + 'intent-1' + ) + expect(transport).toHaveBeenCalledWith( + expect.objectContaining({ + path: '/api/billing/subscribe', + headers: { 'Idempotency-Key': 'intent-1' } + }) + ) + }) + it.each<[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()}