Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Improve authenticator setup feedback (#6953)
Suchintan203ff03fdfc1
diff --git a/skyvern-frontend/src/assets/authenticators/google-authenticator.jpg b/skyvern-frontend/src/assets/authenticators/google-authenticator.jpgnew file mode 100644index 000000000..94932c31aBinary files /dev/null and b/skyvern-frontend/src/assets/authenticators/google-authenticator.jpg differdiff --git a/skyvern-frontend/src/routes/credentials/AuthenticatorAppLogo.tsx b/skyvern-frontend/src/routes/credentials/AuthenticatorAppLogo.tsxnew file mode 100644index 000000000..2d27ce79b--- /dev/null+++ b/skyvern-frontend/src/routes/credentials/AuthenticatorAppLogo.tsx@@ -0,0 +1,12 @@+function AuthenticatorAppLogo({ src }: { src: string }) {+ return (+ <img+ src={src}+ alt=""+ className="size-6 rounded-[6px] object-cover"+ draggable={false}+ />+ );+}++export { AuthenticatorAppLogo };diff --git a/skyvern-frontend/src/routes/credentials/CredentialAuthenticatorSupportContext.ts b/skyvern-frontend/src/routes/credentials/CredentialAuthenticatorSupportContext.tsnew file mode 100644index 000000000..906bbf294--- /dev/null+++ b/skyvern-frontend/src/routes/credentials/CredentialAuthenticatorSupportContext.ts@@ -0,0 +1,58 @@+import {+ createContext,+ createElement,+ useContext,+ type ReactNode,+} from "react";++type CredentialEnterpriseAuthenticatorSupport = {+ label: string;+ apps: string[];+ description: ReactNode;+ contactUrl?: string;+ vendorLabels?: Record<string, string>;+ qrCodeTypes?: CredentialAuthenticatorQrCodeType[];+ inferQrCodeType?: (value: string) => string | null;+};++type CredentialAuthenticatorQrCodeType = {+ id: string;+ label: string;+ description?: ReactNode;+ logo?: ReactNode;+};++type CredentialAuthenticatorSupportCopy = {+ enterpriseApps?: CredentialEnterpriseAuthenticatorSupport;+};++const CredentialAuthenticatorSupportContext =+ createContext<CredentialAuthenticatorSupportCopy>({});++function CredentialAuthenticatorSupportProvider({+ children,+ value,+}: {+ children: ReactNode;+ value: CredentialAuthenticatorSupportCopy;+}) {+ return createElement(+ CredentialAuthenticatorSupportContext.Provider,+ { value },+ children,+ );+}++function useCredentialAuthenticatorSupport() {+ return useContext(CredentialAuthenticatorSupportContext);+}++export {+ CredentialAuthenticatorSupportProvider,+ useCredentialAuthenticatorSupport,+};+export type {+ CredentialAuthenticatorSupportCopy,+ CredentialAuthenticatorQrCodeType,+ CredentialEnterpriseAuthenticatorSupport,+};diff --git a/skyvern-frontend/src/routes/credentials/CredentialItem.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialItem.test.tsxindex 1c75e73d6..bc6a62e52 100644--- a/skyvern-frontend/src/routes/credentials/CredentialItem.test.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialItem.test.tsx@@ -93,7 +93,14 @@ describe("CredentialItem TOTP code preview", () => {mockedGetClient.mockResolvedValue({get: vi.fn().mockRejectedValue({isAxiosError: true,- response: { data: { detail: "Saved authenticator key is invalid." } },+ response: {+ data: {+ detail: {+ error_code: "invalid_authenticator_key",+ message: "Saved authenticator key is invalid.",+ },+ },+ },}),} as never);diff --git a/skyvern-frontend/src/routes/credentials/CredentialItem.tsx b/skyvern-frontend/src/routes/credentials/CredentialItem.tsxindex 81066d0ad..c599350b8 100644--- a/skyvern-frontend/src/routes/credentials/CredentialItem.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialItem.tsx@@ -34,8 +34,8 @@ import { useCredentialTestStore } from "@/store/useCredentialTestStore";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { toast } from "@/components/ui/use-toast";import { copyText } from "@/util/copyText";-import { isAxiosError } from "axios";import { cn } from "@/util/utils";+import { getCredentialErrorMessage } from "./authenticatorSaveError";type Props = {credential: CredentialApiResponse;@@ -120,14 +120,11 @@ function CredentialTotpCodePreview({ credentialId }: { credentialId: string }) {if (!isMountedRef.current) {return;}- const detail = isAxiosError(caught)- ? (caught.response?.data as { detail?: string } | undefined)?.detail- : undefined;setTotpCode(null);setSecondsRemaining(null);setExpiresAt(null);setIsCodeVisible(false);- setError(detail ?? "Unable to load code");+ setError(getCredentialErrorMessage(caught) ?? "Unable to load code");} finally {if (isMountedRef.current) {setIsLoading(false);diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsxindex fd25df182..68101f6c8 100644--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx@@ -1,8 +1,84 @@// @vitest-environment jsdom-import { describe, expect, it } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ cleanup,+} from "@testing-library/react";+import { AxiosError, AxiosHeaders } from "axios";+import { MemoryRouter } from "react-router-dom";+import { afterEach, describe, expect, it, vi } from "vitest";import { getAuthenticatorKeyError } from "./credentialTotpValidation";+import { CredentialsModal } from "./CredentialsModal";+import { CredentialModalTypes } from "./useCredentialModalState";++const postMock = vi.hoisted(() => vi.fn());+const toastMock = vi.hoisted(() => vi.fn());++vi.mock("@/api/AxiosClient", () => ({+ getClient: vi.fn(async () => ({+ post: postMock,+ patch: vi.fn(),+ delete: vi.fn(),+ })),+}));++vi.mock("@/components/ui/use-toast", () => ({+ toast: toastMock,+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++vi.mock("@/hooks/useCustomCredentialServiceConfig", () => ({+ useCustomCredentialServiceConfig: () => ({ parsedConfig: null }),+}));++vi.mock("@/routes/workflows/hooks/useCredentialsQuery", () => ({+ useCredentialsQuery: () => ({ data: [] }),+}));++function axiosErrorWithDetail(detail: unknown): AxiosError {+ const error = new AxiosError("Request failed");+ error.response = {+ data: { detail },+ status: 400,+ statusText: "Bad Request",+ headers: {},+ config: { headers: new AxiosHeaders() },+ };+ return error;+}++function renderPasswordCredentialsModal() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter>+ <CredentialsModal+ isOpen+ onOpenChange={vi.fn()}+ overrideType={CredentialModalTypes.PASSWORD}+ />+ </MemoryRouter>+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});describe("getAuthenticatorKeyError", () => {it("requires an authenticator key when authenticator 2FA is selected", () => {@@ -47,3 +123,90 @@ describe("getAuthenticatorKeyError", () => {).toBeNull();});});++describe("CredentialsModal authenticator save errors", () => {+ async function fillAndSubmitAuthenticatorCredential(totp: string) {+ renderPasswordCredentialsModal();++ await waitFor(() => {+ expect(screen.getByDisplayValue("credentials")).toBeTruthy();+ });+ const usernameInput = Array.from(+ document.querySelectorAll<HTMLInputElement>("input"),+ ).find(+ (input) =>+ input.type === "text" && input.value === "" && input.placeholder === "",+ );+ expect(usernameInput).toBeTruthy();+ fireEvent.change(usernameInput as HTMLInputElement, {+ target: { value: "[email protected]" },+ });+ const passwordInput = document.querySelector('input[type="password"]');+ expect(passwordInput).toBeTruthy();+ fireEvent.change(passwordInput as HTMLInputElement, {+ target: { value: "password" },+ });++ fireEvent.click(screen.getByText("Two-Factor Authentication"));+ const authenticatorInput = screen.getByPlaceholderText(+ "e.g. JBSWY3DPEHPK3PXP",+ );+ fireEvent.change(authenticatorInput, {+ target: { value: totp },+ });++ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ return authenticatorInput as HTMLInputElement;+ }++ it("shows a rejected authenticator QR inline and keeps the submitted value in the field", async () => {+ postMock.mockRejectedValueOnce(+ axiosErrorWithDetail({+ error_code: "authenticator_no_code_secret",+ message: "This QR code enrolls push approval.",+ vendor: "microsoft",+ }),+ );++ const decodedQrPayload = "phonefactor://activate_account?code=123456";+ const authenticatorInput =+ await fillAndSubmitAuthenticatorCredential(decodedQrPayload);++ await waitFor(() => {+ expect(postMock).toHaveBeenCalledWith(+ "/credentials",+ expect.objectContaining({+ credential: expect.objectContaining({+ totp: decodedQrPayload,+ totp_type: "authenticator",+ }),+ }),+ );+ });+ await waitFor(() => {+ expect(screen.getByText(/push-approval app/)).toBeTruthy();+ });+ expect((authenticatorInput as HTMLInputElement).value).toBe(+ decodedQrPayload,+ );+ }, 10_000);++ it("shows enterprise-required feedback inline without a destructive toast", async () => {+ postMock.mockRejectedValueOnce(+ axiosErrorWithDetail({+ error_code: "authenticator_feature_restricted",+ message: "Enterprise plan required.",+ vendor: "okta",+ }),+ );++ await fillAndSubmitAuthenticatorCredential(+ '{"methods":[{"type":"totp","sharedSecret":"JBSWY3DPEHPK3PXP"}]}',+ );++ await waitFor(() => {+ expect(screen.getByText(/Skyvern enterprise plan/)).toBeTruthy();+ });+ expect(toastMock).not.toHaveBeenCalled();+ }, 10_000);+});diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.tsxindex 0fb5c572c..39bf26cb5 100644--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx@@ -52,6 +52,11 @@ import { Textarea } from "@/components/ui/textarea";import { getHostname } from "@/util/getHostname";import { useCustomCredentialServiceConfig } from "@/hooks/useCustomCredentialServiceConfig";import { getAuthenticatorKeyError } from "./credentialTotpValidation";+import {+ getAuthenticatorSaveError,+ getCredentialErrorMessage,+ type AuthenticatorSaveError,+} from "./authenticatorSaveError";const PASSWORD_CREDENTIAL_INITIAL_VALUES = {name: "",@@ -248,6 +253,45 @@ function CredentialsModal({name: false,values: false,});+ // Inline authenticator setup error returned by the backend when it rejects a+ // decoded QR value or pasted key. Cleared whenever the user edits the key.+ const [authenticatorSaveError, setAuthenticatorSaveError] =+ useState<AuthenticatorSaveError | null>(null);++ const handlePasswordCredentialChange = useCallback(+ (next: typeof PASSWORD_CREDENTIAL_INITIAL_VALUES) => {+ setPasswordCredentialValues((prev) => {+ if (next.totp !== prev.totp || next.totp_type !== prev.totp_type) {+ setAuthenticatorSaveError(null);+ }+ return next;+ });+ },+ [],+ );++ const reportCredentialSaveError = useCallback(+ (error: unknown, title = "Error"): string => {+ const authError = getAuthenticatorSaveError(error);+ if (authError && passwordCredentialValues.totp_type === "authenticator") {+ setAuthenticatorSaveError(authError);+ }+ const description =+ authError?.message ??+ getCredentialErrorMessage(error) ??+ (error instanceof Error+ ? error.message+ : "An unexpected error occurred");+ const isEnterpriseUpgrade =+ authError?.code === "enterprise_required" &&+ passwordCredentialValues.totp_type === "authenticator";+ if (!isEnterpriseUpgrade) {+ toast({ title, description, variant: "destructive" });+ }+ return description;+ },+ [passwordCredentialValues.totp_type],+ );const handleEnableEditName = useCallback(() => {setEditingGroups((prev) => ({ ...prev, name: true }));@@ -461,6 +505,7 @@ function CredentialsModal({setCreditCardCredentialValues(createCreditCardCredentialInitialValues());setSecretCredentialValues(SECRET_CREDENTIAL_INITIAL_VALUES);setEditingGroups({ name: false, values: false });+ setAuthenticatorSaveError(null);setTestAndSave(false);setTestUrl("");setTestStatus("idle");@@ -618,6 +663,7 @@ function CredentialsModal({);const startTest = useCallback(async () => {+ setAuthenticatorSaveError(null);try {const client = await getClient(credentialGetter, "sans-api-v1");const proxyPinPayload = getProxyPinPayload();@@ -664,15 +710,11 @@ function CredentialsModal({}, 3000);} catch (error) {setTestStatus("failed");- const detail = (- (error as AxiosError)?.response?.data as { detail?: string }- )?.detail;- setTestFailureReason(detail ?? "Failed to start credential test");- toast({- title: "Failed to start credential test",- description: detail ?? "An unexpected error occurred",- variant: "destructive",- });+ const description = reportCredentialSaveError(+ error,+ "Failed to start credential test",+ );+ setTestFailureReason(description);}}, [credentialGetter,@@ -681,6 +723,7 @@ function CredentialsModal({userContext,pollTestStatus,getProxyPinPayload,+ reportCredentialSaveError,]);const createCredentialMutation = useMutation({@@ -747,12 +790,7 @@ function CredentialsModal({}},onError: (error: AxiosError) => {- const detail = (error.response?.data as { detail?: string })?.detail;- toast({- title: "Error",- description: detail ? detail : error.message,- variant: "destructive",- });+ reportCredentialSaveError(error);},});@@ -829,12 +867,7 @@ function CredentialsModal({}},onError: (error: AxiosError) => {- const detail = (error.response?.data as { detail?: string })?.detail;- toast({- title: "Error",- description: detail ? detail : error.message,- variant: "destructive",- });+ reportCredentialSaveError(error);},});@@ -900,12 +933,7 @@ function CredentialsModal({});},onError: (error: AxiosError) => {- const detail = (error.response?.data as { detail?: string })?.detail;- toast({- title: "Error",- description: detail ? detail : error.message,- variant: "destructive",- });+ reportCredentialSaveError(error);},});@@ -969,6 +997,7 @@ function CredentialsModal({if (authenticatorKeyError) {return;}+ setAuthenticatorSaveError(null);// If test passed, rename the temp credential instead of creating a new oneif (testAndSave && testStatus === "completed" && testCredentialId) {@@ -1263,7 +1292,7 @@ function CredentialsModal({return (<PasswordCredentialContentvalues={passwordCredentialValues}- onChange={setPasswordCredentialValues}+ onChange={handlePasswordCredentialChange}url={testUrl}onUrlChange={setTestUrl}urlRequired={testAndSave}@@ -1273,6 +1302,7 @@ function CredentialsModal({onEnableEditName={handleEnableEditName}onEnableEditValues={handleEnableEditValues}totpError={authenticatorKeyError}+ authenticatorSaveError={authenticatorSaveError}beforeCredentialFields={customVaultCheckbox}afterUrl={<div className="space-y-3">diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsxindex 7e4401b84..2b33fd126 100644--- a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx@@ -12,6 +12,7 @@ import { useEffect, useState } from "react";import { MemoryRouter } from "react-router-dom";import { afterEach, describe, expect, it, vi } from "vitest";+import { CredentialAuthenticatorSupportProvider } from "./CredentialAuthenticatorSupportContext";import { PasswordCredentialContent } from "./PasswordCredentialContent";type Values = {@@ -41,6 +42,36 @@ const SAVED_VALUES: Values = {totp_identifier: "[email protected]",};+const ENTERPRISE_APPS = {+ label: "Enterprise QR support",+ apps: ["Enterprise Authenticator A", "Enterprise Authenticator B"],+ contactUrl: "https://www.skyvern.com/contact",+ qrCodeTypes: [+ {+ id: "example",+ label: "Enterprise Authenticator A",+ },+ {+ id: "opaque",+ label: "Enterprise Authenticator B",+ },+ ],+ inferQrCodeType: (value: string) => {+ if (value.startsWith("example-authenticator://")) {+ return "example";+ }+ if (value.startsWith("opaque-authenticator://")) {+ return "opaque";+ }+ return null;+ },+ vendorLabels: {+ opaque: "Enterprise Authenticator B",+ },+ description:+ "Scan the QR as usual - Skyvern detects these setup codes automatically.",+};+// Mirrors CredentialsModal: starts the form at INITIAL_VALUES, then after mount// applies the loaded credential via setPasswordCredentialValues — same flow// that produced SKY-9864.@@ -267,6 +298,14 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression});expect(qrCall).toBeTruthy();});+ expect(+ screen+ .getByRole("button", { name: /Google Authenticator/ })+ .getAttribute("aria-pressed"),+ ).toBe("true");+ expect(+ screen.getByTestId("authenticator-qr-type-detection").textContent,+ ).toBe("Detected from QR");expect(imageBitmap.close).toHaveBeenCalled();});@@ -318,6 +357,12 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression});expect(qrCall).toBeTruthy();});+ expect(+ screen+ .getByRole("button", { name: /Google Authenticator/ })+ .getAttribute("aria-pressed"),+ ).toBe("false");+ expect(screen.queryByText("Detected from QR")).toBeNull();expect(imageBitmap.close).toHaveBeenCalled();});@@ -561,3 +606,321 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regressionexpect(close).toHaveBeenCalled();});});++describe("PasswordCredentialContent — supported authenticator copy", () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ const NEW_VALUES: Values = {+ name: "New cred",+ username: "[email protected]",+ password: "password",+ totp: "",+ totp_type: "none",+ totp_identifier: "",+ };++ function stubQrCodeScan(rawValue: string) {+ const imageBitmap = { close: vi.fn() } as unknown as ImageBitmap;+ class MockBarcodeDetector {+ detect = vi.fn().mockResolvedValue([{ rawValue }]);+ }+ vi.stubGlobal("createImageBitmap", vi.fn().mockResolvedValue(imageBitmap));+ vi.stubGlobal("BarcodeDetector", MockBarcodeDetector);+ return imageBitmap;+ }++ async function uploadQrCodeImage() {+ await act(async () => {+ fireEvent.change(screen.getByLabelText("Upload QR code image"), {+ target: {+ files: [new File(["qr"], "totp.png", { type: "image/png" })],+ },+ });+ });+ }++ async function openAuthenticatorSection(+ enterpriseApps?: typeof ENTERPRISE_APPS,+ onChangeSpy = vi.fn(),+ ) {+ const content = (+ <MemoryRouter>+ <PasswordCredentialContent values={NEW_VALUES} onChange={onChangeSpy} />+ </MemoryRouter>+ );+ render(+ enterpriseApps ? (+ <CredentialAuthenticatorSupportProvider value={{ enterpriseApps }}>+ {content}+ </CredentialAuthenticatorSupportProvider>+ ) : (+ content+ ),+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Two-Factor Authentication"));+ });+ return onChangeSpy;+ }++ it("always lists generic TOTP apps", async () => {+ await openAuthenticatorSection();+ expect(+ screen.getByText(/Google Authenticator, Authy, 1Password/),+ ).toBeTruthy();+ });++ it("omits enterprise QR type options in the default/OSS context", async () => {+ await openAuthenticatorSection();+ expect(+ screen.getByRole("button", { name: /Google Authenticator/ }),+ ).toBeTruthy();+ expect(screen.queryByText("Enterprise Authenticator A")).toBeNull();+ expect(screen.queryByText("Enterprise Authenticator B")).toBeNull();+ expect(+ screen.queryByText(/detects these setup codes automatically/),+ ).toBeNull();+ });++ it("renders Cloud provider QR type options when the context provides apps", async () => {+ await openAuthenticatorSection(ENTERPRISE_APPS);+ const selector = screen.getByTestId("authenticator-qr-type-selector");+ expect(selector).toBeTruthy();+ const keyInput = screen.getByPlaceholderText("e.g. JBSWY3DPEHPK3PXP");+ expect(+ selector.compareDocumentPosition(keyInput) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: /Google Authenticator/ }),+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Enterprise Authenticator A" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Enterprise Authenticator B" }),+ ).toBeTruthy();+ expect(+ screen.getByText(/detects these setup codes automatically/),+ ).toBeTruthy();+ expect(+ selector.querySelectorAll('[data-testid="authenticator-type-logo"]'),+ ).toHaveLength(3);+ });++ it("highlights the Cloud provider QR type inferred from an uploaded QR code", async () => {+ const imageBitmap = stubQrCodeScan(+ "example-authenticator://activate?payload=opaque",+ );+ const onChangeSpy = await openAuthenticatorSection(ENTERPRISE_APPS);+ await uploadQrCodeImage();++ await waitFor(() => {+ const qrCall = onChangeSpy.mock.calls.find((call) => {+ const next = call[0] as Values;+ return (+ next.totp_type === "authenticator" &&+ next.totp === "example-authenticator://activate?payload=opaque"+ );+ });+ expect(qrCall).toBeTruthy();+ });+ expect(+ screen+ .getByRole("button", { name: /Enterprise Authenticator A/ })+ .getAttribute("aria-pressed"),+ ).toBe("true");+ expect(+ screen.getByTestId("authenticator-qr-type-detection").textContent,+ ).toBe("Detected from QR");+ expect(imageBitmap.close).toHaveBeenCalled();+ });++ it("announces the inferred type via a polite live region naming the detected app", async () => {+ stubQrCodeScan("example-authenticator://activate?payload=opaque");+ await openAuthenticatorSection(ENTERPRISE_APPS);+ await uploadQrCodeImage();++ const liveRegion = await waitFor(() => {+ const region = screen+ .getByTestId("authenticator-qr-type-detection")+ .closest('[role="status"]');+ expect(region).toBeTruthy();+ return region as HTMLElement;+ });+ expect(liveRegion.getAttribute("aria-live")).toBe("polite");+ expect(liveRegion.textContent).toContain("Detected from QR");+ expect(liveRegion.textContent).toContain("Enterprise Authenticator A");+ expect(+ screen.getByTestId("authenticator-qr-type-detection").textContent,+ ).toBe("Detected from QR");+ });++ it("visually marks only the inferred chip as detected, and clears that marker when the user picks another type", async () => {+ stubQrCodeScan("example-authenticator://activate?payload=opaque");+ await openAuthenticatorSection(ENTERPRISE_APPS);+ await uploadQrCodeImage();++ const inferredButton = await waitFor(() => {+ const button = screen.getByRole("button", {+ name: /Enterprise Authenticator A/,+ });+ expect(button.getAttribute("data-inferred")).toBe("true");+ return button;+ });+ expect(+ screen+ .getByRole("button", { name: /Google Authenticator/ })+ .getAttribute("data-inferred"),+ ).toBeNull();++ await act(async () => {+ fireEvent.click(+ screen.getByRole("button", { name: /Google Authenticator/ }),+ );+ });++ expect(inferredButton.getAttribute("data-inferred")).toBeNull();+ expect(screen.queryByText("Detected from QR")).toBeNull();+ expect(+ screen+ .getByRole("button", { name: /Google Authenticator/ })+ .getAttribute("aria-pressed"),+ ).toBe("true");+ });++ it("does not falsely highlight a Cloud enterprise type for an unknown uploaded QR code", async () => {+ const imageBitmap = stubQrCodeScan(+ "unknown-authenticator://activate?payload=opaque",+ );+ const onChangeSpy = await openAuthenticatorSection(ENTERPRISE_APPS);+ await uploadQrCodeImage();++ await waitFor(() => {+ const qrCall = onChangeSpy.mock.calls.find((call) => {+ const next = call[0] as Values;+ return (+ next.totp_type === "authenticator" &&+ next.totp === "unknown-authenticator://activate?payload=opaque"+ );+ });+ expect(qrCall).toBeTruthy();+ });+ expect(+ screen+ .getByRole("button", { name: /Google Authenticator/ })+ .getAttribute("aria-pressed"),+ ).toBe("false");+ expect(+ screen+ .getByRole("button", { name: "Enterprise Authenticator A" })+ .getAttribute("aria-pressed"),+ ).toBe("false");+ expect(+ screen+ .getByRole("button", { name: "Enterprise Authenticator B" })+ .getAttribute("aria-pressed"),+ ).toBe("false");+ expect(screen.queryByText("Detected from QR")).toBeNull();+ expect(imageBitmap.close).toHaveBeenCalled();+ });+});++describe("PasswordCredentialContent — inline authenticator save error", () => {+ afterEach(() => {+ cleanup();+ });++ const AUTH_VALUES: Values = {+ name: "New cred",+ username: "[email protected]",+ password: "password",+ totp: "otpauth://totp/[email protected]?secret=BAD",+ totp_type: "authenticator",+ totp_identifier: "",+ };++ it("shows enterprise copy with a contact link for an enterprise-required error", () => {+ render(+ <MemoryRouter>+ <CredentialAuthenticatorSupportProvider+ value={{ enterpriseApps: ENTERPRISE_APPS }}+ >+ <PasswordCredentialContent+ values={AUTH_VALUES}+ onChange={vi.fn()}+ authenticatorSaveError={{+ code: "enterprise_required",+ message: "This authenticator requires a Skyvern enterprise plan.",+ vendor: "opaque",+ }}+ />+ </CredentialAuthenticatorSupportProvider>+ </MemoryRouter>,+ );++ const enterpriseMessage = screen.getByText(+ "Enterprise Authenticator B requires a Skyvern enterprise plan.",+ );+ expect(enterpriseMessage.closest(".text-destructive")).toBeNull();+ expect(screen.getByTestId("enterprise-authenticator-upgrade")).toBeTruthy();+ const contactLink = screen.getByRole("link", { name: "Contact us" });+ expect(contactLink.getAttribute("href")).toBe(+ "https://www.skyvern.com/contact",+ );+ const input = screen.getByPlaceholderText("e.g. JBSWY3DPEHPK3PXP");+ expect(input.getAttribute("aria-invalid")).toBe("false");+ expect(input.className).not.toContain("border-destructive");+ expect(input.getAttribute("aria-describedby")).toBeTruthy();+ });++ it("shows actionable no-code-secret copy without a contact link", () => {+ render(+ <MemoryRouter>+ <PasswordCredentialContent+ values={AUTH_VALUES}+ onChange={vi.fn()}+ authenticatorSaveError={{+ code: "no_code_secret",+ message:+ "This QR code doesn't contain a code-based setup key. It may enroll a push-approval app or device-bound authenticator. Set up an authenticator app or one-time code instead.",+ }}+ />+ </MemoryRouter>,+ );++ expect(screen.getByText(/push-approval app/)).toBeTruthy();+ expect(screen.queryByRole("link", { name: "Contact us" })).toBeNull();+ const input = screen.getByPlaceholderText("e.g. JBSWY3DPEHPK3PXP");+ expect(input.getAttribute("aria-invalid")).toBe("true");+ expect(input.className).toContain("border-destructive");+ const describedBy = input.getAttribute("aria-describedby");+ expect(describedBy).toBeTruthy();+ expect(document.getElementById(describedBy!)?.textContent).toContain(+ "push-approval app",+ );+ });++ it("keeps the decoded QR value in the field after a save failure", () => {+ render(+ <MemoryRouter>+ <PasswordCredentialContent+ values={AUTH_VALUES}+ onChange={vi.fn()}+ authenticatorSaveError={{+ code: "invalid_authenticator_key",+ message: "Invalid authenticator key.",+ }}+ />+ </MemoryRouter>,+ );++ const input = screen.getByPlaceholderText(+ "e.g. JBSWY3DPEHPK3PXP",+ ) as HTMLInputElement;+ expect(input.value).toBe("otpauth://totp/[email protected]?secret=BAD");+ });+});diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsxindex da3f14771..c6f6bc852 100644--- a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx@@ -1,3 +1,4 @@+import googleAuthenticatorIcon from "@/assets/authenticators/google-authenticator.jpg";import { QRCodeIcon } from "@/components/icons/QRCodeIcon";import {Accordion,@@ -15,14 +16,28 @@ import {EnvelopeClosedIcon,EyeNoneIcon,EyeOpenIcon,+ MagicWandIcon,MobileIcon,Pencil1Icon,ReloadIcon,UploadIcon,} from "@radix-ui/react-icons";-import { useCallback, useEffect, useRef, useState } from "react";+import {+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";import { Link } from "react-router-dom";+import {+ type CredentialAuthenticatorQrCodeType,+ useCredentialAuthenticatorSupport,+} from "./CredentialAuthenticatorSupportContext";+import { AuthenticatorAppLogo } from "./AuthenticatorAppLogo";import { decodeQrCodeImage } from "./decodeQrCodeImage";+import { type AuthenticatorSaveError } from "./authenticatorSaveError";type Props = {values: {@@ -57,8 +72,39 @@ type Props = {onEnableEditName?: () => void;onEnableEditValues?: () => void;totpError?: string | null;+ /** Server-side authenticator setup error surfaced inline near the key field */+ authenticatorSaveError?: AuthenticatorSaveError | null;+};++const STANDARD_AUTHENTICATOR_TYPE_ID = "standard";++const STANDARD_AUTHENTICATOR_TYPE: CredentialAuthenticatorQrCodeType = {+ id: STANDARD_AUTHENTICATOR_TYPE_ID,+ label: "Google Authenticator",+ description: "Standard TOTP setup code",+ logo: <AuthenticatorAppLogo src={googleAuthenticatorIcon} />,};+type AuthenticatorTypeDetectionSource = "qr" | "typed" | "saved" | "backend";++function compactAuthenticatorSecret(value: string): string {+ return value.replace(/[\s-]/g, "");+}++function isStandardAuthenticatorValue(value: string): boolean {+ const trimmed = value.trim();+ if (!trimmed) {+ return false;+ }++ if (/^otpauth:\/\/totp\//i.test(trimmed)) {+ return true;+ }++ const compact = compactAuthenticatorSecret(trimmed);+ return compact.length >= 16 && /^[A-Z2-7]+=*$/i.test(compact);+}+function PasswordCredentialContent({values,onChange,@@ -73,8 +119,29 @@ function PasswordCredentialContent({onEnableEditName,onEnableEditValues,totpError,+ authenticatorSaveError,}: Props) {+ const { enterpriseApps } = useCredentialAuthenticatorSupport();const { name, username, password, totp, totp_type, totp_identifier } = values;++ const enterpriseUpgradeError =+ authenticatorSaveError?.code === "enterprise_required"+ ? authenticatorSaveError+ : null;+ const enterpriseUpgradeVendorLabel = enterpriseUpgradeError?.vendor+ ? enterpriseApps?.vendorLabels?.[+ enterpriseUpgradeError.vendor.toLowerCase()+ ]+ : null;+ const enterpriseUpgradeMessage = enterpriseUpgradeVendorLabel+ ? `${enterpriseUpgradeVendorLabel} requires a Skyvern enterprise plan.`+ : enterpriseUpgradeError?.message;+ const enterpriseContactUrl = enterpriseApps?.contactUrl;+ const destructiveSaveError =+ authenticatorSaveError &&+ authenticatorSaveError.code !== "enterprise_required"+ ? authenticatorSaveError+ : null;const nameReadOnly = editMode && !editingGroups?.name;const valuesReadOnly = editMode && !editingGroups?.values;@@ -87,7 +154,101 @@ function PasswordCredentialContent({const [showPassword, setShowPassword] = useState(false);const [qrCodeScanError, setQrCodeScanError] = useState<string | null>(null);const [isScanningQrCode, setIsScanningQrCode] = useState(false);+ const [selectedAuthenticatorTypeId, setSelectedAuthenticatorTypeId] =+ useState<string | null>(STANDARD_AUTHENTICATOR_TYPE_ID);+ const [inferredAuthenticatorTypeId, setInferredAuthenticatorTypeId] =+ useState<string | null>(null);+ const [+ authenticatorTypeDetectionSource,+ setAuthenticatorTypeDetectionSource,+ ] = useState<AuthenticatorTypeDetectionSource | null>(null);+ const inferredAuthenticatorValueRef = useRef("");const qrCodeInputRef = useRef<HTMLInputElement>(null);+ const authenticatorKeyErrorId = useId();+ const enterpriseUpgradeErrorId = useId();++ const authenticatorTypeOptions = useMemo(+ () => [STANDARD_AUTHENTICATOR_TYPE, ...(enterpriseApps?.qrCodeTypes ?? [])],+ [enterpriseApps?.qrCodeTypes],+ );+ const authenticatorTypeOptionIds = useMemo(+ () => new Set(authenticatorTypeOptions.map(({ id }) => id)),+ [authenticatorTypeOptions],+ );+ const detectionStatusLabel =+ authenticatorTypeDetectionSource === "qr"+ ? "Detected from QR"+ : authenticatorTypeDetectionSource === "typed"+ ? "Detected from value"+ : authenticatorTypeDetectionSource === "saved"+ ? "Detected from saved key"+ : authenticatorTypeDetectionSource === "backend"+ ? "Detected on save"+ : null;+ const inferredAuthenticatorTypeLabel = useMemo(+ () =>+ authenticatorTypeOptions.find(+ ({ id }) => id === inferredAuthenticatorTypeId,+ )?.label ?? null,+ [authenticatorTypeOptions, inferredAuthenticatorTypeId],+ );+ const destructiveAuthenticatorMessages = (+ [totpError, qrCodeScanError, destructiveSaveError?.message] as const+ ).filter((message): message is string => Boolean(message));+ const hasAuthenticatorKeyError = Boolean(+ destructiveAuthenticatorMessages.length,+ );+ const authenticatorKeyDescriptionIds = [+ hasAuthenticatorKeyError ? authenticatorKeyErrorId : null,+ enterpriseUpgradeError ? enterpriseUpgradeErrorId : null,+ ]+ .filter(Boolean)+ .join(" ");++ const inferAuthenticatorTypeId = useCallback(+ (value: string): string | null => {+ if (isStandardAuthenticatorValue(value)) {+ return STANDARD_AUTHENTICATOR_TYPE_ID;+ }++ const inferredEnterpriseType = enterpriseApps?.inferQrCodeType?.(value);+ if (+ inferredEnterpriseType &&+ authenticatorTypeOptionIds.has(inferredEnterpriseType)+ ) {+ return inferredEnterpriseType;+ }++ return null;+ },+ [authenticatorTypeOptionIds, enterpriseApps],+ );++ const applyAuthenticatorTypeInference = useCallback(+ (+ value: string,+ source: AuthenticatorTypeDetectionSource,+ {+ clearUnknownSelection = false,+ }: { clearUnknownSelection?: boolean } = {},+ ) => {+ const inferredTypeId = inferAuthenticatorTypeId(value);+ if (inferredTypeId) {+ inferredAuthenticatorValueRef.current = value;+ setSelectedAuthenticatorTypeId(inferredTypeId);+ setInferredAuthenticatorTypeId(inferredTypeId);+ setAuthenticatorTypeDetectionSource(source);+ return;+ }++ setInferredAuthenticatorTypeId(null);+ setAuthenticatorTypeDetectionSource(null);+ if (clearUnknownSelection) {+ setSelectedAuthenticatorTypeId(null);+ }+ },+ [inferAuthenticatorTypeId],+ );// Sync totpMethod and auto-expand accordion when totp_type prop changes// (e.g. edit data arriving after mount)@@ -101,6 +262,53 @@ function PasswordCredentialContent({setTotpAccordionValue("two-factor-authentication");}}, [totp_type]);++ useEffect(() => {+ if (+ selectedAuthenticatorTypeId &&+ !authenticatorTypeOptionIds.has(selectedAuthenticatorTypeId)+ ) {+ setSelectedAuthenticatorTypeId(STANDARD_AUTHENTICATOR_TYPE_ID);+ }+ if (+ inferredAuthenticatorTypeId &&+ !authenticatorTypeOptionIds.has(inferredAuthenticatorTypeId)+ ) {+ setInferredAuthenticatorTypeId(null);+ setAuthenticatorTypeDetectionSource(null);+ }+ }, [+ authenticatorTypeOptionIds,+ inferredAuthenticatorTypeId,+ selectedAuthenticatorTypeId,+ ]);++ useEffect(() => {+ if (totpMethod !== "authenticator" || !totp) {+ return;+ }+ if (totp === inferredAuthenticatorValueRef.current) {+ return;+ }++ const inferredTypeId = inferAuthenticatorTypeId(totp);+ if (inferredTypeId) {+ inferredAuthenticatorValueRef.current = totp;+ setSelectedAuthenticatorTypeId(inferredTypeId);+ setInferredAuthenticatorTypeId(inferredTypeId);+ setAuthenticatorTypeDetectionSource("saved");+ }+ }, [inferAuthenticatorTypeId, totp, totpMethod]);++ useEffect(() => {+ const vendor = enterpriseUpgradeError?.vendor?.toLowerCase();+ if (vendor && authenticatorTypeOptionIds.has(vendor)) {+ setSelectedAuthenticatorTypeId(vendor);+ setInferredAuthenticatorTypeId(vendor);+ setAuthenticatorTypeDetectionSource("backend");+ }+ }, [authenticatorTypeOptionIds, enterpriseUpgradeError?.vendor]);+const prevUsernameRef = useRef(username);const totpIdentifierLabel =totpMethod === "text"@@ -196,6 +404,14 @@ function PasswordCredentialContent({onEnableEditValues?.();setQrCodeScanError(null);setTotpMethod("authenticator");+ if (!value) {+ inferredAuthenticatorValueRef.current = "";+ setSelectedAuthenticatorTypeId(STANDARD_AUTHENTICATOR_TYPE_ID);+ setInferredAuthenticatorTypeId(null);+ setAuthenticatorTypeDetectionSource(null);+ } else {+ applyAuthenticatorTypeInference(value, "typed");+ }updateValues({ totp: value, totp_type: "authenticator" });};@@ -214,6 +430,9 @@ function PasswordCredentialContent({try {const qrCodeValue = await decodeQrCodeImage(file);setTotpMethod("authenticator");+ applyAuthenticatorTypeInference(qrCodeValue, "qr", {+ clearUnknownSelection: true,+ });updateValues({ totp: qrCodeValue, totp_type: "authenticator" });} catch (caught) {setQrCodeScanError(@@ -226,6 +445,94 @@ function PasswordCredentialContent({}};+ const authenticatorTypeSelector = (+ <div className="space-y-2" data-testid="authenticator-qr-type-selector">+ <div className="flex items-center justify-between gap-3">+ <Label className="text-xs font-medium text-slate-400">+ Authenticator app+ </Label>+ <div role="status" aria-live="polite" className="min-h-4">+ {detectionStatusLabel && inferredAuthenticatorTypeId && (+ <>+ <span+ data-testid="authenticator-qr-type-detection"+ className="text-xs text-blue-300"+ >+ {detectionStatusLabel}+ </span>+ {inferredAuthenticatorTypeLabel && (+ <span className="sr-only">+ {` — ${inferredAuthenticatorTypeLabel}`}+ </span>+ )}+ </>+ )}+ </div>+ </div>+ <div+ role="group"+ aria-label="Authenticator app type"+ className="grid grid-cols-2 gap-2 sm:grid-cols-4"+ >+ {authenticatorTypeOptions.map((option) => {+ const selected = selectedAuthenticatorTypeId === option.id;+ const inferred = inferredAuthenticatorTypeId === option.id;+ return (+ <button+ key={option.id}+ type="button"+ aria-pressed={selected}+ data-inferred={inferred ? "true" : undefined}+ className={cn(+ "inline-flex h-14 w-full min-w-0 items-center gap-2 rounded-md border px-3 text-left text-xs font-medium leading-tight transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",+ selected+ ? "border-blue-400 bg-blue-500/10 text-foreground"+ : "border-slate-700 bg-slate-elevation1 text-slate-300 hover:border-slate-500 hover:bg-slate-elevation3 hover:text-slate-100",+ inferred &&+ "border-blue-300 bg-blue-500/15 ring-1 ring-blue-400/70",+ )}+ onClick={() => {+ onEnableEditValues?.();+ setSelectedAuthenticatorTypeId(option.id);+ setInferredAuthenticatorTypeId(null);+ setAuthenticatorTypeDetectionSource(null);+ }}+ >+ <span+ aria-hidden="true"+ data-testid="authenticator-type-logo"+ className={cn(+ "flex size-8 shrink-0 items-center justify-center rounded-md border",+ selected || inferred+ ? "border-blue-400/50 bg-blue-500/10"+ : "border-slate-700 bg-background/40",+ )}+ >+ {option.logo ?? <QRCodeIcon className="size-4" />}+ </span>+ <span className="min-w-0 flex-1">{option.label}</span>+ <span className="ml-auto flex size-4 shrink-0 items-center justify-center">+ {inferred ? (+ <MagicWandIcon className="size-3 text-blue-300" />+ ) : (+ selected && <CheckIcon className="size-3" />+ )}+ </span>+ {inferred && detectionStatusLabel && (+ <span className="sr-only">{detectionStatusLabel}</span>+ )}+ </button>+ );+ })}+ </div>+ {enterpriseApps?.description && (+ <p className="text-xs leading-5 text-slate-400">+ {enterpriseApps.description}+ </p>+ )}+ </div>+ );+return (<div className="space-y-5"><div className="flex items-center gap-12">@@ -448,24 +755,28 @@ function PasswordCredentialContent({</p></div><p className="text-sm text-slate-400">- <Link- to="https://www.skyvern.com/contact"- target="_blank"- rel="noopener noreferrer"- className="underline underline-offset-2"- >- Contact us to set up two-factor authentication in- workflows- </Link>{" "}- or{" "}+ {enterpriseContactUrl && (+ <>+ <Link+ to={enterpriseContactUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="underline underline-offset-2"+ >+ Contact us to set up two-factor authentication in+ workflows+ </Link>{" "}+ or{" "}+ </>+ )}<Linkto="https://www.skyvern.com/docs/running-tasks/advanced-features#time-based-one-time-password-totp"target="_blank"rel="noopener noreferrer"className="underline underline-offset-2">- see our documentation on how to set up two-factor- authentication in workflows+ {enterpriseContactUrl ? "see" : "See"} our documentation+ on how to set up two-factor authentication in workflows</Link>{" "}to get started.</p>@@ -473,6 +784,7 @@ function PasswordCredentialContent({)}{totpMethod === "authenticator" && (<div className="space-y-4">+ {authenticatorTypeSelector}<div className="flex items-center gap-12"><div className="w-40 shrink-0"><Label className="whitespace-nowrap">@@ -504,9 +816,12 @@ function PasswordCredentialContent({handleAuthenticatorTotpChange(e.target.value)}placeholder="e.g. JBSWY3DPEHPK3PXP"- aria-invalid={Boolean(totpError)}+ aria-invalid={hasAuthenticatorKeyError}+ aria-describedby={+ authenticatorKeyDescriptionIds || undefined+ }className={cn(- totpError &&+ hasAuthenticatorKeyError &&"border-destructive bg-destructive/10 focus-visible:ring-destructive/30",)}/>@@ -537,12 +852,49 @@ function PasswordCredentialContent({</div>)}</div>- {(totpError || qrCodeScanError) && (- <div className="space-y-1 text-xs text-destructive">- {totpError && <p>{totpError}</p>}- {qrCodeScanError && <p>{qrCodeScanError}</p>}+ {destructiveAuthenticatorMessages.length > 0 && (+ <div+ id={authenticatorKeyErrorId}+ className="space-y-1 text-xs text-destructive"+ >+ {destructiveAuthenticatorMessages.map(+ (message, index) => (+ <p key={`${index}-${message}`}>{message}</p>+ ),+ )}</div>)}+ {enterpriseUpgradeError && (+ <div+ id={enterpriseUpgradeErrorId}+ data-testid="enterprise-authenticator-upgrade"+ className="rounded-md border border-warning/50 bg-warning/10 px-3 py-2 text-sm leading-5 text-foreground"+ >+ <span className="font-medium">+ {enterpriseUpgradeMessage}+ </span>+ {enterpriseContactUrl && (+ <>+ {" "}+ <span className="text-muted-foreground">+ <Link+ to={enterpriseContactUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="font-medium text-warning underline underline-offset-2"+ >+ Contact us+ </Link>{" "}+ to enable enterprise authenticator support.+ </span>+ </>+ )}+ </div>+ )}+ <p className="text-sm text-slate-400">+ Works with Google Authenticator, Authy, 1Password, and any+ standard TOTP authenticator app.+ </p><p className="text-sm text-slate-400">You need to find the authenticator key from the websitewhere you are using the credential. Here are some guidesdiff --git a/skyvern-frontend/src/routes/credentials/authenticatorSaveError.test.ts b/skyvern-frontend/src/routes/credentials/authenticatorSaveError.test.tsnew file mode 100644index 000000000..84a75abc1--- /dev/null+++ b/skyvern-frontend/src/routes/credentials/authenticatorSaveError.test.ts@@ -0,0 +1,147 @@+// @vitest-environment jsdom++import { AxiosError, AxiosHeaders } from "axios";+import { describe, expect, it } from "vitest";++import {+ getAuthenticatorSaveError,+ getCredentialErrorMessage,+} from "./authenticatorSaveError";++function axiosErrorWithDetail(detail: unknown): AxiosError {+ const error = new AxiosError("Request failed");+ error.response = {+ data: { detail },+ status: 400,+ statusText: "Bad Request",+ headers: {},+ config: { headers: new AxiosHeaders() },+ };+ return error;+}++describe("getAuthenticatorSaveError", () => {+ it("maps the structured no-code-secret code to actionable code-based setup copy", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail({+ error_code: "authenticator_no_code_secret",+ message: "Push enrollment payloads are not supported.",+ }),+ );++ expect(result?.code).toBe("no_code_secret");+ expect(result?.message).toMatch(/code-based setup key/i);+ expect(result?.message).toMatch(/push-approval/i);+ expect(result?.message).toMatch(/authenticator app or one-time code/i);+ });++ it("maps the structured enterprise-required code to enterprise access copy", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail({+ error_code: "authenticator_feature_restricted",+ message: "Enterprise plan required.",+ }),+ );++ expect(result?.code).toBe("enterprise_required");+ expect(result?.message).toMatch(/enterprise plan/i);+ });++ it("preserves the detected vendor id for enterprise-required copy", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail({+ error_code: "authenticator_feature_restricted",+ message: "Enterprise plan required.",+ vendor: "example",+ }),+ );++ expect(result?.code).toBe("enterprise_required");+ expect(result?.message).toBe(+ "This authenticator requires a Skyvern enterprise plan.",+ );+ expect(result?.vendor).toBe("example");+ });++ it("maps unsupported TOTP config to the backend message", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail({+ error_code: "authenticator_totp_config_unsupported",+ message: "The authenticator setup code is malformed.",+ }),+ );++ expect(result?.code).toBe("unsupported_totp_config");+ expect(result?.message).toBe("The authenticator setup code is malformed.");+ });++ it("falls back to the backend message for an invalid-key code", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail({+ error_code: "invalid_authenticator_key",+ message: "That is not a valid Base32 secret.",+ }),+ );++ expect(result?.code).toBe("invalid_authenticator_key");+ expect(result?.message).toBe("That is not a valid Base32 secret.");+ });++ it("does not infer unsupported push enrollment from unknown future codes", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail({+ error_code: "batch_enrollment_failed",+ message: "The authenticator setup could not be saved.",+ }),+ );++ expect(result?.code).toBe("unknown");+ expect(result?.message).toBe("The authenticator setup could not be saved.");+ });++ it("classifies a legacy string detail that mentions the authenticator key", () => {+ const result = getAuthenticatorSaveError(+ axiosErrorWithDetail(+ "Invalid authenticator key. Paste the raw Base32 setup key.",+ ),+ );++ expect(result?.code).toBe("invalid_authenticator_key");+ expect(result?.message).toContain("Invalid authenticator key");+ });++ it("returns null for a legacy string detail unrelated to the authenticator", () => {+ expect(+ getAuthenticatorSaveError(+ axiosErrorWithDetail("Username and password are required"),+ ),+ ).toBeNull();+ });++ it("returns null when there is no response detail", () => {+ expect(getAuthenticatorSaveError(new Error("boom"))).toBeNull();+ });+});++describe("getCredentialErrorMessage", () => {+ it("returns a legacy string detail verbatim", () => {+ expect(+ getCredentialErrorMessage(axiosErrorWithDetail("Something went wrong")),+ ).toBe("Something went wrong");+ });++ it("returns the message field from a structured detail", () => {+ expect(+ getCredentialErrorMessage(+ axiosErrorWithDetail({+ error_code: "enterprise_required",+ message: "Enterprise plan required.",+ }),+ ),+ ).toBe("Enterprise plan required.");+ });++ it("returns null when no usable detail is present", () => {+ expect(getCredentialErrorMessage(new Error("boom"))).toBeNull();+ });+});diff --git a/skyvern-frontend/src/routes/credentials/authenticatorSaveError.ts b/skyvern-frontend/src/routes/credentials/authenticatorSaveError.tsnew file mode 100644index 000000000..36e76293e--- /dev/null+++ b/skyvern-frontend/src/routes/credentials/authenticatorSaveError.ts@@ -0,0 +1,146 @@+import { isAxiosError } from "axios";++type AuthenticatorErrorCode =+ | "no_code_secret"+ | "unsupported_totp_config"+ | "enterprise_required"+ | "invalid_authenticator_key"+ | "unknown";++type AuthenticatorSaveError = {+ code: AuthenticatorErrorCode;+ message: string;+ vendor?: string;+};++type StructuredErrorDetail = {+ error_code?: unknown;+ message?: unknown;+ vendor?: unknown;+};++const EXACT_ERROR_CODE_MAP: Record<string, AuthenticatorErrorCode> = {+ authenticator_no_code_secret: "no_code_secret",+ authenticator_totp_config_unsupported: "unsupported_totp_config",+ authenticator_feature_restricted: "enterprise_required",+ invalid_authenticator_key: "invalid_authenticator_key",+ authenticator_key_required: "invalid_authenticator_key",+};++const NO_CODE_SECRET_MESSAGE =+ "This QR code doesn't contain a code-based setup key that Skyvern can use. It may enroll a push-approval app or device-bound authenticator. In the site's security settings, choose an authenticator app or one-time code, or use a TOTP setup key instead, then scan that QR code or paste its setup key.";++const INVALID_KEY_MESSAGE =+ "Invalid authenticator key. Paste the raw Base32 setup key or full otpauth:// URI from the website's 2FA setup screen.";+const UNSUPPORTED_TOTP_CONFIG_MESSAGE =+ "We recognized this as an authenticator setup QR, but its code configuration is malformed or unsupported. Use a standard setup key or otpauth:// URI instead.";++function enterpriseMessage(): string {+ return "This authenticator requires a Skyvern enterprise plan.";+}++function classifyCode(rawCode: string): AuthenticatorErrorCode | null {+ const code = rawCode.toLowerCase();+ const exactCode = EXACT_ERROR_CODE_MAP[code];+ if (exactCode) {+ return exactCode;+ }+ return rawCode ? "unknown" : null;+}++function resolveMessage(+ code: AuthenticatorErrorCode,+ backendMessage: string | undefined,+): string {+ switch (code) {+ case "no_code_secret":+ return NO_CODE_SECRET_MESSAGE;+ case "unsupported_totp_config":+ return backendMessage?.trim() || UNSUPPORTED_TOTP_CONFIG_MESSAGE;+ case "enterprise_required":+ return enterpriseMessage();+ case "invalid_authenticator_key":+ return backendMessage?.trim() || INVALID_KEY_MESSAGE;+ case "unknown":+ return backendMessage?.trim() || INVALID_KEY_MESSAGE;+ }+}++function fromStructuredDetail(+ detail: StructuredErrorDetail,+): AuthenticatorSaveError | null {+ const rawCode =+ typeof detail.error_code === "string" ? detail.error_code : "";+ const backendMessage =+ typeof detail.message === "string" ? detail.message : undefined;+ const vendor = typeof detail.vendor === "string" ? detail.vendor : undefined;+ const code = classifyCode(rawCode);+ if (!code) {+ if (backendMessage && /authenticator/i.test(backendMessage)) {+ return { code: "unknown", message: backendMessage.trim(), vendor };+ }+ return null;+ }+ return {+ code,+ message: resolveMessage(code, backendMessage),+ vendor,+ };+}++function fromStringDetail(detail: string): AuthenticatorSaveError | null {+ const trimmed = detail.trim();+ if (!/authenticator key/i.test(trimmed)) {+ return null;+ }+ const code: AuthenticatorErrorCode = /invalid/i.test(trimmed)+ ? "invalid_authenticator_key"+ : "unknown";+ return { code, message: trimmed };+}++function getErrorDetail(error: unknown): unknown {+ if (isAxiosError<{ detail?: unknown }>(error)) {+ return error.response?.data?.detail;+ }+ return undefined;+}++/**+ * Extracts authenticator-specific user-facing error info from Axios failures, including legacy string details and structured `{ error_code, message, vendor? }` details.+ * Returns null when the error is not an authenticator setup failure so callers can fall back to generic toast handling.+ */+function getAuthenticatorSaveError(+ error: unknown,+): AuthenticatorSaveError | null {+ const detail = getErrorDetail(error);+ if (typeof detail === "string") {+ return fromStringDetail(detail);+ }+ if (detail && typeof detail === "object") {+ return fromStructuredDetail(detail as StructuredErrorDetail);+ }+ return null;+}++/**+ * Extracts a plain user-facing string from an Axios error for toast copy,+ * normalizing both the legacy string `detail` and the structured object+ * `detail` shapes. Returns null when no detail is present.+ */+function getCredentialErrorMessage(error: unknown): string | null {+ const detail = getErrorDetail(error);+ if (typeof detail === "string") {+ return detail.trim() || null;+ }+ if (detail && typeof detail === "object") {+ const message = (detail as StructuredErrorDetail).message;+ if (typeof message === "string" && message.trim()) {+ return message.trim();+ }+ }+ return null;+}++export { getAuthenticatorSaveError, getCredentialErrorMessage };+export type { AuthenticatorSaveError, AuthenticatorErrorCode };diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex e5cf574fb..6ca69e620 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -40,6 +40,7 @@ from skyvern.forge.sdk.models import Step, StepStatusfrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.tasks import Task, TaskStatusfrom skyvern.forge.sdk.services import google_drive_service, google_oauth_service+from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResultfrom skyvern.forge.sdk.trace import tracedfrom skyvern.forge.sdk.workflow.models.block import BlockTypeVarfrom skyvern.schemas.workflows import FileStorageType, FileUploadDestination@@ -942,6 +943,13 @@ class AgentFunction:) -> str | None:return None+ async def parse_enterprise_totp_secret_result(+ self,+ totp_secret: str,+ organization_id: str | None = None,+ ) -> AuthenticatorTotpParseResult:+ return AuthenticatorTotpParseResult()+async def prepare_step_execution(self,organization: Organization | None,diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex 5c098032f..5f4a35bea 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -34,7 +34,7 @@ import asyncioimport jsonimport timefrom dataclasses import dataclass-from typing import Annotated, Any+from typing import Annotated, Any, NoReturnimport pyotpimport structlog@@ -112,7 +112,12 @@ from skyvern.forge.sdk.schemas.totp_codes import OTPType, TOTPCode, TOTPCodeCreafrom skyvern.forge.sdk.services import org_auth_servicefrom skyvern.forge.sdk.services.bitwarden import BitwardenServicefrom skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultService-from skyvern.forge.sdk.services.credentials import normalize_totp_config, parse_totp_config+from skyvern.forge.sdk.services.credentials import (+ AuthenticatorTotpErrorCode,+ AuthenticatorTotpParseResult,+ normalize_totp_config,+ parse_totp_config,+)from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterTypefrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody, WorkflowRunStatusfrom skyvern.schemas.credential_folders import (@@ -184,6 +189,31 @@ _TOTP_CODE_PREVIEW_CACHE: dict[tuple[str, str], _TotpCodePreviewCacheEntry] = {}# across workers; entries are bounded and expire at the active TOTP window.+def _authenticator_totp_error_detail(+ *,+ error_code: AuthenticatorTotpErrorCode,+ message: str,+ vendor: str | None = None,+) -> dict[str, str]:+ detail = {"error_code": error_code.value, "message": message}+ if vendor:+ detail["vendor"] = vendor+ return detail+++def _raise_authenticator_totp_http_error(+ *,+ status_code: int,+ error_code: AuthenticatorTotpErrorCode,+ message: str,+ vendor: str | None = None,+) -> NoReturn:+ raise HTTPException(+ status_code=status_code,+ detail=_authenticator_totp_error_detail(error_code=error_code, message=message, vendor=vendor),+ )++def _parse_authenticator_totp_config_or_raise(totp_secret: str | None,*,@@ -192,12 +222,20 @@ def _parse_authenticator_totp_config_or_raise() -> tuple[pyotp.TOTP, str]:raw_totp_secret = (totp_secret or "").strip()if raw_totp_secret == "":- raise HTTPException(status_code=400, detail=missing_detail)+ _raise_authenticator_totp_http_error(+ status_code=400,+ error_code=AuthenticatorTotpErrorCode.AUTHENTICATOR_KEY_REQUIRED,+ message=missing_detail,+ )normalized_totp_secret = normalize_totp_config(raw_totp_secret)totp = parse_totp_config(normalized_totp_secret)if not totp:- raise HTTPException(status_code=400, detail=invalid_detail)+ _raise_authenticator_totp_http_error(+ status_code=400,+ error_code=AuthenticatorTotpErrorCode.INVALID_AUTHENTICATOR_KEY,+ message=invalid_detail,+ )return totp, normalized_totp_secret@@ -221,13 +259,18 @@ async def _parse_enterprise_totp_secret_or_raise(organization_id: str,invalid_detail: str = _AUTHENTICATOR_SECRET_INVALID_DETAIL,) -> str | None:- enterprise_totp_secret = await app.AGENT_FUNCTION.parse_enterprise_totp_secret(+ result: AuthenticatorTotpParseResult = await app.AGENT_FUNCTION.parse_enterprise_totp_secret_result(totp_secret or "",organization_id=organization_id,)- if enterprise_totp_secret == "":- raise HTTPException(status_code=400, detail=invalid_detail)- return enterprise_totp_secret+ if result.error_code is not None:+ _raise_authenticator_totp_http_error(+ status_code=400,+ error_code=result.error_code,+ message=result.message or invalid_detail,+ vendor=result.vendor,+ )+ return result.secretasync def _build_authenticator_totp_for_organization_or_raise(@@ -283,8 +326,9 @@ async def _normalize_authenticator_totp_for_organization_or_raise(organization_id=organization_id,)if enterprise_totp_secret is not None:- # Keep enterprise payloads raw in credential.totp; runtime paths re-parse- # them through the cloud parser before generating codes.+ # The cloud parser has already extracted any vendor QR payload into a+ # standard TOTP config, so new saves can store the canonical secret.+ credential.totp = _parse_authenticator_totp_or_raise(enterprise_totp_secret)return_normalize_authenticator_totp_or_raise(credential)@@ -332,6 +376,8 @@ def _cache_totp_code_preview() -> None:_prune_totp_code_preview_cache(now=now)while len(_TOTP_CODE_PREVIEW_CACHE) >= _TOTP_CODE_PREVIEW_CACHE_MAX_ENTRIES:+ # Dict iteration order makes this FIFO eviction, which is enough for this+ # per-process preview cache._TOTP_CODE_PREVIEW_CACHE.pop(next(iter(_TOTP_CODE_PREVIEW_CACHE)))_TOTP_CODE_PREVIEW_CACHE[(organization_id, credential_id)] = _TotpCodePreviewCacheEntry(diff --git a/skyvern/forge/sdk/services/credentials.py b/skyvern/forge/sdk/services/credentials.pyindex 61d02d9bc..c51959a8e 100644--- a/skyvern/forge/sdk/services/credentials.py+++ b/skyvern/forge/sdk/services/credentials.py@@ -1,4 +1,5 @@import re+from dataclasses import dataclassfrom enum import StrEnumfrom urllib.parse import unquote, urlsplit@@ -22,6 +23,24 @@ class AzureVaultConstants(StrEnum):TOTP = "AZ_TOTP" # Special value to indicate a TOTP code+class AuthenticatorTotpErrorCode(StrEnum):+ """Stable machine-readable errors for authenticator TOTP validation."""++ AUTHENTICATOR_KEY_REQUIRED = "authenticator_key_required"+ INVALID_AUTHENTICATOR_KEY = "invalid_authenticator_key"+ AUTHENTICATOR_NO_CODE_SECRET = "authenticator_no_code_secret"+ AUTHENTICATOR_TOTP_CONFIG_UNSUPPORTED = "authenticator_totp_config_unsupported"+ AUTHENTICATOR_FEATURE_RESTRICTED = "authenticator_feature_restricted"+++@dataclass(frozen=True)+class AuthenticatorTotpParseResult:+ secret: str | None = None+ error_code: AuthenticatorTotpErrorCode | None = None+ message: str | None = None+ vendor: str | None = None++def _strip_totp_input_whitespace(totp_secret: str) -> str:return "".join(totp_secret.split())diff --git a/tests/unit/test_credential_totp_code.py b/tests/unit/test_credential_totp_code.pyindex ce307216b..875c9732e 100644--- a/tests/unit/test_credential_totp_code.py+++ b/tests/unit/test_credential_totp_code.py@@ -14,6 +14,7 @@ from skyvern.forge.sdk.schemas.credentials import (PasswordCredential,TotpType,)+from skyvern.forge.sdk.services.credentials import AuthenticatorTotpErrorCode, AuthenticatorTotpParseResult@pytest.fixture(autouse=True)@@ -57,7 +58,10 @@ def _mock_totp_preview_dependencies(monkeypatch.setattr(credentials.app,"AGENT_FUNCTION",- SimpleNamespace(parse_enterprise_totp_secret=AsyncMock(return_value=None)),+ SimpleNamespace(+ parse_enterprise_totp_secret=AsyncMock(return_value=None),+ parse_enterprise_totp_secret_result=AsyncMock(return_value=AuthenticatorTotpParseResult()),+ ),)monkeypatch.setattr(credentials, "_get_credential_vault_service", AsyncMock(return_value=vault_service))@@ -160,7 +164,138 @@ def test_authenticator_totp_validation_rejects_invalid_secret() -> None:credentials._normalize_authenticator_totp_or_raise(credential)assert exc_info.value.status_code == 400- assert "Invalid authenticator key" in exc_info.value.detail+ assert exc_info.value.detail == {+ "error_code": AuthenticatorTotpErrorCode.INVALID_AUTHENTICATOR_KEY.value,+ "message": credentials._AUTHENTICATOR_SECRET_INVALID_DETAIL,+ }+++async def test_authenticator_totp_validation_returns_enterprise_required_detail(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ parse_result = AsyncMock(+ return_value=AuthenticatorTotpParseResult(+ error_code=AuthenticatorTotpErrorCode.AUTHENTICATOR_FEATURE_RESTRICTED,+ message="Enterprise plan required for this authenticator QR.",+ vendor="okta",+ )+ )+ monkeypatch.setattr(+ credentials.app,+ "AGENT_FUNCTION",+ SimpleNamespace(parse_enterprise_totp_secret_result=parse_result),+ )+ credential = NonEmptyPasswordCredential(+ username="[email protected]",+ password="pw",+ totp="phonefactor://activate_account?sharedSecret=JBSWY3DPEHPK3PXP",+ totp_type=TotpType.AUTHENTICATOR,+ )++ with pytest.raises(HTTPException) as exc_info:+ await credentials._normalize_authenticator_totp_for_organization_or_raise(+ credential,+ organization_id="org_test",+ )++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail == {+ "error_code": AuthenticatorTotpErrorCode.AUTHENTICATOR_FEATURE_RESTRICTED.value,+ "message": "Enterprise plan required for this authenticator QR.",+ "vendor": "okta",+ }+ parse_result.assert_awaited_once()+++async def test_authenticator_totp_validation_returns_enterprise_no_code_detail(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ credentials.app,+ "AGENT_FUNCTION",+ SimpleNamespace(+ parse_enterprise_totp_secret_result=AsyncMock(+ return_value=AuthenticatorTotpParseResult(+ error_code=AuthenticatorTotpErrorCode.AUTHENTICATOR_NO_CODE_SECRET,+ message="This authenticator QR enrolls push approval and has no setup key.",+ vendor="microsoft",+ )+ )+ ),+ )+ credential = NonEmptyPasswordCredential(+ username="[email protected]",+ password="pw",+ totp="phonefactor://activate_account?code=123456",+ totp_type=TotpType.AUTHENTICATOR,+ )++ with pytest.raises(HTTPException) as exc_info:+ await credentials._normalize_authenticator_totp_for_organization_or_raise(+ credential,+ organization_id="org_test",+ )++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail == {+ "error_code": AuthenticatorTotpErrorCode.AUTHENTICATOR_NO_CODE_SECRET.value,+ "message": "This authenticator QR enrolls push approval and has no setup key.",+ "vendor": "microsoft",+ }+++async def test_authenticator_totp_validation_does_not_require_enterprise_for_generic_totp(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ parse_result = AsyncMock(return_value=AuthenticatorTotpParseResult())+ monkeypatch.setattr(+ credentials.app,+ "AGENT_FUNCTION",+ SimpleNamespace(parse_enterprise_totp_secret_result=parse_result),+ )+ credential = NonEmptyPasswordCredential(+ username="[email protected]",+ password="pw",+ totp="JBSW Y3DP-EHPK 3PXP",+ totp_type=TotpType.AUTHENTICATOR,+ )++ await credentials._normalize_authenticator_totp_for_organization_or_raise(+ credential,+ organization_id="org_test",+ )++ assert credential.totp == "JBSWY3DPEHPK3PXP"+ parse_result.assert_awaited_once()+++async def test_authenticator_totp_validation_saves_enterprise_secret_canonically(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ parse_result = AsyncMock(return_value=AuthenticatorTotpParseResult(secret="JBSW Y3DP-EHPK 3PXP"))+ monkeypatch.setattr(+ credentials.app,+ "AGENT_FUNCTION",+ SimpleNamespace(parse_enterprise_totp_secret_result=parse_result),+ )+ credential = NonEmptyPasswordCredential(+ username="[email protected]",+ password="pw",+ totp='{"methods":[{"type":"totp","sharedSecret":"JBSWY3DPEHPK3PXP"}]}',+ totp_type=TotpType.AUTHENTICATOR,+ )++ await credentials._normalize_authenticator_totp_for_organization_or_raise(+ credential,+ organization_id="org_test",+ )++ assert credential.totp == "JBSWY3DPEHPK3PXP"+ parse_result.assert_awaited_once()def test_authenticator_totp_validation_ignores_non_authenticator_methods() -> None:@@ -264,7 +399,10 @@ async def test_get_credential_totp_code_logs_invalid_saved_secret(monkeypatch: p)assert exc_info.value.status_code == 400- assert exc_info.value.detail == credentials._SAVED_AUTHENTICATOR_SECRET_INVALID_DETAIL+ assert exc_info.value.detail == {+ "error_code": AuthenticatorTotpErrorCode.INVALID_AUTHENTICATOR_KEY.value,+ "message": credentials._SAVED_AUTHENTICATOR_SECRET_INVALID_DETAIL,+ }warning_mock.assert_called_once_with("Saved authenticator key is invalid for TOTP code preview",credential_id="cred_test",