Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,30 @@ Create a `tokens.json` file:

The library automatically refreshes tokens when they expire (every 30 minutes). Both tokens rotate on each refresh - the library handles this automatically and notifies via callback.

### Cloudflare "Access Denied" (HTML 403) on every request

Dominion's API host is behind Cloudflare bot protection. From some networks every
request made with Python's default TLS stack is answered with an HTML
`!! Error !! Access Denied` page (HTTP 403), even unauthenticated ones, so both
`login` and token refresh fail. Requests sent with a browser TLS fingerprint get
through. Install the optional `curl_cffi` backend and enable it:

```bash
pip install "dompower[browser]"
dompower --browser-tls --token-file tokens.json accounts
# or: export DOMPOWER_BROWSER_TLS=1
```

Library users can pass `dompower.BrowserSession()` anywhere an
`aiohttp.ClientSession` is expected:

```python
from dompower import BrowserSession, DompowerClient

async with BrowserSession() as session:
client = DompowerClient(session, access_token=..., refresh_token=...)
```

## CLI Usage

### Get Usage Data
Expand Down
2 changes: 2 additions & 0 deletions dompower/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"""

from .auth import TokenManager, TokenUpdateCallback
from .browser_session import BrowserSession
from .client import DompowerClient
from .const import LOGIN_URL
from .exceptions import (
Expand Down Expand Up @@ -74,6 +75,7 @@
"BillPeriodData",
"BillingData",
"BrowserAuthRequiredError",
"BrowserSession",
"CannotConnectError",
"CustomerInfo",
"DompowerClient",
Expand Down
40 changes: 33 additions & 7 deletions dompower/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
import asyncio
import json
import logging
import os
import sys
from datetime import date, timedelta
from pathlib import Path
from typing import Any

import aiohttp

Expand Down Expand Up @@ -66,6 +68,18 @@ def parse_args() -> argparse.Namespace:
help="Increase verbosity (use -vv for debug)",
)

parser.add_argument(
"--browser-tls",
action="store_true",
default=os.environ.get("DOMPOWER_BROWSER_TLS", "") not in ("", "0", "false"),
help=(
"Send requests with a browser TLS fingerprint via curl_cffi "
"(requires 'pip install dompower[browser]'). Use this if Dominion's "
"API answers every request with an HTML 'Access Denied' 403. "
"Also enabled by DOMPOWER_BROWSER_TLS=1."
),
)

subparsers = parser.add_subparsers(dest="command", required=True)

# Usage command
Expand Down Expand Up @@ -215,6 +229,18 @@ def parse_args() -> argparse.Namespace:
return parser.parse_args()


def create_session(args: argparse.Namespace) -> Any:
"""Build the HTTP session for a command (aiohttp, or curl_cffi with
--browser-tls). Returned as Any: BrowserSession mirrors the ClientSession
surface dompower uses but is not a subclass.
"""
if getattr(args, "browser_tls", False):
from .browser_session import BrowserSession

return BrowserSession()
return aiohttp.ClientSession()


def load_tokens(token_file: Path) -> dict[str, str | None]:
"""Load tokens from JSON file."""
if not token_file.exists():
Expand Down Expand Up @@ -333,7 +359,7 @@ def token_callback(access: str, refresh: str) -> None:
save_tokens(args.token_file, access, refresh)
logging.info("Tokens updated and saved to %s", args.token_file)

async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
client = DompowerClient(
session,
access_token=tokens["access_token"],
Expand Down Expand Up @@ -402,7 +428,7 @@ async def cmd_refresh(args: argparse.Namespace) -> int:
def token_callback(access: str, refresh: str) -> None:
save_tokens(args.token_file, access, refresh)

async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
client = DompowerClient(
session,
access_token=tokens["access_token"],
Expand Down Expand Up @@ -516,7 +542,7 @@ async def cmd_auth_helper(args: argparse.Namespace) -> int:
print("Validating tokens...")

try:
async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
client = DompowerClient(
session,
access_token=access_token,
Expand Down Expand Up @@ -581,7 +607,7 @@ async def cmd_login(args: argparse.Namespace) -> int:
print("Logging in...")

try:
async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
auth = GigyaAuthenticator(session, cookie_file=cookie_file)

# Load existing cookies (may bypass TFA)
Expand Down Expand Up @@ -701,7 +727,7 @@ def token_callback(access: str, refresh: str) -> None:
save_tokens(args.token_file, access, refresh)
logging.info("Tokens updated and saved to %s", args.token_file)

async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
client = DompowerClient(
session,
access_token=tokens["access_token"],
Expand Down Expand Up @@ -792,7 +818,7 @@ def token_callback(access: str, refresh: str) -> None:
save_tokens(args.token_file, access, refresh)
logging.info("Tokens updated and saved to %s", args.token_file)

async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
client = DompowerClient(
session,
access_token=tokens["access_token"],
Expand Down Expand Up @@ -905,7 +931,7 @@ def token_callback(access: str, refresh: str) -> None:
save_tokens(args.token_file, access, refresh)
logging.info("Tokens updated and saved to %s", args.token_file)

async with aiohttp.ClientSession() as session:
async with create_session(args) as session:
client = DompowerClient(
session,
access_token=tokens["access_token"],
Expand Down
140 changes: 140 additions & 0 deletions dompower/browser_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""aiohttp-compatible session backed by curl_cffi with a browser TLS fingerprint.

Dominion's API host (prodsvc-dominioncip.smartcmobile.com) sits behind
Cloudflare bot protection. From some networks every request made with
Python's TLS stack, authenticated or not, gets an HTML "Access Denied" 403
(see https://github.com/YeomansIII/dompower/issues/4). The same requests
sent with a browser TLS fingerprint reach the API.

``BrowserSession`` exposes the subset of :class:`aiohttp.ClientSession` that
dompower uses (``request``/``get``/``post`` as async context managers, and
``cookie_jar``), backed by ``curl_cffi``. Install with ``pip install
"dompower[browser]"`` and pass it wherever a ``ClientSession`` is expected::

async with BrowserSession() as session:
client = DompowerClient(session, access_token=..., refresh_token=...)
"""

from __future__ import annotations

import json
from collections.abc import AsyncIterator, Iterator
from contextlib import asynccontextmanager
from typing import Any

DEFAULT_IMPERSONATE = "chrome"


class BrowserCookie:
"""Minimal stand-in for aiohttp's Morsel: ``key``, ``value`` and attributes."""

def __init__(self, cookie: Any) -> None:
self.key: str = cookie.name
self.value: str = cookie.value
self._attrs: dict[str, str] = {
"domain": cookie.domain or "",
"path": cookie.path or "/",
}

def get(self, name: str, default: Any = None) -> Any:
return self._attrs.get(name, default)

def __getitem__(self, name: str) -> str:
return self._attrs[name]


class BrowserCookieJar:
"""The parts of aiohttp's CookieJar that GigyaAuthenticator relies on."""

def __init__(self, session: Any) -> None:
self._session = session

def __iter__(self) -> Iterator[BrowserCookie]:
return (BrowserCookie(c) for c in list(self._session.cookies.jar))

def update_cookies(self, cookies: dict[str, str], response_url: Any = None) -> None:
# Cookies set without a domain are sent to whichever host is requested,
# matching aiohttp's behaviour for update_cookies() without a URL.
for name, value in cookies.items():
self._session.cookies.set(name, value)


class BrowserResponse:
"""Adapts a curl_cffi Response to the aiohttp ClientResponse surface used."""

def __init__(self, response: Any) -> None:
self._response = response
self.status: int = response.status_code
self.headers: Any = response.headers
self.url: Any = response.url

async def text(self) -> str:
return str(self._response.text)

async def json(self, content_type: str | None = None, **_: Any) -> Any:
try:
return self._response.json()
except ValueError:
return json.loads(self._response.text)

async def read(self) -> bytes:
return bytes(self._response.content)


class BrowserSession:
"""Drop-in replacement for ``aiohttp.ClientSession`` as used by dompower.

Args:
impersonate: curl_cffi browser profile (e.g. ``"chrome"``,
``"safari"``). Defaults to the latest Chrome profile.
session: Pre-built ``curl_cffi.requests.AsyncSession``; mainly for
tests. When omitted one is created with ``impersonate``.
"""

def __init__(
self,
impersonate: str = DEFAULT_IMPERSONATE,
*,
session: Any | None = None,
) -> None:
if session is None:
try:
from curl_cffi.requests import ( # type: ignore[import-not-found]
AsyncSession,
)
except ImportError as err: # pragma: no cover - import guard
raise ImportError(
"BrowserSession requires curl_cffi; install with "
'"pip install dompower[browser]"'
) from err
session = AsyncSession(impersonate=impersonate)
self._session = session
self.cookie_jar = BrowserCookieJar(session)

async def __aenter__(self) -> BrowserSession:
return self

async def __aexit__(self, *exc: object) -> None:
await self.close()

async def close(self) -> None:
await self._session.close()

def request(self, method: str, url: str, **kwargs: Any) -> Any:
# aiohttp-only options that curl_cffi does not understand.
kwargs.pop("ssl", None)
kwargs.pop("proxy", None)
return self._request_cm(method.upper(), url, kwargs)

def get(self, url: str, **kwargs: Any) -> Any:
return self.request("GET", url, **kwargs)

def post(self, url: str, **kwargs: Any) -> Any:
return self.request("POST", url, **kwargs)

@asynccontextmanager
async def _request_cm(
self, method: str, url: str, kwargs: dict[str, Any]
) -> AsyncIterator[BrowserResponse]:
response = await self._session.request(method, url, **kwargs)
yield BrowserResponse(response)
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ dependencies = [
]

[project.optional-dependencies]
browser = [
"curl_cffi>=0.7.0",
]
dev = [
"pytest>=8.3.0",
"pytest-asyncio>=0.24.0",
Expand Down
Loading