-
Notifications
You must be signed in to change notification settings - Fork 381
feat(clerk-js,clerk-react,types): Signal MFA support #6659
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
🦋 Changeset detectedLatest commit: 4df6168 The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
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 |
WalkthroughAdds experimental MFA support to sign-in flows. Introduces new MFA methods and types, exposes them under a new mfa namespace on SignInFuture, and wires them through the React state proxy. Includes a changeset declaring minor bumps for @clerk/clerk-js, @clerk/clerk-react, and @clerk/types. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor U as User
participant App as App (React)
participant Proxy as StateProxy.signIn.mfa
participant JS as SignInFuture (clerk-js)
participant API as Clerk API
U->>App: Initiate MFA via phone
App->>Proxy: mfa.sendPhoneCode()
Proxy->>JS: sendMFAPhoneCode()
JS->>API: POST /prepare_second_factor (phone_code)
API-->>JS: 200 OK
JS-->>Proxy: Promise resolved
Proxy-->>App: Done
U->>App: Enter SMS code
App->>Proxy: mfa.verifyPhoneCode({ code })
Proxy->>JS: verifyMFAPhoneCode({ code })
JS->>API: POST /attempt_second_factor (phone_code, code)
alt Success
API-->>JS: 200 OK
JS-->>Proxy: Promise resolved
Proxy-->>App: Success
else Error
API-->>JS: 4xx/5xx
JS-->>Proxy: Promise with { error }
Proxy-->>App: Error surfaced
end
sequenceDiagram
autonumber
actor U as User
participant App as App (React)
participant Proxy as StateProxy.signIn.mfa
participant JS as SignInFuture (clerk-js)
participant API as Clerk API
rect rgba(200,235,255,0.3)
note over U,API: TOTP or Backup Code MFA
U->>App: Enter TOTP or backup code
App->>Proxy: mfa.verifyTOTP({ code }) or mfa.verifyBackupCode({ code })
Proxy->>JS: verifyTOTP(...) / verifyBackupCode(...)
JS->>API: POST /attempt_second_factor (type: totp|backup_code, code)
API-->>JS: Result
JS-->>Proxy: Promise resolved with result/error
Proxy-->>App: Propagate outcome
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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
🧹 Nitpick comments (6)
packages/types/src/signInFuture.ts (1)
54-65
: Add JSDoc and make params readonly (public API polish).These new public types lack JSDoc and use mutable fields. Recommend documenting intent and marking fields readonly.
Apply this diff:
-export interface SignInFutureMFAPhoneCodeVerifyParams { - code: string; -} +/** Parameters to verify an MFA phone code second factor. */ +export interface SignInFutureMFAPhoneCodeVerifyParams { + readonly code: string; +} -export interface SignInFutureTOTPVerifyParams { - code: string; -} +/** Parameters to verify a TOTP second factor. */ +export interface SignInFutureTOTPVerifyParams { + readonly code: string; +} -export interface SignInFutureBackupCodeVerifyParams { - code: string; -} +/** Parameters to verify a backup code second factor. */ +export interface SignInFutureBackupCodeVerifyParams { + readonly code: string; +}packages/clerk-js/src/core/resources/SignIn.ts (5)
30-43
: Type imports are correct; consider naming consistency across MFA param types.Minor:
SignInFutureMFAPhoneCodeVerifyParams
uses an MFA prefix while TOTP/backup code types don’t. Optional alignment for consistency (not blocking).
521-526
: Expose MFA surface with an explicit experimental JSDoc.Add a short JSDoc to mfa to mark the API surface as experimental and describe methods.
Apply this diff:
- mfa = { + /** + * @experimental MFA-related second factor helpers for custom sign-in flows. + * Includes phone code, TOTP, and backup code verification. + */ + mfa = { sendPhoneCode: this.sendMFAPhoneCode.bind(this), verifyPhoneCode: this.verifyMFAPhoneCode.bind(this), verifyTOTP: this.verifyTOTP.bind(this), verifyBackupCode: this.verifyBackupCode.bind(this), };
717-725
: Trim user input and add sign-in guard.Prevents whitespace-related failures and early misuse.
Apply this diff:
- async verifyMFAPhoneCode(params: SignInFutureMFAPhoneCodeVerifyParams): Promise<{ error: unknown }> { - const { code } = params; + async verifyMFAPhoneCode(params: SignInFutureMFAPhoneCodeVerifyParams): Promise<{ error: unknown }> { + if (!this.resource.id) { + throw new Error('Cannot verify MFA phone code without an active sign-in.'); + } + const code = params.code.trim(); return runAsyncResourceTask(this.resource, async () => { await this.resource.__internal_basePost({ body: { code, strategy: 'phone_code' }, action: 'attempt_second_factor', }); }); }
727-735
: Trim code and add sign-in guard (TOTP).Aligns with other guards; avoids subtle user input errors.
Apply this diff:
- async verifyTOTP(params: SignInFutureTOTPVerifyParams): Promise<{ error: unknown }> { - const { code } = params; + async verifyTOTP(params: SignInFutureTOTPVerifyParams): Promise<{ error: unknown }> { + if (!this.resource.id) { + throw new Error('Cannot verify TOTP without an active sign-in.'); + } + const code = params.code.trim(); return runAsyncResourceTask(this.resource, async () => { await this.resource.__internal_basePost({ body: { code, strategy: 'totp' }, action: 'attempt_second_factor', }); }); }
737-745
: Trim code and add sign-in guard (backup code).Same rationale as above.
Apply this diff:
- async verifyBackupCode(params: SignInFutureBackupCodeVerifyParams): Promise<{ error: unknown }> { - const { code } = params; + async verifyBackupCode(params: SignInFutureBackupCodeVerifyParams): Promise<{ error: unknown }> { + if (!this.resource.id) { + throw new Error('Cannot verify backup code without an active sign-in.'); + } + const code = params.code.trim(); return runAsyncResourceTask(this.resource, async () => { await this.resource.__internal_basePost({ body: { code, strategy: 'backup_code' }, action: 'attempt_second_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.
📒 Files selected for processing (4)
.changeset/twelve-fans-smell.md
(1 hunks)packages/clerk-js/src/core/resources/SignIn.ts
(3 hunks)packages/react/src/stateProxy.ts
(1 hunks)packages/types/src/signInFuture.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/twelve-fans-smell.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/react/src/stateProxy.ts
packages/types/src/signInFuture.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/react/src/stateProxy.ts
packages/types/src/signInFuture.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/react/src/stateProxy.ts
packages/types/src/signInFuture.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/react/src/stateProxy.ts
packages/types/src/signInFuture.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/react/src/stateProxy.ts
packages/types/src/signInFuture.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/react/src/stateProxy.ts
packages/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignIn.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/SignIn.ts (2)
packages/clerk-js/src/utils/runAsyncResourceTask.ts (1)
runAsyncResourceTask
(8-30)packages/types/src/signInFuture.ts (3)
SignInFutureMFAPhoneCodeVerifyParams
(54-56)SignInFutureTOTPVerifyParams
(58-60)SignInFutureBackupCodeVerifyParams
(62-64)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
.changeset/twelve-fans-smell.md (1)
1-7
: Changeset looks correct for a minor, experimental feature.Packages and summary align with the public API additions introduced in this PR.
packages/types/src/signInFuture.ts (1)
91-96
: Add optionalchannel
param and JSDoc tomfa.sendPhoneCode
insignInFuture.ts
Change:mfa: { sendPhoneCode: () => Promise<{ error: unknown }>; … }to:
mfa: { /** Send an MFA phone code. Defaults to 'sms' if omitted. */ sendPhoneCode: (params?: { channel?: PhoneCodeChannel }) => Promise<{ error: unknown }>; … }Server-side
SignIn.sendPhoneCode
already acceptschannel
(defaulting to'sms'
) in itsprepare_first_factor
call .packages/react/src/stateProxy.ts (1)
60-65
: LGTM: MFA methods exposed consistently via wrapMethods.Gating and exposure match existing patterns (emailCode/phoneCode).
async sendMFAPhoneCode(): Promise<{ error: unknown }> { | ||
return runAsyncResourceTask(this.resource, async () => { | ||
const phoneCodeFactor = this.resource.supportedSecondFactors?.find(f => f.strategy === 'phone_code'); | ||
|
||
if (!phoneCodeFactor) { | ||
throw new Error('Phone code factor not found'); | ||
} | ||
|
||
const { phoneNumberId } = phoneCodeFactor; | ||
await this.resource.__internal_basePost({ | ||
body: { phoneNumberId, strategy: 'phone_code' }, | ||
action: 'prepare_second_factor', | ||
}); | ||
}); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Guard against misuse, support optional channel, and improve error message.
- Add
id
guard like other flows. - Accept optional
{ channel }
(default 'sms') for parity with first factor. - Make the error actionable.
Apply this diff:
- async sendMFAPhoneCode(): Promise<{ error: unknown }> {
- return runAsyncResourceTask(this.resource, async () => {
- const phoneCodeFactor = this.resource.supportedSecondFactors?.find(f => f.strategy === 'phone_code');
+ async sendMFAPhoneCode(params?: { channel?: PhoneCodeChannel }): Promise<{ error: unknown }> {
+ return runAsyncResourceTask(this.resource, async () => {
+ if (!this.resource.id) {
+ throw new Error('Cannot send MFA phone code without an active sign-in. Call create/first factor first.');
+ }
+ const phoneCodeFactor = this.resource.supportedSecondFactors?.find(f => f.strategy === 'phone_code');
if (!phoneCodeFactor) {
- throw new Error('Phone code factor not found');
+ throw new Error(
+ 'MFA phone code factor not available. Ensure the user has a verified phone number and the first factor succeeded.',
+ );
}
const { phoneNumberId } = phoneCodeFactor;
+ const channel = params?.channel ?? 'sms';
await this.resource.__internal_basePost({
- body: { phoneNumberId, strategy: 'phone_code' },
+ body: { phoneNumberId, strategy: 'phone_code', channel },
action: 'prepare_second_factor',
});
});
}
Additional change required at the top of this file to import the type:
// near the other type imports from '@clerk/types'
import type { PhoneCodeChannel } from '@clerk/types';
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 701 to 715, the
sendMFAPhoneCode flow needs an id guard, support for an optional channel param
(default 'sms'), and a clearer error message; add an `id` guard similar to other
flows (validate phoneNumberId exists and throw a descriptive error like "Phone
code factor missing or missing id"), change the method signature to accept an
optional `{ channel?: PhoneCodeChannel }` and pass `channel` (defaulting to
'sms') into the body when calling __internal_basePost, and ensure the thrown
error is actionable; also add the required type import at the top of the file:
`import type { PhoneCodeChannel } from '@clerk/types';`.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Whatsapp is available as a supported channel only as a first factor during sign up
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@nikosdouvlis Thank you for the clarification! You're absolutely right - if WhatsApp is only available as a first factor during sign up, then adding channel support to the MFA phone code method would be inappropriate.
Let me revise my suggestion to focus on the essential improvements without the channel parameter:
- async sendMFAPhoneCode(): Promise<{ error: unknown }> {
+ async sendMFAPhoneCode(): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
+ if (!this.resource.id) {
+ throw new Error('Cannot send MFA phone code without an active sign-in. Call create/first factor first.');
+ }
const phoneCodeFactor = this.resource.supportedSecondFactors?.find(f => f.strategy === 'phone_code');
if (!phoneCodeFactor) {
- throw new Error('Phone code factor not found');
+ throw new Error(
+ 'MFA phone code factor not available. Ensure the user has a verified phone number and the first factor succeeded.',
+ );
}
const { phoneNumberId } = phoneCodeFactor;
await this.resource.__internal_basePost({
body: { phoneNumberId, strategy: 'phone_code' },
action: 'prepare_second_factor',
});
});
}
This keeps the essential improvements (id guard and better error message) while respecting the platform's channel limitations for MFA.
✏️ Learnings added
Learnt from: nikosdouvlis
PR: clerk/javascript#6659
File: packages/clerk-js/src/core/resources/SignIn.ts:701-715
Timestamp: 2025-08-29T09:10:55.179Z
Learning: WhatsApp channel is only available as a supported channel for phone codes during sign up as a first factor, not for MFA (second factor) flows.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
Description
This PR adds support for multi-factor authentication during sign-in for our custom flows APIs.
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Chores