Skip to main content

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.

CI Python 3.8+ License: MIT Version

๐Ÿ›‘ 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:

  1. Missing Data: Modern sites use LocalStorage and SessionStorage for auth tokens, not just cookies.
  2. Security Blocks: Trying to inject cookies into a blank tab (data:,) fails due to the Same-Origin Policy. You can't set a cookie for example.com while you are on about:blank.
  3. Bot Detection: Repeated logins flag your IP/Account as suspicious.

โœ… The Solution: Teleport

Selenium Teleport acts as a universal state bridge.

  1. Captures Everything: Saves Cookies, LocalStorage, and SessionStorage.
  2. Bypasses Security: Automatically navigates to the site's "Base Domain" first to satisfy the Same-Origin Policy.
  3. 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

  1. Standard mode: Uses driver.get_cookies() / driver.execute_script()
  2. Stealth mode: Uses bot.sb methods which maintain stable connection after challenge handling
  3. Session persistence varies by site - Some sites use complex auth beyond cookies
  4. Encryption requires the cryptography package - Install with pip install selenium-teleport[security]
  5. State files contain sensitive tokens - Always use .gitignore to 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

selenium_teleport-2.1.0.tar.gz (35.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

selenium_teleport-2.1.0-py3-none-any.whl (35.7 kB view details)

Uploaded Python 3

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

Hashes for selenium_teleport-2.1.0.tar.gz
Algorithm Hash digest
SHA256 147f1468050cb2bc9022a4dd0c3cc82a6a9450cfc241b7b927e9ede3c097a7f2
MD5 27954e9c312bb6440fb7c2e2c5c59c33
BLAKE2b-256 24493c9944d692de0424ff2bd495110a413fc16bc468c5b5654a9cbaa9c42823

See more details on using hashes here.

File details

Details for the file selenium_teleport-2.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for selenium_teleport-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0ef0020ce3cb7e79a70ed2c0be1234442a3763ed7d27436b0ab6f0d308ca2279
MD5 0f1588628c175ab7e1c5fbf2491cc688
BLAKE2b-256 e3d98058fea14b77b6b83c3386838b655ddd144a7bfd9463c6d513913550143d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page