Skip to content

Conversation

@tmilewski
Copy link
Member

@tmilewski tmilewski commented Oct 31, 2025

Description

(NOTE: Currently behind a feature flag.)

Enables support for email_code and email_link as a second factor in the AIO components.

This flow is hit when a user is signing-in on a new device. If they are using email alongside password as their first factor, and don't have any MFA options enabled, they will be required to verify.

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

    • Email code and email link now supported as second-factor sign-in methods
    • New-device verification notice shown when signing in from an unfamiliar device
  • Bug Fixes / UX

    • Improved warning/alert presentation and hover/border behavior across verification UI
    • Tag input hover/border behavior refined
  • Localization

    • Added MFA and device-verification strings for 40+ locales
  • Chores

    • Minor package version bumps and bundle size cap adjustment

@tmilewski tmilewski self-assigned this Oct 31, 2025
@changeset-bot
Copy link

changeset-bot bot commented Oct 31, 2025

🦋 Changeset detected

Latest commit: 749ca74

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

This PR includes changesets to release 19 packages
Name Type
@clerk/localizations Minor
@clerk/clerk-js Minor
@clerk/types Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing 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

@vercel
Copy link

vercel bot commented Oct 31, 2025

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

1 Skipped Deployment
Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Skipped Skipped Nov 12, 2025 6:34am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 31, 2025

Walkthrough

Adds email_code and email_link as second-factor sign-in methods with new UI cards and dynamic prepare flow, updates core sign-in routing and types, tweaks Alert/styling behavior, and adds localization keys and notices across many locales.

Changes

Cohort / File(s) Summary
Release Declarations
\.changeset/bright-heads-start.md``
Added changeset bumping @clerk/localizations, @clerk/clerk-js, and @clerk/types; notes support for email_code and email_link as second factors on new-device sign-in.
Core Sign-In Logic
\packages/clerk-js/src/core/resources/SignIn.ts``
Switches email_link handling to a dynamic verification flow: chooses prepareFirstFactor or prepareSecondFactor based on needs_second_factor, tracks dynamic verification key, and reloads status from that key.
Second-Factor UI Entrypoints
\packages/clerk-js/src/ui/components/SignIn/SignInFactorTwo.tsx`, `.../SignInFactorTwoAlternativeMethods.tsx`, `.../SignInFactorTwoCodeForm.tsx``
Adds email_code and email_link handling, centralizes factorAlreadyPrepared check, introduces isNewDevice helper, and surfaces cardNotice for new-device notice in code form.
New Second-Factor Cards
\packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailCodeCard.tsx`, `.../SignInFactorTwoEmailLinkCard.tsx``
New components: EmailCode card (calls prepareSecondFactor with emailAddressId) and EmailLink card (starts email-link flow, handles verification results, modal/activation/redirect). Exports new SignInFactorTwoEmailLinkCardProps and component.
Verification Elements
\packages/clerk-js/src/ui/elements/VerificationCodeCard.tsx`, `.../VerificationLinkCard.tsx``
Added optional cardNotice?: LocalizationKey prop and conditional render of a warning Alert with caption text when provided.
Primitives & Styling
\packages/clerk-js/src/ui/primitives/Alert.tsx`, `packages/clerk-js/src/ui/styledSystem/common.ts``
Border variants refactored to accept hoverStyles flag; normal-state borderColor/boxShadow computed dynamically (handle hasError/hasWarning); hover styles can be disabled.
Small UI Changes
\packages/clerk-js/src/ui/components/OAuthConsent/OAuthConsent.tsx`, `packages/clerk-js/src/ui/elements/TagInput.tsx``
Replaced custom Box warning with Alert in OAuthConsent; TagInput passes hoverStyles: true into borderVariants.
Flow Metadata & Types
\packages/clerk-js/src/ui/elements/contexts/index.tsx`, `packages/shared/src/types/localization.ts`, `packages/shared/src/types/signInCommon.ts``
Added emailCode2Fa to FlowMetadata.part; added emailCodeMfa, emailLinkMfa, newDeviceVerificationNotice to localization types; extended SignInSecondFactor and PrepareSecondFactorParams to include EmailLink types.
Localizations (40+ locales)
\packages/localizations/src/*.ts``
Added emailCodeMfa, emailLinkMfa, and newDeviceVerificationNotice keys across many locales. Most emailCodeMfa fields are placeholders; many emailLinkMfa entries include localized strings.
Bundle Config
\packages/clerk-js/bundlewatch.config.json``
Increased headless bundle size cap from 63KB to 63.2KB.
Machines / Type Suppression
\packages/elements/src/internals/machines/sign-in/verification.machine.ts``
Added a ts-expect-error to suppress a TypeScript complaint before calling attemptSecondFactor with email_link params (type-check suppression only).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ClientSignIn as SignIn (client)
    participant ServerSignIn as SignIn (server)
    participant UI as SignInFactorTwo
    participant EmailCodeCard
    participant EmailLinkCard

    User->>ClientSignIn: submit credentials
    ClientSignIn->>ServerSignIn: prepareFirstFactor()
    ServerSignIn-->>ClientSignIn: status (may be needs_second_factor)
    alt needs_second_factor
        ClientSignIn->>UI: load second factors
        UI->>EmailCodeCard: render (if email_code)
        UI->>EmailLinkCard: render/init (if email_link)
        EmailCodeCard->>ServerSignIn: prepareSecondFactor({ emailAddressId, strategy })
        EmailLinkCard->>ServerSignIn: prepareSecondFactor(...) + startEmailLinkFlow(redirectUrl)
        note right of EmailLinkCard: waits for user to click link in email
        EmailLinkCard->>ServerSignIn: handleVerificationResult → activate session / show modal / set error
    else continue_first_factor
        ClientSignIn->>ServerSignIn: continue first-factor verification
    end
    ServerSignIn-->>User: final auth result / redirect
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

  • Focus review on:
    • packages/clerk-js/src/core/resources/SignIn.ts — dynamic verification routing and verification-key handling.
    • New components: SignInFactorTwoEmailCodeCard.tsx, SignInFactorTwoEmailLinkCard.tsx — state, verification/error/redirect flows.
    • Type updates: packages/shared/src/types/signInCommon.ts and localization type additions in packages/shared/src/types/localization.ts.
    • UI prop usage: cardNotice in VerificationCodeCard / VerificationLinkCard and Alert/styling changes.
    • The ts-expect-error in verification.machine.ts (ensure intentional and safe).

Poem

"i hop and sniff the new device,
codes and links make logging nice;
alert bells hum, a modal glows,
email hops where security goes.
tiny paws approve — now off I bounce!" 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: adding support for email_code and email_link as second factor authentication when signing in on a new device.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tom/supported-factors

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 a119a90 and 749ca74.

📒 Files selected for processing (1)
  • packages/elements/src/internals/machines/sign-in/verification.machine.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{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/elements/src/internals/machines/sign-in/verification.machine.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/elements/src/internals/machines/sign-in/verification.machine.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/elements/src/internals/machines/sign-in/verification.machine.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/elements/src/internals/machines/sign-in/verification.machine.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/elements/src/internals/machines/sign-in/verification.machine.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). (3)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)

Comment @coderabbitai help to get the list of available commands and usage tips.

@tmilewski tmilewski changed the title feat: Prep work to support email_code as a second factor feat: Prep work to support email_code as a second factor Oct 31, 2025
@tmilewski tmilewski changed the title feat: Prep work to support email_code as a second factor feat(clerk-js,localizations,types): Prep work to support email_code as a second factor Nov 3, 2025
@tmilewski tmilewski force-pushed the chris/supported_factors branch from 4ee26f2 to 1b81587 Compare November 4, 2025 21:07
Base automatically changed from chris/supported_factors to main November 4, 2025 21:26
@tmilewski tmilewski force-pushed the tom/supported-factors branch from f63f334 to 5db2bb6 Compare November 11, 2025 20:07
@clerk-cookie clerk-cookie added expo and removed types labels Nov 11, 2025
@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 11, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 749ca74

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

chriscanin and others added 9 commits November 12, 2025 00:35
… to Client and SignIn resources

  - Trusted users automatically see password
  - Untrusted users automatically don't see password
  - Added Expo dummy data.
…tors to Client and SignIn resources for fraud protection
… to Client and SignIn resources

  - Trusted users automatically see password
  - Untrusted users automatically don't see password
  - Added Expo dummy data.
coderabbitai[bot]

This comment was marked as resolved.

@clerk-cookie clerk-cookie removed the expo label Nov 12, 2025
@tmilewski tmilewski changed the title feat(clerk-js,localizations,types): Prep work to support email_code as a second factor feat(clerk-js,localizations,types): Support for email_code and email_link as a second factor when user is signing in on a new device. Nov 12, 2025
@tmilewski tmilewski changed the title feat(clerk-js,localizations,types): Support for email_code and email_link as a second factor when user is signing in on a new device. feat(clerk-js,localizations,types): Support email_code and email_link as 2FA when signing in on new device Nov 12, 2025
@tmilewski tmilewski changed the title feat(clerk-js,localizations,types): Support email_code and email_link as 2FA when signing in on new device feat(clerk-js,localizations,types): email_code & email_link as 2FA when signing in on new device Nov 12, 2025
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

🧹 Nitpick comments (5)
packages/shared/src/types/signInCommon.ts (2)

121-121: Consider renaming EmailLinkConfig for consistency.

While the type inclusion is correct, there's a naming inconsistency: other second-factor configs use the SecondFactorConfig suffix (PhoneCodeSecondFactorConfig, EmailCodeSecondFactorConfig), but EmailLinkConfig does not. Consider introducing an EmailLinkSecondFactorConfig type alias or renaming for clarity and consistency.

Example refactor:

// In factors.ts, add:
export type EmailLinkSecondFactorConfig = EmailLinkConfig;

// Then use it here:
export type PrepareSecondFactorParams = PhoneCodeSecondFactorConfig | EmailCodeSecondFactorConfig | EmailLinkSecondFactorConfig;

63-123: Consider adding JSDoc comments for public API types.

Per coding guidelines, "All public APIs must be documented with JSDoc." These exported types (SignInStatus, SignInFirstFactor, SignInSecondFactor, PrepareSecondFactorParams, etc.) are part of the public API but lack documentation. Adding JSDoc would help consumers understand:

  • When each type is used in the sign-in flow
  • The purpose of each factor strategy
  • The relationship between prepare and attempt parameter types

As per coding guidelines

Example:

/**
 * Represents the possible statuses during the sign-in process.
 * Used to determine which step of authentication the user is currently on.
 */
export type SignInStatus =
  | 'needs_identifier'
  | 'needs_first_factor'
  | 'needs_second_factor'
  | 'needs_new_password'
  | 'complete';

/**
 * Defines the valid second-factor authentication methods.
 * Used when additional verification is required after first-factor auth.
 */
export type SignInSecondFactor = PhoneCodeFactor | TOTPFactor | BackupCodeFactor | EmailCodeFactor | EmailLinkFactor;
packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx (3)

17-21: Remove unused props from the type definition.

The factorAlreadyPrepared and onFactorPrepare props are defined in the type but never used in the component implementation.

Apply this diff to clean up the interface:

-type SignInFactorTwoEmailLinkCardProps = Pick<VerificationCodeCardProps, 'onShowAlternativeMethodsClicked'> & {
+type SignInFactorTwoEmailLinkCardProps = {
   factor: EmailLinkFactor;
-  factorAlreadyPrepared: boolean;
-  onFactorPrepare: () => void;
+  onShowAlternativeMethodsClicked?: React.MouseEventHandler;
 };

23-23: Extract the duplicated isNewDevice helper to a shared utility.

This helper is duplicated in SignInFactorTwoCodeForm.tsx. Consider extracting it to a shared module to follow DRY principles.

Create a shared utility file (e.g., utils/signInHelpers.ts):

import type { SignInResource } from '@clerk/shared/types';

export const isNewDevice = (resource: SignInResource): boolean => 
  resource.clientTrustState === 'new';

Then import it in both files:

+import { isNewDevice } from '../../utils/signInHelpers';
-const isNewDevice = (resource: SignInResource) => resource.clientTrustState === 'new';

37-60: Consider wrapping startEmailLinkVerification in useCallback for proper hook dependencies.

The useEffect calls startEmailLinkVerification, but the function isn't memoized and depends on props and context values. While the empty dependency array is intentional (to run once on mount), this pattern may trigger ESLint warnings.

Wrap the function in useCallback:

+const startEmailLinkVerification = React.useCallback(() => {
-const startEmailLinkVerification = () => {
   startEmailLinkFlow({
     emailAddressId: props.factor.emailAddressId,
     redirectUrl: buildVerificationRedirectUrl({ ctx: signInContext, baseUrl: signInUrl, intent: 'sign-in' }),
   })
     .then(res => handleVerificationResult(res))
     .catch(err => {
       if (isUserLockedError(err)) {
         // @ts-expect-error -- private method for the time being
         return clerk.__internal_navigateWithError('..', err.errors[0]);
       }

       handleError(err, [], card.setError);
     });
+}, [props.factor.emailAddressId, signInContext, signInUrl, startEmailLinkFlow, clerk, card.setError]);
};

 React.useEffect(() => {
   void startEmailLinkVerification();
-}, []);
+}, [startEmailLinkVerification]);
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 6af8a9f and a119a90.

📒 Files selected for processing (2)
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx (1 hunks)
  • packages/shared/src/types/signInCommon.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/shared/src/types/signInCommon.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
**/*.{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/shared/src/types/signInCommon.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/types/signInCommon.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/types/signInCommon.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
**/*.{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/shared/src/types/signInCommon.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
**/*.tsx

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

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
🧬 Code graph analysis (2)
packages/shared/src/types/signInCommon.ts (1)
packages/shared/src/types/factors.ts (3)
  • EmailLinkFactor (26-31)
  • EmailCodeSecondFactorConfig (142-145)
  • EmailLinkConfig (104-106)
packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx (9)
packages/clerk-js/src/ui/elements/VerificationCodeCard.tsx (1)
  • VerificationCodeCardProps (13-32)
packages/shared/src/types/factors.ts (1)
  • EmailLinkFactor (26-31)
packages/shared/src/types/signIn.ts (1)
  • SignInResource (35-93)
packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
  • useCardState (42-70)
packages/clerk-js/src/ui/contexts/components/SignIn.ts (1)
  • useSignInContext (38-169)
packages/clerk-js/src/ui/common/redirects.ts (1)
  • buildVerificationRedirectUrl (7-26)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (64-86)
packages/clerk-js/src/ui/common/EmailLinkStatusCard.tsx (1)
  • EmailLinkStatusCard (38-57)
packages/clerk-js/src/ui/elements/VerificationLinkCard.tsx (1)
  • VerificationLinkCard (25-76)
⏰ 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: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/shared/src/types/signInCommon.ts (1)

89-89: LGTM! Past review concern addressed.

EmailLinkFactor has been correctly added to the SignInSecondFactor union, addressing the previous review feedback. This change is consistent with PrepareSecondFactorParams including EmailLinkConfig and enables email_link as a valid second-factor option.

packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx (2)

76-84: LGTM!

The conditional rendering for the verification modal correctly uses localized strings and the EmailLinkStatusCard component with appropriate status.


25-102: Well-structured component following established patterns.

The component correctly:

  • Uses localization for all user-facing strings
  • Handles errors via the centralized handleError utility
  • Follows the existing email link verification patterns from similar components
  • Properly manages modal state and navigation flow

Comment on lines +62 to +74
const handleVerificationResult = async (si: SignInResource) => {
const ver = si.secondFactorVerification;
if (ver.status === 'expired') {
card.setError(t(localizationKeys('formFieldError__verificationLinkExpired')));
} else if (ver.verifiedFromTheSameClient()) {
setShowVerifyModal(true);
} else {
await setActive({
session: si.createdSessionId,
redirectUrl: afterSignInUrl,
});
}
};
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 | 🔴 Critical

🧩 Analysis chain

Verify that session creation is guaranteed after second factor verification.

The function directly calls setActive with si.createdSessionId without checking if si.status === 'complete' or if createdSessionId is non-null. While this may be the expected flow after second factor verification, defensive checks would prevent potential runtime errors.

Run the following script to verify how other second-factor handlers check status before activation:


🏁 Script executed:

#!/bin/bash
# Search for patterns of setActive calls after second factor verification
rg -nP --type=tsx -A5 -B5 'secondFactorVerification.*status.*complete|setActive.*createdSessionId' -g '!**/test/**'

Length of output: 27


🏁 Script executed:

#!/bin/bash
# Search for setActive patterns with createdSessionId and secondFactorVerification checks
rg -nP -A5 -B5 'setActive.*createdSessionId|secondFactorVerification' -g '*.tsx' -g '!**/test/**'

Length of output: 5400


🏁 Script executed:

#!/bin/bash
# Specifically look at SignInFactorOneEmailLinkCard to compare patterns
fd -t f 'SignInFactorOneEmailLinkCard' -g '*.tsx'

Length of output: 92


🏁 Script executed:

#!/bin/bash
# Check if createdSessionId is ever null-checked in the codebase
rg -nP 'createdSessionId.*null|createdSessionId\s*\?' -g '*.tsx' -g '!**/test/**'

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Search for si.status checks after factor verification
rg -nP 'si\.status.*complete|secondFactorVerification.*status' -g '*.tsx' -g '!**/test/**' -A3 -B3

Length of output: 755


🏁 Script executed:

#!/bin/bash
# Check the SignIn resource type definition to understand createdSessionId contract
fd -t f '*.ts' -g '!**/test/**' -g '!**/node_modules/**' | xargs grep -l 'createdSessionId' | head -5

Length of output: 164


🏁 Script executed:

#!/bin/bash
# Look at the full SignInFactorTwoEmailLinkCard file for context
cat packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx

Length of output: 3943


Add defensive status check before session activation in the else branch.

The code calls setActive without verifying si.status === 'complete', which is inconsistent with SignInFactorOneEmailLinkCard (lines 74-76) and other handlers throughout the codebase. Add the status check before activation on line 71:

} else if (si.status === 'complete') {
  await setActive({
    session: si.createdSessionId,
    redirectUrl: afterSignInUrl,
  });
}

Handle the unexpected case where status is neither 'expired', nor 'verifiedFromTheSameClient', nor 'complete' (e.g., with card.setError).

🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
around lines 62 to 74, the code activates the session unconditionally in the
final else branch; change this to only call setActive when si.status ===
'complete' and, if not complete and not expired and not
verifiedFromTheSameClient, set a card error (use the existing localization key
for an unexpected verification state) so unexpected statuses are handled
defensively.

Comment on lines +86 to +101
return (
<Flow.Part part='emailLink'>
<VerificationLinkCard
cardTitle={localizationKeys('signIn.emailLinkMfa.title')}
cardSubtitle={localizationKeys('signIn.emailLinkMfa.subtitle')}
cardNotice={isNewDevice(signIn) ? localizationKeys('signIn.newDeviceVerificationNotice') : undefined}
formTitle={localizationKeys('signIn.emailLinkMfa.formTitle')}
formSubtitle={localizationKeys('signIn.emailLinkMfa.formSubtitle')}
resendButton={localizationKeys('signIn.emailLinkMfa.resendButton')}
onResendCodeClicked={restartVerification}
safeIdentifier={props.factor.safeIdentifier}
profileImageUrl={signIn.userData.imageUrl}
onShowAlternativeMethodsClicked={props.onShowAlternativeMethodsClicked}
/>
</Flow.Part>
);
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 | 🔴 Critical

🧩 Analysis chain

Verify that the formTitle prop is used by VerificationLinkCard.

Line 92 passes formTitle to VerificationLinkCard, but the component snippet provided only shows usage of formSubtitle in the VerificationLink sub-component. Ensure this prop is actually consumed.

Run the following script to check the VerificationLinkCard prop interface:


🏁 Script executed:

#!/bin/bash
# Find the VerificationLinkCardProps type definition
ast-grep --pattern $'export type VerificationLinkCardProps = {
  $$$
}'

# Also search for formTitle usage in VerificationLinkCard
rg -nP 'formTitle' packages/clerk-js/src/ui/elements/VerificationLinkCard.tsx

Length of output: 32


The web search didn't provide specific information about the VerificationLinkCard component internals. Let me search the codebase directly to check if formTitle is actually used in the component's render logic.


---

🏁 Script executed:

```shell
#!/bin/bash
# Get the full VerificationLinkCard component to see if formTitle is used
cat packages/clerk-js/src/ui/elements/VerificationLinkCard.tsx

Length of output: 3508


Remove the unused formTitle prop from VerificationLinkCard.

The formTitle prop is declared in VerificationLinkCardProps (line 17 of VerificationLinkCard.tsx) but is never consumed anywhere in the component. It should be removed from the interface definition in VerificationLinkCard.tsx and from the call site in SignInFactorTwoEmailLinkCard.tsx (line 92).

🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/SignIn/SignInFactorTwoEmailLinkCard.tsx
around lines 86-101 and
packages/clerk-js/src/ui/components/VerificationLinkCard.tsx at the
VerificationLinkCardProps declaration (around line 17), the formTitle prop is
declared but unused; remove formTitle from the VerificationLinkCardProps
interface/type in VerificationLinkCard.tsx and delete the
formTitle={localizationKeys('signIn.emailLinkMfa.formTitle')} prop from the
VerificationLinkCard call in SignInFactorTwoEmailLinkCard.tsx (also search for
and remove any other uses or default values of formTitle across the component
and its tests/types), then run type-checks to ensure no remaining references
cause errors.

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