Skip to content

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

fix(auth): improve verification code focus and retry feedback (#8386)

Andrew Huangd8a811ad0a95
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
index 85d5b8775f..45eafc4248 100644
--- a/frontend/src/components/mfa/setup/VerifyStep.tsx
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -90,9 +90,9 @@ const TotpVerify = ({
<VerificationCodeForm
name="totp-enrollment-code"
value={totp}
- onChange={(value) => {
+ onChange={(value, reason) => {
setTotp(value.replace(/\D/g, "").slice(0, 6));
- setVerificationError(undefined);
+ if (reason === "input") setVerificationError(undefined);
}}
onSubmit={handleVerify}
submitVariant={variant}
diff --git a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.stories.tsx b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.stories.tsx
index 3e4345aadc..3699f5b553 100644
--- a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.stories.tsx
+++ b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.stories.tsx
@@ -1,8 +1,10 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { AuthPagePanel } from "@app/components/auth/AuthPagePanel";
+import { Alert, AlertDescription, AlertTitle } from "../../generic/Alert";
+import { Button } from "../../generic/Button";
import { CardContent } from "../../generic/Card";
import { VerificationCodeForm, VerificationCodeHeader } from "./VerificationCodeForm";
import { VerificationCodeResend } from "./VerificationCodeResend";
@@ -11,7 +13,8 @@ const meta = {
title: "Authentication/VerificationCodeForm",
component: VerificationCodeForm,
parameters: {
- layout: "centered"
+ layout: "centered",
+ controls: { disable: true }
},
decorators: [
(Story) => (
@@ -32,16 +35,40 @@ const meta = {
export default meta;
type Story = StoryObj<typeof meta>;
-const VerificationExample = ({
- fields = 6,
- error,
- resendState = "ready"
-}: {
- fields?: number;
- error?: string;
- resendState?: "ready" | "resending" | "delayed";
-}) => {
+const VerificationDemo = ({ fields }: { fields: number }) => {
const [value, setValue] = useState("");
+ const [submittedCode, setSubmittedCode] = useState("");
+ const [status, setStatus] = useState<"idle" | "verifying" | "invalid" | "verified">("idle");
+ const [isResending, setIsResending] = useState(false);
+ const [remainingSeconds, setRemainingSeconds] = useState(0);
+ const [formKey, setFormKey] = useState(0);
+ const validCode = fields === 6 ? "123456" : "abcdefgh";
+
+ useEffect(() => {
+ if (status !== "verifying") return undefined;
+
+ const timer = window.setTimeout(() => {
+ setStatus(submittedCode === validCode ? "verified" : "invalid");
+ }, 1000);
+ return () => window.clearTimeout(timer);
+ }, [status, submittedCode, validCode]);
+
+ useEffect(() => {
+ if (!isResending) return undefined;
+
+ const timer = window.setTimeout(() => {
+ setIsResending(false);
+ setRemainingSeconds(5);
+ }, 1000);
+ return () => window.clearTimeout(timer);
+ }, [isResending]);
+
+ useEffect(() => {
+ if (remainingSeconds === 0) return undefined;
+
+ const timer = window.setTimeout(() => setRemainingSeconds((seconds) => seconds - 1), 1000);
+ return () => window.clearTimeout(timer);
+ }, [remainingSeconds]);
return (
<AuthPagePanel>
@@ -51,51 +78,76 @@ const VerificationExample = ({
description={fields === 8 ? "Enter one of your backup recovery codes." : undefined}
/>
<CardContent>
- <VerificationCodeForm
- name={`verification-story-${fields}`}
- fields={fields}
- value={value}
- onChange={setValue}
- onSubmit={() => undefined}
- error={error}
- >
- {fields === 6 && (
- <VerificationCodeResend
- isResending={resendState === "resending"}
- remainingSeconds={resendState === "delayed" ? 20 : 0}
- onResend={() => undefined}
- />
- )}
- </VerificationCodeForm>
+ {status === "verified" ? (
+ <Alert variant="success">
+ <AlertTitle>Code verified</AlertTitle>
+ <AlertDescription>This demo does not sign you in or contact a server.</AlertDescription>
+ </Alert>
+ ) : (
+ <VerificationCodeForm
+ key={formKey}
+ name={`verification-story-${fields}`}
+ fields={fields}
+ value={value}
+ onChange={setValue}
+ onSubmit={() => {
+ setSubmittedCode(value);
+ setStatus("verifying");
+ }}
+ isPending={status === "verifying"}
+ isDisabled={isResending}
+ error={status === "invalid" ? "That code is invalid. Try again." : undefined}
+ >
+ {fields === 6 && (
+ <VerificationCodeResend
+ isResending={isResending}
+ isDisabled={status === "verifying"}
+ remainingSeconds={remainingSeconds}
+ onResend={() => {
+ setValue("");
+ setStatus("idle");
+ setFormKey((key) => key + 1);
+ setIsResending(true);
+ }}
+ />
+ )}
+ </VerificationCodeForm>
+ )}
</CardContent>
</AuthPagePanel>
);
};
-export const EmailCode: Story = {
- render: () => <VerificationExample />
-};
-
-export const PartialCode: Story = {
- args: { value: "123" }
-};
-
-export const Verifying: Story = {
- args: { value: "123456", isPending: true }
-};
-
-export const InvalidCode: Story = {
- render: () => <VerificationExample error="That code is invalid. Try again." />
-};
+const InteractiveExample = ({ initialFields = 6 }: { initialFields?: number }) => {
+ const [fields, setFields] = useState(initialFields);
+ const [session, setSession] = useState(0);
-export const Resending: Story = {
- render: () => <VerificationExample resendState="resending" />
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="space-y-3 text-sm text-label">
+ <p>
+ Interactive demo. Type {fields === 6 ? "123456" : "abcdefgh"} to succeed, or any other
+ complete code to try the error and retry flow. The first complete code submits
+ automatically. No requests are sent.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <Button variant="outline" size="sm" onClick={() => setFields(fields === 6 ? 8 : 6)}>
+ {fields === 6 ? "Use a Recovery Code" : "Use an Email Code"}
+ </Button>
+ <Button variant="ghost" size="sm" onClick={() => setSession((key) => key + 1)}>
+ Restart Demo
+ </Button>
+ </div>
+ </div>
+ <VerificationDemo key={`${fields}-${session}`} fields={fields} />
+ </div>
+ );
};
-export const ResendDelayed: Story = {
- render: () => <VerificationExample resendState="delayed" />
+export const EmailCode: Story = {
+ render: () => <InteractiveExample />
};
export const RecoveryCode: Story = {
- render: () => <VerificationExample fields={8} />
+ render: () => <InteractiveExample initialFields={8} />
};
diff --git a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx
index 8c335daaf0..65546915de 100644
--- a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx
+++ b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeForm.tsx
@@ -50,7 +50,7 @@ type VerificationCodeFormProps = {
isDisabled?: boolean;
isPending?: boolean;
name: string;
- onChange: (value: string) => void;
+ onChange: (value: string, reason: "input" | "reset") => void;
onSubmit: () => void | Promise<void>;
submitVariant?: React.ComponentProps<typeof Button>["variant"];
value: string;
@@ -74,15 +74,18 @@ export const VerificationCodeForm = ({
const [hasAttemptedVerification, setHasAttemptedVerification] = useState(false);
const [hasFailedVerification, setHasFailedVerification] = useState(false);
const onSubmitRef = useRef(onSubmit);
+ const onChangeRef = useRef(onChange);
useEffect(() => {
onSubmitRef.current = onSubmit;
- }, [onSubmit]);
+ onChangeRef.current = onChange;
+ }, [onChange, onSubmit]);
useEffect(() => {
if (hasError && !isPending) {
setHasChangedSinceError(false);
setHasFailedVerification(true);
+ onChangeRef.current("", "reset");
}
}, [hasError, isPending]);
@@ -95,7 +98,7 @@ export const VerificationCodeForm = ({
const handleChange = (nextValue: string) => {
if (hasError) setHasChangedSinceError(true);
- onChange(nextValue);
+ onChange(nextValue, "input");
};
return (
@@ -115,7 +118,7 @@ export const VerificationCodeForm = ({
fields={fields}
onChange={handleChange}
value={value}
- isError={hasError && !hasChangedSinceError}
+ isError={hasError && !isPending && !hasChangedSinceError}
/>
{error && <FieldError className="mt-0">{error}</FieldError>}
</div>
diff --git a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx
index 3334ed2678..43dd9131fe 100644
--- a/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx
+++ b/frontend/src/components/v3/platform/VerificationCode/VerificationCodeInput.tsx
@@ -6,6 +6,7 @@ import {
useRef,
useState
} from "react";
+import { motion, useReducedMotion } from "motion/react";
import { cn } from "../../utils";
@@ -30,10 +31,15 @@ export const VerificationCodeInput = ({
value = ""
}: Props) => {
const inputRef = useRef<HTMLInputElement>(null);
+ const prefersReducedMotion = useReducedMotion();
const pointerAnchorRef = useRef<number | undefined>(undefined);
const [isFocused, setIsFocused] = useState(false);
const [selection, setSelection] = useState<Selection>({ start: 0, end: 0 });
+ useEffect(() => {
+ inputRef.current?.focus();
+ }, []);
+
const syncSelection = useCallback(() => {
const input = inputRef.current;
if (!input) return;
@@ -48,7 +54,7 @@ export const VerificationCodeInput = ({
if (!isError) return;
inputRef.current?.focus();
- inputRef.current?.select();
+ inputRef.current?.setSelectionRange(0, 0);
syncSelection();
}, [isError, syncSelection]);
@@ -166,7 +172,9 @@ export const VerificationCodeInput = ({
return (
<div
- className="group relative w-full"
+ data-slot="verification-code-input"
+ aria-invalid={isError}
+ className="relative w-full"
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
@@ -178,12 +186,7 @@ export const VerificationCodeInput = ({
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"
- )}
+ className="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 max-sm:aspect-square max-sm:h-auto"
key={index}
>
{value[index] ?? ""}
@@ -203,20 +206,25 @@ export const VerificationCodeInput = ({
);
})}
</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>
- )}
+ <div aria-hidden className={cn("pointer-events-none absolute inset-0 z-[1]", gridClassName)}>
+ <motion.div
+ layout
+ initial={false}
+ animate={{ opacity: isFocused ? 1 : 0 }}
+ transition={{ duration: prefersReducedMotion ? 0 : 0.2, ease: [0.23, 1, 0.32, 1] }}
+ data-slot="verification-code-indicator"
+ className={cn(
+ "rounded-md outline outline-1 outline-offset-4",
+ isError ? "outline-danger/55" : "outline-project/45"
+ )}
+ style={{
+ gridColumn: hasSelection
+ ? `${selection.start + 1} / ${selection.end + 1}`
+ : `${activeSlot + 1} / ${activeSlot + 2}`,
+ borderRadius: 6
+ }}
+ />
+ </div>
<input
ref={inputRef}
aria-invalid={isError}
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 582f81f2c3..109650c9e1 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -661,6 +661,7 @@ html[data-platform="ios"] {
[data-slot="input"][aria-invalid="true"],
[data-slot="textarea"][aria-invalid="true"],
+ [data-slot="verification-code-input"][aria-invalid="true"],
[data-slot="input-group"]:has([data-slot="input-group-control"][aria-invalid="true"]) {
animation: inputErrorShake 200ms cubic-bezier(0.77, 0, 0.175, 1);
}
@@ -668,6 +669,7 @@ html[data-platform="ios"] {
@media (prefers-reduced-motion: reduce) {
[data-slot="input"][aria-invalid="true"],
[data-slot="textarea"][aria-invalid="true"],
+ [data-slot="verification-code-input"][aria-invalid="true"],
[data-slot="input-group"]:has([data-slot="input-group-control"][aria-invalid="true"]) {
animation: none;
}