Skip to content

Automate browser based workflows with AI

Add authenticator QR upload support (#6882)

Suchintan01325c074c3e
diff --git a/docs/pr-screenshots/credentials-authenticator-qr-after.png b/docs/pr-screenshots/credentials-authenticator-qr-after.png
new file mode 100644
index 000000000..994a5a06f
Binary files /dev/null and b/docs/pr-screenshots/credentials-authenticator-qr-after.png differ
diff --git a/docs/pr-screenshots/credentials-authenticator-qr-before.png b/docs/pr-screenshots/credentials-authenticator-qr-before.png
new file mode 100644
index 000000000..efa740c4d
Binary files /dev/null and b/docs/pr-screenshots/credentials-authenticator-qr-before.png differ
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
index 496d30ccb..fd25df182 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
@@ -11,12 +11,13 @@ describe("getAuthenticatorKeyError", () => {
).toBe("Authenticator key is required.");
});
- it("rejects Base32-shaped authenticator keys that are too short to be useful", () => {
+ it("lets backend validation decide authenticator key format", () => {
expect(
- getAuthenticatorKeyError({ totp: "A", totp_type: "authenticator" }),
- ).toBe(
- "Authenticator key should be a raw Base32 setup key or full otpauth:// URI.",
- );
+ getAuthenticatorKeyError({
+ totp: "provider-specific-payload",
+ totp_type: "authenticator",
+ }),
+ ).toBeNull();
});
it("accepts a raw Base32 key or a full otpauth URI", () => {
diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx
index 45b22cd2e..7e4401b84 100644
--- a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx
+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx
@@ -270,13 +270,13 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression
expect(imageBitmap.close).toHaveBeenCalled();
});
- it("rejects QR codes that are not 2FA setup values", async () => {
+ it("imports a non-otpauth QR payload for server-side validation", async () => {
const onChangeSpy = vi.fn();
const imageBitmap = { close: vi.fn() } as unknown as ImageBitmap;
class MockBarcodeDetector {
detect = vi.fn().mockResolvedValue([
{
- rawValue: "https://example.com/account/settings",
+ rawValue: "custom-authenticator://activate?payload=opaque",
},
]);
}
@@ -309,19 +309,16 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression
});
await waitFor(() => {
- expect(
- screen.getByText(
- "This QR code doesn't look like a 2FA setup code. Make sure you're scanning the setup QR from the site's 2FA settings.",
- ),
- ).toBeTruthy();
+ const qrCall = onChangeSpy.mock.calls.find((call) => {
+ const next = call[0] as Values;
+ return (
+ next.totp_type === "authenticator" &&
+ next.totp === "custom-authenticator://activate?payload=opaque"
+ );
+ });
+ expect(qrCall).toBeTruthy();
});
expect(imageBitmap.close).toHaveBeenCalled();
- expect(
- onChangeSpy.mock.calls.some((call) => {
- const next = call[0] as Values;
- return next.totp === "https://example.com/account/settings";
- }),
- ).toBe(false);
});
it("shows an inline fallback when the browser cannot scan QR codes", async () => {
@@ -511,4 +508,56 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression
});
expect(reseedCall).toBeTruthy();
});
+
+ it("allows QR upload to set the TOTP payload", async () => {
+ const onChangeSpy = vi.fn();
+ const close = vi.fn();
+ const detect = vi
+ .fn()
+ .mockResolvedValue([{ rawValue: "decoded-qr-payload" }]);
+ class BarcodeDetector {
+ detect: typeof detect;
+
+ constructor() {
+ this.detect = detect;
+ }
+ }
+ vi.stubGlobal("BarcodeDetector", BarcodeDetector);
+ vi.stubGlobal("createImageBitmap", vi.fn().mockResolvedValue({ close }));
+
+ const { container } = render(
+ <MemoryRouter>
+ <PasswordCredentialContent
+ values={{
+ name: "Example Login",
+ username: "[email protected]",
+ password: "password",
+ totp: "",
+ totp_type: "authenticator",
+ totp_identifier: "",
+ }}
+ onChange={onChangeSpy}
+ />
+ </MemoryRouter>,
+ );
+ const input = container.querySelector('input[type="file"]');
+ expect(input).toBeTruthy();
+ const file = new File(["qr"], "qr.png", { type: "image/png" });
+
+ await act(async () => {
+ fireEvent.change(input as HTMLInputElement, {
+ target: { files: [file] },
+ });
+ });
+
+ await waitFor(() =>
+ expect(onChangeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ totp: "decoded-qr-payload",
+ totp_type: "authenticator",
+ }),
+ ),
+ );
+ expect(close).toHaveBeenCalled();
+ });
});
diff --git a/skyvern-frontend/src/routes/credentials/credentialTotpValidation.ts b/skyvern-frontend/src/routes/credentials/credentialTotpValidation.ts
index 2ff94e7cd..af4fabe80 100644
--- a/skyvern-frontend/src/routes/credentials/credentialTotpValidation.ts
+++ b/skyvern-frontend/src/routes/credentials/credentialTotpValidation.ts
@@ -1,7 +1,4 @@
const AUTHENTICATOR_KEY_REQUIRED_MESSAGE = "Authenticator key is required.";
-const AUTHENTICATOR_KEY_FORMAT_MESSAGE =
- "Authenticator key should be a raw Base32 setup key or full otpauth:// URI.";
-const MIN_AUTHENTICATOR_KEY_LENGTH = 16;
type AuthenticatorKeyValues = {
totp: string;
@@ -19,20 +16,6 @@ function getAuthenticatorKeyError(
if (raw === "") {
return AUTHENTICATOR_KEY_REQUIRED_MESSAGE;
}
- if (
- raw.toLowerCase().startsWith("otpauth://") ||
- /(?:^|[?&])secret=/i.test(raw)
- ) {
- return null;
- }
-
- const normalized = raw.replace(/[\s-]/g, "").toUpperCase();
- if (
- normalized.length < MIN_AUTHENTICATOR_KEY_LENGTH ||
- !/^[A-Z2-7]+=*$/.test(normalized)
- ) {
- return AUTHENTICATOR_KEY_FORMAT_MESSAGE;
- }
return null;
}
diff --git a/skyvern-frontend/src/routes/credentials/decodeQrCodeImage.ts b/skyvern-frontend/src/routes/credentials/decodeQrCodeImage.ts
index 89bae9f10..26fd5c317 100644
--- a/skyvern-frontend/src/routes/credentials/decodeQrCodeImage.ts
+++ b/skyvern-frontend/src/routes/credentials/decodeQrCodeImage.ts
@@ -10,18 +10,6 @@ const QR_SCAN_UNSUPPORTED_MESSAGE =
"QR scanning is not supported by this browser. Paste the setup key or otpauth:// URI instead.";
const QR_CODE_NOT_FOUND_MESSAGE =
"No QR code was found in that image. Try a clearer screenshot or paste the setup key.";
-const QR_CODE_INVALID_TOTP_MESSAGE =
- "This QR code doesn't look like a 2FA setup code. Make sure you're scanning the setup QR from the site's 2FA settings.";
-
-function isLikelyTotpSetupValue(value: string): boolean {
- const normalizedValue = value.trim();
- if (normalizedValue.toLowerCase().startsWith("otpauth://")) {
- return true;
- }
-
- const compactValue = normalizedValue.replace(/[\s-]/g, "");
- return compactValue.length >= 16 && /^[A-Z2-7]+=*$/i.test(compactValue);
-}
async function decodeQrCodeImage(file: File): Promise<string> {
const scope = globalThis as BrowserBarcodeDetectorScope;
@@ -51,9 +39,6 @@ async function decodeQrCodeImage(file: File): Promise<string> {
if (!rawValue) {
throw new Error(QR_CODE_NOT_FOUND_MESSAGE);
}
- if (!isLikelyTotpSetupValue(rawValue)) {
- throw new Error(QR_CODE_INVALID_TOTP_MESSAGE);
- }
return rawValue;
} finally {
image.close();
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 793699b87..150e45a5b 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -1977,8 +1977,13 @@ class ForgeAgent:
if self._is_multi_field_totp_sequence(actions):
context = skyvern_context.ensure_context()
cache_key = f"{task.task_id}_totp_cache"
- if cache_key in context.totp_codes:
- context.totp_codes.pop(cache_key)
+ removed_totp_cache = False
+ for key in (cache_key, f"{cache_key}_valid_from", f"{cache_key}_valid_until"):
+ if key in context.totp_codes:
+ context.totp_codes.pop(key)
+ removed_totp_cache = True
+
+ if removed_totp_cache:
LOG.debug(
"Cleaned up TOTP cache after multi-field sequence completion",
task_id=task.task_id,
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index a7f5bf0d2..0ed32375d 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -918,6 +918,13 @@ class AgentFunction:
) -> None:
return
+ async def parse_enterprise_totp_secret(
+ self,
+ totp_secret: str,
+ organization_id: str | None = None,
+ ) -> str | None:
+ return None
+
async def prepare_step_execution(
self,
organization: Organization | None,
diff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.py
index 5163ad5cc..f7e4ac02c 100644
--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py
+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py
@@ -16,7 +16,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
scrub_secrets_from_text,
)
from skyvern.forge.sdk.schemas.credentials import CredentialVaultType, PasswordCredential, TotpType
-from skyvern.forge.sdk.services.credentials import generate_totp_code
+from skyvern.forge.sdk.services.credentials import generate_totp_code, normalize_totp_config
from .banned_blocks import _copilot_block_authoring_policy
from .blockers import _tool_loop_error
@@ -40,6 +40,16 @@ _CREDENTIAL_FILL_FIELDS = frozenset({"username", "password", "totp"})
_CREDENTIAL_FILL_TIMEOUT_MS = 15000
+async def _normalize_totp_config_for_organization(totp_secret: str, organization_id: str) -> str:
+ enterprise_totp_secret = await app.AGENT_FUNCTION.parse_enterprise_totp_secret(
+ totp_secret,
+ organization_id=organization_id,
+ )
+ if enterprise_totp_secret is not None:
+ return enterprise_totp_secret
+ return normalize_totp_config(totp_secret)
+
+
def _runtime_otp_steering_error(credential_id: str) -> str:
return (
f"Credential `{credential_id}` receives one-time codes by email/SMS, so `fill_credential_field` cannot "
@@ -134,7 +144,12 @@ async def _resolve_credential_fill_value(
return None, "", _runtime_otp_steering_error(credential_id)
return None, "", f"Credential `{credential_id}` has no TOTP secret configured."
try:
- value = generate_totp_code(credential.totp)
+ value = generate_totp_code(
+ await _normalize_totp_config_for_organization(
+ credential.totp,
+ copilot_ctx.organization_id,
+ )
+ )
except Exception:
LOG.warning(
"fill_credential_field could not generate a TOTP code",
diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.py
index 3079b92d7..5c098032f 100644
--- a/skyvern/forge/sdk/routes/credentials.py
+++ b/skyvern/forge/sdk/routes/credentials.py
@@ -112,7 +112,7 @@ from skyvern.forge.sdk.schemas.totp_codes import OTPType, TOTPCode, TOTPCodeCrea
from skyvern.forge.sdk.services import org_auth_service
from skyvern.forge.sdk.services.bitwarden import BitwardenService
from skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultService
-from skyvern.forge.sdk.services.credentials import parse_totp_config
+from skyvern.forge.sdk.services.credentials import normalize_totp_config, parse_totp_config
from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterType
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody, WorkflowRunStatus
from skyvern.schemas.credential_folders import (
@@ -194,11 +194,10 @@ def _parse_authenticator_totp_config_or_raise(
if raw_totp_secret == "":
raise HTTPException(status_code=400, detail=missing_detail)
- normalized_input = "".join(raw_totp_secret.split())
- totp = parse_totp_config(normalized_input)
+ 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)
- normalized_totp_secret = normalized_input if normalized_input.lower().startswith("otpauth://") else totp.secret
return totp, normalized_totp_secret
@@ -216,6 +215,40 @@ def _build_authenticator_totp_or_raise(
return totp
+async def _parse_enterprise_totp_secret_or_raise(
+ totp_secret: str | None,
+ *,
+ organization_id: str,
+ invalid_detail: str = _AUTHENTICATOR_SECRET_INVALID_DETAIL,
+) -> str | None:
+ enterprise_totp_secret = await app.AGENT_FUNCTION.parse_enterprise_totp_secret(
+ totp_secret or "",
+ organization_id=organization_id,
+ )
+ if enterprise_totp_secret == "":
+ raise HTTPException(status_code=400, detail=invalid_detail)
+ return enterprise_totp_secret
+
+
+async def _build_authenticator_totp_for_organization_or_raise(
+ totp_secret: str | None,
+ *,
+ organization_id: str,
+ missing_detail: str = _AUTHENTICATOR_SECRET_REQUIRED_DETAIL,
+ invalid_detail: str = _AUTHENTICATOR_SECRET_INVALID_DETAIL,
+) -> pyotp.TOTP:
+ parsed_totp_secret = await _parse_enterprise_totp_secret_or_raise(
+ totp_secret,
+ organization_id=organization_id,
+ invalid_detail=invalid_detail,
+ )
+ return _build_authenticator_totp_or_raise(
+ parsed_totp_secret if parsed_totp_secret is not None else totp_secret,
+ missing_detail=missing_detail,
+ invalid_detail=invalid_detail,
+ )
+
+
def _parse_authenticator_totp_or_raise(
totp_secret: str | None,
*,
@@ -237,6 +270,26 @@ def _normalize_authenticator_totp_or_raise(credential: PasswordCredential | Test
credential.totp = _parse_authenticator_totp_or_raise(credential.totp)
+async def _normalize_authenticator_totp_for_organization_or_raise(
+ credential: PasswordCredential | TestLoginRequest,
+ *,
+ organization_id: str,
+) -> None:
+ if credential.totp_type != TotpType.AUTHENTICATOR:
+ return
+
+ enterprise_totp_secret = await _parse_enterprise_totp_secret_or_raise(
+ credential.totp,
+ 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.
+ return
+
+ _normalize_authenticator_totp_or_raise(credential)
+
+
def _get_cached_totp_code_preview(
*,
organization_id: str,
@@ -501,7 +554,10 @@ async def create_credential(
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> CredentialResponse:
if isinstance(data.credential, NonEmptyPasswordCredential):
- _normalize_authenticator_totp_or_raise(data.credential)
+ await _normalize_authenticator_totp_for_organization_or_raise(
+ data.credential,
+ organization_id=current_org.organization_id,
+ )
credential_service = await _get_credential_vault_service(vault_type_override=data.vault_type)
@@ -697,7 +753,10 @@ async def test_login(
) -> TestLoginResponse:
"""Test a login with inline credentials without requiring a saved credential."""
organization_id = current_org.organization_id
- _normalize_authenticator_totp_or_raise(data)
+ await _normalize_authenticator_totp_for_organization_or_raise(
+ data,
+ organization_id=organization_id,
+ )
# Create a temporary credential
create_request = CreateCredentialRequest(
@@ -1581,7 +1640,10 @@ async def update_credential(
raise HTTPException(status_code=404, detail=f"Credential not found, credential_id={credential_id}")
if isinstance(data.credential, NonEmptyPasswordCredential):
- _normalize_authenticator_totp_or_raise(data.credential)
+ await _normalize_authenticator_totp_for_organization_or_raise(
+ data.credential,
+ organization_id=current_org.organization_id,
+ )
vault_type = existing_credential.vault_type or CredentialVaultType.BITWARDEN
credential_service = app.CREDENTIAL_VAULT_SERVICES.get(vault_type)
@@ -1753,8 +1815,9 @@ async def get_credential_totp_code(
raise HTTPException(status_code=400, detail="This credential does not have an authenticator app configured.")
try:
- totp = _build_authenticator_totp_or_raise(
+ totp = await _build_authenticator_totp_for_organization_or_raise(
credential_item.credential.totp,
+ organization_id=current_org.organization_id,
missing_detail=_SAVED_AUTHENTICATOR_SECRET_INVALID_DETAIL,
invalid_detail=_SAVED_AUTHENTICATOR_SECRET_INVALID_DETAIL,
)
diff --git a/skyvern/forge/sdk/services/bitwarden.py b/skyvern/forge/sdk/services/bitwarden.py
index 5baee2204..52b1fa461 100644
--- a/skyvern/forge/sdk/services/bitwarden.py
+++ b/skyvern/forge/sdk/services/bitwarden.py
@@ -35,7 +35,6 @@ from skyvern.forge.sdk.schemas.credentials import (
PasswordCredential,
SecretCredential,
)
-from skyvern.forge.sdk.services.credentials import normalize_totp_config as normalize_credential_totp_config
from skyvern.utils.strings import is_uuid
LOG = structlog.get_logger()
@@ -522,13 +521,13 @@ class BitwardenService:
@staticmethod
def normalize_totp_config(totp_value: str) -> str:
"""
- Validate the TOTP config from either a raw secret or a TOTP URI.
+ Preserve the raw TOTP value from Bitwarden.
Args:
- totp_value: Raw TOTP secret or URI (otpauth://totp/...)
+ totp_value: Raw TOTP secret, URI, or provider-specific payload.
Returns:
- The raw secret or full TOTP URI config
+ The raw TOTP value
Example:
>>> BitwardenService.normalize_totp_config("AAAAAABBBBBBB")
@@ -536,7 +535,7 @@ class BitwardenService:
>>> BitwardenService.normalize_totp_config("otpauth://totp/[email protected]?secret=AAAAAABBBBBBB")
"otpauth://totp/[email protected]?secret=AAAAAABBBBBBB"
"""
- return normalize_credential_totp_config(totp_value)
+ return totp_value.strip()
@staticmethod
def extract_totp_secret(totp_value: str) -> str:
diff --git a/skyvern/forge/sdk/services/credentials.py b/skyvern/forge/sdk/services/credentials.py
index 95155430d..61d02d9bc 100644
--- a/skyvern/forge/sdk/services/credentials.py
+++ b/skyvern/forge/sdk/services/credentials.py
@@ -1,12 +1,14 @@
import re
from enum import StrEnum
-from urllib.parse import unquote
+from urllib.parse import unquote, urlsplit
import pyotp
import structlog
LOG = structlog.get_logger()
+_SECRET_QUERY_PATTERN = re.compile(r"(?i)(?:^|[?&])secret=([^&#]+)")
+
class OnePasswordConstants(StrEnum):
"""Constants for 1Password integration."""
@@ -24,45 +26,71 @@ def _strip_totp_input_whitespace(totp_secret: str) -> str:
return "".join(totp_secret.split())
-def _is_otpauth_uri(totp_secret: str) -> bool:
- return totp_secret.lower().startswith("otpauth://")
+def _compact_secret_value(totp_secret: str) -> str:
+ return _strip_totp_input_whitespace(totp_secret).replace("-", "")
-def parse_totp_secret(totp_secret: str) -> str:
- if not totp_secret:
- return ""
+def _is_otpauth_uri(totp_secret: str) -> bool:
+ parsed = urlsplit(totp_secret)
+ return parsed.scheme.lower() == "otpauth" and parsed.netloc.lower() == "totp"
- totp_secret_no_dashe = "".join(totp_secret.split("-"))
- totp_secret_no_whitespace = "".join(totp_secret_no_dashe.split())
- try:
- pyotp.TOTP(totp_secret_no_whitespace).byte_secret()
- return totp_secret_no_whitespace
- except Exception:
- LOG.warning("It's not a valid TOTP secret, going to parse it from URI format", exc_info=True)
+def _validate_base32_secret(totp_secret: str) -> str:
+ normalized_secret = _compact_secret_value(totp_secret)
try:
- totp_secret = pyotp.parse_uri(totp_secret_no_whitespace).secret
- totp_secret_no_whitespace = "".join(totp_secret.split())
- return totp_secret_no_whitespace
+ pyotp.TOTP(normalized_secret).byte_secret()
+ return normalized_secret
except Exception:
- LOG.warning("Failed to parse TOTP secret key from URI format, going to extract secret by regex", exc_info=True)
- m = re.search(r"(?i)(?:^|[?&])secret=([^&#]+)", unquote(totp_secret_no_whitespace))
- if m is not None:
- totp_secret = m.group(1)
- totp_secret_no_whitespace = "".join(totp_secret.split())
+ return ""
+
- # Final validation: ensure the result is valid base32
+def _parse_uri_totp(uri: str) -> pyotp.TOTP | None:
try:
- pyotp.TOTP(totp_secret_no_whitespace).byte_secret()
- return totp_secret_no_whitespace
+ parsed_otp = pyotp.parse_uri(uri)
except Exception:
- LOG.error(
- "Invalid TOTP secret, not valid base32, discarding",
- totp_secret_preview=totp_secret_no_whitespace[:4] + "...",
- exc_info=True,
- )
+ LOG.warning("Failed to parse TOTP config from URI", exc_info=True)
+ return None
+ if not isinstance(parsed_otp, pyotp.TOTP):
+ LOG.warning("Parsed OTP URI is not a TOTP config")
+ return None
+ return parsed_otp
+
+
+def parse_totp_secret(totp_secret: str) -> str:
+ if not totp_secret:
return ""
+ stripped_totp_secret = totp_secret.strip()
+ validated_secret = _validate_base32_secret(stripped_totp_secret)
+ if validated_secret:
+ return validated_secret
+
+ normalized_input = _strip_totp_input_whitespace(stripped_totp_secret)
+ unquoted_input = unquote(normalized_input)
+ uri_candidates = [normalized_input]
+ if unquoted_input != normalized_input:
+ uri_candidates.append(unquoted_input)
+
+ for candidate in uri_candidates:
+ if not _is_otpauth_uri(candidate):
+ continue
+ parsed_otp = _parse_uri_totp(candidate)
+ if not parsed_otp:
+ return ""
+ return _validate_base32_secret(parsed_otp.secret)
+
+ match = _SECRET_QUERY_PATTERN.search(unquoted_input)
+ if match is not None:
+ parsed_from_secret_param = _validate_base32_secret(match.group(1))
+ if parsed_from_secret_param:
+ return parsed_from_secret_param
+
+ LOG.error(
+ "Invalid TOTP secret, discarding",
+ totp_secret_preview=_compact_secret_value(stripped_totp_secret)[:4] + "...",
+ )
+ return ""
+
def parse_totp_config(totp_secret: str) -> pyotp.TOTP | None:
"""Parse a raw Base32 TOTP secret or full otpauth URI into a TOTP config."""
@@ -71,15 +99,11 @@ def parse_totp_config(totp_secret: str) -> pyotp.TOTP | None:
totp_secret_no_whitespace = _strip_totp_input_whitespace(totp_secret)
if _is_otpauth_uri(totp_secret_no_whitespace):
- try:
- parsed_otp = pyotp.parse_uri(totp_secret_no_whitespace)
- except Exception:
- LOG.warning("Failed to parse TOTP config from URI", exc_info=True)
- return None
- if not isinstance(parsed_otp, pyotp.TOTP):
- LOG.warning("Parsed OTP URI is not a TOTP config")
- return None
- return parsed_otp
+ return _parse_uri_totp(totp_secret_no_whitespace)
+
+ unquoted_totp_secret = unquote(totp_secret_no_whitespace)
+ if unquoted_totp_secret != totp_secret_no_whitespace and _is_otpauth_uri(unquoted_totp_secret):
+ return _parse_uri_totp(unquoted_totp_secret)
parsed_totp_secret = parse_totp_secret(totp_secret)
if not parsed_totp_secret:
@@ -96,6 +120,10 @@ def normalize_totp_config(totp_secret: str) -> str:
if _is_otpauth_uri(totp_secret_no_whitespace):
return totp_secret_no_whitespace if parse_totp_config(totp_secret_no_whitespace) else ""
+ unquoted_totp_secret = unquote(totp_secret_no_whitespace)
+ if unquoted_totp_secret != totp_secret_no_whitespace and _is_otpauth_uri(unquoted_totp_secret):
+ return unquoted_totp_secret if parse_totp_config(unquoted_totp_secret) else ""
+
return parse_totp_secret(totp_secret)
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index c3572af02..4bd290865 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -612,6 +612,15 @@ class WorkflowRunContext:
" Expected format: vault_id:item_id"
)
+ async def _normalize_totp_config_for_organization(self, totp_secret: str, organization: Organization) -> str:
+ enterprise_totp_secret = await app.AGENT_FUNCTION.parse_enterprise_totp_secret(
+ totp_secret,
+ organization_id=organization.organization_id,
+ )
+ if enterprise_totp_secret is not None:
+ return enterprise_totp_secret
+ return normalize_totp_config(totp_secret)
+
async def _register_credential_parameter_value(
self,
credential_id: str,
@@ -660,7 +669,10 @@ class WorkflowRunContext:
totp_secret_id = f"{random_secret_id}_totp"
self.secrets[totp_secret_id] = BitwardenConstants.TOTP
totp_secret_value = self.totp_secret_value_key(totp_secret_id)
- self.secrets[totp_secret_value] = normalize_totp_config(credential.totp)
+ self.secrets[totp_secret_value] = await self._normalize_totp_config_for_organization(
+ credential.totp,
+ organization,
+ )
self.values[parameter.key]["totp"] = totp_secret_id
def get_credential_totp_identifier(self, parameter_key: str) -> str | None:
@@ -808,7 +820,10 @@ class WorkflowRunContext:
totp_secret_id = f"{random_secret_id}_totp"
self.secrets[totp_secret_id] = OnePasswordConstants.TOTP
totp_secret_value = self.totp_secret_value_key(totp_secret_id)
- self.secrets[totp_secret_value] = normalize_totp_config(field.value)
+ self.secrets[totp_secret_value] = await self._normalize_totp_config_for_organization(
+ field.value,
+ organization,
+ )
self.values[parameter.key]["totp"] = totp_secret_id
elif field.title and field.title.lower() in ["expire date", "expiry date", "expiration date"]:
parts = [part.strip() for part in field.value.strip().split("/")]
@@ -1040,7 +1055,10 @@ class WorkflowRunContext:
totp_secret_id = f"{random_secret_id}_totp"
self.secrets[totp_secret_id] = BitwardenConstants.TOTP
totp_secret_value = self.totp_secret_value_key(totp_secret_id)
- self.secrets[totp_secret_value] = normalize_totp_config(secret_credentials[BitwardenConstants.TOTP])
+ self.secrets[totp_secret_value] = await self._normalize_totp_config_for_organization(
+ secret_credentials[BitwardenConstants.TOTP],
+ organization,
+ )
self.values[parameter.key]["totp"] = totp_secret_id
except BitwardenBaseError as e:
@@ -1094,7 +1112,10 @@ class WorkflowRunContext:
totp_secret_id = f"{random_secret_id}_totp"
self.secrets[totp_secret_id] = AzureVaultConstants.TOTP
totp_secret_value = self.totp_secret_value_key(totp_secret_id)
- self.secrets[totp_secret_value] = normalize_totp_config(totp_secret)
+ self.secrets[totp_secret_value] = await self._normalize_totp_config_for_organization(
+ totp_secret,
+ organization,
+ )
self.values[parameter.key]["totp"] = totp_secret_id
async def register_bitwarden_sensitive_information_parameter_value(
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 17ff708d6..53c0cb490 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -2011,6 +2011,8 @@ async def _handle_multi_field_totp_sequence(
"""
action_index = timing_info["action_index"]
cache_key = f"{task.task_id}_totp_cache"
+ valid_from_key = f"{cache_key}_valid_from"
+ valid_until_key = f"{cache_key}_valid_until"
current_context = skyvern_context.ensure_context()
if action_index == 0:
@@ -2028,8 +2030,9 @@ async def _handle_multi_field_totp_sequence(
# If less than threshold seconds until expiry, use the next TOTP
if seconds_until_expiry < TOTP_EXPIRY_THRESHOLD_SECONDS:
# Force generation of next TOTP by advancing time
- next_time = current_totp_valid_until
- current_totp = totp.at(next_time)
+ totp_valid_from = current_totp_valid_until
+ totp_valid_until = current_totp_valid_until + totp.interval
+ current_totp = totp.at(totp_valid_from)
LOG.debug(
"Using multi-field TOTP flow - using NEXT TOTP due to <20s expiry",
@@ -2041,9 +2044,13 @@ async def _handle_multi_field_totp_sequence(
)
else:
# Use current TOTP
+ totp_valid_from = current_totp_valid_until - totp.interval
+ totp_valid_until = current_totp_valid_until
current_totp = totp.now()
current_context.totp_codes[cache_key] = current_totp
+ current_context.totp_codes[valid_from_key] = str(totp_valid_from)
+ current_context.totp_codes[valid_until_key] = str(totp_valid_until)
else:
# Subsequent digits: reuse cached TOTP
current_totp = current_context.totp_codes.get(cache_key)
@@ -2063,9 +2070,31 @@ async def _handle_multi_field_totp_sequence(
if not totp:
raise ValueError("Invalid TOTP secret or otpauth URI")
- # Get current time and calculate TOTP expiry
+ cached_valid_from = current_context.totp_codes.get(valid_from_key)
+ cached_valid_until = current_context.totp_codes.get(valid_until_key)
+ if not cached_valid_from or not cached_valid_until:
+ LOG.error(
+ "TOTP cache metadata missing for subsequent digit",
+ action_idx=action_index,
+ cache_key=cache_key,
+ )
+ return [ActionFailure(TOTPExpiredError())]
+
+ try:
+ totp_valid_from = int(cached_valid_from)
+ totp_valid_until = int(cached_valid_until)
+ except ValueError:
+ LOG.error(
+ "TOTP cache metadata invalid for subsequent digit",
+ action_idx=action_index,
+ cache_key=cache_key,
+ cached_valid_from=cached_valid_from,
+ cached_valid_until=cached_valid_until,
+ )
+ return [ActionFailure(TOTPExpiredError())]
+
+ # Get current time and check against the cached TOTP window.
current_time = int(time.time())
- totp_valid_until = ((current_time // totp.interval) + 1) * totp.interval
if current_time >= totp_valid_until:
LOG.error(
@@ -2087,10 +2116,6 @@ async def _handle_multi_field_totp_sequence(
# Special handling for the 6th digit (action_index=5): wait if TOTP is not yet valid
if action_index == 5:
- # Calculate when this TOTP becomes valid (valid_from time)
- # If we used the next TOTP window, valid_from is the start of that window
- totp_valid_from = totp_valid_until - totp.interval
-
if current_time < totp_valid_from:
# TOTP is not yet valid, wait until it becomes valid
wait_seconds = totp_valid_from - current_time
diff --git a/tests/unit/test_bitwarden_null_credentials.py b/tests/unit/test_bitwarden_null_credentials.py
index 4311f2ad5..e8b603001 100644
--- a/tests/unit/test_bitwarden_null_credentials.py
+++ b/tests/unit/test_bitwarden_null_credentials.py
@@ -147,6 +147,37 @@ async def test_get_secret_value_by_item_id_preserves_real_values(
assert result[BitwardenConstants.TOTP] == ""
+async def test_get_secret_value_by_item_id_preserves_raw_totp_uri(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ totp_uri = "otpauth://totp/[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example"
+ item_payload = {
+ "id": "55555555-5555-5555-5555-555555555555",
+ "login": {
+ "username": "[email protected]",
+ "password": "hunter2",
+ "totp": totp_uri,
+ },
+ }
+
+ async def fake_run_command(command: list[str], **_: object) -> RunCommandResult:
+ return RunCommandResult(stdout=json.dumps(item_payload), stderr="", returncode=0)
+
+ monkeypatch.setattr(BitwardenService, "run_command", fake_run_command)
+
+ result = await BitwardenService.get_secret_value_from_url(
+ client_id="client-id",
+ client_secret="client-secret",
+ master_password="master-password",
+ bw_organization_id="org-id",
+ bw_collection_ids=None,
+ item_id="55555555-5555-5555-5555-555555555555",
+ )
+
+ assert result[BitwardenConstants.TOTP] == totp_uri
+
+
@pytest.mark.asyncio
async def test_get_credit_card_data_includes_billing_custom_fields(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.py
index 6413ac5a6..577ed6413 100644
--- a/tests/unit/test_copilot_fill_credential_field.py
+++ b/tests/unit/test_copilot_fill_credential_field.py
@@ -116,6 +116,12 @@ class TestResolveCredentialFillValue:
monkeypatch.setattr(
app_instance, "CREDENTIAL_VAULT_SERVICES", {CredentialVaultType.BITWARDEN: vault}, raising=False
)
+ monkeypatch.setattr(
+ app_instance,
+ "AGENT_FUNCTION",
+ SimpleNamespace(parse_enterprise_totp_secret=AsyncMock(return_value=None)),
+ raising=False,
+ )
@pytest.mark.asyncio
async def test_resolves_username_and_password(self, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/test_credential_totp_code.py b/tests/unit/test_credential_totp_code.py
index 911b995ba..ce307216b 100644
--- a/tests/unit/test_credential_totp_code.py
+++ b/tests/unit/test_credential_totp_code.py
@@ -1,5 +1,6 @@
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
+from urllib.parse import quote
import pyotp
import pytest
@@ -53,6 +54,11 @@ def _mock_totp_preview_dependencies(
)
mock_credentials = SimpleNamespace(get_credential=AsyncMock(return_value=db_credential))
monkeypatch.setattr(credentials.app, "DATABASE", SimpleNamespace(credentials=mock_credentials))
+ monkeypatch.setattr(
+ credentials.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(parse_enterprise_totp_secret=AsyncMock(return_value=None)),
+ )
monkeypatch.setattr(credentials, "_get_credential_vault_service", AsyncMock(return_value=vault_service))
return db_credential, vault_service, mock_credentials
@@ -112,6 +118,23 @@ def test_authenticator_totp_validation_preserves_uri_configuration() -> None:
assert credential.totp == totp_uri
+def test_authenticator_totp_validation_preserves_decoded_uri_configuration() -> None:
+ totp_uri = (
+ "otpauth://totp/Example:[email protected]"
+ "?secret=JBSWY3DPEHPK3PXP&issuer=Example&algorithm=SHA256&digits=8&period=60"
+ )
+ credential = NonEmptyPasswordCredential(
+ username="[email protected]",
+ password="pw",
+ totp=quote(totp_uri, safe=""),
+ totp_type=TotpType.AUTHENTICATOR,
+ )
+
+ credentials._normalize_authenticator_totp_or_raise(credential)
+
+ assert credential.totp == totp_uri
+
+
def test_authenticator_totp_validation_normalizes_raw_secret() -> None:
credential = NonEmptyPasswordCredential(
username="[email protected]",
diff --git a/tests/unit/test_multi_field_totp.py b/tests/unit/test_multi_field_totp.py
index d0f33eeb7..b357d24ec 100644
--- a/tests/unit/test_multi_field_totp.py
+++ b/tests/unit/test_multi_field_totp.py
@@ -1,5 +1,6 @@
"""Tests for multi-field TOTP support in script generation."""
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -7,6 +8,21 @@ import pytest
from skyvern.core.script_generations.generate_script import _annotate_multi_field_totp_sequence
from skyvern.core.script_generations.script_skyvern_page import ScriptSkyvernPage
from skyvern.webeye.actions.action_types import ActionType
+from skyvern.webeye.actions.handler import _handle_multi_field_totp_sequence
+
+
+class _FakeTotp:
+ interval = 45
+
+ def __init__(self) -> None:
+ self.at_values: list[int] = []
+
+ def at(self, value: int) -> str:
+ self.at_values.append(value)
+ return f"code-at-{value}"
+
+ def now(self) -> str:
+ return "current-code"
class TestAnnotateMultiFieldTotpSequence:
@@ -29,6 +45,44 @@ class TestAnnotateMultiFieldTotpSequence:
for action in result:
assert "totp_timing_info" not in action
+
+class TestHandleMultiFieldTotpSequence:
+ @pytest.mark.asyncio
+ async def test_next_window_cache_uses_parsed_interval_for_later_digit_wait(self) -> None:
+ context = SimpleNamespace(totp_codes={})
+ fake_totp = _FakeTotp()
+ task = SimpleNamespace(task_id="task_1")
+
+ with (
+ patch("skyvern.webeye.actions.handler.skyvern_context.ensure_context", return_value=context),
+ patch("skyvern.webeye.actions.handler.parse_totp_config", return_value=fake_totp),
+ patch("skyvern.webeye.actions.handler.time.time", return_value=44),
+ ):
+ result = await _handle_multi_field_totp_sequence(
+ {"action_index": 0, "totp_secret": "otpauth://totp/example?secret=abc"},
+ task,
+ )
+
+ assert result is None
+ assert fake_totp.at_values == [45]
+ assert context.totp_codes["task_1_totp_cache"] == "code-at-45"
+ assert context.totp_codes["task_1_totp_cache_valid_from"] == "45"
+ assert context.totp_codes["task_1_totp_cache_valid_until"] == "90"
+
+ with (
+ patch("skyvern.webeye.actions.handler.skyvern_context.ensure_context", return_value=context),
+ patch("skyvern.webeye.actions.handler.parse_totp_config", return_value=fake_totp),
+ patch("skyvern.webeye.actions.handler.time.time", return_value=44),
+ patch("skyvern.webeye.actions.handler.asyncio.sleep", new_callable=AsyncMock) as sleep_mock,
+ ):
+ result = await _handle_multi_field_totp_sequence(
+ {"action_index": 5, "totp_secret": "otpauth://totp/example?secret=abc"},
+ task,
+ )
+
+ assert result is None
+ sleep_mock.assert_awaited_once_with(1)
+
def test_4_digit_sequence_gets_annotated(self) -> None:
"""4 consecutive single-digit inputs with same field_name get annotated."""
actions = [
diff --git a/tests/unit/test_parse_totp_secret.py b/tests/unit/test_parse_totp_secret.py
index c02ea77b9..e9d8bf5b9 100644
--- a/tests/unit/test_parse_totp_secret.py
+++ b/tests/unit/test_parse_totp_secret.py
@@ -1,3 +1,5 @@
+from urllib.parse import quote
+
import pyotp
from skyvern.forge.sdk.services.credentials import generate_totp_code, normalize_totp_config, parse_totp_secret
@@ -45,6 +47,29 @@ def test_generate_totp_code_uses_otpauth_uri_params() -> None:
assert len(generate_totp_code(uri, for_time=0)) == 8
+def test_normalize_totp_config_preserves_url_encoded_otpauth_uri() -> None:
+ uri = (
+ "otpauth://totp/Example:[email protected]"
+ "?secret=JBSWY3DPEHPK3PXP&issuer=Example&algorithm=SHA256&digits=8&period=60"
+ )
+
+ assert normalize_totp_config(quote(uri, safe="")) == uri
+
+
+def test_otpauth_uri_with_unsupported_algorithm_returns_empty() -> None:
+ uri = "otpauth://totp/[email protected]?secret=JBSWY3DPEHPK3PXP&algorithm=NOPE&digits=8&period=45"
+
+ assert parse_totp_secret(uri) == ""
+ assert normalize_totp_config(uri) == ""
+
+
+def test_url_encoded_otpauth_uri_with_unsupported_algorithm_returns_empty() -> None:
+ uri = "otpauth://totp/[email protected]?secret=JBSWY3DPEHPK3PXP&algorithm=NOPE&digits=8&period=45"
+
+ assert parse_totp_secret(quote(uri, safe="")) == ""
+ assert normalize_totp_config(quote(uri, safe="")) == ""
+
+
def test_regex_extraction_valid_secret() -> None:
value = "https://example.com?secret=JBSWY3DPEHPK3PXP&other=stuff"
result = parse_totp_secret(value)
diff --git a/tests/unit/test_totp_identifier_fallback.py b/tests/unit/test_totp_identifier_fallback.py
index 40d3c531d..673de895b 100644
--- a/tests/unit/test_totp_identifier_fallback.py
+++ b/tests/unit/test_totp_identifier_fallback.py
@@ -1,4 +1,5 @@
from types import SimpleNamespace
+from unittest.mock import AsyncMock
import pytest
@@ -52,6 +53,7 @@ async def test_register_credential_parameter_uses_db_totp_identifier(monkeypatch
fake_app = SimpleNamespace(
DATABASE=FakeDatabase(),
CREDENTIAL_VAULT_SERVICES={CredentialVaultType.BITWARDEN: FakeCredentialService()},
+ AGENT_FUNCTION=SimpleNamespace(parse_enterprise_totp_secret=AsyncMock(return_value=None)),
)
monkeypatch.setattr(cm, "app", fake_app)
@@ -98,6 +100,7 @@ async def _register_with_credential(monkeypatch: pytest.MonkeyPatch, credential:
fake_app = SimpleNamespace(
DATABASE=FakeDatabase(),
CREDENTIAL_VAULT_SERVICES={CredentialVaultType.BITWARDEN: FakeCredentialService()},
+ AGENT_FUNCTION=SimpleNamespace(parse_enterprise_totp_secret=AsyncMock(return_value=None)),
)
monkeypatch.setattr(cm, "app", fake_app)