diff --git a/src/components/dialogs/EmailDialog/components/TokenField.test.tsx b/src/components/dialogs/EmailDialog/components/TokenField.test.tsx index f774290df..b61800612 100644 --- a/src/components/dialogs/EmailDialog/components/TokenField.test.tsx +++ b/src/components/dialogs/EmailDialog/components/TokenField.test.tsx @@ -1,6 +1,6 @@ import {fireEvent, render, screen} from '@testing-library/react-native' -import {TokenField} from './TokenField' +import {isValidCode, TokenField} from './TokenField' jest.mock('@lingui/react', () => ({ useLingui: () => ({_: (value: {message: string}) => value.message}), @@ -42,7 +42,7 @@ describe('TokenField', () => { const onChangeText = jest.fn() render() fireEvent.changeText(getInput(), 'abcde23456') - expect(onChangeText).toHaveBeenCalledWith('ABCDE-23456') + expect(onChangeText).toHaveBeenCalledWith('ABCDE23456') }) it('keeps formatted input stable', () => { @@ -52,11 +52,11 @@ describe('TokenField', () => { expect(onChangeText).toHaveBeenCalledWith('ABCDE-23456') }) - it('strips non-alphanumeric characters while preserving digits', () => { + it('strips other characters while preserving digits and supplied hyphens', () => { const onChangeText = jest.fn() render() fireEvent.changeText(getInput(), 'a!b8c-9d e') - expect(onChangeText).toHaveBeenCalledWith('AB8C9-DE') + expect(onChangeText).toHaveBeenCalledWith('AB8C-9DE') }) it('preserves 0 and 1 without mapping them to letters', () => { @@ -77,11 +77,33 @@ describe('TokenField', () => { expect(onChangeText).toHaveBeenCalledWith('ABCDE-F') }) - it('drops a hyphen typed inside the first group', () => { + it('preserves a hyphen regardless of its position', () => { const onChangeText = jest.fn() render() fireEvent.changeText(getInput(), 'AB-') - expect(onChangeText).toHaveBeenCalledWith('AB') + expect(onChangeText).toHaveBeenCalledWith('AB-') + }) + + it('preserves a TOTP code and leading zeros as it is typed', () => { + const onChangeText = jest.fn() + render() + for (const value of ['0', '01', '012', '0123', '01234', '012345']) { + fireEvent.changeText(getInput(), value) + expect(onChangeText).toHaveBeenLastCalledWith(value) + } + }) + + it('does not restore a deleted hyphen', () => { + const onChangeText = jest.fn() + render( + , + ) + fireEvent.changeText(getInput(), 'ABCDE23456') + expect(onChangeText).toHaveBeenCalledWith('ABCDE23456') }) it('defaults autocomplete to off', () => { @@ -133,9 +155,30 @@ describe('TokenField', () => { expect(getInput().props['aria-invalid']).toBeUndefined() }) - it('flags a malformed full-length code independently', () => { - render() - expect(getInput().props['aria-invalid']).toBe(true) + it.each(['012345', '01234567', 'ABCDEFGHIJKL', 'ABCDE23456'])( + 'leaves validation of %s to the caller', + value => { + render() + expect(getInput().props['aria-invalid']).toBeUndefined() + }, + ) + + it('accepts alphanumeric codes with or without the email hyphen', () => { + expect(isValidCode('ABCDE-23456')).toBe(true) + expect(isValidCode('ABCDE23456')).toBe(true) + expect(isValidCode('012345')).toBe(true) + }) + + it.each([ + '', + 'AB-CD', + 'ABCDE-2345', + 'ABCDE--23456', + 'ABCDEF-23456', + 'ABCDE-234567', + 'ABC!234', + ])('rejects malformed code %s', value => { + expect(isValidCode(value)).toBe(false) }) it('does not flag an incomplete code', () => { diff --git a/src/components/dialogs/EmailDialog/components/TokenField.tsx b/src/components/dialogs/EmailDialog/components/TokenField.tsx index 1229f6f93..edafe086f 100644 --- a/src/components/dialogs/EmailDialog/components/TokenField.tsx +++ b/src/components/dialogs/EmailDialog/components/TokenField.tsx @@ -1,27 +1,21 @@ import {type TextInputProps, View} from 'react-native' import {useLingui} from '@lingui/react/macro' +import {checkAndFormatResetCode} from '#/lib/strings/password' import * as TextField from '#/components/forms/TextField' import {Shield_Stroke2_Corner0_Rounded as Shield} from '#/components/icons/Shield' import {IS_ANDROID} from '#/env' /** - * Uppercase letters, preserve all digits, and remove other characters before - * formatting the code with a hyphen after the first five characters. - * Preserve a trailing hyphen typed after exactly five characters. + * Uppercase letters and preserve digits and supplied hyphens without imposing + * a code format. The hosting provider determines which format is valid. */ export function normalizeCode(value: string) { - const normalized = value.toUpperCase().replace(/[^A-Z0-9]/gi, '') - if (normalized.length < 5) return normalized - if (normalized.length === 5) { - // keep the hyphen if the user typed it themselves - return value.endsWith('-') ? `${normalized}-` : normalized - } - return `${normalized.slice(0, 5)}-${normalized.slice(5)}` + return value.toUpperCase().replace(/[^A-Z0-9-]/g, '') } export function isValidCode(value?: string) { - return Boolean(value && /^[A-Z0-9]{5}-[A-Z0-9]{5}$/i.test(value)) + return Boolean(value && checkAndFormatResetCode(value)) } export function TokenField({ @@ -54,10 +48,6 @@ export function TokenField({ | 'onSubmitEditing' >) { const {t: l} = useLingui() - const isFormatInvalid = Boolean( - value && value.length > 10 && !isValidCode(value), - ) - const handleOnChangeText = (v: string) => { onChangeText?.(normalizeCode(v)) } @@ -77,10 +67,8 @@ export function TokenField({ autoFocus={autoFocus} blurOnSubmit={blurOnSubmit} editable={editable} - isInvalid={isInvalid || isFormatInvalid} + isInvalid={isInvalid} label={l`Confirmation code`} - maxLength={11} - placeholder="XXXXX-XXXXX" returnKeyType={returnKeyType} value={value} onChangeText={handleOnChangeText} diff --git a/src/components/dialogs/EmailDialog/data/useConfirmEmail.ts b/src/components/dialogs/EmailDialog/data/useConfirmEmail.ts index 00472be52..02434b585 100644 --- a/src/components/dialogs/EmailDialog/data/useConfirmEmail.ts +++ b/src/components/dialogs/EmailDialog/data/useConfirmEmail.ts @@ -1,5 +1,6 @@ import {useMutation} from '@tanstack/react-query' +import {checkAndFormatResetCode} from '#/lib/strings/password' import {usePdsClient, useSession, useSessionApi} from '#/state/session' import {com} from '#/lexicons' @@ -19,7 +20,7 @@ export function useConfirmEmail({ await pdsClient.call(com.atproto.server.confirmEmail, { email: currentAccount.email.trim(), - token: token.trim(), + token: checkAndFormatResetCode(token) || token.trim(), }) // will update session state at root of app await refreshSession() diff --git a/src/components/dialogs/EmailDialog/data/useManageEmail2FA.ts b/src/components/dialogs/EmailDialog/data/useManageEmail2FA.ts index 9f811b481..30202ac14 100644 --- a/src/components/dialogs/EmailDialog/data/useManageEmail2FA.ts +++ b/src/components/dialogs/EmailDialog/data/useManageEmail2FA.ts @@ -1,5 +1,6 @@ import {useMutation} from '@tanstack/react-query' +import {checkAndFormatResetCode} from '#/lib/strings/password' import {usePdsClient, useSession, useSessionApi} from '#/state/session' import {com} from '#/lexicons' @@ -21,7 +22,7 @@ export function useManageEmail2FA() { await pdsClient.call(com.atproto.server.updateEmail, { email: currentAccount.email, emailAuthFactor: enabled, - token, + token: token ? checkAndFormatResetCode(token) || token : token, }) // will update session state at root of app await refreshSession() diff --git a/src/components/dialogs/EmailDialog/data/useUpdateEmail.ts b/src/components/dialogs/EmailDialog/data/useUpdateEmail.ts index 7293227f5..9a3820fd7 100644 --- a/src/components/dialogs/EmailDialog/data/useUpdateEmail.ts +++ b/src/components/dialogs/EmailDialog/data/useUpdateEmail.ts @@ -1,6 +1,7 @@ import {type Client} from '@atproto/lex' import {useMutation} from '@tanstack/react-query' +import {checkAndFormatResetCode} from '#/lib/strings/password' import {usePdsClient, useSessionApi} from '#/state/session' import {useRequestEmailUpdate} from '#/components/dialogs/EmailDialog/data/useRequestEmailUpdate' import {com} from '#/lexicons' @@ -13,7 +14,7 @@ async function updateEmailAndRefreshSession( ) { await pdsClient.call(com.atproto.server.updateEmail, { email: email.trim(), - token, + token: token ? checkAndFormatResetCode(token) || token : token, }) await refreshSession() } diff --git a/src/components/dialogs/EmailDialog/screens/Manage2FA/Disable.tsx b/src/components/dialogs/EmailDialog/screens/Manage2FA/Disable.tsx index 2fa94c8bf..2e62c413e 100644 --- a/src/components/dialogs/EmailDialog/screens/Manage2FA/Disable.tsx +++ b/src/components/dialogs/EmailDialog/screens/Manage2FA/Disable.tsx @@ -233,9 +233,7 @@ export function Disable() { variant="solid" color="primary" onPress={handleManageEmail2FA} - disabled={ - !token || token.length !== 11 || state.tokenStatus === 'pending' - }> + disabled={!isValidCode(token) || state.tokenStatus === 'pending'}> Disable 2FA diff --git a/src/components/dialogs/EmailDialog/screens/Update.tsx b/src/components/dialogs/EmailDialog/screens/Update.tsx index d537f7919..f7fd00ca8 100644 --- a/src/components/dialogs/EmailDialog/screens/Update.tsx +++ b/src/components/dialogs/EmailDialog/screens/Update.tsx @@ -297,8 +297,7 @@ export function Update(_props: ScreenProps) { onPress={handleUpdateEmail} disabled={ !state.email || - (state.step === 'token' && - (!state.token || state.token.length !== 11)) || + (state.step === 'token' && !isValidCode(state.token)) || state.mutationStatus === 'pending' }> diff --git a/src/components/dialogs/EmailDialog/screens/Verify.tsx b/src/components/dialogs/EmailDialog/screens/Verify.tsx index ee8b61d46..4266409f1 100644 --- a/src/components/dialogs/EmailDialog/screens/Verify.tsx +++ b/src/components/dialogs/EmailDialog/screens/Verify.tsx @@ -364,9 +364,7 @@ export function Verify({config, showScreen}: ScreenProps) { color="primary" onPress={handleConfirmEmail} disabled={ - !state.token || - state.token.length !== 11 || - state.mutationStatus === 'pending' + !isValidCode(state.token) || state.mutationStatus === 'pending' }> void onPressNext()} editable={!isProcessing} isInvalid={errorField === '2fa'} - accessibilityHint={l`Input the code which has been emailed to you`} + accessibilityHint={l`Enter the code from your email or authenticator app`} /> - Check your email for a sign in code and enter it here. + Enter the sign in code from your email or authenticator app. diff --git a/src/screens/Settings/components/DeleteAccountDialog.tsx b/src/screens/Settings/components/DeleteAccountDialog.tsx index 167e20947..72ccc0f70 100644 --- a/src/screens/Settings/components/DeleteAccountDialog.tsx +++ b/src/screens/Settings/components/DeleteAccountDialog.tsx @@ -6,6 +6,7 @@ import {Trans} from '@lingui/react/macro' import {useCleanError} from '#/lib/hooks/useCleanError' import {sanitizeHandle} from '#/lib/strings/handles' +import {checkAndFormatResetCode} from '#/lib/strings/password' import {logger} from '#/logger' import { useChatClient, @@ -117,7 +118,8 @@ function DeleteAccountDialogInner({ if (!currentAccount?.did) { throw new Error('Invalid did') } - const token = confirmCode.replace(WHITESPACE_RE, '') + const strippedCode = confirmCode.replace(WHITESPACE_RE, '') + const token = checkAndFormatResetCode(strippedCode) || strippedCode /* * Inform chat service of intent to delete account. A non-2xx response * throws, so reaching the next line means the chat service accepted it - diff --git a/src/screens/Settings/components/DisableEmail2FADialog.tsx b/src/screens/Settings/components/DisableEmail2FADialog.tsx index 395b6bad6..66e9fcc81 100644 --- a/src/screens/Settings/components/DisableEmail2FADialog.tsx +++ b/src/screens/Settings/components/DisableEmail2FADialog.tsx @@ -5,6 +5,7 @@ import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' import {cleanError} from '#/lib/strings/errors' +import {checkAndFormatResetCode} from '#/lib/strings/password' import {matchXrpcError} from '#/lib/xrpc-error' import {usePdsClient, useSession, useSessionApi} from '#/state/session' import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' @@ -58,9 +59,10 @@ export function DisableEmail2FADialog({ setIsProcessing(true) try { if (currentAccount?.email) { + const token = confirmationCode.trim() await pdsClient.call(com.atproto.server.updateEmail, { email: currentAccount.email, - token: confirmationCode.trim(), + token: checkAndFormatResetCode(token) || token, emailAuthFactor: false, }) await refreshSession() diff --git a/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx b/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx index 9b9b9e824..db3b2f445 100644 --- a/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx +++ b/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx @@ -1,6 +1,7 @@ import {act} from 'react' import {fireEvent, render, screen} from '@testing-library/react-native' +import {com} from '#/lexicons' import {ChangePasswordDialog} from '../ChangePasswordDialog' const mockCall = jest.fn() @@ -174,6 +175,10 @@ describe('ChangePasswordDialog', () => { fillCodeStage() await submit() + expect(mockCall).toHaveBeenCalledWith(com.atproto.server.resetPassword, { + token: 'ABCDE-23456', + password: 'new-password', + }) expect(isDismissPrevented()).toBe(true) expect(isDisabled('Change password')).toBe(true) expect(isDisabled('Back')).toBe(true) diff --git a/src/screens/Settings/components/__tests__/DisableEmail2FADialog.test.tsx b/src/screens/Settings/components/__tests__/DisableEmail2FADialog.test.tsx index 6ff410fcb..a2a78dfa2 100644 --- a/src/screens/Settings/components/__tests__/DisableEmail2FADialog.test.tsx +++ b/src/screens/Settings/components/__tests__/DisableEmail2FADialog.test.tsx @@ -148,7 +148,7 @@ describe('DisableEmail2FADialog', () => { const control = renderDialog() enterCodeStage() fireEvent.changeText(getInput(), 'abcde23456') - expect(getInput().props.value).toBe('ABCDE-23456') + expect(getInput().props.value).toBe('ABCDE23456') await act(async () => { fireEvent.press(screen.getByTestId('confirmBtn'))