-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdriver.py
More file actions
722 lines (615 loc) · 33.1 KB
/
Copy pathdriver.py
File metadata and controls
722 lines (615 loc) · 33.1 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
import os
import logging
import asyncio
from typing import Optional
from playwright.async_api import async_playwright, Playwright, BrowserContext, Page
from boundier.config import BoundierConfig
from boundier.chatgpt.selectors import ChatGPTSelectors, load_selectors
logger = logging.getLogger("boundier.driver")
class PlaywrightDriver:
def __init__(self, config: BoundierConfig):
self.config = config
self.selectors: ChatGPTSelectors = load_selectors()
self.playwright: Optional[Playwright] = None
self.context: Optional[BrowserContext] = None
self.page: Optional[Page] = None
self._session_verified = False
self._last_gist_sync_time = 0.0
self._gist_sync_lock = asyncio.Lock()
self._lease_lock = asyncio.Lock()
async def start(self):
"""Initializes Playwright, loads/launches Chromium context with persistent configuration."""
logger.info("Starting Playwright driver for ChatGPT...")
self.playwright = await async_playwright().start()
user_data_dir = os.path.abspath(self.config.playwright.user_data_dir)
os.makedirs(user_data_dir, exist_ok=True)
viewport_dims = {
"width": self.config.playwright.viewport.width,
"height": self.config.playwright.viewport.height
}
locale = "en-US"
extra_headers = {
"accept-language": "en-US,en;q=0.9"
}
# Load persistent storage state from Gist, local storage_state.json, or environment variable if present
storage_state_str = None
if os.environ.get("GITHUB_PAT") and os.environ.get("ENCRYPTION_KEY"):
storage_state_str = await self._load_gist_session_state()
if not storage_state_str and os.path.exists("storage_state.json"):
try:
with open("storage_state.json", "r", encoding="utf-8") as f:
storage_state_str = f.read()
logger.info("Sync: Loaded persistent session state from local 'storage_state.json'.")
except Exception as e:
logger.warning(f"Failed to read local storage_state.json: {e}")
if not storage_state_str:
storage_state_str = os.environ.get("CHATGPT_STORAGE_STATE")
logger.info(f"Launching Chromium context. Profile dir: '{user_data_dir}', Headless: {self.config.playwright.headless}")
args = [
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--no-first-run",
"--disable-features=Translate,OptimizationHints,BackForwardCache,MediaRouter",
"--disable-infobars"
]
try:
self.context = await self.playwright.chromium.launch_persistent_context(
user_data_dir=user_data_dir,
headless=self.config.playwright.headless,
viewport=viewport_dims,
locale=locale,
extra_http_headers=extra_headers,
args=args
)
except Exception as launch_err:
logger.warning(f"Error launching Chromium with profile directory '{user_data_dir}' ({launch_err}). Resetting profile directory for Chromium compatibility...")
import shutil
if os.path.exists(user_data_dir):
try:
shutil.rmtree(user_data_dir, ignore_errors=True)
except Exception as rmtree_err:
logger.warning(f"Failed to clear profile directory: {rmtree_err}")
self.context = await self.playwright.chromium.launch_persistent_context(
user_data_dir=user_data_dir,
headless=self.config.playwright.headless,
viewport=viewport_dims,
locale=locale,
extra_http_headers=extra_headers,
args=args
)
self.context.set_default_timeout(self.config.playwright.timeout_ms)
# Block only telemetry/ad tracking endpoints to save bandwidth without affecting UI rendering speed
async def route_intercept(route):
req = route.request
url_lower = req.url.lower()
blocked_patterns = [
"sentry.io",
"datadoghq",
"google-analytics.com",
"mixpanel.com",
"segment.io",
"amplitude",
"hotjar",
"browser-intake",
"doubleclick.net",
"googleadservices.com",
"browser-intake-datadoghq.com"
]
if any(pattern in url_lower for pattern in blocked_patterns):
try:
await route.abort()
return
except Exception:
pass
try:
await route.continue_()
except Exception:
pass
await self.context.route("**/*", route_intercept)
# Add init script to remove webdriver trace and spoof Win32 platform and plugins for Cloudflare Turnstile stealth
init_script = """
const newProto = Object.getPrototypeOf(navigator);
try { delete newProto.webdriver; } catch(e) {}
try { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); } catch(e) {}
try { Object.defineProperty(navigator, 'platform', { get: () => 'Win32' }); } catch(e) {}
try { Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); } catch(e) {}
try { Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); } catch(e) {}
try { Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 1 }); } catch(e) {}
if (!window.chrome) {
window.chrome = { runtime: {} };
}
"""
await self.context.add_init_script(init_script)
# Inject session cookies into context
if storage_state_str:
try:
import json
state_dict = json.loads(storage_state_str)
cookies = []
if isinstance(state_dict, dict):
cookies = state_dict.get("cookies", [])
elif isinstance(state_dict, list):
cookies = state_dict
if isinstance(cookies, list) and cookies:
await self.context.add_cookies(cookies)
logger.info("Successfully injected session cookies into browser context.")
except Exception as e:
logger.error(f"Error restoring session cookies: {e}")
self._leased_pages = set()
pages = self.context.pages
if pages:
self.page = pages[0]
await self._setup_page(self.page)
else:
self.page = await self.create_new_page()
logger.info("Playwright driver initialized successfully.")
async def _setup_page(self, page: Page):
"""Sets up console handlers, pageerror handlers, and blocks tracking/telemetry on the page."""
page.on("console", lambda msg: logger.info(f"BROWSER CONSOLE: [{msg.type}] {msg.text}"))
page.on("pageerror", lambda err: logger.error(f"BROWSER EXCEPTION: {err}"))
# Block telemetry, ads, and tracking resources to save RAM and network overhead
blocked_domains = [
"sentry.io",
"datadoghq",
"google-analytics.com",
"mixpanel.com",
"segment.io",
"amplitude",
"hotjar",
"browser-intake",
"doubleclick.net",
"googleadservices.com",
"browser-intake-datadoghq.com"
]
async def route_filter(route):
url = route.request.url.lower()
if any(domain in url for domain in blocked_domains):
await route.abort()
else:
await route.continue_()
await page.route("**/*", route_filter)
async def create_new_page(self) -> Page:
"""Helper to create and initialize a new page tab in the browser context."""
page = await self.context.new_page()
await self._setup_page(page)
return page
async def lease_page(self) -> Page:
"""Leases a page from the pool or opens a new tab if within max_pages limit."""
while True:
async with self._lease_lock:
if not hasattr(self, "_leased_pages"):
self._leased_pages = set()
# Clear closed pages from leased set
active_pages = self.context.pages
self._leased_pages = {p for p in self._leased_pages if p in active_pages}
# 1. Look for a currently idle page
for page in active_pages:
if page not in self._leased_pages:
self._leased_pages.add(page)
logger.info(f"Leased existing idle page/tab: {id(page)}")
use_count = getattr(page, "_use_count", 0) + 1
page._use_count = use_count
return page
# 2. Create a new tab if below max limit
max_pages = getattr(self.config.playwright, "max_pages", 3)
if len(active_pages) < max_pages:
new_page = await self.create_new_page()
self._leased_pages.add(new_page)
logger.info(f"Created and leased new browser page/tab: {id(new_page)} (Total tabs: {len(self.context.pages)})")
new_page._use_count = 1
return new_page
logger.info("Max browser pages reached. Waiting for an idle page/tab to become free...")
await asyncio.sleep(0.5)
async def release_page(self, page: Page):
"""Releases a page back to the pool, recycling it if the use limit is reached."""
should_restart = False
async with self._lease_lock:
if not hasattr(self, "_leased_pages"):
self._leased_pages = set()
if page in self._leased_pages:
self._leased_pages.remove(page)
use_count = getattr(page, "_use_count", 0)
if use_count >= 10: # Recycle tabs every 10 uses to avoid DOM bloating
logger.info(f"Tab {id(page)} reached use threshold ({use_count}/10). Closing...")
try:
await page.close()
except Exception as e:
logger.warning(f"Failed to close recycled page: {e}")
else:
logger.info(f"Released page/tab back to pool: {id(page)}")
try:
# Force V8 garbage collection to free unused JS memory heap back to the OS
await page.evaluate("window.gc && window.gc()")
logger.info(f"Triggered forced V8 garbage collection on tab: {id(page)}")
except Exception as e:
logger.warning(f"Failed to trigger V8 garbage collection: {e}")
if not hasattr(self, "_processed_requests"):
self._processed_requests = 0
self._processed_requests += 1
# Restart browser if requests count exceeds limit and no other pages are leased
if self._processed_requests >= 5 and len(self._leased_pages) == 0:
should_restart = True
self._processed_requests = 0
if should_restart:
logger.info("Processed threshold requests. Restarting browser context to purge memory...")
try:
await self.stop()
await self.start()
logger.info("Browser context restarted successfully. Memory purged.")
except Exception as restart_err:
logger.error(f"Failed to restart browser context: {restart_err}", exc_info=True)
async def stop(self):
"""Closes browser context and shuts down Playwright instance."""
logger.info("Stopping Playwright driver...")
if self.context:
await self.context.close()
self.context = None
if self.playwright:
await self.playwright.stop()
self.playwright = None
logger.info("Playwright driver stopped successfully.")
async def solve_turnstile_if_present(self, page: Page) -> bool:
"""Detects and clicks Cloudflare Turnstile checkbox if present on the page."""
# Rate-limit auto-click attempts to avoid spamming Cloudflare and invalidating human verification
now = asyncio.get_event_loop().time()
last_attempt = getattr(page, "_last_turnstile_attempt", 0.0)
if now - last_attempt < 5.0:
return False
page._last_turnstile_attempt = now
if getattr(page, "_turnstile_solved_count", 0) >= 5:
return False
try:
for frame in page.frames:
if "cloudflare" in frame.url or "challenges" in frame.url:
logger.info("Cloudflare Turnstile challenge detected in iframe! Attempting auto-solve...")
# Try direct element click first
checkbox = frame.locator('input[type="checkbox"], .cb-i, span.mark, label').first
if await checkbox.count() > 0 and await checkbox.is_visible():
await checkbox.click(force=True)
page._turnstile_solved_count = getattr(page, "_turnstile_solved_count", 0) + 1
logger.info(f"[SUCCESS] Clicked Cloudflare Turnstile checkbox! ({page._turnstile_solved_count}/5)")
return True
# Fallback: Click center-left of the iframe with human mouse movement
iframe_selectors = [
'iframe[src*="challenges.cloudflare.com"]',
'iframe[src*="cloudflare"]',
'iframe[src*="challenges"]'
]
for sel in iframe_selectors:
loc = page.locator(sel).first
if await loc.count() > 0 and await loc.is_visible():
box = await loc.bounding_box()
if box:
click_x = box["x"] + min(40, box["width"] / 2)
click_y = box["y"] + (box["height"] / 2)
await page.mouse.move(click_x, click_y, steps=5)
await page.mouse.click(click_x, click_y)
page._turnstile_solved_count = getattr(page, "_turnstile_solved_count", 0) + 1
logger.info(f"[SUCCESS] Clicked Turnstile bounding box! ({page._turnstile_solved_count}/5)")
return True
return False
except Exception as e:
logger.warning(f"Error checking/solving Cloudflare Turnstile challenge: {e}")
return False
async def check_session_active(self, navigate: bool = True) -> bool:
"""Checks if an active logged-in session exists on ChatGPT, optionally navigating first."""
if not self.page:
raise RuntimeError("PlaywrightDriver is not running. Call start() first.")
url = "https://chatgpt.com"
try:
if navigate and "chatgpt.com" not in self.page.url:
logger.info(f"Checking session status by loading: {url}")
await self.page.goto(url, wait_until="domcontentloaded", timeout=self.config.playwright.timeout_ms)
# Check redirect status
current_url = self.page.url
page_title = await self.page.title()
logger.info(f"Session check diagnostics - URL: {current_url} | Title: {page_title}")
# If on an authentication URL or redirect page, user is NOT logged in
auth_keywords = ["auth", "login", "callback", "google", "apple", "microsoft", "auth0"]
if any(kw in current_url.lower() for kw in auth_keywords) and "chatgpt.com/" not in current_url:
logger.warning(f"Session unverified: Redirected to landing page/login URL: {current_url}")
return False
has_input = False
has_profile = False
has_login = False
if current_url != "about:blank":
# Wait for page elements to hydrate (polling up to 120 seconds)
logger.info("Waiting for page elements to hydrate (polling up to 120 seconds)...")
import asyncio
start_wait = asyncio.get_event_loop().time()
while asyncio.get_event_loop().time() - start_wait < 120.0:
# Solve Turnstile challenge if present during hydration
await self.solve_turnstile_if_present(self.page)
chat_input = self.page.locator(self.selectors.chat_input).first
profile_btn = self.page.locator(self.selectors.profile_menu_button).first
login_btn = self.page.locator('[data-testid="login-button"], [data-testid="signup-button"], [data-testid="welcome-login-button"], button:has-text("Log in"), a:has-text("Log in"), button:has-text("Sign up"), a:has-text("Sign up"), a[href*="auth/login"], a[href*="login"]').first
has_input = (await chat_input.count() > 0) and (await chat_input.is_visible())
has_profile = (await profile_btn.count() > 0) and (await profile_btn.is_visible())
has_login = (await login_btn.count() > 0) and (await login_btn.is_visible())
# We have determined state if we see login button (definitely logged out)
if has_login:
break
# Or if we see profile button and login button is absent (definitely logged in)
if has_profile and not has_login:
break
await asyncio.sleep(1.0)
logger.info(f"Page elements checking complete. has_input={has_input}, has_profile={has_profile}, has_login={has_login}")
# Log post-hydration diagnostics
current_url = self.page.url
page_title = await self.page.title()
logger.info(f"Post-hydration diagnostics - URL: {current_url} | Title: {page_title}")
try:
text_content = await self.page.locator("body").text_content()
clean_text = text_content.strip()[:400].replace('\n', ' ')
logger.info(f"Page text content snippet: {clean_text}")
except Exception:
pass
# If a login/signup button is visible, the user is NOT authenticated
if has_login:
logger.warning("Session unverified: Login/Signup button is visible (user is logged out).")
return False
# Authentication requires user profile button AND absence of login buttons
# (Note: has_input is NOT used as indicator because guest users also see chat input)
if has_profile and not has_login:
logger.info("Session verified: User is authenticated (profile button found, login button absent).")
return True
logger.warning(f"Session unverified: chat_input_exists={has_input}, profile_exists={has_profile}, login_button_exists={has_login}")
try:
os.makedirs("logs/diagnostics", exist_ok=True)
await self.page.screenshot(path="logs/diagnostics/session_unverified.jpg", type="jpeg", quality=50)
logger.info("Saved diagnostics screenshot to logs/diagnostics/session_unverified.jpg")
except Exception as ss_err:
logger.warning(f"Failed to save unverified session screenshot: {ss_err}")
return False
except Exception as e:
logger.error(f"Error checking session status: {e}", exc_info=True)
return False
async def wait_for_manual_login(self, timeout_seconds: int = 300) -> bool:
"""Enters a polling loop waiting for the operator to log in manually via browser GUI."""
if self.config.playwright.headless:
logger.error("Cannot perform manual login loop in headless mode! Set headless=false in config.yaml")
return False
logger.warning(f"Awaiting manual login. You have {timeout_seconds} seconds to log in using the browser window...")
elapsed = 0
poll_interval = 2
consecutive_successes = 0
while elapsed < timeout_seconds:
# Crucial: Do NOT navigate/reload during polling to avoid interrupting the user's login typing!
is_active = await self.check_session_active(navigate=False)
if is_active:
consecutive_successes += 1
if consecutive_successes >= 2:
logger.info("Manual login verified (consecutive checks passed)! Resuming execution.")
return True
else:
consecutive_successes = 0
await asyncio.sleep(poll_interval)
elapsed += poll_interval
logger.error("Manual login wait period timed out.")
return False
def trigger_background_gist_sync(self):
import time
if time.time() - self._last_gist_sync_time > 86400:
logger.info("Triggering background Gist session sync...")
asyncio.create_task(self.save_gist_session_state())
async def ensure_authenticated(self, force: bool = False) -> bool:
"""Verifies session active status. If inactive, restarts in headed mode and polls for manual login."""
logger.info("Verifying ChatGPT session status...")
# Check current status without re-navigating
is_active = await self.check_session_active(navigate=False)
if is_active:
logger.info("Session is active. Proceeding.")
self._session_verified = True
self.trigger_background_gist_sync()
return True
# If not detected on active DOM, reload chatgpt.com once to be sure
is_active = await self.check_session_active(navigate=True)
if is_active:
logger.info("Session is active after page reload. Proceeding.")
self._session_verified = True
self.trigger_background_gist_sync()
return True
# Check if headless mode is forced/mandatory (e.g. running on Linux without DISPLAY)
import sys
if sys.platform != "win32" and "DISPLAY" not in os.environ:
logger.error("ChatGPT session is unauthenticated. Headless Linux environment detected: Cannot launch headed browser for manual authentication.")
logger.error("Please run the session exporter script locally: 'python -m tests.export_session'")
logger.error("Then add the output as the 'CHATGPT_STORAGE_STATE' environment variable in your Render dashboard to authenticate.")
return False
logger.warning("ChatGPT session has expired or is invalid. Relaunching in HEADED mode for manual authentication...")
# If running headless, we must stop and restart in headed mode
was_headless = self.config.playwright.headless
if was_headless:
logger.info("Temporarily switching headless configuration to False for authentication...")
self.config.playwright.headless = False
await self.stop()
await self.start()
# Navigate to login page
await self.page.goto("https://chatgpt.com", wait_until="domcontentloaded")
print("\n" + "="*80)
print("AUTHENTICATION REQUIRED:")
print("ChatGPT requires login. A Chromium window has been opened.")
print("Please log in manually using Google, email, or your preferred method.")
print("The bot will wait and automatically detect when you have successfully logged in.")
print("="*80 + "\n")
# Poll for active login
# Wait up to 300 seconds (5 minutes)
authenticated = await self.wait_for_manual_login(timeout_seconds=300)
if authenticated:
logger.info("Authentication successful!")
# Save storage state locally and to Gist on successful login
await self.save_session_state()
# If we temporarily switched to headed mode, restart in the user's configured mode
if was_headless:
logger.info("Re-applying headless mode config and restarting browser driver...")
self.config.playwright.headless = was_headless
await self.stop()
await self.start()
return True
else:
logger.error("Authentication failed or timed out.")
return False
def _get_fernet_key(self, passphrase: str) -> bytes:
import base64
import hashlib
key_hash = hashlib.sha256(passphrase.encode('utf-8')).digest()
return base64.urlsafe_b64encode(key_hash)
async def _load_gist_session_state(self) -> Optional[str]:
"""Loads and decrypts CHATGPT_STORAGE_STATE from a private GitHub Gist using GITHUB_PAT and ENCRYPTION_KEY."""
github_pat = os.environ.get("GITHUB_PAT")
encryption_key = os.environ.get("ENCRYPTION_KEY")
if not github_pat or not encryption_key:
return None
logger.info("Sync: GITHUB_PAT and ENCRYPTION_KEY detected. Looking for persistent session Gist...")
try:
import json
import urllib.request
import urllib.error
from cryptography.fernet import Fernet
# 1. Find the Gist ID
url = "https://api.github.com/gists"
headers = {
"Authorization": f"token {github_pat}",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Boundier-Bot"
}
req = urllib.request.Request(url, headers=headers)
loop = asyncio.get_running_loop()
def run_get():
try:
with urllib.request.urlopen(req) as res:
return json.loads(res.read().decode("utf-8"))
except Exception as err:
logger.warning(f"Error listing Gists: {err}")
return []
gists = await loop.run_in_executor(None, run_get)
raw_url = None
for gist in gists:
if "boundier_session.enc" in gist["files"]:
raw_url = gist["files"]["boundier_session.enc"]["raw_url"]
break
if not raw_url:
logger.info("Sync: No existing session Gist found. Will create a new one on successful login.")
return None
# 2. Fetch raw encrypted content
req_raw = urllib.request.Request(raw_url, headers=headers)
def run_get_raw():
try:
with urllib.request.urlopen(req_raw) as res:
return res.read().decode("utf-8")
except Exception as err:
logger.warning(f"Error fetching Gist file raw content: {err}")
return ""
encrypted_data = await loop.run_in_executor(None, run_get_raw)
if not encrypted_data:
return None
# 3. Decrypt
fernet_key = self._get_fernet_key(encryption_key)
fernet = Fernet(fernet_key)
decrypted_data = fernet.decrypt(encrypted_data.encode('utf-8')).decode('utf-8')
logger.info("Sync: Successfully loaded and decrypted persistent session from Gist.")
return decrypted_data
except Exception as e:
logger.warning(f"Sync: Failed to load persistent session from Gist: {e}")
return None
async def save_session_state(self):
"""Saves current browser storage state locally to 'storage_state.json' and syncs to Gist if configured."""
if not self.context:
return
try:
import json
state = await self.context.storage_state()
state_str = json.dumps(state, indent=2)
with open("storage_state.json", "w", encoding="utf-8") as f:
f.write(state_str)
logger.info("Sync: Saved persistent session state to local 'storage_state.json'.")
except Exception as e:
logger.warning(f"Failed to save local storage_state.json: {e}")
# Also trigger Gist sync if GITHUB_PAT is set
await self.save_gist_session_state()
async def save_gist_session_state(self):
"""Encrypts and pushes the current browser storage state to a private GitHub Gist."""
async with self._gist_sync_lock:
import time
if time.time() - self._last_gist_sync_time < 86000: # Keep a small margin
return
github_pat = os.environ.get("GITHUB_PAT")
encryption_key = os.environ.get("ENCRYPTION_KEY")
if not github_pat or not encryption_key or not self.context:
return
try:
import json
import urllib.request
from cryptography.fernet import Fernet
logger.info("Sync: Exporting and encrypting browser storage state to persist on Gist...")
state = await self.context.storage_state()
state_str = json.dumps(state)
fernet_key = self._get_fernet_key(encryption_key)
fernet = Fernet(fernet_key)
encrypted_data = fernet.encrypt(state_str.encode('utf-8')).decode('utf-8')
# 1. Find existing Gist
url_list = "https://api.github.com/gists"
headers = {
"Authorization": f"token {github_pat}",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Boundier-Bot"
}
loop = asyncio.get_running_loop()
def find_and_save():
# Find Gist ID
req = urllib.request.Request(url_list, headers=headers)
try:
with urllib.request.urlopen(req) as res:
gists = json.loads(res.read().decode("utf-8"))
except Exception as err:
logger.warning(f"Sync: Error listing Gists during save: {err}")
gists = []
gist_id = None
for gist in gists:
if "boundier_session.enc" in gist["files"]:
gist_id = gist["id"]
break
if gist_id:
# Update existing Gist
url_update = f"https://api.github.com/gists/{gist_id}"
data = {
"files": {
"boundier_session.enc": {
"content": encrypted_data
}
}
}
req_update = urllib.request.Request(
url_update,
headers=headers,
method="PATCH",
data=json.dumps(data).encode("utf-8")
)
with urllib.request.urlopen(req_update) as res:
res.read()
logger.info(f"Sync: Successfully updated existing session Gist: {gist_id}")
else:
# Create new Gist
url_create = "https://api.github.com/gists"
data = {
"description": "Boundier Bot Encrypted Session Storage State",
"public": False,
"files": {
"boundier_session.enc": {
"content": encrypted_data
}
}
}
req_create = urllib.request.Request(
url_create,
headers=headers,
method="POST",
data=json.dumps(data).encode("utf-8")
)
with urllib.request.urlopen(req_create) as res:
new_gist = json.loads(res.read().decode("utf-8"))
logger.info(f"Sync: Successfully created new private session Gist: {new_gist['id']}")
await loop.run_in_executor(None, find_and_save)
self._last_gist_sync_time = time.time()
except Exception as e:
logger.warning(f"Sync: Failed to save persistent session state to Gist: {e}")