Skip to content

Automate browser based workflows with AI

fix(SKY-9864): stop overwriting totp_identifier on hydration (#6002)

Celal Zamanoğlue0d1703dd1d8
diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx
new file mode 100644
index 000000000..57263498a
--- /dev/null
+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx
@@ -0,0 +1,253 @@
+// @vitest-environment jsdom
+
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
+import { useEffect, useState } from "react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { PasswordCredentialContent } from "./PasswordCredentialContent";
+
+type Values = {
+ name: string;
+ username: string;
+ password: string;
+ totp: string;
+ totp_type: "authenticator" | "email" | "text" | "none";
+ totp_identifier: string;
+};
+
+const INITIAL_VALUES: Values = {
+ name: "",
+ username: "",
+ password: "",
+ totp: "",
+ totp_type: "none",
+ totp_identifier: "",
+};
+
+const SAVED_VALUES: Values = {
+ name: "Example Login",
+ username: "[email protected]",
+ password: "",
+ totp: "",
+ totp_type: "email",
+ totp_identifier: "[email protected]",
+};
+
+// Mirrors CredentialsModal: starts the form at INITIAL_VALUES, then after mount
+// applies the loaded credential via setPasswordCredentialValues — same flow
+// that produced SKY-9864.
+function ModalLikeHarness({
+ appliedValues,
+ onChangeSpy,
+}: {
+ appliedValues: Values | null;
+ onChangeSpy: (next: Values) => void;
+}) {
+ const [values, setValues] = useState<Values>(INITIAL_VALUES);
+ useEffect(() => {
+ if (appliedValues) {
+ setValues(appliedValues);
+ }
+ }, [appliedValues]);
+ return (
+ <MemoryRouter>
+ <PasswordCredentialContent
+ values={values}
+ onChange={(next) => {
+ onChangeSpy(next);
+ setValues(next);
+ }}
+ editMode
+ editingGroups={{ name: false, values: false }}
+ />
+ </MemoryRouter>
+ );
+}
+
+describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression)", () => {
+ afterEach(() => cleanup());
+
+ it("preserves saved totp_identifier when modal hydrates an email-TOTP credential into a form that started at PASSWORD_CREDENTIAL_INITIAL_VALUES", async () => {
+ // Reproduces the bug:
+ // 1. CredentialsModal initially renders PasswordCredentialContent with
+ // PASSWORD_CREDENTIAL_INITIAL_VALUES (totp_type="none").
+ // 2. The modal's useEffect then setPasswordCredentialValues({...cred...})
+ // with the saved cred — totp_type="email" plus the saved
+ // totp_identifier (e.g. "[email protected]").
+ // 3. The sync useEffect inside PasswordCredentialContent flips totpMethod
+ // from default "authenticator" to "email", which triggers the
+ // auto-fill useEffect with methodChanged=true and silently overwrites
+ // the saved totp_identifier with username.
+ const onChangeSpy = vi.fn();
+
+ const { rerender } = render(
+ <ModalLikeHarness appliedValues={null} onChangeSpy={onChangeSpy} />,
+ );
+
+ // Now simulate the modal applying the loaded credential's values via
+ // setPasswordCredentialValues (a single render with a non-null appliedValues
+ // prop, then the inner useEffect calls setValues).
+ await act(async () => {
+ rerender(
+ <ModalLikeHarness
+ appliedValues={SAVED_VALUES}
+ onChangeSpy={onChangeSpy}
+ />,
+ );
+ });
+
+ // The component must NOT have called onChange with totp_identifier set to
+ // the username — that would silently corrupt the saved value on next save.
+ const corruptingCalls = onChangeSpy.mock.calls.filter((call) => {
+ const next = call[0] as Values;
+ return (
+ next.totp_identifier === SAVED_VALUES.username &&
+ next.totp_identifier !== SAVED_VALUES.totp_identifier
+ );
+ });
+ expect(corruptingCalls).toEqual([]);
+ });
+
+ it("auto-fills totp_identifier with the username when the user explicitly switches the method to Email and the identifier is blank", async () => {
+ const onChangeSpy = vi.fn();
+
+ render(
+ <ModalLikeHarness
+ appliedValues={{
+ name: "New cred",
+ username: "[email protected]",
+ password: "",
+ totp: "",
+ totp_type: "none",
+ totp_identifier: "",
+ }}
+ onChangeSpy={onChangeSpy}
+ />,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByText("Two-Factor Authentication"));
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Email"));
+ });
+
+ const autoFillCall = onChangeSpy.mock.calls.find((call) => {
+ const next = call[0] as Values;
+ return (
+ next.totp_type === "email" &&
+ next.totp_identifier === "[email protected]"
+ );
+ });
+ expect(autoFillCall).toBeTruthy();
+ });
+
+ it("preserves an intentionally-empty totp_identifier when hydrating a saved email-TOTP credential", async () => {
+ // Regression for the empty-string false-positive in the username-rename
+ // follow-on path: at mount, prevUsername="" and identifier="". After
+ // hydration, identifier is still "" — same value as prevUsername, so
+ // identifierMatchedPrevUsername=true. Without the prevUsername!=="" guard,
+ // the effect silently fires updateValues({ totp_identifier: username }),
+ // overwriting a value the user deliberately saved as blank.
+ const onChangeSpy = vi.fn();
+
+ const { rerender } = render(
+ <ModalLikeHarness appliedValues={null} onChangeSpy={onChangeSpy} />,
+ );
+
+ await act(async () => {
+ rerender(
+ <ModalLikeHarness
+ appliedValues={{
+ name: "Example Login",
+ username: "[email protected]",
+ password: "",
+ totp: "",
+ totp_type: "email",
+ totp_identifier: "",
+ }}
+ onChangeSpy={onChangeSpy}
+ />,
+ );
+ });
+
+ const refillCalls = onChangeSpy.mock.calls.filter((call) => {
+ const next = call[0] as Values;
+ return next.totp_identifier === "[email protected]";
+ });
+ expect(refillCalls).toEqual([]);
+ });
+
+ it("clears totp_identifier when the user switches the method from Email to Text", async () => {
+ // Symmetric to the Text → Email reseed case: an email-shaped identifier
+ // (or anything from email mode) isn't a valid phone number, so clicking
+ // Text on a saved email-TOTP credential must wipe the field.
+ const onChangeSpy = vi.fn();
+
+ render(
+ <ModalLikeHarness
+ appliedValues={{
+ name: "Example Login",
+ username: "[email protected]",
+ password: "",
+ totp: "",
+ totp_type: "email",
+ totp_identifier: "[email protected]",
+ }}
+ onChangeSpy={onChangeSpy}
+ />,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByText("Text Message"));
+ });
+
+ const clearCall = onChangeSpy.mock.calls.find((call) => {
+ const next = call[0] as Values;
+ return next.totp_type === "text" && next.totp_identifier === "";
+ });
+ expect(clearCall).toBeTruthy();
+ });
+
+ it("reseeds totp_identifier to username when the user switches the method from Text to Email", async () => {
+ // Regression for the Text→Email case raised in PR review: a phone
+ // number entered under Text mode must NOT silently persist as the
+ // email identifier when the user clicks the Email tile, since it's
+ // not a valid email identifier.
+ const onChangeSpy = vi.fn();
+
+ render(
+ <ModalLikeHarness
+ appliedValues={{
+ name: "Example Login",
+ username: "[email protected]",
+ password: "",
+ totp: "",
+ totp_type: "text",
+ totp_identifier: "+14155551234",
+ }}
+ onChangeSpy={onChangeSpy}
+ />,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByText("Email"));
+ });
+
+ const reseedCall = onChangeSpy.mock.calls.find((call) => {
+ const next = call[0] as Values;
+ return (
+ next.totp_type === "email" &&
+ next.totp_identifier === "[email protected]"
+ );
+ });
+ expect(reseedCall).toBeTruthy();
+ });
+});
diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx
index ebb83f875..8a6de2789 100644
--- a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx
+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx
@@ -92,7 +92,6 @@ function PasswordCredentialContent({
}
}, [totp_type]);
const prevUsernameRef = useRef(username);
- const prevTotpMethodRef = useRef<typeof totpMethod>(totpMethod);
const totpIdentifierLabel =
totpMethod === "text"
? "TOTP Identifier (Phone)"
@@ -117,46 +116,58 @@ function PasswordCredentialContent({
[name, onChange, password, totp, totp_identifier, totp_type, username],
);
+ // Keep totp_identifier in sync ONLY when the user renames their username
+ // and the identifier was previously auto-filled to match that username.
+ // Method-change auto-fill lives in handleTotpMethodChange — that path is
+ // the only place we know the change came from the user (not from data
+ // hydration, which would silently overwrite a saved identifier).
useEffect(() => {
const prevUsername = prevUsernameRef.current;
- const prevMethod = prevTotpMethodRef.current;
if (totpMethod === "email") {
+ // prevUsername !== "" guards against an empty-string false-positive
+ // during initial hydration (where prev and identifier are both "").
const usernameChanged = username !== prevUsername;
- const identifierBlank = totp_identifier.trim() === "";
- const identifierMatchedPrevUsername = totp_identifier === prevUsername;
- const methodChanged = prevMethod !== "email";
-
- if (
- identifierBlank ||
- methodChanged ||
- (usernameChanged && identifierMatchedPrevUsername)
- ) {
+ const identifierMatchedPrevUsername =
+ prevUsername !== "" && totp_identifier === prevUsername;
+ if (usernameChanged && identifierMatchedPrevUsername) {
updateValues({ totp_identifier: username });
}
}
- if (totpMethod === "text" && prevMethod !== "text") {
- const wasAutoFilled = totp_identifier === prevUsername;
- if (wasAutoFilled || totp_identifier.trim() === "") {
- updateValues({ totp_identifier: "" });
- }
- }
-
prevUsernameRef.current = username;
- prevTotpMethodRef.current = totpMethod;
}, [totpMethod, totp_identifier, updateValues, username]);
- // Update totp_type when totpMethod changes; also enter edit mode for values
+ // User explicitly switched the 2FA method. Apply method-specific identifier
+ // defaults here (rather than in a useEffect) so data-hydration setTotpMethod
+ // calls don't accidentally trigger them.
const handleTotpMethodChange = (
method: "authenticator" | "email" | "text",
) => {
onEnableEditValues?.();
+ const prevMethod = totpMethod;
setTotpMethod(method);
- updateValues({
+
+ const updates: Partial<Props["values"]> = {
totp: method === "authenticator" ? totp : "",
totp_type: method,
- });
+ };
+
+ if (method === "email" && prevMethod !== "email") {
+ // Always reseed to username — whatever the previous method left in
+ // the field (a phone number from text, or nothing) is unlikely to be
+ // a valid email identifier.
+ updates.totp_identifier = username;
+ }
+
+ if (method === "text" && prevMethod !== "text") {
+ // Always clear — an email or username-shaped value from the previous
+ // method isn't a valid phone identifier, and we can't infer the user's
+ // phone number from email-mode data.
+ updates.totp_identifier = "";
+ }
+
+ updateValues(updates);
};
return (