Skip to content

Conversation

@dstaley
Copy link
Member

@dstaley dstaley commented Aug 19, 2025

Description

This PR adds support for captcha to our Signal SignUp implementation, which is not intended for public use yet.

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

    • Experimental: CAPTCHA support added to the Sign Up (Signal) password flow. Users may see a managed or invisible verification step; flow falls back gracefully if CAPTCHA is unavailable.
  • Chores

    • Added release metadata to publish a minor version noting the experimental CAPTCHA support.
    • Updated bundle size threshold for the JavaScript package.

@changeset-bot
Copy link

changeset-bot bot commented Aug 19, 2025

🦋 Changeset detected

Latest commit: 724451a

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

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo 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

@vercel
Copy link

vercel bot commented Aug 19, 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 20, 2025 10:09pm

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 19, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 724451a

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 19, 2025

📝 Walkthrough

Walkthrough

Adds CAPTCHA handling to the signup password flow: SignUpFuture.password now calls CaptchaChallenge.managedOrInvisible({ action: 'signup' }) to obtain captchaToken and captchaWidgetType and includes them plus strategy: 'password' in the signup request; errors during CAPTCHA retrieval now throw. CaptchaChallenge.managedOrInvisible was changed to return captchaWidgetType (new explicit Promise return type that may include captchaError, captchaAction, captchaToken, captchaWidgetType or be undefined) and its error-path behavior was refined. A changeset was added to declare a minor release and note experimental Signal SignUp CAPTCHA support. No public signatures were modified.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

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.


🪧 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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: 0

🧹 Nitpick comments (9)
packages/clerk-js/src/utils/captcha/CaptchaChallenge.ts (4)

39-46: Document the new return shape and semantics of managedOrInvisible.
The public API now returns either an object or undefined depending on action and environment. Please reflect this in the JSDoc to avoid ambiguity for consumers.

Apply this diff to augment the JSDoc:

   /**
    * Triggers a smart challenge if the user is required to solve a CAPTCHA.
    * The type of the challenge depends on the dashboard configuration.
    * By default, smart (managed) captcha is preferred. If the customer has selected invisible, this method
    * will fall back to using the invisible captcha instead.
    *
    * Managed challenged start as non-interactive and escalate to interactive if necessary.
+   *
+   * Returns:
+   * - For opts.action === 'verify': An object containing either { captchaToken, captchaWidgetType } on success,
+   *   or { captchaError, captchaAction: 'verify' } on failure/unavailability.
+   * - For other actions (e.g. 'signup'): On success, an object possibly containing { captchaToken, captchaWidgetType }.
+   *   If CAPTCHA is disabled in the environment, returns {}.
+   *   If CAPTCHA is enabled but token retrieval fails, returns undefined (callers should treat this as a hard failure).
    */

57-64: Prevent opts from overriding environment-driven widgetType/siteKey/nonce.
Spreading opts after widgetType allows callers to override widgetType (and other critical fields), which can desynchronize the widget type used vs. the value reported upstream. Put opts first and explicitly override controlled fields. Also prefer opts?.nonce ?? nonce ?? undefined for consistency with invisible().

Apply this diff:

-      const captchaResult = await getCaptchaToken({
-        captchaProvider,
-        invisibleSiteKey: captchaPublicKeyInvisible,
-        nonce: nonce || undefined,
-        siteKey: captchaSiteKey,
-        widgetType: captchaWidgetType,
-        ...opts,
-      }).catch(e => {
+      const captchaResult = await getCaptchaToken({
+        ...(opts ?? {}),
+        captchaProvider,
+        invisibleSiteKey: captchaPublicKeyInvisible,
+        nonce: opts?.nonce ?? nonce ?? undefined,
+        siteKey: captchaSiteKey,
+        widgetType: captchaWidgetType,
+      }).catch(e => {

64-71: Consider lightweight debug logging in the error path.
In production, differentiating provider errors from unexpected exceptions is valuable. If a logger exists, log e.captchaError vs. generic error at debug level before returning.

Would you like a patch that integrates with the project’s logging facility if available?


74-77: Clarify the empty-object return for signup.
Returning {} when CAPTCHA is disabled is fine. Consider adding captchaAction for parity/traceability or leave as-is and document it (see earlier JSDoc suggestion).

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

108-116: Strengthen the error message when CAPTCHA is unavailable.
Throwing a ClerkRuntimeError with an empty message violates the guideline to provide meaningful error messages and recovery suggestions. Add actionable text.

Apply this diff:

-      if (!captchaParams) {
-        throw new ClerkRuntimeError('', { code: 'captcha_unavailable' });
-      }
+      if (!captchaParams) {
+        throw new ClerkRuntimeError(
+          'CAPTCHA is unavailable or failed to initialize. Ask the user to retry or reload the page.',
+          { code: 'captcha_unavailable' },
+        );
+      }

491-505: Prefer ClerkRuntimeError over generic Error and include actionable messages.
Using generic Error makes consumers’ error handling inconsistent. Also, return messages should hint at next steps.

Apply this diff:

-  private async getCaptchaToken(): Promise<{ captchaToken?: string; captchaWidgetType?: CaptchaWidgetType }> {
+  private async getCaptchaToken(): Promise<{ captchaToken?: string; captchaWidgetType?: CaptchaWidgetType }> {
     const captchaChallenge = new CaptchaChallenge(SignUp.clerk);
     const response = await captchaChallenge.managedOrInvisible({ action: 'signup' });
     if (!response) {
-      throw new Error('Captcha challenge failed');
+      throw new ClerkRuntimeError('CAPTCHA is unavailable or failed to initialize.', {
+        code: 'captcha_unavailable',
+      });
     }
 
     const { captchaError, captchaToken, captchaWidgetType } = response;
     if (captchaError) {
-      throw new Error(captchaError);
+      throw new ClerkRuntimeError(`CAPTCHA error: ${captchaError}`, { code: 'captcha_failed' });
     }
 
     return { captchaToken, captchaWidgetType };
   }

508-518: Only include CAPTCHA fields in the request when defined.
Omit undefined fields to keep the payload minimal and avoid server-side ambiguity.

Apply this diff:

       await this.resource.__internal_basePost({
         path: this.resource.pathRoot,
-        body: {
-          strategy: 'password',
-          emailAddress,
-          password,
-          captchaToken,
-          captchaWidgetType,
-        },
+        body: {
+          strategy: 'password',
+          emailAddress,
+          password,
+          ...(captchaToken ? { captchaToken } : {}),
+          ...(captchaWidgetType !== undefined ? { captchaWidgetType } : {}),
+        },
       });

106-116: Add test coverage for happy-path, disabled, and failure scenarios.
No tests were added. Please cover:

  • Environment with CAPTCHA enabled → token fetched → request contains captchaToken and captchaWidgetType.
  • Environment with CAPTCHA disabled → request excludes CAPTCHA fields.
  • Token retrieval error → SignUp.create throws ClerkRuntimeError('captcha_unavailable'); SignUpFuture.password throws ClerkRuntimeError('captcha_failed' or 'captcha_unavailable').

I can scaffold unit/integration tests (jest + msw) for these cases. Want me to draft them?

Also applies to: 491-505, 508-518

.changeset/blue-cloths-create.md (1)

5-5: Nit: Use “CAPTCHA” capitalization in the note.
Consistent capitalization improves clarity in release notes.

Apply this diff:

-[Experimental] Add support for captcha to Signal SignUp
+[Experimental] Add support for CAPTCHA to Signal SignUp
📜 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 6a1fb13 and d98c7fc.

📒 Files selected for processing (3)
  • .changeset/blue-cloths-create.md (1 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (2 hunks)
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/blue-cloths-create.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/resources/SignUp.ts
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.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/clerk-js/src/utils/captcha/CaptchaChallenge.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/clerk-js/src/utils/captcha/CaptchaChallenge.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
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.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
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.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
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.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/resources/SignUp.ts
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.ts
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)
packages/types/src/displayConfig.ts (1)
  • CaptchaWidgetType (7-7)
🪛 LanguageTool
.changeset/blue-cloths-create.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...Add support for captcha to Signal SignUp

(QB_NEW_EN)

🔇 Additional comments (3)
packages/clerk-js/src/utils/captcha/CaptchaChallenge.ts (2)

1-1: Type-only import looks correct and matches usage.
Importing CaptchaWidgetType as a type keeps the runtime footprint lean.


47-52: Return type widening to undefined is safely handled

All call sites of managedOrInvisible already guard against a falsy return or never destructure it unchecked:

  • packages/clerk-js/src/core/resources/SignUp.ts
    • Lines 110–113 and 493–496 check for !captchaParams/!response and throw.
  • packages/clerk-js/src/utils/tests/captcha.spec.ts
    • The return value is awaited but never destructured.
  • packages/clerk-js/src/utils/captcha/CaptchaChallenge.ts → managedInModal simply returns managedOrInvisible (no external calls).

No action needed.

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

11-11: Type import for CaptchaWidgetType is appropriate.
Keeps the runtime clean and aligns with packages/types.


const { captchaError, captchaToken, captchaWidgetType } = response;
if (captchaError) {
throw new Error(captchaError);
Copy link
Member

Choose a reason for hiding this comment

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

❓ do we know if captchaError is already an error type? Wondering if it's necessary to wrap it in new Error() again 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.

TypeScript says it's a string. Given this is the value that's submitted to FAPI I'm reasonably confident that's correct.

const captchaChallenge = new CaptchaChallenge(SignUp.clerk);
const response = await captchaChallenge.managedOrInvisible({ action: 'signup' });
if (!response) {
throw new Error('Captcha challenge failed');
Copy link
Member

Choose a reason for hiding this comment

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

Should this use ClerkRuntimeError? Or not because it's only internal?

Copy link
Member Author

Choose a reason for hiding this comment

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

this is me kicking that can down the road until I can do an error pass across the entire implementation 😅

Copy link
Member

Choose a reason for hiding this comment

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

Don't forget 😉

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

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

491-505: Use ClerkRuntimeError with actionable message when CAPTCHA response is missing

Throwing a plain Error here is inconsistent with the rest of the file and makes handling harder. Prefer ClerkRuntimeError with a meaningful message and code.

Apply this diff:

   const response = await captchaChallenge.managedOrInvisible({ action: 'signup' });
   if (!response) {
-    throw new Error('Captcha challenge failed');
+    throw new ClerkRuntimeError('Captcha challenge failed', { code: 'captcha_unavailable' });
   }
🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)

506-522: Add targeted tests for the new CAPTCHA path in SignUpFuture.password

No tests are present in this PR. Please add coverage for:

  • CAPTCHA disabled/bypass: ensures no captcha fetch, no throw, body excludes captcha fields.
  • CAPTCHA enabled: includes captchaToken and captchaWidgetType in the request body.
  • CAPTCHA/API error on first attempt: environment reload + second attempt succeeds.
  • CAPTCHA challenge returns undefined: verifies ClerkRuntimeError is thrown (if gating requires CAPTCHA).

I can help scaffold tests with appropriate mocks for CaptchaChallenge, __unstable__environment.reload, and the FAPI client.

📜 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 f469327 and fb26e86.

📒 Files selected for processing (1)
  • packages/clerk-js/src/core/resources/SignUp.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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
**/*

⚙️ 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/resources/SignUp.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). (4)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
🔇 Additional comments (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)

11-11: Confirmed CaptchaWidgetType Export

Verified that CaptchaWidgetType is exported from @clerk/types in packages/types/src/displayConfig.ts (line 7). The existing type-only import is correct and will not cause TS errors.

Comment on lines 506 to 522
async password({ emailAddress, password }: { emailAddress: string; password: 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: { emailAddress, password },
body: {
strategy: 'password',
emailAddress,
password,
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

Password flow unconditionally requires CAPTCHA; bypass and retry semantics missing

As written, password() always requests a CAPTCHA token and will throw if CAPTCHA is disabled/unavailable (e.g., bypass or dev env). This diverges from create() and authenticateWithRedirectOrPopup(), which gate CAPTCHA and retry on environment/captcha errors. This will break password signup in environments where CAPTCHA is intentionally bypassed or temporarily unavailable.

Proposed fix:

  • Gate CAPTCHA retrieval on the same conditions used elsewhere (respect build flag and client bypass).
  • Retry once on CAPTCHA-related API errors after reloading the environment.
  • Spread optional captchaParams into the request body to omit absent fields.

Apply this diff:

   async password({ emailAddress, password }: { emailAddress: string; password: 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: 'password',
-          emailAddress,
-          password,
-          captchaToken,
-          captchaWidgetType,
-          captchaError,
-        },
-      });
+      const shouldFetchCaptcha = !__BUILD_DISABLE_RHC__ && !SignUp.clerk.client?.captchaBypass;
+
+      let captchaParams: Partial<{
+        captchaToken: string;
+        captchaWidgetType: CaptchaWidgetType;
+        captchaError: unknown;
+      }> = {};
+
+      if (shouldFetchCaptcha) {
+        captchaParams = await this.getCaptchaToken();
+      }
+
+      const post = () =>
+        this.resource.__internal_basePost({
+          path: this.resource.pathRoot,
+          body: {
+            strategy: 'password',
+            emailAddress,
+            password,
+            ...captchaParams,
+          },
+        });
+
+      try {
+        await post();
+      } catch (e) {
+        if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
+          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+          await SignUp.clerk.__unstable__environment!.reload();
+          if (shouldFetchCaptcha) {
+            captchaParams = await this.getCaptchaToken();
+          }
+          await post();
+        } else {
+          throw e;
+        }
+      }
     });
   }
📝 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 password({ emailAddress, password }: { emailAddress: string; password: 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: { emailAddress, password },
body: {
strategy: 'password',
emailAddress,
password,
captchaToken,
captchaWidgetType,
captchaError,
},
});
});
}
async password({ emailAddress, password }: { emailAddress: string; password: string }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
const shouldFetchCaptcha = !__BUILD_DISABLE_RHC__ && !SignUp.clerk.client?.captchaBypass;
let captchaParams: Partial<{
captchaToken: string;
captchaWidgetType: CaptchaWidgetType;
captchaError: unknown;
}> = {};
if (shouldFetchCaptcha) {
captchaParams = await this.getCaptchaToken();
}
const post = () =>
this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
strategy: 'password',
emailAddress,
password,
...captchaParams,
},
});
try {
await post();
} catch (e) {
if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await SignUp.clerk.__unstable__environment!.reload();
if (shouldFetchCaptcha) {
captchaParams = await this.getCaptchaToken();
}
await post();
} else {
throw e;
}
}
});
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignUp.ts around lines 506-522, the
password() flow always requests a CAPTCHA token which fails in bypass/dev
environments; update it to only call getCaptchaToken when the same
CAPTCHA-enabled conditions used by create() and
authenticateWithRedirectOrPopup() are met (respecting build flags and client
bypass), spread the optional captchaParams into the POST body so absent fields
aren’t sent, and wrap the API call in a retry that, on CAPTCHA-related API
errors, reloads the environment and retries the POST once before failing.

@dstaley dstaley merged commit 4ac7b25 into main Aug 20, 2025
37 checks passed
@dstaley dstaley deleted the ds.feat/signals-signup-captcha branch August 20, 2025 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants