Repository navigation
feat(account): add @comfyorg/account with session core, credits client, and Firebase identity - #17127
MaanilVerma wants to merge 248 commits into
Conversation
`apps/website` cannot import from the main app's `src/`: its tsconfig maps only `@/* -> ./src/*` and the editor is not a package. So the Workshop pages, which show a credit price per model run, had no way to reach `CREDITS_PER_USD` and copied it instead — there is already a second `211` in `apps/website/src/config/credits.ts` on the workshop branch. The module was a good candidate to share as-is: pure conversion and `Intl` formatting, no Vue, no app imports. This follows the move `formatUtil` and `networkUtil` already made. The file lands in the package, and `vite.config.mts` plus `tsconfig.json` alias the old `@/base/credits/comfyCredits` path onto it, so all 17 importers are untouched — including three that `vi.mock` that exact path, which keeps working for the same reason it does for `formatUtil` today.
The coverage test asserts every page under src/pages appears in llms.txt, and /workshop does not, because it is behind a launch flag and carries noindex on every route. Adding it to EXCLUDED_PAGES would have worked and left a trap: the entry would have to be removed by hand at launch, in a different file from the flag that lifts noindex, or llms.txt would silently keep omitting a page that is now public. A page kept out of search indexes has no business in llms.txt either, so the test now derives that half of its exclusions from isNoindexPathname. Lifting noindex at launch makes this test start requiring the page in the same change.
Everything on Workshop is a Router partner model, and the snippet builder said so three times: the TypeScript one imports @comfyorg/sdk, the Python one imports comfy_sdk, and the HTTP one hardcodes the Router URL. Cloud workflows and deployed endpoints are next, and none of those three carry over. A workflow has no comfy.models.run equivalent at all. This puts one interface in front of that. A model resolves to a run target, and the target owns both which snippet languages it can offer and how to build them. The page and the form keep dealing only in fields and values, so neither learns which backend it is describing. Router is still the only implementation and its snippets are byte for byte what they were, which a test asserts directly against the builder. The model record gains an optional runTarget that the current generator does not emit, so the committed catalog is unchanged and every entry resolves to Router by absence rather than by a regenerated field.
WorkshopForm.vue had no test at all, which put the model-page diff under the website's 80% patch-coverage gate. The behaviour worth pinning is the seeding branch. The form is handed an empty value bag when a page first renders, and has to turn that into the model's schema defaults; re-render it after an edit and it must leave the visitor's values alone. Getting that backwards either sends a request with no aspect ratio or throws away what someone typed, and neither shows up as a type error.
One committed blob of 31,674 lines was the wrong shape and got worse with every field: adding the generated form fields would have taken the same file past 51,000. A one-model change produced an unreviewable diff, and the shape was written down twice, once as hand-rolled decoders in the generator and once as interfaces the site read. The catalog is now an Astro content collection: one file per model under src/content/workshop-models, a Zod schema in content.config.ts, and a small manifest holding the source ref. The largest model file is 8 KB, so a model change is a diff on that model. The schema is the only description of the shape. The generator validates against it and the site reads through it, so decodeModel and decodeRole are gone along with the parallel interface, and the generator is 134 lines of parse, project and write. Making Zod the boundary immediately found something the old decoder was hiding. decodeRole rebuilt each role from known fields, silently dropping `extras`, which six Luma roles use to describe base64 input as an alternative to a URL. Nothing renders it yet, but it is real API surface and it is now carried rather than lost a second time. Those six models are the only semantic change in the regenerated catalog; the other 262 are identical. Verified by running the generator against the partner client rather than hand-editing the data.
…o ben/workshop-browse
The catalog moved to a content collection, so the browse page no longer imports a committed blob. It reads the collection at build time and hands the island card-sized records. That also fixes what the previous shape leaked. Each entry carries the model's full input schema under `parameters`, which is the bulk of the record and which a card has no use for. Importing the catalog into a module the island bundled meant shipping all of it to the browser. `toBrowseModel` is now an explicit projection, and a test asserts the projection has no `parameters` key so a future field cannot quietly ride along. The catalog-integrity test reads the collection from disk and parses each file through the schema, so it still fails on a missing or duplicated model and now also fails on one that does not match the schema.
…them
Persisting the derived fields duplicated what `parameters` and `roles`
already say and took the catalog from 31,674 lines to over 51,000. With
the collection in place they are derived from an entry instead, so the
generator writes only what the Router client gives it and the field
policy lives in code where it can be read and tested.
Two conversions were also wrong, and both narrowed what the Router
actually accepts.
A schema shaped `anyOf: [{enum: [...]}, {type: 'string'}]` means "one of
these, or anything". Collecting the enum and ignoring the open variant
turned four fields into closed selects: `voice` on ElevenLabs and Fish
Audio, and `avatar_id` on HeyGen. Those list stock options but also take
an id you cloned yourself, so a closed select made your own voice
unreachable. They are now text fields carrying the listed values as
suggestions.
A float with no `multipleOf` accepts any precision. Defaulting to a step
of 0.01 made 73 fields reject values the provider allows, so the step is
now only set when the schema sets it.
Both are covered directly, and a catalog-wide test asserts no field ends
up with a 0.01 step its schema did not ask for.
…ben/workshop-model-form
The detail page read a single generated JSON blob and a `fields` array baked into it. Both are gone: it now reads the per-model content collection, and derives the form fields at build time from the schema the provider actually publishes. Two field unions had grown in parallel, one per module. They are now one, kept next to the code that derives it, so the page picks up both of the fixes that union carries: values a model merely suggests render as a typable field with completions rather than a closed dropdown, and number fields no longer get a step the provider never asked for. Related models are passed in from the page instead of being read from a module-level array, which is what let the module stop importing the blob.
…n/workshop-model-page
…sable 200s; session module is the entry - a sign-out or a different user abandons the in-flight mint so a later caller cannot join a request made with the previous identity's token, and a commit that crossed an identity epoch is refused except for the popup mint the port then confirms - an exchange response with an empty token or an expiry already inside the fresh margin is an exchange failure, not a session - ./session points at session.ts; the core barrel is gone - @testing-library/user-event is declared where the package uses it
…ng commit and keeps a short-but-future token The website chain still wrote storage inside mint and rejected any token inside the fresh margin. Align it with the cloud chain: a superseded or signed-out mint no longer writes the credential, and a short server token is accepted and left to the valid-on-read path, only a past or empty one is refused.
createSessionClient no longer owns the network/parse/validate: that is a standalone exchangeToken the client calls through a thin wrapper, which is the pure exchange boundary the review asked for. Behaviour unchanged; the 255 package tests pass as-is.
It only returned response.ok; the one caller inlines the check. (DrJKL M7a)
SessionSnapshot gains a 'pending' phase for before the identity port has delivered even once, and drops the 'settled' boolean overload; 'signed-out' now means a delivered null. Hosts read one discriminant instead of phase+settled. (DrJKL M1)
…ptor
Replace the parallel inFlight/inFlightUid/inFlightForced locals with a single optional {promise,uid,forced} descriptor, cleared in one place. Behavior-preserving; session tests pass unedited. (DrJKL M3, base part; the commit() consolidation lands at the cloud tip where the adoption/refresh commit blocks are.)
dante01yoon
left a comment
There was a problem hiding this comment.
The billing/package-boundary changes are mostly in place, but the base session client still has a forced-remint race that can restore the stale token. I also left one API-boundary question because the public export does not match the stated follow-up.
| return undefined | ||
| } | ||
| if (result.status === 'ok') { | ||
| credential = result.session |
There was a problem hiding this comment.
issue: An older ordinary mint can overwrite a newer forced remint. remint() deliberately starts a second request while a non-forced mint is in flight, but both refreshWith() calls commit unconditionally here. If the forced response wins and the old response finishes later, this line republishes and persists the stale token that prompted the remint. The existing test releases the old request but only checks the forced return value; could we guard the commit with a mint sequence and assert the final getToken() plus stored token?
There was a problem hiding this comment.
Done — ported the mint-sequence winner guard to the base: each mint takes a monotonic id and a commit is rejected unless it is still the newest, so a slow ordinary mint can no longer republish or persist its stale token over a forced remint. b4762c1c91. Locked by a red-green regression test ("does not republish or persist an older mint that lost to a forced remint").
| * fake through `@comfyorg/account/testing`. `attachIdentity` accepts only | ||
| * the branded form. | ||
| */ | ||
| export interface IdentityPort<TUser extends AccountUser = AccountUser> { |
There was a problem hiding this comment.
question: The follow-up says IdentityPort is no longer publicly exported, but ./session points directly at this file, so this exported interface remains available from @comfyorg/account/session in addition to /testing. The private brand does prevent arbitrary ports from reaching attachIdentity, so this is not the race blocker above, but is the public type export intentional?
There was a problem hiding this comment.
Done — moved IdentityPort out of ./session into core/identity.ts, so it is no longer exported from @comfyorg/account/session; the /testing seam re-exports it from there. The brand + createTestIdentity remain the public seam. 747a37bc39 (type-only; package suite green).
dante01yoon
left a comment
There was a problem hiding this comment.
Strict package/consumer-boundary follow-up found two additional blockers beyond the already-posted forced-remint race.
| if (!active) return | ||
| identityEpoch += 1 | ||
| identitySettled = true | ||
| if (!next || next.uid !== currentUser?.uid) abandonInFlight() |
There was a problem hiding this comment.
issue: A same-UID identity event can still adopt a mint started before that identity event. This only abandons the shared mint when the UID changes; the callback then starts refreshWith() for the replacement user and joins the old same-UID request. The original waiter is epoch-rejected, but this new waiter captured the new epoch and commits the old response. This can preserve stale claims/session state across same-user reauthentication. Could every identity event make the prior mint unjoinable, with a regression test using two user objects with the same UID?
There was a problem hiding this comment.
Done — abandonInFlight() now runs on every identity event, not only on a uid change, so a same-uid re-auth starts a fresh mint instead of joining (and committing) the mint started under the prior identity. 07b95a7766. Red-green regression test: "makes a same-uid re-auth mint afresh instead of adopting the in-flight mint".
| typeof body === 'object' && | ||
| body !== null && | ||
| 'message' in body && | ||
| body.message === MISSING_CUSTOMER_MESSAGE |
There was a problem hiding this comment.
issue: This infers backend customer state from the literal display message Failed to find customer, and exports the recovery from the supposedly auth/session-only package. A copy change disables recovery; reuse of the text on another 409 can provision and replay a customer/payment request incorrectly. This also bypasses the contract-first boundary because no deterministic error code/schema distinguishes this state. Could this remain out of the V1 account package until the backend exposes a generated, machine-readable missing-customer code?
There was a problem hiding this comment.
Agreed the message match isn't the contract-first end state. The constraint today: the auth middleware returns this as echo.NewHTTPError(409, "Failed to find customer") — a plain message with no machine-readable code — so a message match is currently the only signal available to detect it.
We've fenced it to contain exactly the misfires you flag: it fires only on a 409, only for /customers/*, only while the requesting identity is unchanged, and it provisions at most once (deduped) before a single retry — so a business-level 409, or the same text reused on another endpoint, can't blind-retry a payment request.
It's also a fallback rather than the primary path now: the backend provision-on-reads (that 409 is treated as a fixed bug server-side), so this should rarely fire. We'll switch detection to a generated missing-customer code the moment the backend exposes one on the 409 — that's the proper fix and we'll track it; keeping the self-heal in V1 as the defensive net until then.
The identity handler only abandoned the in-flight mint on a uid change, so a same-uid re-auth could adopt a mint started under the previous identity and commit its stale response. Abandon on every identity event; a same-uid re-auth now mints for itself. Regression test (red without the fix). (Jaewon r3979631200 / DrJKL A2)
refreshWith committed unconditionally, so a slow ordinary mint could overwrite and persist a token already superseded by a newer forced remint. Stamp each mint with a monotonic id (via MintHandle) and commit only the newest; a lost race returns the winning credential rather than republishing the stale one. Regression test asserts getToken + stored token (red without the guard). (Jaewon r3979426467 / DrJKL A1)
…e locale 4c30629 gave the workspaceAuth.errors.tokenExchangeFailed locale entry a {error} interpolation but left the package reference table on the old string, so the copy-parity test that pins the two together (workspaceAuthStore.copy.test) fails. The table is documented as extracted verbatim from that locale entry, so bring it back in step.
dante01yoon
left a comment
There was a problem hiding this comment.
Re-reviewed the new head. The forced-remint winner guard, same-UID identity invalidation, IdentityPort export boundary, and cache-precedence fixes are sound with focused tests. Approval is still blocked by the existing customerRecovery finding: missing-customer state remains inferred from a literal backend message and exported from the auth/session-only package. CI is also still running.
|
@dante01yoon Missing Customer Case: Agreed the message match isn't the contract-first end state. The constraint today: the auth middleware returns this as echo.NewHTTPError(409, "Failed to find customer") — a plain message with no machine-readable code — so a message match is currently the only signal available to detect it. We've fenced it to contain exactly the misfires you flag: it fires only on a 409, only for /customers/*, only while the requesting identity is unchanged, and it provisions at most once (deduped) before a single retry — so a business-level 409, or the same text reused on another endpoint, can't blind-retry a payment request. It's also a fallback rather than the primary path now: the backend provision-on-reads (that 409 is treated as a fixed bug server-side), so this should rarely fire. We'll switch detection to a generated missing-customer code the moment the backend exposes one on the 409 — that's the proper fix and we'll track it; keeping the self-heal in V1 as the defensive net until then. |
## Summary One shared sign-in system for comfy.org and cloud.comfy.org: a new `@comfyorg/account` package holds the session core, and both apps adopt it instead of each hand-rolling their own auth. This PR combines the ten PRs that built it, already reviewed and individually CI-green, into one branch for final review. ## Combined from | # | Title | Highlights | |---|---|---| | [#17127](#17127) | feat(account): add `@comfyorg/account` with session core, credits client, and Firebase identity | The package itself: valid-on-read session mint/refresh with a 5-minute floor, uid-keyed cache, single-flight dedupe, an identity-epoch guard so a stale mint can't publish after sign-out. Shared credits client, Firebase identity entry, password-rule and social-button components, shared error copy. No consumer yet. | | [#17120](#17120) | refactor(auth): adopt `@comfyorg/account` in cloud sign-in | Cloud repoints its sign-in, Turnstile, and password-rule code to the package and deletes the inline originals. Two deliberate account-enumeration closures: an unknown-email password reset now resolves as sent, and `user-not-found`/`wrong-password` collapse into one invalid-credential message. | | [#16980](#16980) | feat(auth): sign in to Comfy from comfy.org with Google or GitHub | Google/GitHub sign-in on comfy.org behind the `workshop-auth` flag, matching the cloud app's actual behavior (error copy, timeout handling, funnel events), not just its look. | | [#16983](#16983) | feat(workshop): establish a signed-in workspace session | A minted, auto-refreshed workspace session for signed-in visitors. Fixes a redirect race where a fast page could reach `signedIn` before its own redirect ran, and closes an open-redirect hole in the post-sign-in return URL. | | [#16984](#16984) | feat(website): show the signed-in account and credits in the site header | Account and credit balance in the header, desktop and mobile, with a real four-state UI (sign-in link, error retry, signing-in, signed-in) instead of the retry and loading states looking identical. | | [#16986](#16986) | feat(workshop): keep the form across sign-in and purchase round trips | A Workshop model form's values survive a sign-in or purchase round trip instead of being lost. Stashed values are validated against the current field's kind before restoring, so a changed form degrades to defaults rather than injecting a mismatch. | | [#16987](#16987) | feat(auth): sign in or create a Comfy account with email and password | Email/password sign-in, sign-up, and forgot-password on comfy.org. Sign-in and sign-up switch panels without a page reload. Firebase loads lazily inside the submit handler so a flag-off visitor never ships the chunk. | | [#17125](#17125) | feat(account): cloud-host capabilities for the session client | Grows the package with what cloud's unified auth needs: workspace-targeted minting, an opt-in refresh scheduler with backoff, `invalidate()` for scope changes, and credential preservation across a transient mint failure. No `apps/website` changes. | | [#17126](#17126) | refactor(cloud): unified auth path delegates to `@comfyorg/account` | Cloud's flag-gated (`unified_cloud_auth`) mint and refresh internals become wrappers over the shared client: one lifecycle implementation for both apps. Identity reaches the client through a Firebase-entry port rather than a hand-rolled push from Pinia. Carries ADR-AUTH-IDENTITY-0028. | | [#17163](#17163) | feat(account): cross-tab refresh coordination for the unified session | With multiple tabs open, one tab refreshes the session token and the others adopt the result over BroadcastChannel, instead of every tab minting its own copy. A tab that loses its leader falls back to a self-mint after a short random hold. | ## Breaking None across the stack. `unified_cloud_auth` and `workshop-auth` both default off, so unflagged builds see no behavior change. Existing session storage keys, telemetry events, and deeplinks are unchanged. ## Review Focus Two merge conflicts came up assembling the ten branches into one, both resolved by hand: - `useWorkspaceAuth.test.ts`: main had picked up an unrelated global-Pinia test migration after this stack's last sync, colliding with #17126's newer event-driven identity-port mock. Took #17126's version, verified as a strict superset of every test on the stack's other branches. - `packages/account/package.json`: two branches added different `exports` entries (`./web`, `./SocialAuthButtons.vue`) for files that both exist in the merged tree. Kept both. The identity-port wiring in ADR-AUTH-IDENTITY-0028 is worth a close look: `authStore` no longer pushes identity into the session client, and every mint waits for the port to have delivered the app's current user instead. Out of scope: cross-domain session (a comfy.org sign-in carrying over to cloud.comfy.org and platform.comfy.org) needs backend changes not yet landed (cloud #8601, #8602). ## Testing Each of the ten PRs shipped its own automated coverage and manual checklist; combined here rather than repeated per-file. Automated, per PR: package suite 247/247 (#17127, #17125), cloud adoption suites (`authStore.test.ts`, `useAuthActions.test.ts`, Turnstile) unchanged (#17120), website suite 212/1504 plus e2e (#16980, #16983, #16984, #16986, #16987), unified-lifecycle suite 94 tests through the fake identity port with zero edits to four dependent suites (#17126), scheduler and cross-tab channel suites plus a live two-tab Playwright spec (#17163). Typecheck and lint clean on every branch and on the combined result. **Combined manual QA checklist** (carried over from the individual PRs, needs a live Firebase project and backend): - [ ] Sign in with Google and GitHub from comfy.org, confirm the popup, scopes, and redirect match cloud - [ ] Open the sign-up dialog with Turnstile enabled, confirm the challenge renders and unblocks submit; trigger an expired/failed challenge and confirm the error renders - [ ] Create an account with email/password on comfy.org, then sign in with it - [ ] Request a password reset for a registered email, confirm you get the mail; request one for an unregistered email, confirm the identical "sent" state - [ ] Enter a wrong password, confirm the error doesn't reveal whether the email is registered - [ ] Click between sign-in and sign-up a few times, confirm no reload and Back/Forward track the mode - [ ] Sign in, confirm the header shows the account with a minted session and credit balance; refocus the tab and confirm a silent refresh - [ ] Fill in a Workshop form, sign in, confirm your values are back on return; include a media field and confirm it isn't restored with a stale filename - [ ] Visit a `returnTo` with an embedded control character pointing off-site, confirm you land on `/workshop/`, not the external site - [ ] Sign in, then reload `/login/`, confirm you land on the home page without the form flashing - [ ] Flag-on cloud backend: login, workspace switch, shortened-TTL expiry, 401 replay, logout - [ ] `DISTRIBUTION=cloud` build, sign in, open two tabs, confirm one tab holds the refresh lock via `navigator.locks.query()`; close the leader tab and confirm the lease moves to the survivor --------- Co-authored-by: Maanil Verma <maanil@comfy.org> Co-authored-by: benjcooley <benjcooley@gmail.com>
|
The combined unified-auth PR (#17283) has been merged to main. Keeping this open for tracking the remaining e2e work. |
Summary
Introduces
@comfyorg/account, named for the account layer the TDD describes and that this package grows into; this stack ships its session and identity half. It contains a framework-free session core (Firebase identity to workspace Cloud JWT), a credits read client, a Firebase identity module, and the shared auth copy, password-rule, and Turnstile surfaces both hosts used to hand-roll separately.Changes
core/session.ts:createSessionClient, valid-on-read freshness (never resolves with under 5 min left), uid-keyed cache, single-flight mint dedupe, identity-epoch guard so a mint can't publish after sign-out.core/credits.ts:createBillingClient, identity-keyed dedupe, one 401 re-mint retry.core/customerRecovery.ts: the cloud app's missing-customer 409 rule (provision once, retry the read once), shared so hosts on the/customers/*shape adopt the same sequence instead of reimplementing it.firebase/index.ts:createFirebaseIdentity, popup sign-in mirroringauthStore.ts's scopes and prompt. A host can bind the entry to anAuthit already holds instead of initializing a second Firebase app, and none of the network-shaped actions carry a timeout unless the host asks for one, matching how the cloud app runs them today.PasswordRules.vueandSocialAuthButtons.vue: unstyled, prop-driven components so both hosts render the same rule list and provider buttons without duplicating the markup, styling stays with each host.authErrorMessagenow resolves against either a shipped locale or a host's own copy table, so a host on its own i18n system gets the same code and fallback resolution the shipped tables get.auth/user-not-foundandauth/wrong-passwordresolve to the invalid-credential line in every locale, and a password reset for an unknown email resolves as sent, which is how Firebase answers with email enumeration protection on.Breaking: None. New package, no existing importer touched here.
Review Focus
session.tsvs.workspaceAuthStore.ts'srequestToken: any behavioral divergence beyond the documented timeout and freshness additions is a bug.Testing
Automated: 247/247 package tests, typecheck and lint clean.
Manual: none. This PR has no consumer, #17120 carries the manual sign-in checklist.