Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Aug 29, 2025

Description

Adding baseline debug logging to SignIn and SignUp components

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

  • Refactor

    • Adds baseline debug logging across SignIn and SignUp flows for improved observability.
    • Authentication status is now exposed via accessors and emits debug transitions when it changes.
    • Unifies parameter handling across first/second-factor and verification flows for consistent behavior.
    • Sign-in creation now returns a resource representation (may affect SDK consumer behavior).
  • Chores

    • Adds a changeset to publish a patch release.

@changeset-bot
Copy link

changeset-bot bot commented Aug 29, 2025

🦋 Changeset detected

Latest commit: 180635d

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 Patch
@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 29, 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 29, 2025 5:54pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 29, 2025

Walkthrough

Adds debug logging across SignIn and SignUp flows, converts their public status fields to private backing fields with getter/setter that log transitions, changes SignIn.create return type to Promise<SignInResource>, refactors factor methods to accept params, and adds a patch changeset.

Changes

Cohort / File(s) Summary of changes
Release metadata
.changeset/thirty-knives-refuse.md
Adds a patch changeset for @clerk/clerk-js announcing baseline debug logging for SignIn/SignUp.
SignIn instrumentation & API changes
packages/clerk-js/src/core/resources/SignIn.ts
Adds debugLogger calls across create/prepare/attempt flows; replaces public status field with private _status and public getter/setter that log transitions; changes create return type from Promise<this> to Promise<SignInResource>; refactors first/second factor methods to accept/use params consistently and update request bodies to spread config from params.
SignUp instrumentation & flow tweak
packages/clerk-js/src/core/resources/SignUp.ts
Adds debugLogger calls for create/prepare/attempt verification; replaces public status with private _status plus getter/setter that log transitions; create clones params into finalParams, may derive strategy from clerk.client?.signIn.firstFactorVerification.strategy when transfer + CAPTCHA bypass apply; posts normalized metadata and renames minor params.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI
  participant SignIn
  participant DebugLogger as DebugLogger
  participant Backend

  User->>UI: Trigger sign-in
  UI->>SignIn: create(params)
  SignIn->>DebugLogger: debug("SignIn.create", {id, strategy})
  SignIn->>Backend: POST /sign_in (strategy, config)
  Backend-->>SignIn: SignInResource
  SignIn->>DebugLogger: debug("status transition", {from, to})
  SignIn-->>UI: SignInResource

  rect rgba(230,247,255,0.4)
    note over SignIn: First/Second factor flows use params.* consistently
    UI->>SignIn: prepare/attemptFirstFactor(params)
    SignIn->>DebugLogger: debug("prepare/attemptFirstFactor", {id, strategy})
    SignIn->>Backend: POST factor (params.strategy, config)
    Backend-->>SignIn: response
    SignIn->>DebugLogger: debug("status transition", {from, to})
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant UI
  participant SignUp
  participant ClerkClient as Clerk Client
  participant DebugLogger as DebugLogger
  participant Backend

  User->>UI: Trigger sign-up
  UI->>SignUp: create(params)
  SignUp->>DebugLogger: debug("SignUp.create", {id, strategy})
  alt transfer && CAPTCHA bypass
    SignUp->>ClerkClient: read signIn.firstFactorVerification.strategy
    ClerkClient-->>SignUp: strategy?
    SignUp->>SignUp: set params.strategy = derived strategy (if present)
  end
  SignUp->>Backend: POST /sign_up (params with strategy, normalized metadata)
  Backend-->>SignUp: SignUpResource
  SignUp->>DebugLogger: debug("status transition", {from, to})
  SignUp-->>UI: SignUpResource

  note over SignUp: prepare/attemptVerification also emit debug logs
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I thump my paw—logs softly sing,
Status hops and watches spring,
Params align, the factors hum,
A borrowed strategy greets the sun. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/clerkjs-error-debug-logs

🪧 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 or @coderabbit 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.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 29, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 180635d

@jacekradko jacekradko requested a review from brkalow August 29, 2025 15:41
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

Caution

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

⚠️ Outside diff range comments (2)
packages/clerk-js/src/core/resources/SignUp.ts (2)

128-152: Avoid param reassignment; derive strategy safely during transfer

Reassigning function params can trip ESLint (no-param-reassign) and reduce readability. Also, only set params.strategy when the inferred value is in the allowed bypass list to prevent invalid strategies sneaking in.

Apply:

-  create = async (params: SignUpCreateParams): Promise<SignUpResource> => {
-    debugLogger.debug('SignUp.create', { id: this.id, strategy: params.strategy });
+  create = async (params: SignUpCreateParams): Promise<SignUpResource> => {
+    debugLogger.debug('SignUp.create', { id: this.id, strategy: params.strategy });
+    let nextParams = params;
     if (!__BUILD_DISABLE_RHC__ && !this.clientBypass() && !this.shouldBypassCaptchaForAttempt(params)) {
       const captchaChallenge = new CaptchaChallenge(SignUp.clerk);
       const captchaParams = await captchaChallenge.managedOrInvisible({ action: 'signup' });
       if (!captchaParams) {
         throw new ClerkRuntimeError('', { code: 'captcha_unavailable' });
       }
-      params = { ...params, ...captchaParams };
+      nextParams = { ...nextParams, ...captchaParams };
     }
 
-    if (params.transfer && this.shouldBypassCaptchaForAttempt(params)) {
-      const strategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
-      if (strategy) {
-        params.strategy = strategy as SignUpCreateParams['strategy'];
-      }
+    if (nextParams.transfer && this.shouldBypassCaptchaForAttempt(nextParams)) {
+      const inferred = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
+      const allowed = SignUp.clerk.__unstable__environment?.displayConfig.captchaOauthBypass ?? [];
+      if (inferred && allowed.includes(inferred)) {
+        nextParams = { ...nextParams, strategy: inferred as SignUpCreateParams['strategy'] };
+      }
     }
 
     return this._basePost({
       path: this.pathRoot,
-      body: normalizeUnsafeMetadata(params),
+      body: normalizeUnsafeMetadata(nextParams),
     });
   };

495-516: Guard against undefined environment and client in captcha bypass
Remove non-null assertions in shouldBypassCaptchaForAttempt and default to an empty array:

-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
+    const captchaOauthBypass =
+      SignUp.clerk.__unstable__environment?.displayConfig.captchaOauthBypass ?? [];

     if (captchaOauthBypass.some(strategy => strategy === params.strategy)) {
       return true;
     }

     if (
       params.transfer &&
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      captchaOauthBypass.some(strategy => strategy === SignUp.clerk.client!.signIn.firstFactorVerification.strategy)
+      captchaOauthBypass.some(
+        strategy => strategy === SignUp.clerk.client?.signIn.firstFactorVerification.strategy,
+      )
     ) {
       return true;
     }
🧹 Nitpick comments (3)
packages/clerk-js/src/core/resources/SignIn.ts (3)

136-142: Create() debug context is appropriate

Captures id and strategy discriminated via 'in'. Consider adding transfer flag when present for richer traces (optional).

Apply:

- debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined });
+ debugLogger.debug('SignIn.create', {
+   id: this.id,
+   strategy: 'strategy' in params ? params.strategy : undefined,
+   transfer: 'transfer' in params ? (params as { transfer?: boolean }).transfer : undefined,
+});

151-206: Factor preparation switch reads from params correctly

Config extraction aligns with type unions and avoids reading from factor state. Good.

To eliminate several as assertions, consider introducing typed builders per strategy to construct configs, improving type safety and reducing casts.


208-225: Nit: avoid duplicating strategy in request body

For non-passkey branches, { ...params } already contains strategy. No functional bug, but removing the extra property may appease linters.

Apply:

-    let config;
+    let config: Record<string, unknown>;
     switch (params.strategy) {
       case 'passkey':
         config = {
           publicKeyCredential: JSON.stringify(serializePublicKeyCredentialAssertion(params.publicKeyCredential)),
         };
         break;
       default:
-        config = { ...params };
+        config = { ...params };
     }
 
     return this._basePost({
-      body: { ...config, strategy: params.strategy },
+      body: 'strategy' in config ? config : { ...config, strategy: params.strategy },
       action: 'attempt_first_factor',
     });
📜 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 263722e and 24ffe10.

📒 Files selected for processing (3)
  • .changeset/thirty-knives-refuse.md (1 hunks)
  • packages/clerk-js/src/core/resources/SignIn.ts (6 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/thirty-knives-refuse.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/core/resources/SignIn.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/core/resources/SignIn.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/core/resources/SignIn.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/core/resources/SignIn.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/core/resources/SignIn.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/core/resources/SignIn.ts
🧬 Code graph analysis (2)
packages/clerk-js/src/core/resources/SignUp.ts (3)
packages/types/src/signUpCommon.ts (4)
  • SignUpStatus (25-25)
  • SignUpField (27-27)
  • SignUpCreateParams (81-104)
  • AttemptVerificationParams (57-65)
packages/clerk-js/src/utils/debug.ts (1)
  • debugLogger (150-179)
packages/types/src/signUp.ts (1)
  • SignUpResource (41-116)
packages/clerk-js/src/core/resources/SignIn.ts (5)
packages/types/src/signInCommon.ts (5)
  • SignInStatus (61-66)
  • SignInCreateParams (123-164)
  • PrepareFirstFactorParams (98-108)
  • AttemptFirstFactorParams (110-117)
  • AttemptSecondFactorParams (121-121)
packages/clerk-js/src/utils/debug.ts (1)
  • debugLogger (150-179)
packages/types/src/signIn.ts (1)
  • SignInResource (34-91)
packages/types/src/factors.ts (9)
  • PassKeyConfig (102-102)
  • EmailLinkConfig (96-98)
  • EmailCodeConfig (95-95)
  • PhoneCodeConfig (99-99)
  • Web3SignatureConfig (100-100)
  • ResetPasswordPhoneCodeFactorConfig (92-92)
  • ResetPasswordEmailCodeFactorConfig (93-93)
  • SamlConfig (110-113)
  • EnterpriseSSOConfig (115-119)
packages/clerk-js/src/core/errors.ts (1)
  • clerkInvalidStrategy (59-61)
⏰ 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). (23)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
.changeset/thirty-knives-refuse.md (1)

1-5: Changeset entry looks good

Patch release scoped to @clerk/clerk-js with a concise summary. No issues.

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

38-39: Good: centralized debug logger import

Consistent with SignIn; enables buffered logging before real logger init.


75-107: Status accessors with transition logging look solid

Backed by a private field; logs only on change; avoids null spam.


153-159: Good: prepareVerification debug log

Includes id and strategy; helpful for flow traces.


161-167: Good: attemptVerification debug log

Consistent with prepare; minimal context, no PII leakage.

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

56-57: Good: centralized debug logger import

Matches SignUp; consistent instrumentation.


93-115: Status accessors with transition logging look correct

Logs only on actual changes; avoids null noise.


263-277: Second factor instrumentation is consistent

Minimal and helpful debug logs; no PII exposure.

params.strategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
const strategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
if (strategy) {
params.strategy = strategy as SignUpCreateParams['strategy'];
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 want to modify the input params directly vs the prior _params?

Copy link
Member Author

Choose a reason for hiding this comment

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

We should not: 9202934

};

prepareFirstFactor = (factor: PrepareFirstFactorParams): Promise<SignInResource> => {
prepareFirstFactor = (params: PrepareFirstFactorParams): Promise<SignInResource> => {
Copy link
Member Author

Choose a reason for hiding this comment

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

Renamed this to params for consistency with other methods and classes

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)

128-153: Don’t override a caller-provided strategy; improve CAPTCHA error; log effective params

  • Overwrites params.strategy when transfer+bypass are true. Only infer when strategy is absent to avoid surprising callers.
  • Provide a meaningful error message for CAPTCHA failures.
  • Log the final effective strategy/transfer to aid traceability.
  • Nice: cloning into finalParams avoids mutating inputs. (Follow-up to prior thread.)

Apply:

-  create = async (params: SignUpCreateParams): Promise<SignUpResource> => {
-    debugLogger.debug('SignUp.create', { id: this.id, strategy: params.strategy });
+  /**
+   * Create a sign-up.
+   * Strategy is inferred only when not explicitly provided.
+   * @public
+   */
+  create = async (params: SignUpCreateParams): Promise<SignUpResource> => {
+    debugLogger.debug('SignUp.create', { id: this.id, strategy: params.strategy });
 
     let finalParams = { ...params };
 
     if (!__BUILD_DISABLE_RHC__ && !this.clientBypass() && !this.shouldBypassCaptchaForAttempt(params)) {
       const captchaChallenge = new CaptchaChallenge(SignUp.clerk);
       const captchaParams = await captchaChallenge.managedOrInvisible({ action: 'signup' });
       if (!captchaParams) {
-        throw new ClerkRuntimeError('', { code: 'captcha_unavailable' });
+        throw new ClerkRuntimeError('Captcha challenge unavailable or failed to initialize.', {
+          code: 'captcha_unavailable',
+        });
       }
       finalParams = { ...finalParams, ...captchaParams };
     }
 
-    if (finalParams.transfer && this.shouldBypassCaptchaForAttempt(finalParams)) {
+    if (finalParams.transfer && !finalParams.strategy && this.shouldBypassCaptchaForAttempt(finalParams)) {
       const strategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
       if (strategy) {
         finalParams = { ...finalParams, strategy: strategy as SignUpCreateParams['strategy'] };
       }
     }
 
-    return this._basePost({
+    debugLogger.debug('SignUp.create.final', {
+      id: this.id,
+      strategy: finalParams.strategy,
+      transfer: !!finalParams.transfer,
+    });
+    return this._basePost({
       path: this.pathRoot,
       body: normalizeUnsafeMetadata(finalParams),
     });
   };

Optional follow-up: consider inferring transfer-bypass strategy before launching CAPTCHA to avoid unnecessary challenges when we already know we’ll bypass.

📜 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 24ffe10 and 9202934.

📒 Files selected for processing (1)
  • packages/clerk-js/src/core/resources/SignUp.ts (4 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/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 (4)
packages/types/src/signUpCommon.ts (4)
  • SignUpStatus (25-25)
  • SignUpCreateParams (81-104)
  • PrepareVerificationParams (29-55)
  • AttemptVerificationParams (57-65)
packages/clerk-js/src/utils/debug.ts (1)
  • debugLogger (150-179)
packages/clerk-js/src/utils/captcha/CaptchaChallenge.ts (1)
  • CaptchaChallenge (8-92)
packages/shared/src/error.ts (1)
  • ClerkRuntimeError (241-281)
⏰ 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: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/src/core/resources/SignUp.ts (4)

38-39: Logging instrumentation import — OK

Brings in debug logger without side effects; aligns with the PR goal.


75-79: Private backing field for status — OK

Encapsulation looks good; snapshot/fromJSON still map through the accessor.


156-161: prepareVerification debug log — OK

Captures strategy context without leaking sensitive data.


164-169: attemptVerification debug log — OK

Consistent with prepareVerification; good for tracing.

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 (3)
packages/clerk-js/src/core/resources/SignIn.ts (3)

56-56: Add a consistent log source for easier filtering.

Pass a stable source to all debug logs and avoid repeating the class name string.

 import { debugLogger } from '@/utils/debug';
+const LOG_SOURCE = 'SignIn';
- debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined });
+ debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined }, LOG_SOURCE);
- debugLogger.debug('SignIn.prepareFirstFactor', { id: this.id, strategy: params.strategy });
+ debugLogger.debug('SignIn.prepareFirstFactor', { id: this.id, strategy: params.strategy }, LOG_SOURCE);
- debugLogger.debug('SignIn.attemptFirstFactor', { id: this.id, strategy: params.strategy });
+ debugLogger.debug('SignIn.attemptFirstFactor', { id: this.id, strategy: params.strategy }, LOG_SOURCE);
- debugLogger.debug('SignIn.prepareSecondFactor', { id: this.id, strategy: params.strategy });
+ debugLogger.debug('SignIn.prepareSecondFactor', { id: this.id, strategy: params.strategy }, LOG_SOURCE);
- debugLogger.debug('SignIn.attemptSecondFactor', { id: this.id, strategy: params.strategy });
+ debugLogger.debug('SignIn.attemptSecondFactor', { id: this.id, strategy: params.strategy }, LOG_SOURCE);

Also applies to: 149-149, 164-164, 221-221, 276-276, 284-284


112-126: Also log transitions to null to capture full lifecycle.

Currently transitions to null are silent. Logging all changes helps trace resets (e.g., after finalize/failure).

-    if (value && previousStatus !== value) {
+    if (previousStatus !== value) {
       debugLogger.debug('SignIn.status', { id: this.id, from: previousStatus, to: value });
     }

220-237: Avoid duplicating strategy in the request body.

Spreading params then re-setting strategy duplicates the key. Harmless but noisy.

-    switch (params.strategy) {
+    switch (params.strategy) {
       case 'passkey':
         config = {
           publicKeyCredential: JSON.stringify(serializePublicKeyCredentialAssertion(params.publicKeyCredential)),
         };
         break;
       default:
-        config = { ...params };
+        {
+          const { strategy, ...rest } = params as Record<string, unknown>;
+          config = rest;
+        }
     }
📜 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 9202934 and 180635d.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/resources/SignIn.ts (6 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/core/resources/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/SignIn.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/SignIn.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/SignIn.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/SignIn.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/SignIn.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/SignIn.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/SignIn.ts (6)
packages/types/src/signInCommon.ts (5)
  • SignInStatus (61-66)
  • SignInCreateParams (123-164)
  • PrepareFirstFactorParams (98-108)
  • AttemptFirstFactorParams (110-117)
  • AttemptSecondFactorParams (121-121)
packages/clerk-js/src/utils/debug.ts (1)
  • debugLogger (150-179)
packages/types/src/signIn.ts (1)
  • SignInResource (34-91)
packages/types/src/factors.ts (9)
  • PassKeyConfig (102-102)
  • EmailLinkConfig (96-98)
  • EmailCodeConfig (95-95)
  • PhoneCodeConfig (99-99)
  • Web3SignatureConfig (100-100)
  • ResetPasswordPhoneCodeFactorConfig (92-92)
  • ResetPasswordEmailCodeFactorConfig (93-93)
  • SamlConfig (110-113)
  • EnterpriseSSOConfig (115-119)
packages/clerk-js/src/core/errors.ts (1)
  • clerkInvalidStrategy (59-61)
packages/clerk-js/src/utils/passkeys.ts (1)
  • serializePublicKeyCredentialAssertion (233-233)
⏰ 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: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (7)
packages/clerk-js/src/core/resources/SignIn.ts (7)

93-93: Private backing field for status looks good.

Matches the interface and enables controlled updates.


103-111: Getter is clean and typed correctly.

No further action.


148-154: create(): correct return type and minimal logging.

Return type aligns with SignInResource; logging avoids PII. LGTM.


275-281: prepareSecondFactor logging: LGTM.

Minimal, non-PII, consistent with create/first-factor.


284-289: attemptSecondFactor logging: LGTM.

Consistent and safe.


163-213: Confirm prepareFirstFactor handles all non-OAuth first-factor strategies and that no OAuth (‘oauth_*’) strategies are routed here. prepareFirstFactor currently handles passkey, email_link, email_code, phone_code, web3_metamask_signature, web3_base_signature, web3_coinbase_wallet_signature, web3_okx_wallet_signature, reset_password_phone_code, reset_password_email_code, saml and enterprise_sso; OAuth strategies should be invoked via authenticateWithRedirect/create—verify no callers pass an ‘oauth_*’ strategy to prepareFirstFactor.


226-227: No change required: backend expects a JSON string
The Frontend API schema for passkey verification defines public_key_credential as a string, so wrapping the serialized object in JSON.stringify is correct.

@jacekradko jacekradko merged commit efb6fac into main Aug 29, 2025
39 checks passed
@jacekradko jacekradko deleted the feat/clerkjs-error-debug-logs branch August 29, 2025 18:46
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.

3 participants