Skip to content

feat(clerk-js): Password manager autofill OTP codes #6247

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/polite-pants-talk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': minor
---

Password managers will now autofill OTP code verifications.
1 change: 0 additions & 1 deletion integration/templates/elements-next/src/app/otp/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export default function OTP() {
className='segmented-otp-with-props-wrapper flex justify-center has-[:disabled]:opacity-50'
type='otp'
data-testid='segmented-otp-with-props'
passwordManagerOffset={4}
length={4}
render={({ value, status }) => {
return (
Expand Down
7 changes: 0 additions & 7 deletions integration/tests/elements/otp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,12 +221,5 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withEmailCodes] })('OTP @elem
// Check that only 4 segments are rendered
await expect(otpSegmentsWrapper.locator('> div')).toHaveCount(4);
});

test('passwordManagerOffset', async ({ page }) => {
const otp = page.getByTestId(otpTypes.segmentedOtpWithProps);

// The computed styles are different on CI/local etc. so it's not use to check the exact value
await expect(otp).toHaveCSS('clip-path', /inset\(0px \d+\.\d+px 0px 0px\)/i);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export const APPEARANCE_KEYS = containsAllElementsConfigKeys([
'otpCodeField',
'otpCodeFieldInputs',
'otpCodeFieldInput',
'otpCodeFieldInputContainer',
'otpCodeFieldErrorText',
'formResendCodeLink',

Expand Down
126 changes: 95 additions & 31 deletions packages/clerk-js/src/ui/elements/CodeControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { PropsWithChildren } from 'react';
import React, { useCallback } from 'react';

import type { LocalizationKey } from '../customizables';
import { descriptors, Flex, Input } from '../customizables';
import { Box, descriptors, Flex, Input } from '../customizables';
import { useCardState } from '../elements/contexts';
import { useLoadingStatus } from '../hooks';
import type { PropsOfComponent } from '../styledSystem';
Expand Down Expand Up @@ -160,6 +160,7 @@ export const OTPResendButton = () => {
export const OTPCodeControl = React.forwardRef<{ reset: any }>((_, ref) => {
const [disabled, setDisabled] = React.useState(false);
const refs = React.useRef<Array<HTMLInputElement | null>>([]);
const hiddenInputRef = React.useRef<HTMLInputElement>(null);
const firstClickRef = React.useRef(false);

const { otpControl, isLoading, isDisabled, centerAlign = true } = useOTPInputContext();
Expand All @@ -169,6 +170,11 @@ export const OTPCodeControl = React.forwardRef<{ reset: any }>((_, ref) => {
reset: () => {
setValues(values.map(() => ''));
setDisabled(false);

if (hiddenInputRef.current) {
hiddenInputRef.current.value = '';
}

setTimeout(() => focusInputAt(0), 0);
},
}));
Expand All @@ -183,6 +189,13 @@ export const OTPCodeControl = React.forwardRef<{ reset: any }>((_, ref) => {
}
}, [feedback]);

// Update hidden input when values change
React.useEffect(() => {
if (hiddenInputRef.current) {
hiddenInputRef.current.value = values.join('');
}
}, [values]);

const handleMultipleCharValue = ({ eventValue, inputPosition }: { eventValue: string; inputPosition: number }) => {
const eventValues = (eventValue || '').split('');

Expand Down Expand Up @@ -274,40 +287,91 @@ export const OTPCodeControl = React.forwardRef<{ reset: any }>((_, ref) => {
}
};

// Handle hidden input changes (for password manager autofill)
const handleHiddenInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value.replace(/\D/g, '').slice(0, length);
const newValues = value.split('').concat(Array.from({ length: length - value.length }, () => ''));
setValues(newValues);

// Focus the appropriate visible input
if (value.length > 0) {
focusInputAt(Math.min(value.length - 1, length - 1));
}
};

const centerSx = centerAlign ? { justifyContent: 'center', alignItems: 'center' } : {};

return (
<Flex
isLoading={isLoading}
hasError={feedbackType === 'error'}
elementDescriptor={descriptors.otpCodeFieldInputs}
gap={2}
sx={t => ({ direction: 'ltr', padding: t.space.$1, marginLeft: `-${t.space.$1}`, ...centerSx })}
<Box
elementDescriptor={descriptors.otpCodeFieldInputContainer}
sx={{ position: 'relative' }}
>
{values.map((value, index: number) => (
<SingleCharInput
elementDescriptor={descriptors.otpCodeFieldInput}
key={index}
value={value}
onClick={handleOnClick(index)}
onChange={handleOnChange(index)}
onKeyDown={handleOnKeyDown(index)}
onInput={handleOnInput(index)}
onPaste={handleOnPaste(index)}
id={`digit-${index}-field`}
ref={node => (refs.current[index] = node)}
autoFocus={index === 0 || undefined}
autoComplete='one-time-code'
aria-label={`${index === 0 ? 'Enter verification code. ' : ''}Digit ${index + 1}`}
isDisabled={isDisabled || isLoading || disabled || feedbackType === 'success'}
hasError={feedbackType === 'error'}
isSuccessfullyFilled={feedbackType === 'success'}
type='text'
inputMode='numeric'
name={`codeInput-${index}`}
/>
))}
</Flex>
{/* Hidden input for password manager compatibility */}
<Input
ref={hiddenInputRef}
type='text'
autoComplete='one-time-code'
data-otp-hidden-input
inputMode='numeric'
pattern={`[0-9]{${length}}`}
minLength={length}
maxLength={length}
spellCheck={false}
aria-hidden='true'
tabIndex={-1}
onChange={handleHiddenInputChange}
onFocus={() => {
// When password manager focuses the hidden input, focus the first visible input
focusInputAt(0);
}}
sx={() => ({
...common.visuallyHidden(),
left: '-9999px',
pointerEvents: 'none',
})}
/>

<Flex
isLoading={isLoading}
hasError={feedbackType === 'error'}
elementDescriptor={descriptors.otpCodeFieldInputs}
gap={2}
sx={t => ({ direction: 'ltr', padding: t.space.$1, marginLeft: `-${t.space.$1}`, ...centerSx })}
role='group'
aria-label='Verification code input'
>
{values.map((value: string, index: number) => (
<SingleCharInput
elementDescriptor={descriptors.otpCodeFieldInput}
// eslint-disable-next-line react/no-array-index-key
key={index}
value={value}
onClick={handleOnClick(index)}
onChange={handleOnChange(index)}
onKeyDown={handleOnKeyDown(index)}
onInput={handleOnInput(index)}
onPaste={handleOnPaste(index)}
id={`digit-${index}-field`}
ref={node => (refs.current[index] = node)}
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus={index === 0 || undefined}
autoComplete='off'
aria-label={`${index === 0 ? 'Enter verification code. ' : ''}Digit ${index + 1}`}
isDisabled={isDisabled || isLoading || disabled || feedbackType === 'success'}
hasError={feedbackType === 'error'}
isSuccessfullyFilled={feedbackType === 'success'}
type='text'
inputMode='numeric'
name={`codeInput-${index}`}
data-otp-segment
data-1p-ignore
data-lpignore='true'
maxLength={1}
pattern='[0-9]'
/>
))}
</Flex>
</Box>
);
});

Expand Down
Loading
Loading