Skip to content

Conversation

@dstaley
Copy link
Member

@dstaley dstaley commented Aug 22, 2025

Description

This PR implements sign-in/sign-up transfer support in our Signal implementation, which is not yet intended for public use. It also fixes two smaller issues, one where useSignUpSignal was not exported, and another where sign-up errors were sent to the incorrect Signal.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Sign-in and sign-up now indicate when an account/session is transferable and can expose an existing session ID.
    • Optional transfer flag when initiating sign-in or sign-up.
    • Sign-up adds SSO flow with captcha handling and redirect support.
    • Experimental React hook for sign-up signals added.
  • Bug Fixes

    • Sign-up error handling now signals errors more directly.
  • Chores

    • Package versions bumped; bundle size threshold adjusted.

@vercel
Copy link

vercel bot commented Aug 22, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Aug 26, 2025 3:14am

@changeset-bot
Copy link

changeset-bot bot commented Aug 22, 2025

🦋 Changeset detected

Latest commit: 7418bf2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/clerk-js Minor
@clerk/clerk-react Minor
@clerk/types Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/elements Patch
@clerk/nextjs Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/localizations Patch
@clerk/nuxt Patch
@clerk/shared Patch
@clerk/testing Patch
@clerk/themes Patch
@clerk/vue Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 22, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6614

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6614

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6614

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6614

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6614

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6614

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6614

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6614

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6614

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6614

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6614

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6614

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6614

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6614

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6614

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6614

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6614

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6614

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6614

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6614

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6614

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6614

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6614

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6614

commit: 7418bf2

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

Walkthrough

Adds transfer and external-account SSO flows: SignIn/SignUp futures gain transferability and existingSession getters; create accepts a transfer flag; SignUp adds captcha-guarded create and sso flows and SignUp.sso; state now emits signUp error signals; react exports useSignUpSignal; types and a bundlewatch threshold updated.

Changes

Cohort / File(s) Summary
Changeset
\.changeset/late-results-melt.md
New changeset bumping three Clerk packages and noting experimental Signal transfer support.
SignIn resource
packages/clerk-js/src/core/resources/SignIn.ts
Added isTransferable and existingSession getters; SignInFuture.create accepts optional transfer?: boolean and forwards it.
SignUp resource (implementation)
packages/clerk-js/src/core/resources/SignUp.ts
Added isTransferable and existingSession getters; added create({ transfer? }) with captcha handling; added sso({ strategy, redirectUrl, redirectUrlComplete }) in SignUpFuture and SignUp.
State handling
packages/clerk-js/src/core/state.ts
On SignUp resource error, emits signUpErrorSignal({ error }) instead of signaling a resource update.
React experimental exports
packages/react/src/experimental.ts
Re-exported useSignUpSignal alongside useSignInSignal.
State proxy (react)
packages/react/src/stateProxy.ts
Added isTransferable: false to signIn/signUp proxies; added create and sso gate methods to signUp proxy.
Types: SignIn
packages/types/src/signIn.ts
Added isTransferable: boolean, optional existingSession?: { sessionId: string }, and transfer?: boolean to create / SignInCreateParams.
Types: SignUp
packages/types/src/signUp.ts
Added isTransferable: boolean, optional existingSession?: { sessionId: string }, create({ transfer? }), and sso({...}) signatures to SignUpFutureResource.
Bundlewatch config
packages/clerk-js/bundlewatch.config.json
Increased ./dist/clerk.legacy.browser.js maxSize threshold from 119KB to 120KB.

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant SignUpFuture
  participant CaptchaSvc as CaptchaService
  participant API
  participant Browser

  rect rgba(70,130,180,0.08)
  Note over App,SignUpFuture: Sign-up (create) with optional transfer
  App->>SignUpFuture: create({ transfer? })
  SignUpFuture->>CaptchaSvc: fetch captchaToken
  CaptchaSvc-->>SignUpFuture: captchaToken
  SignUpFuture->>API: POST /sign-up { transfer, captchaToken, ... }
  API-->>SignUpFuture: { externalAccount?.status, externalVerificationUrl?, error? }
  alt status == "transferable"
    SignUpFuture-->>App: isTransferable = true (return)
  else status == "failed" or "unverified" && externalVerificationUrl
    SignUpFuture->>Browser: navigate externalVerificationUrl
    SignUpFuture-->>App: return
  else
    SignUpFuture-->>App: return { error }
  end
  end
Loading
sequenceDiagram
  participant App
  participant SignInFuture
  participant API

  Note over App,SignInFuture: Sign-in create with optional transfer flag
  App->>SignInFuture: create({ identifier?, transfer? })
  SignInFuture->>API: POST /sign-in { identifier, transfer? }
  API-->>SignInFuture: { firstFactorVerification?.status, error?.meta?.sessionId }
  alt status == "transferable"
    SignInFuture-->>App: isTransferable = true
  else error indicates already-signed-in
    SignInFuture-->>App: existingSession = { sessionId }
  else
    SignInFuture-->>App: return { error }
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

"I hopped through code with a twitch and a grin,
added transfers and SSO tucked safely in.
Captchas I fetched, redirects I sent,
signals now whisper where errors went.
— A rabbit, updating your sign-in den 🐇"

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ds.feat/signals-transfer

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/types/src/signIn.ts (1)

222-264: Tighten the “transfer-only” variant to require transfer: true

The standalone union arm is indeed needed to allow calls like signIn.create({ transfer: true }) (and similarly for signUp), but it’s too permissive as written (it even allows {} and { transfer: false }). Instead, change it to only permit the literal true in that branch, while retaining the intersection for the other variants.

• File: packages/types/src/signIn.ts
Replace the last union arm so that it requires transfer: true rather than an optional boolean.

 export type SignInCreateParams = (
   | {
       strategy: OAuthStrategy | SamlStrategy | EnterpriseSSOStrategy;
       redirectUrl: string;
       actionCompleteRedirectUrl?: string;
       identifier?: string;
       oidcPrompt?: string;
       oidcLoginHint?: string;
     }
   | {
       strategy: TicketStrategy;
       ticket: string;
     }
   | {
       strategy: GoogleOneTapStrategy;
       token: string;
     }
   | {
       strategy: PasswordStrategy;
       password: string;
       identifier: string;
     }
   | { strategy: PasskeyStrategy }
   | {
       strategy:
         | PhoneCodeStrategy
         | EmailCodeStrategy
         | Web3Strategy
         | ResetPasswordEmailCodeStrategy
         | ResetPasswordPhoneCodeStrategy;
       identifier: string;
     }
   | {
       strategy: EmailLinkStrategy;
       identifier: string;
       redirectUrl?: string;
     }
   | {
       identifier: string;
     }
-  | { transfer?: boolean }
 ) & { transfer?: boolean };
+  | { transfer: true }
 ) & { transfer?: boolean };

This ensures:

  • signIn.create({ transfer: true }) still types correctly.
  • You can’t pass an empty object or { transfer: false } alone.
  • All other variants retain an optional transfer flag via the intersection.
🧹 Nitpick comments (13)
.changeset/late-results-melt.md (1)

1-8: Expand the changeset note with concrete API surface and migration hints.

Current note is too terse for a minor bump across three packages. Please list the experimental APIs and behavioral changes added in this PR so downstreams understand what shipped:

  • SignInFuture: getters isTransferable, existingSession; create({ transfer? }).
  • SignUp/SignUpFuture: analogous transfer support and SSO helpers.
  • React experimental exports: useSignUpSignal.
  • State: SignUp errors now emitted via signUpErrorSignal.

If this feature is gated/undocumented, add a one-liner stating it’s experimental and subject to change, and point to any internal docs or follow-up docs PR.

packages/clerk-js/src/core/state.ts (1)

39-47: Reset fetch status on error to avoid stuck “loading” UIs

On error, we currently only emit the error signal—so if your UI went into fetching, it never returns to idle. To fix this, update the onResourceError handler in packages/clerk-js/src/core/state.ts to also reset the fetch status:

• In onResourceError, after signaling the error, emit the corresponding fetch-idle signal.
• For example:

--- a/packages/clerk-js/src/core/state.ts
+++ b/packages/clerk-js/src/core/state.ts
@@ private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
     if (payload.resource instanceof SignIn) {
-      this.signInErrorSignal({ error: payload.error });
+      this.signInErrorSignal({ error: payload.error });
+      this.signInFetchSignal({ status: 'idle' });
     }

     if (payload.resource instanceof SignUp) {
-      this.signUpErrorSignal({ error: payload.error });
+      this.signUpErrorSignal({ error: payload.error });
+      this.signUpFetchSignal({ status: 'idle' });
     }
 };

This ensures that any “loading” state is promptly cleared when an error occurs.

packages/types/src/signIn.ts (1)

132-134: Add JSDoc for new fields on SignInFutureResource.

Document the semantics to keep the public API self-describing:

  • isTransferable: true when the first factor supports transfer to an existing session.
  • existingSession: present when sign-in failed due to identifier_already_signed_in and contains the sessionId to target for transfer.

This helps IDE hovers and downstream TS users.

packages/clerk-js/src/core/resources/SignIn.ts (3)

486-667: Add focused tests for the new Future surface (unit or integration).

Please add tests covering:

  • isTransferable toggling based on firstFactorVerification.status.
  • existingSession extraction when error.code === 'identifier_already_signed_in'.
  • create({ transfer: true }) passes through and results in expected server interaction.
  • sso() + create path remains unaffected by transfer unless explicitly set.

Happy to scaffold test cases using your preferred test runner; say the word and I’ll draft them.


512-523: Add inline JSDoc to the existingSession getter

The error code string "identifier_already_signed_in" is used consistently across the codebase (in both UI and core logic, as well as tests), so documenting its meaning here will improve maintainability and help future refactors.

• File: packages/clerk-js/src/core/resources/SignIn.ts
Lines: 512–523

Suggested diff:

   /**
-   * Present when sign-in failed because the identifier is already signed in elsewhere.
-   * Contains the { sessionId } that may be targeted for transfer.
+   * Returns the session ID when sign-in failed with code
+   * `"identifier_already_signed_in"` and the payload includes a `sessionId`.
+   * This indicates the identifier is already signed in; the returned
+   * `{ sessionId }` may be used to transfer or resume that session.
+   *
+   * @returns {{ sessionId: string } | undefined}
   */
    get existingSession() {
      if (
        this.resource.firstFactorVerification.status === 'failed' &&
        this.resource.firstFactorVerification.error?.code === 'identifier_already_signed_in' &&
        this.resource.firstFactorVerification.error?.meta?.sessionId
      ) {
        return { sessionId: this.resource.firstFactorVerification.error.meta.sessionId };
      }

      return undefined;
    }

508-511: Add JSDoc for isTransferable (status literal confirmed valid)

I’ve confirmed that "transferable" is a member of VerificationStatus (see packages/types/src/verification.ts:26) and is consistently used for first-factor flows throughout the codebase. Adding a short JSDoc here will clarify when this flag flips to true and how callers (e.g., custom UIs) should handle it.

• Location: packages/clerk-js/src/core/resources/SignIn.ts around line 508
• Status literal verified in:

  • packages/types/src/verification.ts:26
  • Multiple usage sites in hooks, machines, SignUp/SignIn resources, and tests

Suggested inline JSDoc:

   /**
+  * Returns true when the user’s first-factor verification status is
+  * “transferable”, indicating the flow can be continued on an existing session.
+  * Callers can use this to prompt a “Continue on existing session” UI path.
   */
   get isTransferable() {
     return this.resource.firstFactorVerification.status === 'transferable';
   }
packages/types/src/signUp.ts (2)

125-127: Document new fields and harden param typing (readonly) on create()

Add concise JSDoc for the new Future fields and mark the transfer param as readonly to signal immutability at the call site. This also satisfies the “All public APIs must be documented with JSDoc” guideline.

 export interface SignUpFutureResource {
   status: SignUpStatus | null;
   unverifiedFields: SignUpIdentificationField[];
-  isTransferable: boolean;
-  existingSession?: { sessionId: string };
-  create: (params: { transfer?: boolean }) => Promise<{ error: unknown }>;
+  /**
+   * True when the external account can be transferred into this sign-up flow.
+   * Derived from backend verification signals for external accounts.
+   */
+  isTransferable: boolean;
+  /**
+   * Present when the identifier is already signed in elsewhere (e.g. SSO already used).
+   * Use to prompt "Continue with existing session".
+   */
+  existingSession?: { readonly sessionId: string };
+  /**
+   * Starts the sign-up. When `transfer` is true, the backend may attempt to transfer
+   * a matched external account into the new sign-up.
+   */
+  create: (params: { readonly transfer?: boolean }) => Promise<{ error: unknown }>;

133-135: Narrow SSO strategy typing to known strategy unions

strategy: string is too loose for a public API. Tightening to the existing strategy unions improves DX and catches mistakes at compile time.

-  sso: (params: { strategy: string; redirectUrl: string; redirectUrlComplete: string }) => Promise<{ error: unknown }>;
+  /**
+   * Initiate SSO during sign-up using OAuth/SAML/Enterprise strategies.
+   */
+  sso: (params: {
+    strategy: OAuthStrategy | SamlStrategy | EnterpriseSSOStrategy;
+    redirectUrl: string;
+    redirectUrlComplete: string;
+  }) => Promise<{ error: unknown }>;
packages/clerk-js/src/core/resources/SignUp.ts (5)

117-120: Guard access to firstFactorVerification.strategy in transfer path

Avoid potential undefined access; only set params.strategy when available. Keeps this path resilient in atypical client states.

-    if (params.transfer && this.shouldBypassCaptchaForAttempt(params)) {
-      params.strategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
-    }
+    if (params.transfer && this.shouldBypassCaptchaForAttempt(params)) {
+      const strategy = SignUp.clerk.client?.signIn?.firstFactorVerification?.strategy;
+      if (strategy) {
+        params.strategy = strategy;
+      }
+    }

498-509: Return a typed session object only when sessionId is a string

Minor robustness: ensure we never return { sessionId: undefined } if the meta shape changes.

-  get existingSession() {
-    if (
-      (this.resource.verifications.externalAccount.status === 'failed' ||
-        this.resource.verifications.externalAccount.status === 'unverified') &&
-      this.resource.verifications.externalAccount.error?.code === 'identifier_already_signed_in' &&
-      this.resource.verifications.externalAccount.error?.meta?.sessionId
-    ) {
-      return { sessionId: this.resource.verifications.externalAccount.error?.meta?.sessionId };
-    }
-
-    return undefined;
-  }
+  get existingSession() {
+    const v = this.resource.verifications.externalAccount;
+    const code = v.error?.code;
+    const sessionId = v.error?.meta?.sessionId;
+    if ((v.status === 'failed' || v.status === 'unverified') && code === 'identifier_already_signed_in') {
+      return typeof sessionId === 'string' ? { sessionId } : undefined;
+    }
+    return undefined;
+  }

526-534: Deduplicate captcha logic: delegate to SignUp.create and add captcha-retry fallback

SignUpFuture.create reimplements captcha handling that already exists in SignUp.create and misses the environment-reload retry used elsewhere. Delegate to create for consistency and add the same retry. Fewer moving parts, less drift.

-  async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
-    return runAsyncResourceTask(this.resource, async () => {
-      const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
-      await this.resource.__internal_basePost({
-        path: this.resource.pathRoot,
-        body: { transfer, captchaToken, captchaWidgetType, captchaError },
-      });
-    });
-  }
+  async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
+    return runAsyncResourceTask(this.resource, async () => {
+      try {
+        await this.resource.create({ transfer });
+      } catch (e) {
+        if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
+          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+          await SignUp.clerk.__unstable__environment!.reload();
+          await this.resource.create({ transfer });
+        } else {
+          throw e;
+        }
+      }
+    });
+  }

572-604: Reuse create() and mirror captcha-retry behavior in SSO flow

This mirrors authenticateWithRedirectOrPopup’s resilience (captcha environment reload) and avoids duplicating captcha plumbing by delegating to create. Also maps redirectUrlComplete to actionCompleteRedirectUrl which create already understands.

-  async sso({
-    strategy,
-    redirectUrl,
-    redirectUrlComplete,
-  }: {
-    strategy: string;
-    redirectUrl: string;
-    redirectUrlComplete: string;
-  }): Promise<{ error: unknown }> {
-    return runAsyncResourceTask(this.resource, async () => {
-      const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
-      await this.resource.__internal_basePost({
-        path: this.resource.pathRoot,
-        body: {
-          strategy,
-          redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl),
-          redirectUrlComplete,
-          captchaToken,
-          captchaWidgetType,
-          captchaError,
-        },
-      });
-
-      const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;
-
-      if (status === 'unverified' && !!externalVerificationRedirectURL) {
-        windowNavigate(externalVerificationRedirectURL);
-      } else {
-        clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
-      }
-    });
-  }
+  async sso({
+    strategy,
+    redirectUrl,
+    redirectUrlComplete,
+  }: {
+    strategy: string;
+    redirectUrl: string;
+    redirectUrlComplete: string;
+  }): Promise<{ error: unknown }> {
+    return runAsyncResourceTask(this.resource, async () => {
+      const redirectUrlWithAuth = SignUp.clerk.buildUrlWithAuth(redirectUrl);
+      const createWithSSO = () =>
+        this.resource.create({
+          strategy,
+          redirectUrl: redirectUrlWithAuth,
+          actionCompleteRedirectUrl: redirectUrlComplete,
+        });
+
+      try {
+        await createWithSSO();
+      } catch (e) {
+        if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
+          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+          await SignUp.clerk.__unstable__environment!.reload();
+          await createWithSSO();
+        } else {
+          throw e;
+        }
+      }
+
+      const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;
+      if (status === 'unverified' && !!externalVerificationRedirectURL) {
+        windowNavigate(externalVerificationRedirectURL);
+      } else {
+        clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
+      }
+    });
+  }

Happy to push a follow-up commit if you want this refactor applied across the analogous SignInFuture flow as well.


526-534: Add tests for transfer and SSO “Future” flows

No tests are shown in this PR. Please add focused unit/integration coverage for:

  • SignUpFuture.isTransferable: true only when externalAccount.status === 'transferable' and error.code === 'external_account_exists'.
  • SignUpFuture.existingSession: returns sessionId when error.code === 'identifier_already_signed_in' and meta.sessionId present; otherwise undefined.
  • SignUpFuture.create: calls SignUp.create with { transfer }, and retries after environment reload on captcha error.
  • SignUpFuture.sso:
    • Posts with buildUrlWithAuth(redirectUrl) and maps redirectUrlComplete -> actionCompleteRedirectUrl when delegating to create.
    • Navigates to externalVerificationRedirectURL on 'unverified'; throws via clerkInvalidFAPIResponse otherwise.
  • SignUp.create (transfer path): when bypass applies, sets strategy from client.signIn.firstFactorVerification if present.

I can draft the tests (Jest + msw) and a small helper to fabricate SignUp.verifications.externalAccount snapshots if you’d like.

Also applies to: 572-604, 491-497, 498-509

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 083820d and 520692b.

📒 Files selected for processing (7)
  • .changeset/late-results-melt.md (1 hunks)
  • packages/clerk-js/src/core/resources/SignIn.ts (2 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (3 hunks)
  • packages/clerk-js/src/core/state.ts (1 hunks)
  • packages/react/src/experimental.ts (1 hunks)
  • packages/types/src/signIn.ts (1 hunks)
  • packages/types/src/signUp.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/late-results-melt.md
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/core/state.ts
  • packages/types/src/signUp.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/experimental.ts
  • packages/types/src/signIn.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
🧬 Code graph analysis (2)
packages/types/src/signIn.ts (1)
packages/types/src/strategies.ts (1)
  • OAuthStrategy (18-18)
packages/clerk-js/src/core/resources/SignUp.ts (3)
packages/clerk-js/src/utils/runAsyncResourceTask.ts (1)
  • runAsyncResourceTask (8-30)
packages/clerk-js/src/utils/windowNavigate.ts (1)
  • windowNavigate (19-23)
packages/clerk-js/src/core/errors.ts (1)
  • clerkInvalidFAPIResponse (79-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (5)
packages/clerk-js/src/core/state.ts (1)

45-45: Correct fix: route SignUp errors to the error signal.

This aligns SignUp with SignIn and prevents polluting the resource signal with error payloads.

packages/types/src/signIn.ts (1)

139-140: LGTM: create accepts transfer?: boolean.

Type surface matches the runtime support added in SignInFuture.create.

packages/clerk-js/src/core/resources/SignIn.ts (1)

570-576: LGTM: create now forwards transfer to the API.

Matches the types and the feature intent.

packages/react/src/experimental.ts (1)

4-4: Good fix: export useSignUpSignal.

Restores parity with useSignInSignal and makes the experimental API discoverable.

packages/clerk-js/src/core/resources/SignUp.ts (1)

491-497: Transferability check looks correct

The predicate matches the described backend states for transferability. Nice and explicit.

export { PlanDetailsButton } from './components/PlanDetailsButton';
export { SubscriptionDetailsButton } from './components/SubscriptionDetailsButton';
export { useSignInSignal } from './hooks/useClerkSignal';
export { useSignInSignal, useSignUpSignal } from './hooks/useClerkSignal';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Ensure the hook is actually exported from hooks/useClerkSignal and add JSDoc at the source.

Add or verify JSDoc on the hook definition so consumers see guidance in IDEs (experimental, subject to change).


🏁 Script executed:

#!/bin/bash
# Confirm the named export exists and is correctly spelled.
rg -n "^export\s+\{\s*useSignInSignal\s*,\s*useSignUpSignal\s*\}" packages/react/src/hooks/useClerkSignal.ts
rg -n "export function useSignUpSignal|export const useSignUpSignal" packages/react/src/hooks/useClerkSignal.ts

Length of output: 263


🏁 Script executed:

#!/bin/bash
# Verify presence of useSignInSignal and its export
rg -n "useSignInSignal" packages/react/src/hooks/useClerkSignal.ts
rg -C3 -n "export function useSignInSignal" packages/react/src/hooks/useClerkSignal.ts

# Verify presence of useSignUpSignal export context and surrounding JSDoc
rg -C3 -n "export function useSignUpSignal" packages/react/src/hooks/useClerkSignal.ts
rg -C3 -n "/\*\*" packages/react/src/hooks/useClerkSignal.ts

Length of output: 589


Add JSDoc to exported hooks in useClerkSignal.ts

Both useSignInSignal (line 58) and useSignUpSignal (line 62) are correctly exported, but neither has preceding JSDoc comments. Please add descriptive JSDoc blocks above each function so IDEs surface usage details and mark these as experimental. For example:

• File: packages/react/src/hooks/useClerkSignal.ts
– Line 57–58 (before export function useSignInSignal):

/**
 * Returns a signal that tracks the sign-in process.
 *
 * @remarks
 * Experimental: subject to change.
 *
 * @returns A signal object for sign-in state.
 */
export function useSignInSignal() {  }

• File: packages/react/src/hooks/useClerkSignal.ts
– Line 61–62 (before export function useSignUpSignal):

/**
 * Returns a signal that tracks the sign-up process.
 *
 * @remarks
 * Experimental: subject to change.
 *
 * @returns A signal object for sign-up state.
 */
export function useSignUpSignal() {  }

This ensures consumers see the experimental-status notice and return type guidance in their IDEs.

🤖 Prompt for AI Agents
In packages/react/src/hooks/useClerkSignal.ts around lines 57–62, the exported
functions useSignInSignal and useSignUpSignal lack JSDoc comments; add
descriptive JSDoc blocks immediately above each export that briefly describe
what the hook returns, include an "@remarks Experimental: subject to change."
line, and an "@returns" annotation describing the returned signal object so IDEs
surface usage and the experimental status.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/clerk-js/bundlewatch.config.json (1)

1-35: Add tests for new Signal transfer and error-routing behavior introduced by this PR.

This config change accompanies new runtime features (transfer flag, new getters, SignUp.sso, and error signal routing). Ensure unit/integration coverage exists for:

  • SignInFuture/SignUpFuture isTransferable and existingSession getters.
  • create({ transfer }) flows for both sign-in and sign-up, including captcha paths.
  • SignUp.sso(...) external-account redirect and error propagation to the dedicated sign-up error signal.
  • react: experimental re-export of useSignUpSignal.
    I can help draft test cases if needed.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 520692b and bbf37eb.

📒 Files selected for processing (1)
  • packages/clerk-js/bundlewatch.config.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/bundlewatch.config.json
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/bundlewatch.config.json
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/bundlewatch.config.json (1)

5-5: Build artifact missing – please generate and measure gzip/brotli sizes

It looks like packages/clerk-js/dist/clerk.legacy.browser.js isn’t present in the repo, so we can’t verify the bundle size automatically. To tighten your bundle budget and avoid masking unintended growth:

  • Run the project build (e.g., pnpm build) to emit dist/clerk.legacy.browser.js.
  • Execute the sizing script from your repo root to record raw, gzip, and brotli outputs.
  • In packages/clerk-js/bundlewatch.config.json, set maxSize to the measured gzip size plus ~0.5 KB headroom.
  • Investigate why the legacy bundle grew (likely new polyfills for transfer/SSO); consider deferring or lazy-loading these in the legacy build.

Once you’ve measured and updated the threshold, please confirm here.

Comment on lines +493 to +494
this.resource.verifications.externalAccount.status === 'transferable' &&
this.resource.verifications.externalAccount.error?.code === 'external_account_exists'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would expect the transferable status is all we need to check for here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

happy to take your word for it, but this is a direct copy-paste of the existing logic https://github.com/clerk/javascript/blob/main/packages/clerk-js/src/core/clerk.ts#L1935-L1936

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense, just thinking from first principles here 😅 I'm not sure why the extra check exists

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add a TODO note to it that we can likely drop the extra check!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)

491-497: Simplify transferable check and add explicit return type

The extra error-code coupling is brittle. The server-reported status should be authoritative. Also add an explicit return type and JSDoc since this is part of the experimental API surface.

Apply this diff:

-  get isTransferable() {
-    // TODO: we can likely remove the error code check as the status should be sufficient
-    return (
-      this.resource.verifications.externalAccount.status === 'transferable' &&
-      this.resource.verifications.externalAccount.error?.code === 'external_account_exists'
-    );
-  }
+  /**
+   * @experimental True if the external account can be transferred to the current user (as reported by FAPI).
+   */
+  get isTransferable(): boolean {
+    return this.resource.verifications.externalAccount.status === 'transferable';
+  }
🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)

499-510: Add explicit return type and minor readability refactor for existingSession

Make the return type explicit and avoid repeating the long property chain. Keeps semantics identical.

-  get existingSession() {
-    if (
-      (this.resource.verifications.externalAccount.status === 'failed' ||
-        this.resource.verifications.externalAccount.status === 'unverified') &&
-      this.resource.verifications.externalAccount.error?.code === 'identifier_already_signed_in' &&
-      this.resource.verifications.externalAccount.error?.meta?.sessionId
-    ) {
-      return { sessionId: this.resource.verifications.externalAccount.error?.meta?.sessionId };
-    }
-
-    return undefined;
-  }
+  get existingSession(): { sessionId: string } | undefined {
+    const ext = this.resource.verifications.externalAccount;
+    const sid = ext.error?.meta?.sessionId;
+    if ((ext.status === 'failed' || ext.status === 'unverified') && ext.error?.code === 'identifier_already_signed_in' && sid) {
+      return { sessionId: sid };
+    }
+    return undefined;
+  }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bbf37eb and b029a38.

📒 Files selected for processing (4)
  • packages/clerk-js/src/core/resources/SignIn.ts (2 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (3 hunks)
  • packages/types/src/signIn.ts (1 hunks)
  • packages/types/src/signUp.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/types/src/signIn.ts
  • packages/types/src/signUp.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/resources/SignUp.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/resources/SignUp.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/SignUp.ts (3)
packages/clerk-js/src/utils/runAsyncResourceTask.ts (1)
  • runAsyncResourceTask (8-30)
packages/clerk-js/src/utils/windowNavigate.ts (1)
  • windowNavigate (19-23)
packages/clerk-js/src/core/errors.ts (1)
  • clerkInvalidFAPIResponse (79-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan

Comment on lines +527 to +535
async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { transfer, captchaToken, captchaWidgetType, captchaError },
});
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Unconditional captcha breaks OAuth bypass for transfer flows; mirror SignUp.create semantics

This always triggers a captcha challenge, diverging from SignUp.create (Lines 108-120) which bypasses captcha for OAuth strategies and transfer flows. In environments relying on captchaOauthBypass, this can fail with “Captcha challenge failed” and/or add unnecessary friction. Also, when transfer is true we should inject the first-factor strategy to align with the bypass logic.

Apply this diff to:

  • Respect captchaBypass and captchaOauthBypass
  • Inject the first-factor strategy during transfer bypass
  • Only fetch captcha when needed
   async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
     return runAsyncResourceTask(this.resource, async () => {
-      const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
-      await this.resource.__internal_basePost({
-        path: this.resource.pathRoot,
-        body: { transfer, captchaToken, captchaWidgetType, captchaError },
-      });
+      // Mirror SignUp.create captcha-bypass semantics for transfer flows
+      const captchaBypass = SignUp.clerk.client?.captchaBypass;
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
+      const firstFactorStrategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
+      const shouldBypassCaptcha = Boolean(
+        transfer && firstFactorStrategy && captchaOauthBypass.some(s => s === firstFactorStrategy),
+      );
+
+      const body: Record<string, unknown> = { transfer };
+      if (!__BUILD_DISABLE_RHC__ && !captchaBypass && !shouldBypassCaptcha) {
+        const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
+        Object.assign(body, { captchaToken, captchaWidgetType, captchaError });
+      } else if (transfer && firstFactorStrategy) {
+        Object.assign(body, { strategy: firstFactorStrategy });
+      }
+
+      await this.resource.__internal_basePost({
+        path: this.resource.pathRoot,
+        body,
+      });
     });
   }

Optional follow-up: factor the bypass computation into a shared helper to keep SignUp and SignUpFuture in lockstep.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { transfer, captchaToken, captchaWidgetType, captchaError },
});
});
}
async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
// Mirror SignUp.create captcha-bypass semantics for transfer flows
const captchaBypass = SignUp.clerk.client?.captchaBypass;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
const firstFactorStrategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
const shouldBypassCaptcha = Boolean(
transfer && firstFactorStrategy && captchaOauthBypass.some(s => s === firstFactorStrategy),
);
const body: Record<string, unknown> = { transfer };
if (!__BUILD_DISABLE_RHC__ && !captchaBypass && !shouldBypassCaptcha) {
const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
Object.assign(body, { captchaToken, captchaWidgetType, captchaError });
} else if (transfer && firstFactorStrategy) {
Object.assign(body, { strategy: firstFactorStrategy });
}
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body,
});
});
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignUp.ts around lines 527 to 535, the
create method always requests a captcha which breaks OAuth/transfer bypass
behavior; change it to mirror SignUp.create (lines 108-120) by computing captcha
bypass (respecting captchaBypass and captchaOauthBypass and bypassing when
strategy is OAuth or transfer flow), only call getCaptchaToken when captcha is
needed, and when transfer===true include the firstFactorStrategy in the request
body to enable transfer bypass; update the body passed to __internal_basePost to
conditionally include captchaToken/captchaWidgetType/captchaError and
firstFactorStrategy so transfer and OAuth flows skip the captcha challenge.

Comment on lines +573 to +604
async sso({
strategy,
redirectUrl,
redirectUrlComplete,
}: {
strategy: string;
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
strategy,
redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl),
redirectUrlComplete,
captchaToken,
captchaWidgetType,
captchaError,
},
});

const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;

if (status === 'unverified' && !!externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
} else {
clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
}
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix SSO body field name, use union type for strategy, and mirror captcha-bypass + one-retry-on-captcha-error semantics

  • Server expects actionCompleteRedirectUrl (not redirectUrlComplete) when posting to FAPI (see authenticateWithRedirectOrPopup above).
  • Use the union type for strategy instead of string.
  • Respect captchaOauthBypass for SSO strategies and implement the environment-reload-on-captcha-error retry used elsewhere for resilience.
   async sso({
     strategy,
     redirectUrl,
     redirectUrlComplete,
   }: {
-    strategy: string;
+    strategy: SignUpCreateParams['strategy'];
     redirectUrl: string;
     redirectUrlComplete: string;
   }): Promise<{ error: unknown }> {
     return runAsyncResourceTask(this.resource, async () => {
-      const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
-      await this.resource.__internal_basePost({
-        path: this.resource.pathRoot,
-        body: {
-          strategy,
-          redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl),
-          redirectUrlComplete,
-          captchaToken,
-          captchaWidgetType,
-          captchaError,
-        },
-      });
+      const redirectUrlWithAuth = SignUp.clerk.buildUrlWithAuth(redirectUrl);
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
+      const shouldBypassCaptcha = captchaOauthBypass.some(s => s === strategy);
+
+      const postOnce = async () => {
+        const body: Record<string, unknown> = {
+          strategy,
+          redirectUrl: redirectUrlWithAuth,
+          actionCompleteRedirectUrl: redirectUrlComplete,
+        };
+        if (!shouldBypassCaptcha) {
+          const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
+          Object.assign(body, { captchaToken, captchaWidgetType, captchaError });
+        }
+        await this.resource.__internal_basePost({
+          path: this.resource.pathRoot,
+          body,
+        });
+      };
+
+      try {
+        await postOnce();
+      } catch (e) {
+        if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
+          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+          await SignUp.clerk.__unstable__environment!.reload();
+          await postOnce();
+        } else {
+          throw e;
+        }
+      }
 
       const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;
 
       if (status === 'unverified' && !!externalVerificationRedirectURL) {
         windowNavigate(externalVerificationRedirectURL);
       } else {
         clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
       }
     });
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async sso({
strategy,
redirectUrl,
redirectUrlComplete,
}: {
strategy: string;
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
strategy,
redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl),
redirectUrlComplete,
captchaToken,
captchaWidgetType,
captchaError,
},
});
const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;
if (status === 'unverified' && !!externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
} else {
clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
}
});
}
async sso({
strategy,
redirectUrl,
redirectUrlComplete,
}: {
strategy: SignUpCreateParams['strategy'];
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
const redirectUrlWithAuth = SignUp.clerk.buildUrlWithAuth(redirectUrl);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
const shouldBypassCaptcha = captchaOauthBypass.some(s => s === strategy);
const postOnce = async () => {
const body: Record<string, unknown> = {
strategy,
redirectUrl: redirectUrlWithAuth,
actionCompleteRedirectUrl: redirectUrlComplete,
};
if (!shouldBypassCaptcha) {
const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
Object.assign(body, { captchaToken, captchaWidgetType, captchaError });
}
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body,
});
};
try {
await postOnce();
} catch (e) {
if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await SignUp.clerk.__unstable__environment!.reload();
await postOnce();
} else {
throw e;
}
}
const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;
if (status === 'unverified' && !!externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
} else {
clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
}
});
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignUp.ts around lines 573 to 604, the
SSO method needs three fixes: change the POST body field redirectUrlComplete to
actionCompleteRedirectUrl (server expects actionCompleteRedirectUrl), change the
strategy parameter type from string to the existing strategy union type used
elsewhere in the codebase, and implement captcha-bypass +
one-retry-on-captcha-error semantics for SSO: include the captchaOauthBypass
flag (read from the same config/source used elsewhere) in the POST body, and if
getCaptchaToken returns a captchaError, reload the environment/state and retry
the POST exactly once before failing. Ensure the rest of the flow (handling
externalVerificationRedirectURL and clerkInvalidFAPIResponse) remains unchanged.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/react/src/stateProxy.ts (1)

70-76: SignUp proxy methods are correctly wired; optional existingSession placeholder for shape parity

The create and sso methods on the SignUp proxy are already returning Promises in your types, so wrapping them with gateMethod (which itself is async) preserves the expected return types:

  • SignUpFutureResource defines
    create: (params: { transfer?: boolean }) => Promise<{ error: unknown }>
    sso: (params: { strategy: string; redirectUrl: string; redirectUrlComplete: string }) => Promise<{ error: unknown }>
  • Wrapping a Promise-returning function in an async wrapper returns the same Promise<…> shape, not a nested Promise.

As an optional refactoring to keep the pre-load object shape aligned with the future resource, you may add an explicit existingSession: undefined placeholder. The SignUpFutureResource already exposes existingSession?: { sessionId: string }, so this ensures parity with SignIn:

         unverifiedFields: [],
         isTransferable: false,
+        // Keep shape parity with SignUpFutureResource while Clerk loads
+        existingSession: undefined,

         create: this.gateMethod(target, 'create'),
         sso: this.gateMethod(target, 'sso'),

No further verification is required—both methods return Promises as expected.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b029a38 and 7418bf2.

📒 Files selected for processing (1)
  • packages/react/src/stateProxy.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/react/src/stateProxy.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/react/src/stateProxy.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/react/src/stateProxy.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/react/src/stateProxy.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/react/src/stateProxy.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/react/src/stateProxy.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/react/src/stateProxy.ts (1)

46-46: The helper script will print the relevant sections of the SignIn and SignUp future types and confirm whether React code already reads existingSession. Once we have that, we can decide if adding the placeholder is safe.

@dstaley dstaley merged commit 2ed539c into main Aug 26, 2025
39 checks passed
@dstaley dstaley deleted the ds.feat/signals-transfer branch August 26, 2025 03:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants