Skip to content

Automate browser based workflows with AI

SKY-13245 Add Magic Link tab to the Credentials page (re-land) (#7908)

Suchintan1b346bf55502
diff --git a/skyvern-frontend/src/components/PushTotpCodeForm.test.ts b/skyvern-frontend/src/components/PushTotpCodeForm.test.ts
index 324f566ee..3868074f8 100644
--- a/skyvern-frontend/src/components/PushTotpCodeForm.test.ts
+++ b/skyvern-frontend/src/components/PushTotpCodeForm.test.ts
@@ -1,7 +1,60 @@
-import { describe, expect, it } from "vitest";
+// @vitest-environment jsdom
+
+import { createElement } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { getClient } from "@/api/AxiosClient";
import { OtpType } from "@/api/types";
+import { PushTotpCodeForm } from "./PushTotpCodeForm";
import { buildSendTotpCodeRequest } from "./pushTotpCodeRequest";
+const { toast } = vi.hoisted(() => ({ toast: vi.fn() }));
+
+vi.mock("@/api/AxiosClient", () => ({ getClient: vi.fn() }));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => null,
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({
+ useToast: () => ({ toast }),
+}));
+
+const mockedGetClient = vi.mocked(getClient);
+
+function renderForm(fixedOtpType?: (typeof OtpType)[keyof typeof OtpType]) {
+ const queryClient = new QueryClient({
+ defaultOptions: { mutations: { retry: false } },
+ });
+
+ return render(
+ createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(PushTotpCodeForm, { fixedOtpType }),
+ ),
+ );
+}
+
+function selectOtpType(container: HTMLElement, otpType: string) {
+ const otpTypeSelect = container.querySelector("select");
+ expect(otpTypeSelect).not.toBeNull();
+ fireEvent.change(otpTypeSelect!, { target: { value: otpType } });
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
describe("buildSendTotpCodeRequest", () => {
it("includes explicit magic-link type and optional metadata", () => {
expect(
@@ -42,3 +95,152 @@ describe("buildSendTotpCodeRequest", () => {
});
});
});
+
+describe("PushTotpCodeForm", () => {
+ it("uses magic-link wording for the identifier placeholder", () => {
+ renderForm(OtpType.MagicLink);
+
+ expect(
+ screen.getByPlaceholderText("Email receiving the magic link"),
+ ).toBeTruthy();
+ expect(screen.queryByRole("combobox", { name: "OTP Type" })).toBeNull();
+ });
+
+ it("blocks fixed magic-link submissions without an http(s) link", () => {
+ const post = vi.fn().mockResolvedValue({});
+ mockedGetClient.mockResolvedValue({ post } as never);
+ renderForm(OtpType.MagicLink);
+
+ fireEvent.change(
+ screen.getByPlaceholderText("Email receiving the magic link"),
+ {
+ target: { value: "[email protected]" },
+ },
+ );
+ fireEvent.change(screen.getByLabelText("Verification content"), {
+ target: { value: "Your verification code is 123456" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send Magic Link" }));
+
+ expect(
+ screen.getByText(
+ "Paste the full magic link message — no http(s) link found.",
+ ),
+ ).toBeTruthy();
+ expect(post).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("allows non-fixed magic-link submissions for backend classification", async () => {
+ const post = vi.fn().mockResolvedValue({});
+ mockedGetClient.mockResolvedValue({ post } as never);
+ const { container } = renderForm();
+
+ selectOtpType(container, OtpType.MagicLink);
+
+ expect(
+ screen.getByPlaceholderText("Email receiving the magic link"),
+ ).toBeTruthy();
+ expect(
+ screen.getByPlaceholderText("Paste the full email body or magic link"),
+ ).toBeTruthy();
+
+ fireEvent.change(
+ screen.getByPlaceholderText("Email receiving the magic link"),
+ {
+ target: { value: "[email protected]" },
+ },
+ );
+ fireEvent.change(screen.getByLabelText("Verification content"), {
+ target: { value: "Your verification code is 123456" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send Magic Link" }));
+
+ await waitFor(() => {
+ expect(post).toHaveBeenCalledWith("/credentials/totp", {
+ totp_identifier: "[email protected]",
+ content: "Your verification code is 123456",
+ type: OtpType.MagicLink,
+ source: "manual_ui",
+ });
+ });
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it("uses magic-link toast copy when the selected type is submitted", async () => {
+ const post = vi.fn().mockResolvedValue({});
+ mockedGetClient.mockResolvedValue({ post } as never);
+ const { container } = renderForm();
+
+ selectOtpType(container, OtpType.MagicLink);
+ fireEvent.change(screen.getByLabelText("Identifier"), {
+ target: { value: "[email protected]" },
+ });
+ fireEvent.change(screen.getByLabelText("Verification content"), {
+ target: { value: "Open https://example.com/login?token=abc" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send Magic Link" }));
+
+ await waitFor(() => {
+ expect(post).toHaveBeenCalledWith("/credentials/totp", {
+ totp_identifier: "[email protected]",
+ content: "Open https://example.com/login?token=abc",
+ type: OtpType.MagicLink,
+ source: "manual_ui",
+ });
+ expect(toast).toHaveBeenCalledWith({
+ title: "Magic link sent",
+ description: "Skyvern will process it shortly.",
+ });
+ });
+ });
+
+ it("uses magic-link error copy when the selected type fails", async () => {
+ const post = vi.fn().mockRejectedValue(new Error("request failed"));
+ mockedGetClient.mockResolvedValue({ post } as never);
+ const { container } = renderForm();
+
+ selectOtpType(container, OtpType.MagicLink);
+ fireEvent.change(screen.getByLabelText("Identifier"), {
+ target: { value: "[email protected]" },
+ });
+ fireEvent.change(screen.getByLabelText("Verification content"), {
+ target: { value: "https://example.com/login?token=abc" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send Magic Link" }));
+
+ await waitFor(() => {
+ expect(toast).toHaveBeenCalledWith({
+ variant: "destructive",
+ title: "Failed to send magic link",
+ description: "Check the identifier and message format, then retry.",
+ });
+ });
+ });
+
+ it("keeps default numeric-code submissions unchanged", async () => {
+ const post = vi.fn().mockResolvedValue({});
+ mockedGetClient.mockResolvedValue({ post } as never);
+ renderForm();
+
+ fireEvent.change(
+ screen.getByPlaceholderText("Email or phone receiving the code"),
+ {
+ target: { value: " [email protected] " },
+ },
+ );
+ fireEvent.change(screen.getByLabelText("Verification content"), {
+ target: { value: " 123456 " },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send 2FA Code" }));
+
+ await waitFor(() => {
+ expect(post).toHaveBeenCalledWith("/credentials/totp", {
+ totp_identifier: "[email protected]",
+ content: "123456",
+ type: OtpType.Totp,
+ source: "manual_ui",
+ });
+ });
+ });
+});
diff --git a/skyvern-frontend/src/components/PushTotpCodeForm.tsx b/skyvern-frontend/src/components/PushTotpCodeForm.tsx
index 3df87acfe..bbf38d980 100644
--- a/skyvern-frontend/src/components/PushTotpCodeForm.tsx
+++ b/skyvern-frontend/src/components/PushTotpCodeForm.tsx
@@ -15,6 +15,7 @@ import {
import { useToast } from "@/components/ui/use-toast";
import { AutoResizingTextarea } from "@/components/AutoResizingTextarea/AutoResizingTextarea";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { containsHttpUrl } from "@/util/httpUrl";
import { cn } from "@/util/utils";
import {
buildSendTotpCodeRequest,
@@ -27,17 +28,24 @@ type Props = {
defaultWorkflowRunId?: string | null;
defaultWorkflowId?: string | null;
defaultTaskId?: string | null;
+ fixedOtpType?: OtpTypeValue;
showAdvancedFields?: boolean;
+ onOtpTypeChange?: (otpType: OtpTypeValue) => void;
onSuccess?: () => void;
};
+const MAGIC_LINK_CONTENT_ERROR =
+ "Paste the full magic link message — no http(s) link found.";
+
function PushTotpCodeForm({
className,
defaultIdentifier,
defaultWorkflowRunId,
defaultWorkflowId,
defaultTaskId,
+ fixedOtpType,
showAdvancedFields = false,
+ onOtpTypeChange,
onSuccess,
}: Props) {
const [identifier, setIdentifier] = useState(defaultIdentifier?.trim() ?? "");
@@ -49,6 +57,10 @@ function PushTotpCodeForm({
const [taskId, setTaskId] = useState(defaultTaskId?.trim() ?? "");
const [otpType, setOtpType] = useState<OtpTypeValue>(OtpType.Totp);
const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [contentError, setContentError] = useState<string | null>(null);
+ const effectiveOtpType = fixedOtpType ?? otpType;
+ const isMagicLink = effectiveOtpType === OtpType.MagicLink;
+ const requiresMagicLinkUrl = fixedOtpType === OtpType.MagicLink;
const credentialGetter = useCredentialGetter();
const { toast } = useToast();
@@ -111,7 +123,7 @@ function PushTotpCodeForm({
},
onSuccess: () => {
toast({
- title: "2FA code sent",
+ title: isMagicLink ? "Magic link sent" : "2FA code sent",
description: "Skyvern will process it shortly.",
});
setContent("");
@@ -120,7 +132,9 @@ function PushTotpCodeForm({
onError: () => {
toast({
variant: "destructive",
- title: "Failed to send code",
+ title: isMagicLink
+ ? "Failed to send magic link"
+ : "Failed to send code",
description: "Check the identifier and message format, then retry.",
});
},
@@ -131,11 +145,16 @@ function PushTotpCodeForm({
if (!canSubmit || mutation.isPending) {
return;
}
+ if (requiresMagicLinkUrl && !containsHttpUrl(trimmedContent)) {
+ setContentError(MAGIC_LINK_CONTENT_ERROR);
+ return;
+ }
+ setContentError(null);
const payload = buildSendTotpCodeRequest({
identifier: trimmedIdentifier,
content: trimmedContent,
- otpType,
+ otpType: effectiveOtpType,
workflowRunId: trimmedWorkflowRunId,
workflowId: trimmedWorkflowId,
taskId: trimmedTaskId,
@@ -154,7 +173,11 @@ function PushTotpCodeForm({
<Label htmlFor="totp-identifier-input">Identifier</Label>
<Input
id="totp-identifier-input"
- placeholder="Email or phone receiving the code"
+ placeholder={
+ effectiveOtpType === OtpType.MagicLink
+ ? "Email receiving the magic link"
+ : "Email or phone receiving the code"
+ }
autoComplete="off"
value={identifier}
onChange={(event) => setIdentifier(event.target.value)}
@@ -166,36 +189,60 @@ function PushTotpCodeForm({
<AutoResizingTextarea
id="totp-content-input"
placeholder={
- otpType === OtpType.MagicLink
+ effectiveOtpType === OtpType.MagicLink
? "Paste the full email body or magic link"
: "Paste the full email/SMS body or the 6-digit code"
}
value={content}
- onChange={(event) => setContent(event.target.value)}
+ onChange={(event) => {
+ setContent(event.target.value);
+ setContentError(null);
+ }}
readOnly={mutation.isPending}
+ aria-invalid={requiresMagicLinkUrl && contentError !== null}
+ aria-describedby={
+ requiresMagicLinkUrl && contentError
+ ? "totp-content-error"
+ : undefined
+ }
className="min-h-[4.5rem]"
/>
+ {requiresMagicLinkUrl && contentError && (
+ <p
+ id="totp-content-error"
+ role="alert"
+ className="text-xs text-destructive"
+ >
+ {contentError}
+ </p>
+ )}
<p className="text-xs text-slate-400">
We only store this to help the current login. Avoid pasting unrelated
sensitive data.
</p>
</div>
- <div className="space-y-1">
- <Label htmlFor="totp-type-input">OTP Type</Label>
- <Select
- value={otpType}
- onValueChange={(value: OtpTypeValue) => setOtpType(value)}
- disabled={mutation.isPending}
- >
- <SelectTrigger id="totp-type-input" className="w-48">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={OtpType.Totp}>Numeric code</SelectItem>
- <SelectItem value={OtpType.MagicLink}>Magic link</SelectItem>
- </SelectContent>
- </Select>
- </div>
+ {fixedOtpType === undefined && (
+ <div className="space-y-1">
+ <Label htmlFor="totp-type-input">OTP Type</Label>
+ <Select
+ value={otpType}
+ onValueChange={(value: OtpTypeValue) => {
+ setOtpType(value);
+ setContentError(null);
+ onOtpTypeChange?.(value);
+ }}
+ disabled={mutation.isPending}
+ >
+ <SelectTrigger id="totp-type-input" className="w-48">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={OtpType.Totp}>Numeric code</SelectItem>
+ <SelectItem value={OtpType.MagicLink}>Magic link</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ )}
{showAdvancedFields && (
<div className="space-y-2">
@@ -247,7 +294,11 @@ function PushTotpCodeForm({
)}
<Button type="submit" disabled={!canSubmit || mutation.isPending}>
- {mutation.isPending ? "Sending…" : "Send 2FA Code"}
+ {mutation.isPending
+ ? "Sending…"
+ : isMagicLink
+ ? "Send Magic Link"
+ : "Send 2FA Code"}
</Button>
</form>
);
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsPage.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsPage.test.tsx
new file mode 100644
index 000000000..caffd241d
--- /dev/null
+++ b/skyvern-frontend/src/routes/credentials/CredentialsPage.test.tsx
@@ -0,0 +1,266 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { useTotpCodesQuery } from "@/hooks/useTotpCodesQuery";
+import { CredentialsPage } from "./CredentialsPage";
+
+vi.mock("@/components/PushTotpCodeForm", () => ({
+ PushTotpCodeForm: () => <div />,
+}));
+
+vi.mock("@/hooks/useTotpCodesQuery", () => ({
+ useTotpCodesQuery: vi.fn(),
+}));
+
+vi.mock("./useCredentialModalState", () => ({
+ CredentialModalTypes: {
+ PASSWORD: "password",
+ CREDIT_CARD: "credit_card",
+ SECRET: "secret",
+ },
+ useCredentialModalState: () => ({
+ setIsOpen: vi.fn(),
+ setType: vi.fn(),
+ }),
+}));
+
+vi.mock("./useBackgroundCredentialTest", () => ({
+ useBackgroundCredentialTest: () => ({
+ startBackgroundTest: vi.fn(),
+ }),
+}));
+
+vi.mock("./hooks/useCredentialFoldersQuery", () => ({
+ useCredentialFoldersQuery: () => ({
+ data: [],
+ isLoading: false,
+ }),
+}));
+
+vi.mock("./CredentialsList", () => ({
+ CredentialsList: () => <div />,
+}));
+
+vi.mock("./BitwardenCredentialsList", () => ({
+ BitwardenCredentialsList: () => <div />,
+}));
+
+vi.mock("./OnePasswordCredentialsList", () => ({
+ OnePasswordCredentialsList: () => <div />,
+}));
+
+vi.mock("./CredentialsModal", () => ({
+ CredentialsModal: () => <div />,
+}));
+
+vi.mock("./CreateCredentialFolderDialog", () => ({
+ CreateCredentialFolderDialog: () => <div />,
+}));
+
+vi.mock("./ViewAllCredentialFoldersDialog", () => ({
+ ViewAllCredentialFoldersDialog: () => <div />,
+}));
+
+const mockedUseTotpCodesQuery = vi.mocked(useTotpCodesQuery);
+
+function LocationSearch() {
+ return <output data-testid="location-search">{useLocation().search}</output>;
+}
+
+function renderPage(url: string) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={[url]}>
+ <CredentialsPage />
+ <LocationSearch />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+describe("CredentialsPage tabs", () => {
+ it("describes support for 2FA codes and magic links", () => {
+ renderPage("/credentials");
+
+ expect(
+ screen.getByText(
+ "Securely store your passwords, credit cards, secrets, and manage incoming 2FA codes and magic links for your agents.",
+ ),
+ ).toBeTruthy();
+ });
+
+ it("scrolls the tab strip horizontally on mount and tab changes", async () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
+ function (this: Element) {
+ const isScrollContainer =
+ this instanceof HTMLElement &&
+ this.classList.contains("overflow-x-auto");
+ const tabName = this.textContent?.trim();
+ const left = isScrollContainer
+ ? 0
+ : tabName === "Magic Links"
+ ? 400
+ : tabName === "Passwords"
+ ? -200
+ : 0;
+ const width = isScrollContainer ? 300 : 100;
+
+ return {
+ bottom: 0,
+ height: 0,
+ left,
+ right: left + width,
+ top: 0,
+ width,
+ x: left,
+ y: 0,
+ toJSON: () => ({}),
+ };
+ },
+ );
+ const scrollLeftSetter = vi.spyOn(Element.prototype, "scrollLeft", "set");
+
+ renderPage("/credentials?tab=magicLinks");
+
+ expect(scrollLeftSetter).toHaveBeenCalledWith(200);
+
+ scrollLeftSetter.mockClear();
+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Passwords" }));
+
+ await waitFor(() => {
+ expect(scrollLeftSetter).toHaveBeenCalledWith(0);
+ });
+ });
+
+ it("re-scrolls the active tab when resizing makes the strip overflow", () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+ let containerWidth = 500;
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
+ function (this: Element) {
+ const isScrollContainer =
+ this instanceof HTMLElement &&
+ this.classList.contains("overflow-x-auto");
+ const left =
+ !isScrollContainer && this.textContent?.trim() === "Magic Links"
+ ? 400
+ : 0;
+ const width = isScrollContainer ? containerWidth : 100;
+
+ return {
+ bottom: 0,
+ height: 0,
+ left,
+ right: left + width,
+ top: 0,
+ width,
+ x: left,
+ y: 0,
+ toJSON: () => ({}),
+ };
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(
+ function (this: HTMLElement) {
+ return this.classList.contains("overflow-x-auto") ? containerWidth : 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, "scrollWidth", "get").mockImplementation(
+ function (this: HTMLElement) {
+ return this.classList.contains("overflow-x-auto") ? 500 : 0;
+ },
+ );
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
+ callback(0);
+ return 1;
+ });
+ const scrollLeftSetter = vi.spyOn(Element.prototype, "scrollLeft", "set");
+
+ renderPage("/credentials?tab=magicLinks");
+ scrollLeftSetter.mockClear();
+ containerWidth = 300;
+
+ fireEvent(window, new Event("resize"));
+
+ expect(scrollLeftSetter).toHaveBeenCalledWith(200);
+ });
+
+ it("selects the Magic Links tab from the URL and renders its empty state without an icon", () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+
+ renderPage("/credentials?tab=magicLinks");
+
+ expect(
+ screen
+ .getByRole("tab", { name: "Magic Links" })
+ .getAttribute("aria-selected"),
+ ).toBe("true");
+ expect(
+ screen.getByRole("tab", { name: "Magic Links" }).querySelector("svg"),
+ ).toBeNull();
+ expect(
+ screen.getByText(
+ "No magic links yet. Paste a magic link message above or connect an email account.",
+ ),
+ ).toBeTruthy();
+ expect(screen.queryByPlaceholderText("Search credentials…")).toBeNull();
+ expect(screen.queryByText("self-hosted Bitwarden")).toBeNull();
+ });
+
+ it("falls back to passwords and normalizes an invalid tab parameter", async () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+
+ renderPage("/credentials?tab=not-a-tab");
+
+ expect(
+ screen
+ .getByRole("tab", { name: "Passwords" })
+ .getAttribute("aria-selected"),
+ ).toBe("true");
+ await waitFor(() => {
+ expect(screen.getByTestId("location-search").textContent).toBe(
+ "?tab=passwords",
+ );
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx b/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx
index 2b2fc6d20..7de9d2b10 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx
@@ -1,4 +1,11 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useDebounce } from "use-debounce";
import { Button } from "@/components/ui/button";
import { TableSearchInput } from "@/components/TableSearchInput";
@@ -32,13 +39,14 @@ import { ViewAllCredentialFoldersDialog } from "./ViewAllCredentialFoldersDialog
import type { CredentialFolder } from "./types/credentialFolderTypes";
const subHeaderText =
- "Securely store your passwords, credit cards, secrets, and manage incoming 2FA codes for your agents.";
+ "Securely store your passwords, credit cards, secrets, and manage incoming 2FA codes and magic links for your agents.";
const TAB_VALUES = [
"passwords",
"creditCards",
"secrets",
"twoFactor",
+ "magicLinks",
] as const;
type TabValue = (typeof TAB_VALUES)[number];
const DEFAULT_TAB: TabValue = "passwords";
@@ -52,6 +60,78 @@ function CredentialsPage() {
const tabParam = searchParams.get("tab");
const matchedTab = TAB_VALUES.find((tab) => tab === tabParam);
const activeTab: TabValue = matchedTab ?? DEFAULT_TAB;
+ const isIncomingCodesTab =
+ activeTab === "twoFactor" || activeTab === "magicLinks";
+ const tabScrollContainerRef = useRef<HTMLDivElement | null>(null);
+ const tabTriggerRefs = useRef<Record<TabValue, HTMLButtonElement | null>>({
+ passwords: null,
+ creditCards: null,
+ secrets: null,
+ twoFactor: null,
+ magicLinks: null,
+ });
+
+ const scrollActiveTabIntoView = useCallback(() => {
+ const activeTabTrigger = tabTriggerRefs.current[activeTab];
+ const scrollContainer = tabScrollContainerRef.current;
+ if (!activeTabTrigger || !scrollContainer) {
+ return;
+ }
+
+ const triggerRect = activeTabTrigger.getBoundingClientRect();
+ const containerRect = scrollContainer.getBoundingClientRect();
+ const triggerLeft =
+ triggerRect.left - containerRect.left + scrollContainer.scrollLeft;
+ const triggerRight = triggerLeft + triggerRect.width;
+ const visibleLeft = scrollContainer.scrollLeft;
+ const visibleRight = visibleLeft + containerRect.width;
+
+ if (triggerLeft < visibleLeft) {
+ scrollContainer.scrollLeft = triggerLeft;
+ } else if (triggerRight > visibleRight) {
+ scrollContainer.scrollLeft = triggerRight - containerRect.width;
+ }
+ }, [activeTab]);
+
+ useLayoutEffect(() => {
+ scrollActiveTabIntoView();
+ }, [scrollActiveTabIntoView]);
+
+ useEffect(() => {
+ if (
+ typeof window === "undefined" ||
+ typeof window.requestAnimationFrame !== "function"
+ ) {
+ return;
+ }
+
+ let animationFrameId: number | null = null;
+ const handleResize = () => {
+ if (animationFrameId !== null) {
+ window.cancelAnimationFrame(animationFrameId);
+ }
+
+ animationFrameId = window.requestAnimationFrame(() => {
+ animationFrameId = null;
+ const scrollContainer = tabScrollContainerRef.current;
+ if (
+ !scrollContainer ||
+ scrollContainer.scrollWidth <= scrollContainer.clientWidth
+ ) {
+ return;
+ }
+ scrollActiveTabIntoView();
+ });
+ };
+
+ window.addEventListener("resize", handleResize);
+ return () => {
+ window.removeEventListener("resize", handleResize);
+ if (animationFrameId !== null) {
+ window.cancelAnimationFrame(animationFrameId);
+ }
+ };
+ }, [scrollActiveTabIntoView]);
useEffect(() => {
if (tabParam && !matchedTab) {
@@ -199,7 +279,7 @@ function CredentialsPage() {
</DropdownMenu>
</div>
- <div className={cn("space-y-4", activeTab === "twoFactor" && "hidden")}>
+ <div className={cn("space-y-4", isIncomingCodesTab && "hidden")}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<h2 className="text-lg font-semibold">Folders</h2>
@@ -282,14 +362,55 @@ function CredentialsPage() {
onValueChange={handleTabChange}
>
<div className="flex flex-wrap items-center justify-between gap-4">
- <TabsList className="bg-slate-elevation1">
- <TabsTrigger value="passwords">Passwords</TabsTrigger>
- <TabsTrigger value="creditCards">Credit Cards</TabsTrigger>
- <TabsTrigger value="secrets">Secrets</TabsTrigger>
- <TabsTrigger value="twoFactor">2FA</TabsTrigger>
- </TabsList>
+ <div
+ ref={tabScrollContainerRef}
+ className="-mx-1 flex w-full max-w-full overflow-x-auto px-1 pb-1 md:m-0 md:w-auto md:max-w-none md:overflow-visible md:p-0"
+ >
+ <TabsList className="bg-slate-elevation1">
+ <TabsTrigger
+ ref={(trigger) => {
+ tabTriggerRefs.current.passwords = trigger;
+ }}
+ value="passwords"
+ >
+ Passwords
+ </TabsTrigger>
+ <TabsTrigger
+ ref={(trigger) => {
+ tabTriggerRefs.current.creditCards = trigger;
+ }}
+ value="creditCards"
+ >
+ Credit Cards
+ </TabsTrigger>
+ <TabsTrigger
+ ref={(trigger) => {
+ tabTriggerRefs.current.secrets = trigger;
+ }}
+ value="secrets"
+ >
+ Secrets
+ </TabsTrigger>
+ <TabsTrigger
+ ref={(trigger) => {
+ tabTriggerRefs.current.twoFactor = trigger;
+ }}
+ value="twoFactor"
+ >
+ 2FA
+ </TabsTrigger>
+ <TabsTrigger
+ ref={(trigger) => {
+ tabTriggerRefs.current.magicLinks = trigger;
+ }}
+ value="magicLinks"
+ >
+ Magic Links
+ </TabsTrigger>
+ </TabsList>
+ </div>
<div className="flex items-center gap-3">
- {selectedFolderId && activeTab !== "twoFactor" && (
+ {selectedFolderId && !isIncomingCodesTab && (
<Button
variant="link"
size="sm"
@@ -299,7 +420,7 @@ function CredentialsPage() {
View all credentials
</Button>
)}
- {activeTab !== "twoFactor" && (
+ {!isIncomingCodesTab && (
<TableSearchInput
value={search}
onChange={setSearch}
@@ -352,6 +473,10 @@ function CredentialsPage() {
<TabsContent value="twoFactor" className="space-y-4">
<CredentialsTotpTab />
</TabsContent>
+
+ <TabsContent value="magicLinks" className="space-y-4">
+ <CredentialsTotpTab variant="magicLink" />
+ </TabsContent>
</Tabs>
<CredentialsModal onStartBackgroundTest={startBackgroundTest} />
@@ -367,7 +492,7 @@ function CredentialsPage() {
/>
{/* Footer note - only for Passwords and Credit Cards tabs */}
- {activeTab !== "twoFactor" && (
+ {!isIncomingCodesTab && (
<div className="mt-8 border-t border-slate-700 pt-4">
<div className="text-sm italic text-neutral-600 dark:text-slate-400">
<strong>Note:</strong> This feature requires a Bitwarden-compatible
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.test.tsx
new file mode 100644
index 000000000..daee188b1
--- /dev/null
+++ b/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.test.tsx
@@ -0,0 +1,203 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { getClient } from "@/api/AxiosClient";
+import { OtpType } from "@/api/types";
+import { useTotpCodesQuery } from "@/hooks/useTotpCodesQuery";
+import { CredentialsTotpTab } from "./CredentialsTotpTab";
+
+vi.mock("@/api/AxiosClient", () => ({ getClient: vi.fn() }));
+
+vi.mock("@/hooks/useTotpCodesQuery", () => ({
+ useTotpCodesQuery: vi.fn(),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => null,
+}));
+
+const mockedGetClient = vi.mocked(getClient);
+const mockedUseTotpCodesQuery = vi.mocked(useTotpCodesQuery);
+
+function renderTab(variant?: "twoFactor" | "magicLink") {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <CredentialsTotpTab variant={variant} />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("CredentialsTotpTab", () => {
+ it("pins magic-link listings and submissions", async () => {
+ const post = vi.fn().mockResolvedValue({});
+ mockedGetClient.mockResolvedValue({ post } as never);
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+
+ renderTab("magicLink");
+
+ expect(mockedUseTotpCodesQuery).toHaveBeenCalledWith({
+ params: {
+ totp_identifier: undefined,
+ otp_type: OtpType.MagicLink,
+ limit: 50,
+ },
+ });
+ expect(document.querySelector("#totp-type-filter")).toBeNull();
+ expect(document.querySelector("#totp-type-input")).toBeNull();
+ expect(
+ screen.getByRole("heading", {
+ name: "Automatic magic links from your inbox",
+ }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "Skyvern can find magic links in a connected Gmail inbox without manual forwarding.",
+ ),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("heading", { name: "Push a Magic Link" }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(/Prefer to send magic links programmatically/),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "No magic links yet. Paste a magic link message above or connect an email account.",
+ ),
+ ).toBeTruthy();
+
+ fireEvent.change(
+ screen.getByPlaceholderText("Email receiving the magic link"),
+ {
+ target: { value: " [email protected] " },
+ },
+ );
+ fireEvent.change(screen.getByLabelText("Verification content"), {
+ target: { value: " https://example.com/login?token=abc " },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send Magic Link" }));
+
+ await waitFor(() => {
+ expect(post).toHaveBeenCalledWith("/credentials/totp", {
+ totp_identifier: "[email protected]",
+ content: "https://example.com/login?token=abc",
+ type: OtpType.MagicLink,
+ source: "manual_ui",
+ });
+ });
+ });
+
+ it("keeps the two-factor default on all types with its selector visible", () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+
+ renderTab();
+
+ expect(mockedUseTotpCodesQuery).toHaveBeenCalledWith({
+ params: {
+ totp_identifier: undefined,
+ otp_type: undefined,
+ limit: 50,
+ },
+ });
+ expect(document.querySelector("#totp-type-filter")).toBeTruthy();
+ expect(document.querySelector("#totp-type-filter")?.textContent).toBe(
+ "All types",
+ );
+ expect(document.querySelector("#totp-type-input")?.textContent).toBe(
+ "Numeric code",
+ );
+ expect(
+ screen.getByRole("heading", {
+ name: "Automatic 2FA from your inbox",
+ }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("heading", { name: "Push a 2FA Code" }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(/Prefer to send codes programmatically/),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "No 2FA codes yet. Paste a verification message above or configure automatic forwarding.",
+ ),
+ ).toBeTruthy();
+ });
+
+ it("updates the push-card copy when Magic link is selected", () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: [],
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: false,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+
+ renderTab();
+ const otpTypeSelect = document.querySelector("#totp-type-input");
+ expect(otpTypeSelect).not.toBeNull();
+ fireEvent.keyDown(otpTypeSelect!, { key: "ArrowDown" });
+ fireEvent.click(screen.getByRole("option", { name: "Magic link" }));
+
+ expect(
+ screen.getByRole("heading", { name: "Push a Magic Link" }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "Paste the magic link message you received. Skyvern extracts the link and attaches it to the relevant run.",
+ ),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(/Prefer to send magic links programmatically/),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole("heading", { name: "Push a 2FA Code" }),
+ ).toBeNull();
+ });
+
+ it("uses the magic-link unavailable alert copy", () => {
+ mockedUseTotpCodesQuery.mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ isFetching: false,
+ isFeatureUnavailable: true,
+ } as unknown as ReturnType<typeof useTotpCodesQuery>);
+
+ renderTab("magicLink");
+
+ expect(screen.getByText("Magic link listing unavailable")).toBeTruthy();
+ expect(screen.getByRole("alert").textContent).toContain(
+ "Once available, this tab will automatically populate with magic links.",
+ );
+ });
+});
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx b/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx
index 073a2ddbf..5b4f234cf 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx
@@ -34,21 +34,16 @@ import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
import { GmailIcon } from "@/components/icons/GmailIcon";
import { OutlookIcon } from "@/components/icons/OutlookIcon";
import CloudContext from "@/store/CloudContext";
+import { safeHttpUrl } from "@/util/httpUrl";
type OtpTypeFilter = "all" | OtpTypeValue;
+type CredentialsTotpTabVariant = "twoFactor" | "magicLink";
-const LIMIT_OPTIONS = [25, 50, 100] as const;
+type Props = {
+ variant?: CredentialsTotpTabVariant;
+};
-function safeHttpUrl(value: string): string | null {
- try {
- const url = new URL(value);
- return url.protocol === "http:" || url.protocol === "https:"
- ? url.toString()
- : null;
- } catch {
- return null;
- }
-}
+const LIMIT_OPTIONS = [25, 50, 100] as const;
function otpTypeLabel(otpType: OtpTypeValue | null): string {
switch (otpType) {
@@ -88,21 +83,39 @@ function renderCodeContent(code: TotpCode) {
return code.code;
}
-function CredentialsTotpTab() {
+function CredentialsTotpTab({ variant = "twoFactor" }: Props) {
const isCloud = useContext(CloudContext);
const [identifierFilter, setIdentifierFilter] = useState("");
const [otpTypeFilter, setOtpTypeFilter] = useState<OtpTypeFilter>("all");
const [limit, setLimit] = useState<(typeof LIMIT_OPTIONS)[number]>(50);
+ const [selectedPushOtpType, setSelectedPushOtpType] = useState<OtpTypeValue>(
+ OtpType.Totp,
+ );
+ const isMagicLink = variant === "magicLink";
+ const effectivePushOtpType = isMagicLink
+ ? OtpType.MagicLink
+ : selectedPushOtpType;
+ const isPushMagicLink = effectivePushOtpType === OtpType.MagicLink;
+ const variantArtifactPlural = isMagicLink ? "magic links" : "codes";
+ const automaticInboxArtifact = isMagicLink
+ ? variantArtifactPlural
+ : "verification codes and magic links";
+ const inboxProviders = isCloud ? "Gmail or Outlook" : "Gmail";
+ const automaticInboxDescription = `Skyvern can find ${automaticInboxArtifact} in a connected ${inboxProviders} inbox without manual forwarding.`;
const queryClient = useQueryClient();
const queryParams = useMemo(() => {
return {
totp_identifier: identifierFilter.trim() || undefined,
- otp_type: otpTypeFilter === "all" ? undefined : otpTypeFilter,
+ otp_type: isMagicLink
+ ? OtpType.MagicLink
+ : otpTypeFilter === "all"
+ ? undefined
+ : otpTypeFilter,
limit,
};
- }, [identifierFilter, limit, otpTypeFilter]);
+ }, [identifierFilter, isMagicLink, limit, otpTypeFilter]);
const { data, isLoading, isFetching, isFeatureUnavailable } =
useTotpCodesQuery({
@@ -130,12 +143,12 @@ function CredentialsTotpTab() {
</div>
<div>
<h2 className="text-base font-semibold">
- Automatic 2FA from your inbox
+ {isMagicLink
+ ? "Automatic magic links from your inbox"
+ : "Automatic 2FA from your inbox"}
</h2>
<p className="mt-1 max-w-2xl text-sm text-neutral-600 dark:text-slate-400">
- {isCloud
- ? "Skyvern can find verification codes and magic links in a connected Gmail or Outlook inbox without manual forwarding."
- : "Skyvern can find verification codes and magic links in a connected Gmail inbox without manual forwarding."}
+ {automaticInboxDescription}
</p>
</div>
</div>
@@ -148,13 +161,16 @@ function CredentialsTotpTab() {
</div>
<div className="rounded-lg border border-slate-700 bg-slate-elevation1 p-6">
- <h2 className="text-lg font-semibold">Push a 2FA Code</h2>
+ <h2 className="text-lg font-semibold">
+ {isPushMagicLink ? "Push a Magic Link" : "Push a 2FA Code"}
+ </h2>
<p className="mt-1 text-sm text-neutral-600 dark:text-slate-400">
- Paste the verification message you received. Skyvern extracts the code
- and attaches it to the relevant run.
+ {isPushMagicLink
+ ? "Paste the magic link message you received. Skyvern extracts the link and attaches it to the relevant run."
+ : "Paste the verification message you received. Skyvern extracts the code and attaches it to the relevant run."}
</p>
<p className="mt-2 text-sm text-neutral-600 dark:text-slate-400">
- Prefer to send codes programmatically? See the{" "}
+ {`Prefer to send ${isPushMagicLink ? "magic links" : "codes"} programmatically? See the `}
<a
href="https://docs.skyvern.com/api-reference/credentials/send-totp-code"
target="_blank"
@@ -167,7 +183,9 @@ function CredentialsTotpTab() {
</p>
<PushTotpCodeForm
className="mt-4"
+ fixedOtpType={isMagicLink ? OtpType.MagicLink : undefined}
showAdvancedFields
+ onOtpTypeChange={setSelectedPushOtpType}
onSuccess={handleFormSuccess}
/>
</div>
@@ -184,24 +202,28 @@ function CredentialsTotpTab() {
onChange={(event) => setIdentifierFilter(event.target.value)}
/>
</div>
- <div className="space-y-1">
- <Label htmlFor="totp-type-filter">OTP Type</Label>
- <Select
- value={otpTypeFilter}
- onValueChange={(value: OtpTypeFilter) =>
- setOtpTypeFilter(value)
- }
- >
- <SelectTrigger id="totp-type-filter" className="w-40">
- <SelectValue placeholder="All types" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All types</SelectItem>
- <SelectItem value={OtpType.Totp}>Numeric code</SelectItem>
- <SelectItem value={OtpType.MagicLink}>Magic link</SelectItem>
- </SelectContent>
- </Select>
- </div>
+ {!isMagicLink && (
+ <div className="space-y-1">
+ <Label htmlFor="totp-type-filter">OTP Type</Label>
+ <Select
+ value={otpTypeFilter}
+ onValueChange={(value: OtpTypeFilter) =>
+ setOtpTypeFilter(value)
+ }
+ >
+ <SelectTrigger id="totp-type-filter" className="w-40">
+ <SelectValue placeholder="All types" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All types</SelectItem>
+ <SelectItem value={OtpType.Totp}>Numeric code</SelectItem>
+ <SelectItem value={OtpType.MagicLink}>
+ Magic link
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ )}
<div className="space-y-1">
<Label htmlFor="totp-limit-filter">Limit</Label>
<Select
@@ -240,11 +262,15 @@ function CredentialsTotpTab() {
{isFeatureUnavailable && (
<Alert variant="destructive">
- <AlertTitle>2FA listing unavailable</AlertTitle>
+ <AlertTitle>
+ {isMagicLink
+ ? "Magic link listing unavailable"
+ : "2FA listing unavailable"}
+ </AlertTitle>
<AlertDescription>
Upgrade the backend to include{" "}
<code>GET /v1/credentials/totp</code>. Once available, this tab
- will automatically populate with codes.
+ will automatically populate with {variantArtifactPlural}.
</AlertDescription>
</Alert>
)}
@@ -281,8 +307,9 @@ function CredentialsTotpTab() {
colSpan={6}
className="text-center text-sm text-neutral-600 dark:text-slate-300"
>
- No 2FA codes yet. Paste a verification message above or
- configure automatic forwarding.
+ {isMagicLink
+ ? "No magic links yet. Paste a magic link message above or connect an email account."
+ : "No 2FA codes yet. Paste a verification message above or configure automatic forwarding."}
</TableCell>
</TableRow>
) : null}
diff --git a/skyvern-frontend/src/routes/root/SideNav.test.tsx b/skyvern-frontend/src/routes/root/SideNav.test.tsx
index 8889a0cbf..287d33c12 100644
--- a/skyvern-frontend/src/routes/root/SideNav.test.tsx
+++ b/skyvern-frontend/src/routes/root/SideNav.test.tsx
@@ -191,6 +191,23 @@ describe("SideNav", () => {
expect(screen.getByRole("button", { name: /Integrations/i })).toBeTruthy();
});
+ it("includes the Magic Links credentials child", () => {
+ window.localStorage.setItem(
+ "skyvern-sidebar-open-groups",
+ JSON.stringify({ "/credentials": true }),
+ );
+
+ render(
+ <MemoryRouter>
+ <SideNav />
+ </MemoryRouter>,
+ );
+
+ expect(
+ screen.getByRole("link", { name: "Magic Links" }).getAttribute("href"),
+ ).toBe("/credentials?tab=magicLinks");
+ });
+
it("preserves a stored recipes state on short screens", () => {
window.localStorage.setItem(
"skyvern-sidebar-open-groups",
diff --git a/skyvern-frontend/src/routes/root/SideNav.tsx b/skyvern-frontend/src/routes/root/SideNav.tsx
index 4d6220718..76963f14f 100644
--- a/skyvern-frontend/src/routes/root/SideNav.tsx
+++ b/skyvern-frontend/src/routes/root/SideNav.tsx
@@ -8,6 +8,7 @@ import {
GlobeIcon,
IdCardIcon,
LightningBoltIcon,
+ Link2Icon,
ListBulletIcon,
LockClosedIcon,
PersonIcon,
@@ -228,6 +229,11 @@ function SideNav({ collapsed }: Props = {}) {
to: "/credentials?tab=twoFactor",
icon: <CounterClockwiseClockIcon className="size-3.5" />,
},
+ {
+ label: "Magic Links",
+ to: "/credentials?tab=magicLinks",
+ icon: <Link2Icon className="size-3.5" />,
+ },
],
},
{
diff --git a/skyvern-frontend/src/util/httpUrl.test.ts b/skyvern-frontend/src/util/httpUrl.test.ts
new file mode 100644
index 000000000..ce14631bd
--- /dev/null
+++ b/skyvern-frontend/src/util/httpUrl.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { safeHttpUrl } from "./httpUrl";
+
+describe("safeHttpUrl", () => {
+ it.each(["http://example.com/path", "https://example.com/path?token=abc"])(
+ "accepts %s",
+ (value) => {
+ expect(safeHttpUrl(value)).toBe(value);
+ },
+ );
+
+ it.each([
+ "javascript:alert(1)",
+ "data:text/html,<h1>unsafe</h1>",
+ "ftp://example.com/file",
+ "not a url",
+ ])("rejects %s", (value) => {
+ expect(safeHttpUrl(value)).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/util/httpUrl.ts b/skyvern-frontend/src/util/httpUrl.ts
new file mode 100644
index 000000000..f4168aa04
--- /dev/null
+++ b/skyvern-frontend/src/util/httpUrl.ts
@@ -0,0 +1,24 @@
+const HTTP_URL_PATTERN = /\bhttps?:\/\/[^\s<>"']+/gi;
+
+function safeHttpUrl(value: string): string | null {
+ try {
+ const url = new URL(value);
+ return url.protocol === "http:" || url.protocol === "https:"
+ ? url.toString()
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+function containsHttpUrl(value: string): boolean {
+ for (const match of value.matchAll(HTTP_URL_PATTERN)) {
+ if (safeHttpUrl(match[0]) !== null) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+export { containsHttpUrl, safeHttpUrl };