Repository navigation
Framework-agnostic method clients, with React and Svelte on top - #983
Draft
mmailaender wants to merge 34 commits into
Draft
mmailaender wants to merge 34 commits into
mmailaender wants to merge 34 commits into
Conversation
… a store shape Bindings for other frameworks need the types that `AuthClientConfig` refers to and a way to keep method secrets. Today they derive the types from the config and re-implement the key namespacing of `NamespacedStorage`. - `@convex-dev/auth/browser` exports `AmbientSignInClient`, `AmbientSignInContext`, `AuthSignInApi`, `ConvexMutationApi`, `SignInFunction`, `SignInStorage`, `SignInValues`, `SignInValuesReader`, and `ReadableStore`. - `AuthClient.methodStorage` is a public `SignInStorage` over the namespaced session storage. It is the smallest surface the email + password flows need (their link secrets live there, under unchanged keys), and the one a binding needs for a method of its own. `AuthClient.storage` and `NamespacedStorage` stay internal. - `ReadableStore<T>` (`get` + `subscribe`) is the state shape of the method clients that follow. `useSyncExternalStore` takes it as is, and Svelte, Vue and Solid adapt it in a few lines. `react/store.ts` has the React read. - The passkey flows take a `ConvexMutationApi` instead of a `ConvexReactClient` (a `ConvexReactClient` satisfies it). - ESLint rejects an import of React, `convex/react`, `next`, or a module of the React bindings from `src/browser`, `src/lib`, and the `.ts` modules of `src/methods` (except the OAuth providers' `react.ts`).
`oauth()` was only reachable through `@convex-dev/auth/methods/oauth/react`,
which imports React, so a binding for another framework had to copy it.
- `@convex-dev/auth/methods/oauth/browser` exports `oauth()`, its result and
error types, and `createOauthState(authClient)`, whose `flowError` is a
`ReadableStore`. `createOauthSignIn` stays `@internal`, like
`useOauthSignIn`, until the API for custom providers is stable.
- `@convex-dev/auth/methods/{google,apple,github}/browser` export
`createSignInWith<Provider>({ authClient, api })`, the counterparts of the
`useSignInWith<Provider>` hooks.
The entries are named `browser` after `@convex-dev/auth/browser`, the
framework-agnostic client of the core: `methods/<method>/react` is the React
binding, `methods/<method>/browser` the client any binding wraps, and
`methods/<method>` (`index.ts`) stays the values that the backend shares
with the clients in any runtime. The OAuth client reads `window` and
navigates, so it doesn't belong in `index.ts`.
Each flow of a method gets a factory that takes what it needs
(`{ authClient, signInApi, api }`) and returns plain async functions plus a
`ReadableStore` for `pending`. A client reads its options when it uses them,
so a binding can pass getters.
- `@convex-dev/auth/methods/username-password/browser`:
`createSignInWithUsernamePassword` and `createSignUpWithUsernamePassword`.
They return the results the hooks return, with a thrown error folded into
`OTHER_ERROR`.
- `methods/anonymous/browser.ts`: `createSignInAnonymously`. Not in the
`exports` map, like the rest of the anonymous method.
The React hooks wrap the factories. `useMethodClient` (in `react/store.ts`)
makes one client per hook instance, so each form keeps its own `pending`,
and hands it the options of the latest render, so its callbacks run with the
latest arguments like the old `useCallback`s did. `useReadableStore` reads a
store with `useSyncExternalStore`. No behaviour change for the hooks.
`@convex-dev/auth/methods/email-password/browser` exports a factory per flow: `createSignInWithEmailPassword`, `createSignUpWithEmailPassword`, `createCompleteSignUpWithEmailPassword`, `createStartPasswordRecovery`, `createCompletePasswordRecovery`, `createStartChangeEmail`, and `createCompleteChangeEmail`, with the result and state types the hooks return. The link state machines and their secrets move into the shared layer. The secrets stay under their keys, now through `AuthClient.methodStorage`. - A landing page client has a `start()` that presents the link once the `AuthClient` has loaded, and returns a cleanup that cancels a start still waiting for it. It runs once per client, which keeps the StrictMode guarantee of the hooks. - The password-reset client leaves the `checkPasswordRecovery` subscription to the binding, which owns the Convex client: `checkArgs()` gives the query arguments (or `"skip"`), and `stateFor(check)` the state of the page for the latest result. `progress` tells the binding when to render again. - The mutations that mint no session take a `ConvexMutationApi`. The hooks pass the client of the surrounding `ConvexProvider`, and still throw the error of `useMutation` without one. The hooks wrap the factories, and keep their state machine per instance. No behaviour change for the hooks.
…ents `@convex-dev/auth/methods/username-passkey/browser` exports the passkey method without React, in three layers: - The clients of a page: `createSignInWithUsernamePasskey` (the login form: the identifier-first flow and autofill, with `pending` and `autofill` as `ReadableStore`s and a `startAutofill()` that returns its stop), `createAddPasskey` and `createRemovePasskey`. - Their building blocks: `createPasskeyAutofill` (the conditional-mediation loop with its pause/resume gates, the challenge refresh, and `available`/`status`/`lastError`), `createPasskeyCeremonySlot` (one modal ceremony at a time, `ALREADY_PENDING`, the autofill pause around it), and the flows `runSignInOrSignUpFlow`, `runAddPasskeyFlow`, `runRemovePasskeyFlow`. - The ceremonies: `browserCeremonies` and the functions it bundles, `resolveCeremonies` and `foldClientError`, with the wire types of the passkey component and the result types of the method's functions. The autofill loop and the ceremony slot move out of `react_impl.tsx` into `autofill.ts`, unchanged in behaviour; `usePasskeyAutofill` and `usePasskeyCeremonySlot` wrap them and keep their signatures. The sign-in and management hooks wrap the new clients, one per hook instance, so the pauses still hold across an effect restart. `autofill.ts`, `signInClient.ts` and `management/managementClient.ts` take the ceremonies as an option and never import `client.ts` or `@simplewebauthn/browser`, so `react-custom.tsx` still doesn't either. Only `browser.ts` and `react.tsx` bring in the browser ceremonies.
- CHANGELOG: an Unreleased entry for the `browser` entries of the methods, the new `@convex-dev/auth/browser` exports, and `AuthClient.methodStorage`. - The FAQ entry about other frameworks says how to build a binding on `@convex-dev/auth/browser` and the `methods/<method>/browser` entries. - AGENTS.md lists `browser.ts` in the layout of a method, and the ESLint rule that keeps React out of the framework-agnostic modules.
- Autofill locks out the modal sign-in before it publishes "signingIn": store listeners run synchronously, and one that called signIn could otherwise start a modal flow next to the autofill assertion. - A second start() of the autofill controller stops the first loop, and a late stop of a stopped loop no longer aborts the running one. - AuthClient.methodStorage refuses the token keys and the ambient sign-ins' prefix. - useMethodClient hands a client the options of committed renders only. - The OAuth provider clients read their options when signing in, like the other method clients. - Note that ReadableStore is not Svelte's store contract. - Remove react/functionReference.ts, which nothing uses any more.
…very code - useCompletePasswordRecovery subscribes with the emailCode of the render again. The client reads the options of committed renders, which lagged one render behind for the query arguments. - Autofill counts its running verifications: a loop stopped mid-verification no longer clears the lock of a newer loop's pick, and a new loop waits for that verification before it asks for another pick. - A stop settles the autofill state: "idle" when a request waited, and the end of the pick when one verified, instead of leaving "signingIn" (and a pending sign-in client) for good. - A thrown verification unlocks before it publishes "stopped". - The OAuth provider clients' signIn rejects instead of throwing. - CHANGELOG: list SignInValues and SignInValuesReader, and the refused keys.
…r loop - A stop publishes "idle" a microtask later, and only when no loop started in the meantime: an effect's cleanup followed by its next run keeps "waiting", as on main. - When a stopped loop's pick ends while a newer loop runs, the state moves to "waiting", so a newer loop parked on a pause doesn't show "signingIn" (and a pending sign-in) until the resume. - Document the "idle" state after a stop.
…ts its end - disable() stops a running loop first: its request stayed pending, and a pick could still reach onAssertion and publish "signedIn". - A pick that verifies past its loop's stop reports its end whenever no loop runs any more, instead of only when the state still reads "signingIn": a newer loop that found no autofill and was stopped in turn no longer hides it. - Document when "idle" follows a stop, and test the stop/start/stop tick, the parked loop's single request, and a newer loop's "stopped".
…of the page clients The sign-in, add and remove tests checked results only, so a skipped ceremony or a wrong argument passed. They now assert each ceremony's options, each mutation's arguments, and that adding re-authenticates before it registers.
Upstream added the Discord sign-in method (convex#914). Give it the same framework-agnostic client as the other providers, at @convex-dev/auth/methods/discord/browser, and cover Apple and Discord in the provider client tests.
…are the provider factories The React OAuth hooks now wrap createOauthState and createOauthSignIn instead of reading the ambient values themselves, so the OAuth logic exists once. The four provider browser modules map their api to the references and call one shared createOauthMethodSignIn; the React hooks reuse that mapping. useAuthClient moves to react/client.tsx.
…ents, and pass the options through methods/username-passkey/browser now exports the page clients, the ceremonies (browserCeremonies, resolveCeremonies and what a custom ceremony needs), and the result and option types. The autofill loop, the ceremony slot, the run…Flow functions and the wire types stay internal; the tests import them from their own modules. The flows take the options of the page clients, so the clients hand them through instead of copying them into a context. The pending store of the sign-in page follows its two sources instead of re-implementing a derived subscription, and the hooks return the autofill state as is.
…usePasskeyCeremonySlot hooks Nothing but their tests used them since the sign-in hook wraps the framework-agnostic client. Their tests now run on createPasskeyAutofill and createPasskeyCeremonySlot, against the same fake browser.
…start of the link landing pages runSignInMutation (browser/signInMutation.ts) runs a mutation that mints a session, adopts it, and folds a thrown error into OTHER_ERROR. The username + password clients and the email + password sign-in use it, and the username + password clients count their pending calls with createPendingTracker like the other methods. The landing pages of the email links share startOnceLoaded, and the password-reset page counts its pending calls with createPendingTracker.
startOnceLoaded runs the flow when the AuthClient has loaded, whether that is now or on a later change, with one check instead of two paths.
…nd factory The shared OAuth state and types are exported by @convex-dev/auth/methods/oauth/browser, which a binding imports anyway to register oauth().
…urns it A binding whose query returns its error instead of throwing it, like useQuery of convex-svelte, passes it to stateFor, which answers with an OTHER_ERROR state after the outcome and the missing secret, as for the other link pages. The React hook calls it with the check alone, and its state type is unchanged.
@convex-dev/auth/svelte binds the AuthClient to runes, context and convex-svelte (setupConvexAuth, useAuthActions, useAuthToken), the counterpart of @convex-dev/auth/react. @convex-dev/auth/ssr/sveltekit is the server side (the handle hook, the access token, isAuthenticated), and @convex-dev/auth/ssr/sveltekit/client the client side, the counterparts of the Next.js bindings. They come from @mmailaender/convex-auth-svelte, with the same API. The runes live in svelte/client.svelte.ts. tsc emits it as client.svelte.js with the runes left in place, which the Svelte compiler of the app compiles, as with svelte-package. The Svelte entries carry a svelte export condition, so vite-plugin-svelte treats the package as a Svelte library (not prebundled, not externalized for SSR). svelte, convex-svelte and @sveltejs/kit are optional peer dependencies. ESLint keeps Svelte out of the framework-agnostic modules, and runes out of every module but the .svelte.ts ones. The tests run in a Vitest project with vite-plugin-svelte.
@convex-dev/auth/methods/<method>/svelte for username-password, email-password, username-passkey, oauth, google, apple, github and discord. Each helper makes the client of its flow from the browser module of the method, and reads its stores through fromReadableStore, a createSubscriber adapter. A page client starts in onMount.
Setting up Svelte (the SPA setup and the auth state), Setting up SvelteKit (the auth routes, the handle hook, the layout load and the client setup), and Sign-in methods with Svelte (the helpers of each method, where they differ from the React hooks, and the signIn list of SvelteKit). They are adapted from the READMEs of @mmailaender/convex-auth-svelte.
…rm submits useCompletePasswordRecovery read the whole progress store in the arguments of its checkPasswordRecovery query, so each change of pending or of the outcome made convex-svelte unsubscribe and subscribe again with the same arguments. The arguments now read only the secret, through selectStore, a new store helper that only tells its subscribers when the selected part changes.
bindAuthClient: the Convex client gets a new token fetcher on a session switch and keeps it across a refresh, and a session revoked on the server signs the client out. useAuthToken follows the client. The SvelteKit handle leaves the auth routes alone, isAuthenticatedSvelteKit asks the backend once per request, and convexAuthSvelteKitAccessToken drops an expired token.
…oors of convex-svelte createSubscriber needs Svelte 5.7, and convex-svelte 0.15 needs svelte ^5.19.0 and @sveltejs/kit ^2.12.0.
Prettier formatted the html code blocks as HTML, which turned Svelte
handlers like onclick={() => signOut()} into broken attributes and quoted
the other expressions. Each Svelte code block now has a prettier-ignore,
and AGENTS.md says why. The SvelteKit examples import the generated api
with the relative path of the file they name, from convex/ at the root
of the project, and the guide says how to adjust them for src/convex/.
The guides name the raised svelte and @sveltejs/kit floors.
…odules The framework-agnostic rule now covers ssr/*.ts, which both the Next.js and the SvelteKit bindings import, and rejects an import of ssr/nextjs/ like one of the React bindings.
…t hooks The OAuth not-registered error also says that /oauth/react and /oauth/svelte export the same oauth().
No binding calls it since usePasskeyAutofill is gone: a page that turns autofill off stops the loop with the function that start() returns.
…fill and selectStore docs
Upstream added the magic link method with React hooks of its own. They now wrap `createSendEmailMagicLink` and `createSignInWithEmailMagicLink` of the new `methods/email-magic-link/browser` entry, which share the link flow helpers with email + password (`browser/linkFlow.ts`). The Svelte helpers are at `methods/email-magic-link/svelte`.
`examples/sveltekit` is the Next.js example in SvelteKit, on the Svelte bindings and with the same backend. Its 17 Playwright tests cover sign-up, sign-in and sign-out with username + password, the start and the errors of the GitHub flow, the server-rendered session (redirects, the refresh in the handle hook after the access token expired, a revoked session), the httpOnly refresh cookie, and the refusals of the auth routes. The new E2E workflow runs them against a local Convex backend (`CONVEX_AGENT_MODE=anonymous`), so it needs no deployment or secrets.
|
@mmailaender is attempting to deploy a commit to the Convex Team on Vercel. A member of the Team first needs to authorize it. |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
I've updated convex-auth-svelte to Convex Auth v2, and its alpha is out. The session layer (
@convex-dev/auth/browserand/ssr) worked for it as it is. The browser logic of each sign-in method lives inside its React hooks, though, so the Svelte package ended up with 2,137 lines of code: 748 of them copies of upstream code that isn't exported without React, and most of the rest the same flows the React hooks run.username-passkey/client.tssays it "becomes a public entry point only when a real non-React consumer asks for one". This PR is that ask, taken one step further: it moves the method flows into a framework-agnostic layer and puts React and Svelte on top of it, both in this package. I see it as a starting point for the discussion, so names and scope are open.What it does
@convex-dev/auth/methods/<method>/browser(username-password,email-password,email-magic-link,username-passkey,oauth,google,apple,github,discord). Every hook has acreate…counterpart there, which returns plain async functions with the hook's results, plus its state (likepending) as aReadableStore, which is{ get, subscribe }.react/store.ts(useMethodClient,useReadableStore). The passkey autofill loop moves fromreact_impl.tsxinto a framework-agnostic controller,username-passkey/autofill.ts. Email + password and magic link share the link flow (keep the secret, present the link once the session has loaded) inbrowser/linkFlow.ts.@convex-dev/auth/svelte,@convex-dev/auth/ssr/sveltekit(with/ssr/sveltekit/client) and@convex-dev/auth/methods/<method>/svelte. They mirror the React and Next.js API, with the refresh token in an httpOnly cookie for SvelteKit.tscemits the one runes module asclient.svelte.js, and the consumer's Svelte compiler compiles it, the same assvelte-packagedoes.svelte,convex-svelteand@sveltejs/kitare optional peers, likereactandnext.examples/sveltekitis the Next.js example in SvelteKit, with the same backend. Its 17 Playwright tests run in a new E2E workflow against a local Convex backend (CONVEX_AGENT_MODE=anonymous), so the workflow needs no deployment or secrets.@convex-dev/auth/browserexports the contract a binding needs (AuthSignInApi,AmbientSignInClient,AmbientSignInContext,ReadableStore, ...), andAuthClient.methodStoragegives method clients the namespaced storage. It refuses the token keys and the ambient sign-in prefix.browser/,lib/, the sharedssr/*.tsmodules and the.tsmodules ofmethods/, and keeps the rune globals out of everything but.svelte.tsfiles.No existing export is renamed or removed.
Lines of code
Counted without blank and comment-only lines, on
main(9c5a625c) and on this branch:react/, the method hooks andssr/nextjs)methods/without React, Svelte and server code)browser/)ssr/sveltekit)Next.js is unchanged, so the React part shrinks from 1,696 to 852. The Svelte count includes magic link, which convex-auth-svelte doesn't have yet.
The shared layer grows by more than React shrinks: +1,478 against -844. Most of the difference is state that React kept in hooks and the layer now has to hold itself: pending counters, the progress of the email link pages, subscriptions, and starting and cancelling a page client. That's the part both bindings no longer write. About 50 lines are fixes in the autofill controller, for restarting or stopping autofill while a pick is still being verified. React on
mainhas the same races.React behaviour
The existing React tests pass. The ones for
usePasskeyAutofillandusePasskeyCeremonySlotnow test the controllers those hooks moved into, with the same cases. Differences you can observe:pendingcomes throughuseSyncExternalStore, so it updates synchronously and never inside a transition. For username + password it now stays true until the last of several concurrent calls ends, as it already did for email + password.useInsertionEffect). The only place that read options during render, the query arguments of the password recovery, takes the render'semailCodedirectly.useAmbientSignInValueOpen questions
AuthClient(throughambientSignIns), while the other clients takesignInApiandconvexas options. I'd suggest one context per binding,{ authClient, signInApi, convex }. That makes it consistent and also removes the options-as-getters contract, whichuseMethodClientimplements with aProxy. What do you think?ConvexMutationApihas no query, socreateCompletePasswordRecoveryexposescheckArgs()andstateFor(check), and each binding runs the check query itself. With awatchQuery-like function on that seam, it could return onestatestore, like the other link flows. Would that be ok for you?methodStorageis an unprefixed view with a deny-list, so the email + password secrets keep their current keys. For new keys I'd rather have a prefixed view, e.g.methodStorage(prefix).Testing
pnpm build,pnpm test(1,319 tests, including acore-svelteVitest project),pnpm typecheck,pnpm lint,pnpm check:declarationsandpnpm check:jsdoc(80 examples) pass. Each new client has unit tests without React. The E2E workflow runs the 17 tests ofexamples/sveltekit: sign-up, sign-in and sign-out, the GitHub redirect and its errors, the server-rendered session (redirects, the refresh in thehandlehook after the access token expired, a revoked session), the httpOnly refresh cookie, and the refusals of the auth routes. On top of that, convex-auth-svelte's reference app passes its 36 e2e tests, which cover every method, with every import switched to this branch's@convex-dev/auth.docs/upstreaming.md in convex-auth-svelte maps each of its modules to its counterpart here.