Save and restore browser state (Cookies, LocalStorage, SessionStorage) to instantly skip login screens in Selenium automation.
Project description
๐ Selenium Teleport
Save and restore browser state (Cookies, LocalStorage, SessionStorage) to instantly skip login screens.
๐ The Problem
Automating checkouts or complex workflows is hard because logging in every time is slow and triggers bot detection.
Most developers try to save cookies, but it fails because:
- Missing Data: Modern sites use
LocalStorageandSessionStoragefor auth tokens, not just cookies. - Security Blocks: Trying to inject cookies into a blank tab (
data:,) fails due to the Same-Origin Policy. You can't set a cookie forexample.comwhile you are onabout:blank. - Bot Detection: Repeated logins flag your IP/Account as suspicious.
โ The Solution: Teleport
Selenium Teleport acts as a universal state bridge.
- Captures Everything: Saves Cookies, LocalStorage, and SessionStorage.
- Bypasses Security: Automatically navigates to the site's "Base Domain" first to satisfy the Same-Origin Policy.
- Injects & Teleports: Safely injects the state and "teleports" the browser to your destination URL, instantly authenticated.
sequenceDiagram
participant S as Script
participant B as Browser
participant F as State File
%% Save Flow
Note over S,F: ๐พ SAVE STATE
S->>B: Login manually or via script
S->>B: Extract Cookies + Local/Session Storage
B->>F: Save to JSON (or encrypted)
%% Restore Flow
Note over S,F: ๐ TELEPORT (Restore)
S->>B: Open New Browser
S->>F: Load JSON
S->>B: 1. Navigate to Base Domain (e.g. example.com)
Note right of B: Satisfies Same-Origin Policy
S->>B: 2. Inject Cookies + Storage
S->>B: 3. Navigate to Dashboard
Note right of B: โก User is instantly logged in!
โจ Features
Core Features
- Complete State Capture - Cookies, LocalStorage, SessionStorage, IndexedDB info
- Same-Origin Bypass - Navigates to base domain before injection
- Anti-Detection - Built-in undetected-chromedriver integration
- StealthBot Support - Full integration with sb-stealth-wrapper v0.4.0+
- Context Manager - Auto-save on successful exit
Security Features (v2.1.0)
- ๐ State Encryption - Encrypt state files using Fernet symmetric encryption
- โฐ Token Expiry Validation - Automatically detect and remove expired cookies
- ๐ Domain Validation - Prevent cross-domain state injection attacks
- ๐ก๏ธ Path Sanitization - Prevent path traversal attacks
- ๐ซ SSRF Protection - Block requests to private/internal IPs
Enterprise Features
- Configuration Management - Environment variables or config file based settings
- Modular Architecture - Clean separation of concerns for maintainability
- Comprehensive Exceptions - Detailed error hierarchy for proper handling
- GDPR Compliance - Secure state deletion functionality
๐ฆ Installation
# Basic installation
pip install selenium-teleport
# With stealth mode (Cloudflare bypass)
pip install selenium-teleport[stealth]
# With encryption support
pip install selenium-teleport[security]
# Full installation (all features)
pip install selenium-teleport[stealth,security]
๐ Quick Start
Standard Mode
from selenium_teleport import create_driver, Teleport
driver = create_driver(profile_path="my_profile")
with Teleport(driver, "session.json") as t:
if t.has_state():
t.load("https://example.com/dashboard")
else:
driver.get("https://example.com/login")
# Login manually...
driver.quit()
๏ฟฝ With Encryption
import os
from selenium_teleport import create_driver, Teleport, generate_key
# Generate a key once and store it securely
# key = generate_key()
# print(key) # Save this!
# Set encryption key via environment variable
os.environ["TELEPORT_ENCRYPTION_KEY"] = "your-fernet-key-here"
driver = create_driver()
with Teleport(driver, "session.enc", encrypt=True) as t:
if t.has_state():
t.load("https://example.com/dashboard")
else:
driver.get("https://example.com/login")
# Login...
driver.quit()
๐ก๏ธ Stealth Mode (sb-stealth-wrapper v0.4.0+)
For sites with bot detection (Cloudflare, DataDome, etc.):
from sb_stealth_wrapper import StealthBot
from selenium_teleport import save_state_stealth, load_state_stealth
import os
# Use success_criteria to confirm page is fully loaded
with StealthBot(success_criteria="Dashboard") as bot:
# Restore state if it exists
if os.path.exists("state.json"):
load_state_stealth(bot, "state.json", "https://example.com")
else:
bot.safe_get("https://example.com/login")
# Login using bot.smart_click(), etc.
# Save state for next time
save_state_stealth(bot, "state.json")
Or use create_driver with stealth mode:
from selenium_teleport import create_driver, save_state_stealth, load_state_stealth
with create_driver(use_stealth_wrapper=True, success_criteria="Welcome") as bot:
bot.safe_get("https://example.com")
# Your automation code...
๐ API Reference
State Management
| Function | Description |
|---|---|
save_state(driver, file_path, encrypt=False) |
Save Cookies, LocalStorage, SessionStorage to JSON |
load_state(driver, file_path, url, validate_expiry=True, validate_domain=True) |
Load state and navigate to URL with validation |
delete_state(file_path, secure=True) |
Securely delete state file (GDPR compliance) |
get_state_info(file_path) |
Get metadata about a state file |
Stealth Mode (sb-stealth-wrapper)
| Function | Description |
|---|---|
save_state_stealth(bot, file_path, encrypt=False) |
Save state using bot.sb methods |
load_state_stealth(bot, file_path, url, validate_expiry=True) |
Load state and navigate using bot.sb |
Context Managers
| Class/Function | Description |
|---|---|
Teleport(driver, file_path, auto_save=True, encrypt=False) |
Context manager with auto-save |
teleport_session(driver, file_path, destination_url=None) |
Functional context manager |
Security Functions
| Function | Description |
|---|---|
generate_key() |
Generate a new Fernet encryption key |
encrypt_state(state, key) |
Encrypt a state dictionary |
decrypt_state(data, key) |
Decrypt encrypted state data |
validate_domain_match(state_domain, target_url) |
Check if domains match |
remove_expired_cookies(cookies) |
Filter out expired cookies |
Configuration
| Function | Description |
|---|---|
TeleportConfig |
Configuration dataclass |
get_config() |
Get global configuration |
set_config(config) |
Set global configuration |
create_driver() Parameters
| Parameter | Default | Description |
|---|---|---|
profile_path |
"selenium_profile" |
Browser profile location |
headless |
False |
Headless mode (not recommended for stealth) |
browser |
"chrome" |
Browser to use ("chrome" or "edge") |
use_undetected |
True |
Use undetected-chromedriver |
use_stealth_wrapper |
False |
Use sb-stealth-wrapper |
success_criteria |
None |
(Stealth) Text confirming page is loaded |
proxy |
None |
(Stealth) Proxy in format user:pass@host:port |
โ๏ธ Configuration
Environment Variables
| Variable | Description |
|---|---|
TELEPORT_ENCRYPTION_KEY |
Fernet encryption key (enables encryption) |
TELEPORT_VALIDATE_EXPIRY |
"true" or "false" to validate cookie expiry |
TELEPORT_VALIDATE_DOMAIN |
"true" or "false" to validate domain match |
TELEPORT_LOG_LEVEL |
DEBUG, INFO, WARNING, ERROR |
TELEPORT_ALLOWED_DOMAINS |
Comma-separated whitelist of domains |
Programmatic Configuration
from selenium_teleport import TeleportConfig, set_config
config = TeleportConfig(
encryption_enabled=True,
encryption_key="your-key-here",
validate_expiry=True,
validate_domain=True,
log_level="INFO",
)
set_config(config)
๐จ Exception Handling
from selenium_teleport import (
TeleportError, # Base exception
SecurityError, # Security violations
DomainMismatchError, # State domain doesn't match target
PathTraversalError, # Path traversal attack detected
SSRFError, # SSRF attack detected
EncryptionError, # Encryption/decryption failed
StateError, # State file issues
StateFileNotFoundError, # State file doesn't exist
InvalidStateError, # Invalid state file format
ExpiredSessionError, # All cookies expired
DriverError, # Driver creation issues
)
try:
load_state(driver, "state.json", "https://example.com")
except DomainMismatchError as e:
print(f"Security: {e.message}")
except ExpiredSessionError:
print("Session expired, need to re-login")
except StateFileNotFoundError:
print("No saved state, performing fresh login")
โ ๏ธ Important Notes
- Standard mode: Uses
driver.get_cookies()/driver.execute_script() - Stealth mode: Uses
bot.sbmethods which maintain stable connection after challenge handling - Session persistence varies by site - Some sites use complex auth beyond cookies
- Encryption requires the
cryptographypackage - Install withpip install selenium-teleport[security] - State files contain sensitive tokens - Always use
.gitignoreto exclude them
๐งช Tested Sites
- โ Hacker News
- โ Reddit
- โ Gmail (with persistent profile)
- โ Various Cloudflare-protected sites (stealth mode)
๐ Project Structure
selenium_teleport/
โโโ __init__.py # Public API
โโโ drivers.py # Driver creation
โโโ state.py # State save/load
โโโ stealth.py # StealthBot integration
โโโ context.py # Context managers
โโโ security.py # Encryption & validation
โโโ config.py # Configuration
โโโ cookies.py # Cookie utilities
โโโ storage.py # Storage extraction
โโโ utils.py # URL helpers
โโโ exceptions.py # Exception hierarchy
๐จโ๐ป Author
Dhiraj Das - dhirajdas.dev
๐ License
MIT License - see LICENSE for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file selenium_teleport-2.1.0.tar.gz.
File metadata
- Download URL: selenium_teleport-2.1.0.tar.gz
- Upload date:
- Size: 35.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
147f1468050cb2bc9022a4dd0c3cc82a6a9450cfc241b7b927e9ede3c097a7f2
|
|
| MD5 |
27954e9c312bb6440fb7c2e2c5c59c33
|
|
| BLAKE2b-256 |
24493c9944d692de0424ff2bd495110a413fc16bc468c5b5654a9cbaa9c42823
|
File details
Details for the file selenium_teleport-2.1.0-py3-none-any.whl.
File metadata
- Download URL: selenium_teleport-2.1.0-py3-none-any.whl
- Upload date:
- Size: 35.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0ef0020ce3cb7e79a70ed2c0be1234442a3763ed7d27436b0ab6f0d308ca2279
|
|
| MD5 |
0f1588628c175ab7e1c5fbf2491cc688
|
|
| BLAKE2b-256 |
e3d98058fea14b77b6b83c3386838b655ddd144a7bfd9463c6d513913550143d
|