Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

improvement(auth): improve verification code input (#7470)

Andrew Huang32b27410fcce
diff --git a/backend/e2e-test/routes/v3/auth-email-signup.spec.ts b/backend/e2e-test/routes/v3/auth-email-signup.spec.ts
index 285512fe31..9305567017 100644
--- a/backend/e2e-test/routes/v3/auth-email-signup.spec.ts
+++ b/backend/e2e-test/routes/v3/auth-email-signup.spec.ts
@@ -77,7 +77,26 @@ describe("Auth Email Signup V3", () => {
body: { email: testEmail, code: "000000" }
});
- expect(res.statusCode).toBeGreaterThanOrEqual(400);
+ expect(res.statusCode).toBe(401);
+ expect(res.json()).toMatchObject({
+ statusCode: 401,
+ message: "Invalid token",
+ error: "InvalidToken"
+ });
+ expect(res.json()).not.toHaveProperty("details");
+
+ const missingChallenge = await testServer.inject({
+ method: "POST",
+ url: "/api/v3/signup/email/verify",
+ body: { email: "[email protected]", code: "000000" }
+ });
+ expect(missingChallenge.statusCode).toBe(401);
+ expect(missingChallenge.json()).toMatchObject({
+ statusCode: 401,
+ message: "Invalid token",
+ error: "InvalidToken"
+ });
+ expect(missingChallenge.json()).not.toHaveProperty("details");
});
test("Complete account with valid signup token creates user", async () => {
@@ -211,7 +230,16 @@ describe("Auth Email Signup V3", () => {
});
expect(first.statusCode).toBe(200);
- // Step 3: second request within cooldown — must return 400 for both paths to be indistinguishable
+ // Step 3: wrong-code verification must match the response for a new-account challenge
+ const verifyAttempt = await testServer.inject({
+ method: "POST",
+ url: "/api/v3/signup/email/verify",
+ body: { email, code: "000000" }
+ });
+ expect(verifyAttempt.statusCode).toBe(401);
+ expect(verifyAttempt.json()).not.toHaveProperty("details");
+
+ // Step 4: second request within cooldown — must return 400 for both paths to be indistinguishable
const second = await testServer.inject({
method: "POST",
url: "/api/v3/signup/email/signup",
@@ -236,11 +264,13 @@ describe("Auth Email Signup V3", () => {
// Exhaust all 3 tries with a wrong code
for (let i = 0; i < 3; i += 1) {
// eslint-disable-next-line no-await-in-loop
- await testServer.inject({
+ const attempt = await testServer.inject({
method: "POST",
url: "/api/v3/signup/email/verify",
body: { email, code: "000000" }
});
+ expect(attempt.statusCode).toBe(401);
+ expect(attempt.json()).not.toHaveProperty("details");
}
// Correct code should now also fail because the record was deleted
@@ -250,6 +280,6 @@ describe("Auth Email Signup V3", () => {
body: { email, code: correctCode }
});
- expect(res.statusCode).toBeGreaterThanOrEqual(400);
+ expect(res.statusCode).toBe(401);
});
});
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 1fb7143fb3..618d899b09 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -90,7 +90,6 @@
"qrcode": "^1.5.4",
"randexp": "^0.5.3",
"react": "^18.3.1",
- "react-code-input": "^3.10.1",
"react-colorful": "^5.6.1",
"react-complex-tree": "^2.6.1",
"react-day-picker": "^9.13.0",
@@ -14066,60 +14065,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/react-code-input": {
- "version": "3.10.1",
- "resolved": "https://registry.npmjs.org/react-code-input/-/react-code-input-3.10.1.tgz",
- "integrity": "sha512-B1RqSc32BzFP9eoV5LWhRTmbJ8I3rKs+6E01yaJwDqcVBE4kKgRJHBmPcXRD58qkCPssnF/Aq5UDNzIiTw7eNg==",
- "license": "MIT",
- "dependencies": {
- "classnames": "^2.2.5",
- "react": "^16.3.2",
- "react-dom": "^16.3.2"
- },
- "peerDependencies": {
- "react": "^15.5.4 ||^16.2.0 || ^17.0.0",
- "react-dom": "^15.5.4 ||^16.2.0 || ^17.0.0"
- }
- },
- "node_modules/react-code-input/node_modules/react": {
- "version": "16.14.0",
- "resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz",
- "integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==",
- "license": "MIT",
- "dependencies": {
- "loose-envify": "^1.1.0",
- "object-assign": "^4.1.1",
- "prop-types": "^15.6.2"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/react-code-input/node_modules/react-dom": {
- "version": "16.14.0",
- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz",
- "integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==",
- "license": "MIT",
- "dependencies": {
- "loose-envify": "^1.1.0",
- "object-assign": "^4.1.1",
- "prop-types": "^15.6.2",
- "scheduler": "^0.19.1"
- },
- "peerDependencies": {
- "react": "^16.14.0"
- }
- },
- "node_modules/react-code-input/node_modules/scheduler": {
- "version": "0.19.1",
- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz",
- "integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",
- "license": "MIT",
- "dependencies": {
- "loose-envify": "^1.1.0",
- "object-assign": "^4.1.1"
- }
- },
"node_modules/react-colorful": {
"version": "5.6.1",
"resolved": "https://registry.npmjs.org/react-colorful/-/react-colorful-5.6.1.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 48672351c0..2d1ea8db21 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -121,7 +121,6 @@
"qrcode": "^1.5.4",
"randexp": "^0.5.3",
"react": "^18.3.1",
- "react-code-input": "^3.10.1",
"react-colorful": "^5.6.1",
"react-complex-tree": "^2.6.1",
"react-day-picker": "^9.13.0",
diff --git a/frontend/public/locales/en/translations.json b/frontend/public/locales/en/translations.json
index c83c477a99..cdd57db3d9 100644
--- a/frontend/public/locales/en/translations.json
+++ b/frontend/public/locales/en/translations.json
@@ -323,6 +323,9 @@
"step1-submit": "Get Started",
"step2-message": "We've sent a verification code to",
"step2-code-error": "Oops. Your code is wrong. Please try again.",
+ "step2-code-error-tries": "Oops! Wrong code, {{triesLeft}} more attempts.",
+ "step2-code-error-tries-singular": "Oops! Wrong code, 1 more attempt.",
+ "step2-code-error-exhausted": "Please request a new code.",
"step2-resend-alert": "Don't see the code?",
"step2-resend-submit": "Resend",
"step2-resend-progress": "Resending...",
diff --git a/frontend/public/locales/es/translations.json b/frontend/public/locales/es/translations.json
index 1d217b89d5..e0342a9bc9 100644
--- a/frontend/public/locales/es/translations.json
+++ b/frontend/public/locales/es/translations.json
@@ -305,6 +305,9 @@
"step1-submit": "Empezar",
"step2-message": "Hemos enviado un código a",
"step2-code-error": "Oops. Tu código es incorrecto. Intentos restantes:",
+ "step2-code-error-tries": "¡Ups! Código incorrecto, quedan {{triesLeft}} intentos.",
+ "step2-code-error-tries-singular": "¡Ups! Código incorrecto, queda 1 intento.",
+ "step2-code-error-exhausted": "Solicita un código nuevo.",
"step2-resend-alert": "¿No ves el código?",
"step2-resend-submit": "Volver a enviar",
"step2-resend-progress": "Reenviando...",
diff --git a/frontend/public/locales/fr/translations.json b/frontend/public/locales/fr/translations.json
index 538b700c65..7d59957a7a 100644
--- a/frontend/public/locales/fr/translations.json
+++ b/frontend/public/locales/fr/translations.json
@@ -285,6 +285,9 @@
"step1-submit": "C'est parti",
"step2-message": "Nous avons envoyé un email de vérification à",
"step2-code-error": "Oops. Votre code est faux. Veuillez réessayer.",
+ "step2-code-error-tries": "Oups ! Code incorrect, encore {{triesLeft}} tentatives.",
+ "step2-code-error-tries-singular": "Oups ! Code incorrect, encore 1 tentative.",
+ "step2-code-error-exhausted": "Veuillez demander un nouveau code.",
"step2-resend-alert": "Vous ne voyez pas le code?",
"step2-resend-submit": "Renvoyer",
"step2-resend-progress": "Envoie en cours...",
diff --git a/frontend/public/locales/ko/translations.json b/frontend/public/locales/ko/translations.json
index a9eb653cc2..ad35d8b918 100644
--- a/frontend/public/locales/ko/translations.json
+++ b/frontend/public/locales/ko/translations.json
@@ -252,6 +252,9 @@
"step1-submit": "시작하기",
"step2-message": "<email>{{email}}</email><wrapper>로 인증 메일을 전송하였습니다</wrapper><email>{{email}}</email>",
"step2-code-error": "코드가 잘못된 것 같아요. 다시 시도해주세요.",
+ "step2-code-error-tries": "잘못된 코드입니다. {{triesLeft}}번 더 시도할 수 있습니다.",
+ "step2-code-error-tries-singular": "잘못된 코드입니다. 1번 더 시도할 수 있습니다.",
+ "step2-code-error-exhausted": "새 코드를 요청해 주세요.",
"step2-spam-alert": "스팸함에 메일이 있지는 않은지 확인하세요",
"step3-message": "거의다 끝났어요!",
"step4-message": "긴급복구 키트 저장하기",
diff --git a/frontend/public/locales/pt-BR/translations.json b/frontend/public/locales/pt-BR/translations.json
index 9a0ab6768f..6e84c2a9ae 100644
--- a/frontend/public/locales/pt-BR/translations.json
+++ b/frontend/public/locales/pt-BR/translations.json
@@ -282,6 +282,9 @@
"step1-submit": "Iniciar",
"step2-message": "<wrapper>Enviamos um e-mail de verificação para</wrapper><email>{{email}}</email>",
"step2-code-error": "Ops. Seu código está errado. Por favor, tente novamente.",
+ "step2-code-error-tries": "Ops! Código incorreto, mais {{triesLeft}} tentativas.",
+ "step2-code-error-tries-singular": "Ops! Código incorreto, mais 1 tentativa.",
+ "step2-code-error-exhausted": "Solicite um novo código.",
"step2-spam-alert": "Certifique-se de verificar sua caixa de entrada de spam.",
"step3-message": "Quase lá!",
"step4-message": "Guarde o seu Kit de Emergência",
diff --git a/frontend/public/locales/tr/translations.json b/frontend/public/locales/tr/translations.json
index 5a564eb605..1da283a835 100644
--- a/frontend/public/locales/tr/translations.json
+++ b/frontend/public/locales/tr/translations.json
@@ -303,6 +303,9 @@
"step1-submit": "Başla",
"step2-message": "Şu adrese bir doğrulama maili yolladık",
"step2-code-error": "Tüh. Kodun hatalı. Lütfen tekrar dene.",
+ "step2-code-error-tries": "Tüh! Yanlış kod, {{triesLeft}} deneme daha kaldı.",
+ "step2-code-error-tries-singular": "Tüh! Yanlış kod, 1 deneme daha kaldı.",
+ "step2-code-error-exhausted": "Lütfen yeni bir kod isteyin.",
"step2-resend-alert": "Kodu ulaşamadı mı?",
"step2-resend-submit": "Tekrar Yolla",
"step2-resend-progress": "Tekrar yollanıyor...",
diff --git a/frontend/src/components/auth/CodeInputStep.tsx b/frontend/src/components/auth/CodeInputStep.tsx
index 07471d6ed6..7287babca1 100644
--- a/frontend/src/components/auth/CodeInputStep.tsx
+++ b/frontend/src/components/auth/CodeInputStep.tsx
@@ -13,6 +13,9 @@ import { useSendVerificationEmail, useVerifySignupEmailVerificationCode } from "
import SecurityClient from "../utilities/SecurityClient";
import { AuthPagePanel } from "./AuthPagePanel";
+import { waitForMinimumAuthVerificationLoading } from "./authTiming";
+
+const MAX_SIGNUP_VERIFICATION_ATTEMPTS = 3;
interface CodeInputStepProps {
email: string;
@@ -33,12 +36,15 @@ export default function CodeInputStep({
const {
mutateAsync: verifyCode,
isPending: isVerifying,
- isError: isCodeError
+ reset: resetVerificationCode
} = useVerifySignupEmailVerificationCode();
const { t } = useTranslation();
const [code, setCode] = useState("");
+ const [isCompletingVerification, setIsCompletingVerification] = useState(false);
+ const [verificationError, setVerificationError] = useState<unknown>();
+ const [triesLeft, setTriesLeft] = useState(MAX_SIGNUP_VERIFICATION_ATTEMPTS);
const [, forceRender] = useState(0);
@@ -52,14 +58,43 @@ export default function CodeInputStep({
}, []);
const remainingCooldown = Math.max(0, Math.ceil((resendCooldownEndTime - Date.now()) / 1000));
+ const isInvalidTokenError =
+ axios.isAxiosError(verificationError) &&
+ verificationError.response?.data?.error === "InvalidToken";
+ let verificationErrorMessage = t("signup.step2-code-error");
+ if (isInvalidTokenError && triesLeft === 0) {
+ verificationErrorMessage = t("signup.step2-code-error-exhausted");
+ } else if (isInvalidTokenError) {
+ verificationErrorMessage = t(
+ triesLeft === 1 ? "signup.step2-code-error-tries-singular" : "signup.step2-code-error-tries",
+ { triesLeft }
+ );
+ }
const handleVerify = async () => {
- const { token } = await verifyCode({ email, code });
- SecurityClient.setSignupToken(token);
- onComplete();
+ const verificationStartedAt = Date.now();
+ setIsCompletingVerification(true);
+
+ try {
+ const { token } = await verifyCode({ email, code });
+ await waitForMinimumAuthVerificationLoading(verificationStartedAt);
+ SecurityClient.setSignupToken(token);
+ onComplete();
+ } catch (error) {
+ if (axios.isAxiosError(error) && error.response?.data?.error === "InvalidToken") {
+ setTriesLeft((current) => Math.max(0, current - 1));
+ }
+ setVerificationError(error);
+ } finally {
+ setIsCompletingVerification(false);
+ }
};
const handleResend = async () => {
+ setVerificationError(undefined);
+ setTriesLeft(MAX_SIGNUP_VERIFICATION_ATTEMPTS);
+ resetVerificationCode();
+
try {
const { cooldownSeconds } = await resendEmail({ email });
onResendCooldownChange(Date.now() + cooldownSeconds * 1000);
@@ -96,9 +131,8 @@ export default function CodeInputStep({
value={code}
onChange={setCode}
onSubmit={handleVerify}
- submitLabel={String(t("signup.verify"))}
- isPending={isVerifying}
- error={isCodeError ? t("signup.step2-code-error") : undefined}
+ isPending={isVerifying || isCompletingVerification}
+ error={verificationError ? verificationErrorMessage : undefined}
>
<VerificationCodeResend
isResending={isResending}
diff --git a/frontend/src/components/auth/Mfa.tsx b/frontend/src/components/auth/Mfa.tsx
index d309fefa8b..4aaf254ae7 100644
--- a/frontend/src/components/auth/Mfa.tsx
+++ b/frontend/src/components/auth/Mfa.tsx
@@ -32,6 +32,7 @@ import { useGenerateAuthenticationOptions, useVerifyAuthentication } from "@app/
import { RecoveryCodesStep } from "../mfa/setup";
import { AuthPageLayout } from "./AuthPageLayout";
import { AuthPagePanel } from "./AuthPagePanel";
+import { waitForMinimumAuthVerificationLoading } from "./authTiming";
const MAX_MFA_ATTEMPTS = 5;
const CLIENT_RESEND_DELAY_SECONDS = 20;
@@ -149,6 +150,7 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccount
const verifyMfa = async () => {
if (!mfaCode.trim() || !isCodeComplete) return;
+ const verificationStartedAt = Date.now();
setIsLoading(true);
let sessionToken: string;
@@ -185,6 +187,7 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccount
}
try {
+ await waitForMinimumAuthVerificationLoading(verificationStartedAt);
await finalizeAfterMfaVerification(sessionToken, method, showRecoveryCodeInput);
} finally {
setIsLoading(false);
@@ -204,6 +207,7 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccount
};
const handleWebAuthnVerification = async () => {
+ const verificationStartedAt = Date.now();
setIsLoading(true);
const mfaToken = getMfaTempToken();
@@ -275,6 +279,7 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccount
}
try {
+ await waitForMinimumAuthVerificationLoading(verificationStartedAt);
await finalizeAfterMfaVerification(sessionToken, MfaMethod.WEBAUTHN, false);
} finally {
setIsLoading(false);
@@ -436,7 +441,6 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccount
value={mfaCode}
onChange={setMfaCode}
onSubmit={verifyMfa}
- submitLabel={String(t("mfa.verify"))}
isPending={isLoading}
isDisabled={typeof triesLeft === "number" && triesLeft <= 0}
error={
diff --git a/frontend/src/components/auth/authTiming.ts b/frontend/src/components/auth/authTiming.ts
new file mode 100644
index 0000000000..008cc47bc8
--- /dev/null
+++ b/frontend/src/components/auth/authTiming.ts
@@ -0,0 +1,6 @@
+import { waitForMinimumDuration } from "@app/lib/fn/promise";
+
+const MIN_AUTH_VERIFICATION_LOADING_MS = 500;
+
+export const waitForMinimumAuthVerificationLoading = (startedAt: number) =>
+ waitForMinimumDuration(startedAt, MIN_AUTH_VERIFICATION_LOADING_MS);
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
index 31f6fa083d..4e2d7ad684 100644
--- a/frontend/src/components/mfa/setup/VerifyStep.tsx
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -20,6 +20,7 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const { mutateAsync: enrollMfa, isPending: isVerifying } = useEnrollMfa();
const [qrCodeUrl, setQrCodeUrl] = useState("");
const [totp, setTotp] = useState("");
+ const [verificationError, setVerificationError] = useState<string>();
useEffect(() => {
if (registration?.otpUrl) {
@@ -31,13 +32,15 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const manualSecret = registration?.otpUrl?.split("secret=")[1]?.split("&")[0];
const handleVerify = async () => {
+ setVerificationError(undefined);
try {
await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
createNotification({ text: "Authenticator app configured", type: "success" });
await onVerified();
} catch {
// The mutation's global error handler already surfaces the (more detailed)
- // failure toast; just swallow here so onVerified isn't called on failure.
+ // failure toast; keep a local signal so the manual Retry action appears.
+ setVerificationError("Invalid code. Please try again.");
}
};
@@ -66,10 +69,13 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
<VerificationCodeForm
name="totp-enrollment-code"
value={totp}
- onChange={(value) => setTotp(value.replace(/\D/g, "").slice(0, 6))}
+ onChange={(value) => {
+ setTotp(value.replace(/\D/g, "").slice(0, 6));
+ setVerificationError(undefined);
+ }}
onSubmit={handleVerify}
- submitLabel="Verify code"
isPending={isVerifying}
+ error={verificationError}
/>
</div>
);
diff --git a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx
index d83536e668..536081285a 100644
--- a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx
+++ b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx
@@ -1,4 +1,4 @@
-import { ReactNode, useEffect, useState } from "react";
+import { ReactNode, useEffect, useRef, useState } from "react";
import { AnimatedCollapse } from "../../generic/AnimatedCollapse";
import { Button } from "../../generic/Button";
@@ -53,7 +53,6 @@ type VerificationCodeFormProps = {
name: string;
onChange: (value: string) => void;
onSubmit: () => void | Promise<void>;
- submitLabel?: ReactNode;
value: string;
};
@@ -66,19 +65,33 @@ export const VerificationCodeForm = ({
name,
onChange,
onSubmit,
- submitLabel = "Verify",
value
}: VerificationCodeFormProps) => {
const isComplete = value.trim().length === fields;
const hasError = Boolean(error);
const [hasChangedSinceError, setHasChangedSinceError] = useState(false);
+ const [hasAttemptedVerification, setHasAttemptedVerification] = useState(false);
+ const [hasFailedVerification, setHasFailedVerification] = useState(false);
+ const onSubmitRef = useRef(onSubmit);
+
+ useEffect(() => {
+ onSubmitRef.current = onSubmit;
+ }, [onSubmit]);
useEffect(() => {
if (hasError && !isPending) {
setHasChangedSinceError(false);
+ setHasFailedVerification(true);
}
}, [hasError, isPending]);
+ useEffect(() => {
+ if (hasAttemptedVerification || !isComplete || isDisabled || isPending) return;
+
+ setHasAttemptedVerification(true);
+ onSubmitRef.current();
+ }, [hasAttemptedVerification, isComplete, isDisabled, isPending]);
+
const handleChange = (nextValue: string) => {
if (hasError) setHasChangedSinceError(true);
onChange(nextValue);
@@ -102,9 +115,11 @@ export const VerificationCodeForm = ({
value={value}
isError={hasError && !hasChangedSinceError}
/>
- {error && <FieldError>{error}</FieldError>}
+ <div className="min-h-4.5">
+ {error && <FieldError className="mt-0">{error}</FieldError>}
+ </div>
</div>
- <AnimatedCollapse isOpen={isComplete || Boolean(isPending)} contentClassName="px-1">
+ <AnimatedCollapse isOpen={hasFailedVerification}>
<Button
type="submit"
variant="project"
@@ -113,7 +128,7 @@ export const VerificationCodeForm = ({
isPending={isPending}
isDisabled={!isComplete || isDisabled || isPending}
>
- {submitLabel}
+ Retry
</Button>
</AnimatedCollapse>
{children}
diff --git a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx
index 7b1d385e0d..3334ed2678 100644
--- a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx
+++ b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx
@@ -1,27 +1,14 @@
-/* eslint-disable react/jsx-props-no-spreading */
-import ReactCodeInput from "react-code-input";
+import {
+ type KeyboardEvent,
+ type PointerEvent,
+ useCallback,
+ useEffect,
+ useRef,
+ useState
+} from "react";
import { cn } from "../../utils";
-const codeInputStyle = {
- inputStyle: {
- fontFamily: "var(--font-jetbrains-mono)",
- margin: "0",
- MozAppearance: "textfield",
- width: "100%",
- borderRadius: "6px",
- fontSize: "20px",
- height: "68px",
- padding: "0",
- backgroundColor: "var(--color-container)",
- color: "var(--color-foreground)",
- border: "1px solid var(--color-border)",
- textAlign: "center",
- outlineColor: "transparent",
- borderColor: "var(--color-border)"
- }
-} as const;
-
type Props = {
fields?: number;
isError?: boolean;
@@ -30,19 +17,248 @@ type Props = {
value?: string;
};
-export const VerificationCodeInput = ({ fields = 6, isError, name, onChange, value }: Props) => (
- <ReactCodeInput
- name={name}
- inputMode={fields === 6 ? "tel" : "latin"}
- type="text"
- fields={fields}
- onChange={onChange}
- value={value}
- {...codeInputStyle}
- className={cn(
- "code-input-v3",
- fields === 8 && "code-input-v3-recovery",
- isError && "code-input-v3-error"
- )}
- />
-);
+type Selection = {
+ end: number;
+ start: number;
+};
+
+export const VerificationCodeInput = ({
+ fields = 6,
+ isError,
+ name,
+ onChange,
+ value = ""
+}: Props) => {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const pointerAnchorRef = useRef<number | undefined>(undefined);
+ const [isFocused, setIsFocused] = useState(false);
+ const [selection, setSelection] = useState<Selection>({ start: 0, end: 0 });
+
+ const syncSelection = useCallback(() => {
+ const input = inputRef.current;
+ if (!input) return;
+
+ setSelection({
+ start: input.selectionStart ?? 0,
+ end: input.selectionEnd ?? 0
+ });
+ }, []);
+
+ useEffect(() => {
+ if (!isError) return;
+
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ syncSelection();
+ }, [isError, syncSelection]);
+
+ useEffect(() => {
+ const input = inputRef.current;
+ if (!input || input.value === value) return;
+
+ input.value = value.slice(0, fields);
+ input.setSelectionRange(input.value.length, input.value.length);
+ syncSelection();
+ }, [fields, syncSelection, value]);
+
+ const getPointerCellIndex = (event: PointerEvent<HTMLDivElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ const relativePosition = (event.clientX - bounds.left) / bounds.width;
+
+ return Math.max(0, Math.min(fields - 1, Math.floor(relativePosition * fields)));
+ };
+
+ const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0) return;
+
+ event.preventDefault();
+ const input = inputRef.current;
+ if (!input) return;
+
+ const cellIndex = getPointerCellIndex(event);
+ const selectionStart = Math.min(cellIndex, input.value.length);
+ const selectionEnd =
+ cellIndex < input.value.length ? Math.min(cellIndex + 1, input.value.length) : selectionStart;
+
+ pointerAnchorRef.current = cellIndex;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ input.focus();
+ input.setSelectionRange(selectionStart, selectionEnd);
+ syncSelection();
+ };
+
+ const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ const anchor = pointerAnchorRef.current;
+ if (anchor === undefined) return;
+
+ const input = inputRef.current;
+ if (!input) return;
+
+ const cellIndex = getPointerCellIndex(event);
+ const start = Math.min(anchor, cellIndex, input.value.length);
+ const end = Math.min(Math.max(anchor, cellIndex) + 1, input.value.length);
+
+ input.setSelectionRange(start, end);
+ syncSelection();
+ };
+
+ const handlePointerUp = (event: PointerEvent<HTMLDivElement>) => {
+ if (pointerAnchorRef.current === undefined) return;
+
+ pointerAnchorRef.current = undefined;
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ const input = inputRef.current;
+ if (!input) return;
+
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "a") {
+ event.preventDefault();
+ input.setSelectionRange(0, input.value.length);
+ syncSelection();
+ return;
+ }
+
+ if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
+
+ event.preventDefault();
+ const start = input.selectionStart ?? 0;
+ const end = input.selectionEnd ?? 0;
+
+ if (event.shiftKey) {
+ const anchor = input.selectionDirection === "backward" ? end : start;
+ const focus = input.selectionDirection === "backward" ? start : end;
+ let nextFocus = focus;
+
+ if (event.key === "ArrowLeft") nextFocus = Math.max(0, focus - 1);
+ if (event.key === "ArrowRight") nextFocus = Math.min(input.value.length, focus + 1);
+ if (event.key === "Home") nextFocus = 0;
+ if (event.key === "End") nextFocus = input.value.length;
+
+ input.setSelectionRange(
+ Math.min(anchor, nextFocus),
+ Math.max(anchor, nextFocus),
+ nextFocus < anchor ? "backward" : "forward"
+ );
+ } else {
+ let position = start;
+
+ if (event.key === "ArrowLeft") position = start === end ? Math.max(0, start - 1) : start;
+ if (event.key === "ArrowRight") {
+ position = start === end ? Math.min(input.value.length, end + 1) : end;
+ }
+ if (event.key === "Home") position = 0;
+ if (event.key === "End") position = input.value.length;
+
+ input.setSelectionRange(position, position);
+ }
+
+ syncSelection();
+ };
+
+ const activeSlot = Math.min(selection.start, fields - 1);
+ const hasSelection = isFocused && selection.start < selection.end;
+ const gridClassName = cn(
+ "grid w-full grid-cols-6 gap-3 max-sm:gap-2",
+ fields === 8 && "grid-cols-8 gap-2 max-sm:gap-1.5"
+ );
+
+ return (
+ <div
+ className="group relative w-full"
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ >
+ <div className={gridClassName}>
+ {Array.from({ length: fields }, (_, index) => {
+ const isActive = isFocused && selection.start === selection.end && index === activeSlot;
+
+ return (
+ <div
+ aria-hidden
+ className={cn(
+ "relative flex h-[68px] min-w-0 items-center justify-center rounded-md border border-border bg-container font-jetbrains-mono text-xl text-foreground outline outline-1 outline-offset-4 outline-transparent transition-colors max-sm:aspect-square max-sm:h-auto",
+ "group-hover:border-foreground/20",
+ isActive && "border-project/45 outline-project/45",
+ isError && "border-danger/55"
+ )}
+ key={index}
+ >
+ {value[index] ?? ""}
+ {isActive && (
+ <span
+ className={cn(
+ "absolute top-1/2 h-6 w-px -translate-y-1/2 bg-foreground motion-safe:animate-pulse",
+ !value[index] && "left-1/2",
+ value[index] &&
+ (selection.start > index
+ ? "left-[calc(50%+0.4rem)]"
+ : "left-[calc(50%-0.4rem)]")
+ )}
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ {hasSelection && (
+ <div
+ aria-hidden
+ className={cn("pointer-events-none absolute inset-0 z-[1]", gridClassName)}
+ >
+ <div
+ className={cn(
+ "rounded-md outline outline-1 outline-offset-4",
+ isError ? "outline-danger/55" : "outline-project/45"
+ )}
+ style={{ gridColumn: `${selection.start + 1} / ${selection.end + 1}` }}
+ />
+ </div>
+ )}
+ <input
+ ref={inputRef}
+ aria-invalid={isError}
+ aria-label={fields === 8 ? "Recovery code" : "Verification code"}
+ autoCapitalize="off"
+ autoComplete="one-time-code"
+ className="absolute inset-0 z-10 h-full w-full cursor-text opacity-0"
+ defaultValue={value}
+ inputMode={fields === 6 ? "numeric" : "text"}
+ maxLength={fields === 6 ? undefined : fields}
+ name={name}
+ onBlur={() => setIsFocused(false)}
+ onChange={(event) => {
+ const input = event.currentTarget;
+ const nextValue = (fields === 6 ? input.value.replace(/\D/g, "") : input.value).slice(
+ 0,
+ fields
+ );
+
+ input.value = nextValue;
+ const nextSelectionStart = Math.min(
+ input.selectionStart ?? nextValue.length,
+ nextValue.length
+ );
+ const nextSelectionEnd = Math.min(
+ input.selectionEnd ?? nextSelectionStart,
+ nextValue.length
+ );
+
+ setSelection({ start: nextSelectionStart, end: nextSelectionEnd });
+ onChange(nextValue);
+ }}
+ onFocus={() => {
+ setIsFocused(true);
+ syncSelection();
+ }}
+ onKeyDown={handleKeyDown}
+ onKeyUp={syncSelection}
+ onSelect={syncSelection}
+ spellCheck={false}
+ type="text"
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/index.css b/frontend/src/index.css
index e0f315c83a..e99c4e60f2 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -524,55 +524,3 @@ input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
-
-/* v3-style focus treatment for ReactCodeInput */
-.code-input-v3 {
- display: grid !important;
- width: 100%;
- grid-template-columns: repeat(6, minmax(0, 1fr));
- gap: 0.75rem;
-}
-
-.code-input-v3 input {
- min-width: 0;
- width: 100% !important;
- outline: 1px solid transparent !important;
- outline-offset: 4px;
- transition:
- border-color 150ms,
- outline-color 150ms;
-}
-
-.code-input-v3 input:hover {
- border-color: color-mix(in srgb, var(--color-foreground) 20%, transparent) !important;
-}
-
-.code-input-v3 input:focus {
- border-color: color-mix(in srgb, var(--color-project) 45%, var(--color-border)) !important;
- outline-color: color-mix(in srgb, var(--color-project) 45%, transparent) !important;
- box-shadow: none;
-}
-
-.code-input-v3-recovery {
- grid-template-columns: repeat(8, minmax(0, 1fr));
- gap: 0.5rem;
-}
-
-@media (width < 40rem) {
- .code-input-v3 {
- gap: 0.5rem;
- }
-
- .code-input-v3 input {
- height: auto !important;
- aspect-ratio: 1;
- }
-
- .code-input-v3-recovery {
- gap: 0.375rem;
- }
-}
-
-.code-input-v3-error input {
- border-color: color-mix(in srgb, var(--color-danger) 55%, var(--color-border)) !important;
-}
diff --git a/frontend/src/lib/fn/promise.ts b/frontend/src/lib/fn/promise.ts
new file mode 100644
index 0000000000..9da08a852e
--- /dev/null
+++ b/frontend/src/lib/fn/promise.ts
@@ -0,0 +1,9 @@
+export const waitForMinimumDuration = async (startedAt: number, durationMs: number) => {
+ const remainingDuration = Math.max(0, durationMs - (Date.now() - startedAt));
+
+ if (remainingDuration > 0) {
+ await new Promise((resolve) => {
+ setTimeout(resolve, remainingDuration);
+ });
+ }
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
index 38f79cca3c..c293f8f3a9 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
@@ -5,8 +5,17 @@ import { useNavigate } from "@tanstack/react-router";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
-import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
-import { VerificationCodeForm } from "@app/components/v3";
+import { Button, FormControl, Input } from "@app/components/v2";
+import {
+ Button as V3Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ VerificationCodeForm
+} from "@app/components/v3";
import { useUser } from "@app/context";
import {
useRequestEmailChangeOTP,
@@ -150,13 +159,12 @@ export const ChangeEmailSection = () => {
const isOtpModalOpen = otpStep !== null;
const otpRecipient = otpStep === "currentEmail" ? (user?.email ?? "") : pendingEmail;
- const otpSubTitle =
+ const otpDescription =
otpStep === "currentEmail"
- ? `Enter the 6-digit code sent to your current email: ${otpRecipient}`
- : `Enter the 6-digit code sent to your new email: ${otpRecipient}`;
+ ? "Enter the 6-digit code sent to your current email."
+ : "Enter the 6-digit code sent to your new email.";
const otpTitle =
otpStep === "currentEmail" ? "Confirm from current email" : "Confirm from new email";
- const otpButtonLabel = otpStep === "currentEmail" ? "Confirm" : "Confirm Email Change";
const isOtpSubmitLoading = otpStep === "currentEmail" ? isVerifyingCurrent : isUpdatingEmail;
const onOtpSubmit = otpStep === "currentEmail" ? handleCurrentOtpSubmit : handleNewOtpSubmit;
@@ -206,20 +214,25 @@ export const ChangeEmailSection = () => {
</form>
</div>
- <Modal
- isOpen={isOtpModalOpen}
+ <Dialog
+ open={isOtpModalOpen}
onOpenChange={(isOpen) => {
if (!isOpen) closeOtpModal();
}}
>
- <ModalContent title={otpTitle} subTitle={otpSubTitle}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{otpTitle}</DialogTitle>
+ <DialogDescription>
+ {otpDescription} <span className="font-medium text-foreground">{otpRecipient}</span>
+ </DialogDescription>
+ </DialogHeader>
<VerificationCodeForm
key={otpStep ?? "closed"}
name="email-change-verification-code"
value={typedOTP}
onChange={setTypedOTP}
onSubmit={onOtpSubmit}
- submitLabel={otpButtonLabel}
isPending={isOtpSubmitLoading}
>
{otpStep === "newEmail" && (
@@ -229,19 +242,14 @@ export const ChangeEmailSection = () => {
completed.
</p>
)}
- <div className="flex justify-center">
- <Button
- type="button"
- colorSchema="secondary"
- variant="outline"
- onClick={closeOtpModal}
- >
+ <DialogFooter>
+ <V3Button type="button" variant="outline" onClick={closeOtpModal}>
Cancel
- </Button>
- </div>
+ </V3Button>
+ </DialogFooter>
</VerificationCodeForm>
- </ModalContent>
- </Modal>
+ </DialogContent>
+ </Dialog>
</>
);
};