-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmain.py
More file actions
118 lines (100 loc) · 3.82 KB
/
Copy pathmain.py
File metadata and controls
118 lines (100 loc) · 3.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""Complete a live RFC 6238 TOTP challenge with Stagehand V4."""
import asyncio
import base64
import hashlib
import hmac
import os
import struct
import time
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from stagehand import Page, Stagehand, browserbase
load_dotenv()
DEMO_URL = "https://authenticationtest.com/totpChallenge/"
class Credentials(BaseModel):
email: str
password: str
totp_secret: str = Field(description="TOTP secret key shown by the demo")
class AuthResult(BaseModel):
success: bool
message: str
def generate_totp(secret: str, window: int = 0) -> str:
normalized = secret.upper().replace(" ", "").rstrip("=")
padding = "=" * ((8 - len(normalized) % 8) % 8)
key = base64.b32decode(normalized + padding)
counter = int(time.time() // 30) + window
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
code = struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF
return str(code % 1_000_000).zfill(6)
async def submit(stagehand: Stagehand, page: Page, credentials: Credentials) -> None:
await stagehand.act(
"Fill the email field with %email%",
page=page,
variables={"email": credentials.email},
)
await stagehand.act(
"Fill the password field with %password%",
page=page,
variables={"password": credentials.password},
)
seconds_left = 30 - int(time.time()) % 30
if seconds_left < 12:
await asyncio.sleep(seconds_left + 1)
code = generate_totp(credentials.totp_secret)
await stagehand.act(
"Fill the TOTP code field with %code%",
page=page,
variables={"code": code},
)
await stagehand.act("Click the submit or login button", page=page)
async def main() -> None:
api_key = os.environ.get("BROWSERBASE_API_KEY")
if not api_key:
raise RuntimeError("BROWSERBASE_API_KEY is required")
browser = await browserbase.launch(api_key=api_key)
try:
stagehand = await Stagehand.create(
browser=browser,
)
try:
pages = await browser.context.pages()
page = pages[0] if pages else await browser.context.new_page()
await page.goto(DEMO_URL, wait_until="domcontentloaded", timeout=60_000)
extracted = await stagehand.extract(
"Extract the test email, password, and TOTP secret shown on the page",
Credentials,
page=page,
)
credentials = extracted.data
await submit(stagehand, page, credentials)
await page.wait_for_timeout(1_000)
result = await stagehand.extract(
"Check whether the TOTP login succeeded and return its message",
AuthResult,
page=page,
)
if not result.data.success:
await page.goto(DEMO_URL, wait_until="domcontentloaded")
await submit(stagehand, page, credentials)
await page.wait_for_timeout(1_000)
result = await stagehand.extract(
"Check whether the TOTP login succeeded and return its message",
AuthResult,
page=page,
)
if not result.data.success:
raise RuntimeError(f"TOTP authentication failed: {result.data.message}")
print(f"TOTP authentication succeeded: {result.data.message}")
finally:
await stagehand.close()
finally:
await browser.close()
print("Session closed successfully")
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as error:
print(f"TOTP example failed: {error}")
print("Docs: https://docs.stagehand.dev/v4/first-steps/introduction")
raise