Replace reCAPTCHA auth with token-bootstrap flow

The Android reCAPTCHA Enterprise key cannot be used from any
non-Android context (browser, server, headless). Certificate
pinning prevents MITM token capture. Every approach to bypass
reCAPTCHA has been exhausted.

New approach: user provides UserId + RefreshToken (one-time
extraction from the PerfectDraft app via HTTP Toolkit or similar).
The integration validates by calling /auth/renewaccesstokens,
which does NOT require reCAPTCHA, then refreshes forever.

Changes:
- config_flow.py: two-step flow (email, then tokens), validates
  via refresh endpoint, reauth asks for fresh tokens
- api.py: refresh_access_token() calls /auth/renewaccesstokens
  with {UserId, RefreshToken}, removed authenticate() method,
  added x-api-key header to all authenticated requests
- const.py: added CONF_USER_ID, removed reCAPTCHA constants
- __init__.py: passes user_id to client.set_tokens()
- strings.json + translations: updated for new flow steps
- Deleted recaptcha.py and static/recaptcha.html
- test_harness.py: updated for refresh-based flow

Made-with: Cursor
This commit is contained in:
2026-04-12 12:26:12 +02:00
parent b383fdc20a
commit fcba32fecd
9 changed files with 194 additions and 506 deletions
+3 -1
View File
@@ -12,6 +12,7 @@ from .const import (
CONF_ACCESS_TOKEN,
CONF_ID_TOKEN,
CONF_REFRESH_TOKEN,
CONF_USER_ID,
DOMAIN,
PLATFORMS,
)
@@ -26,9 +27,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
client = PerfectDraftApiClient(session)
client.set_tokens(
access_token=entry.data[CONF_ACCESS_TOKEN],
access_token=entry.data.get(CONF_ACCESS_TOKEN),
id_token=entry.data.get(CONF_ID_TOKEN),
refresh_token=entry.data.get(CONF_REFRESH_TOKEN),
user_id=entry.data.get(CONF_USER_ID),
)
coordinator = PerfectDraftDataUpdateCoordinator(hass, client, entry)
+35 -56
View File
@@ -6,7 +6,7 @@ from typing import Any
import aiohttp
from .const import API_BASE_URL, API_KEY, RECAPTCHA_ACTION
from .const import API_BASE_URL, API_KEY
from .exceptions import (
AuthenticationError,
PerfectDraftApiError,
@@ -16,7 +16,6 @@ from .exceptions import (
_LOGGER = logging.getLogger(__name__)
class PerfectDraftApiClient:
"""Async client for api.perfectdraft.com."""
@@ -26,6 +25,7 @@ class PerfectDraftApiClient:
self._access_token: str | None = None
self._id_token: str | None = None
self._refresh_token: str | None = None
self._user_id: str | None = None
@property
def access_token(self) -> str | None:
@@ -35,80 +35,56 @@ class PerfectDraftApiClient:
def refresh_token(self) -> str | None:
return self._refresh_token
@property
def user_id(self) -> str | None:
return self._user_id
def set_tokens(
self,
access_token: str,
access_token: str | None = None,
id_token: str | None = None,
refresh_token: str | None = None,
user_id: str | None = None,
) -> None:
"""Restore tokens from persisted config entry data."""
self._access_token = access_token
if access_token is not None:
self._access_token = access_token
if id_token is not None:
self._id_token = id_token
if refresh_token is not None:
self._refresh_token = refresh_token
async def authenticate(
self, email: str, password: str, recaptcha_token: str
) -> dict[str, str]:
"""Sign in and return the token triple.
Returns dict with keys AccessToken, IdToken, RefreshToken.
"""
url = f"{self._base}/authentication/sign-in"
payload = {
"email": email,
"password": password,
"recaptchaToken": recaptcha_token,
"recaptchaAction": RECAPTCHA_ACTION,
}
headers = {"x-api-key": API_KEY}
try:
async with self._session.post(
url, json=payload, headers=headers
) as resp:
if resp.status == 401 or resp.status == 403:
body = await resp.text()
raise AuthenticationError(
f"Sign-in rejected ({resp.status}): {body}"
)
if resp.status != 200:
body = await resp.text()
raise PerfectDraftApiError(resp.status, body)
data = await resp.json()
except aiohttp.ClientError as exc:
raise PerfectDraftConnectionError(str(exc)) from exc
self._access_token = data["AccessToken"]
self._id_token = data["IdToken"]
self._refresh_token = data["RefreshToken"]
_LOGGER.debug("Authenticated successfully")
return data
if user_id is not None:
self._user_id = user_id
async def refresh_access_token(
self, refresh_token: str | None = None
) -> dict[str, str]:
"""Use the refresh token to obtain a new access token.
self,
user_id: str | None = None,
refresh_token: str | None = None,
) -> dict[str, Any]:
"""Refresh tokens via /auth/renewaccesstokens.
The exact endpoint is not yet confirmed; we try the most likely
candidates based on the API's Cognito-style token pattern.
This endpoint does NOT require reCAPTCHA.
"""
uid = user_id or self._user_id
token = refresh_token or self._refresh_token
if not token:
raise AuthenticationError("No refresh token available")
if not uid or not token:
raise AuthenticationError(
"UserId and RefreshToken are both required for token refresh"
)
url = f"{self._base}/authentication/refresh"
payload = {"refreshToken": token}
headers = {"x-api-key": API_KEY}
url = f"{self._base}/auth/renewaccesstokens"
payload = {"UserId": uid, "RefreshToken": token}
headers = {"x-api-key": API_KEY, "Content-Type": "application/json"}
try:
async with self._session.post(
url, json=payload, headers=headers
) as resp:
if resp.status in (401, 403):
raise AuthenticationError("Refresh token expired or invalid")
if resp.status in (400, 401, 403):
body = await resp.text()
raise AuthenticationError(
f"Token refresh failed ({resp.status}): {body}"
)
if resp.status != 200:
body = await resp.text()
raise PerfectDraftApiError(resp.status, body)
@@ -120,6 +96,7 @@ class PerfectDraftApiClient:
self._id_token = data.get("IdToken", self._id_token)
if "RefreshToken" in data:
self._refresh_token = data["RefreshToken"]
self._user_id = uid
_LOGGER.debug("Token refreshed successfully")
return data
@@ -130,7 +107,9 @@ class PerfectDraftApiClient:
"""Make an authenticated API request with automatic 401 retry."""
url = f"{self._base}{path}"
headers = kwargs.pop("headers", {})
headers["x-access-token"] = self._access_token or ""
headers["x-api-key"] = API_KEY
if self._access_token:
headers["x-access-token"] = self._access_token
try:
async with self._session.request(
+82 -179
View File
@@ -2,28 +2,23 @@
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
import aiohttp
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant, callback
from homeassistant.const import CONF_EMAIL
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
CONF_ACCESS_TOKEN,
CONF_ID_TOKEN,
CONF_MACHINE_ID,
CONF_REFRESH_TOKEN,
CONF_SCAN_INTERVAL,
CONF_USER_ID,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
MIN_SCAN_INTERVAL,
RECAPTCHA_ACTION,
RECAPTCHA_SITE_KEY,
)
from .exceptions import (
AuthenticationError,
@@ -34,83 +29,6 @@ from .api import PerfectDraftApiClient
_LOGGER = logging.getLogger(__name__)
RECAPTCHA_HTML_PATH = Path(__file__).parent / "static" / "recaptcha.html"
RECAPTCHA_CALLBACK_PATH = "/api/perfectdraft/recaptcha_callback"
RECAPTCHA_PAGE_PATH = "/api/perfectdraft/recaptcha"
_recaptcha_html_cache: str | None = None
def _get_recaptcha_html() -> str:
global _recaptcha_html_cache
if _recaptcha_html_cache is None:
raw = RECAPTCHA_HTML_PATH.read_text()
raw = raw.replace("RECAPTCHA_SITE_KEY", RECAPTCHA_SITE_KEY)
raw = raw.replace("RECAPTCHA_ACTION", RECAPTCHA_ACTION)
_recaptcha_html_cache = raw
return _recaptcha_html_cache
def _register_views(hass: HomeAssistant) -> None:
"""Register the reCAPTCHA views once."""
key = f"{DOMAIN}_views_registered"
if hass.data.get(key):
return
hass.http.register_view(RecaptchaPageView())
hass.http.register_view(RecaptchaCallbackView())
hass.data[key] = True
class RecaptchaPageView(HomeAssistantView):
"""Serve the reCAPTCHA HTML page."""
url = RECAPTCHA_PAGE_PATH
name = "api:perfectdraft:recaptcha"
requires_auth = False
async def get(self, request):
return aiohttp.web.Response(
text=_get_recaptcha_html(),
content_type="text/html",
)
class RecaptchaCallbackView(HomeAssistantView):
"""Receive the reCAPTCHA token from the browser and resume the config flow."""
url = RECAPTCHA_CALLBACK_PATH
name = "api:perfectdraft:recaptcha_callback"
requires_auth = False
async def post(self, request):
hass = request.app["hass"]
try:
data = await request.json()
except Exception:
return aiohttp.web.json_response(
{"error": "invalid body"}, status=400
)
flow_id = data.get("flow_id")
token = data.get("token")
if not flow_id or not token:
return aiohttp.web.json_response(
{"error": "missing flow_id or token"}, status=400
)
# Stash the token where the flow can find it, then signal "done"
hass.data.setdefault(f"{DOMAIN}_recaptcha_tokens", {})[flow_id] = token
try:
await hass.config_entries.flow.async_configure(flow_id)
except Exception:
_LOGGER.exception("Failed to resume config flow %s", flow_id)
return aiohttp.web.json_response(
{"error": "flow error"}, status=500
)
return aiohttp.web.json_response({"ok": True})
class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for PerfectDraft."""
@@ -119,97 +37,80 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
def __init__(self) -> None:
self._email: str | None = None
self._password: str | None = None
self._recaptcha_token: str | None = None
self._user_id: str | None = None
self._refresh_token: str | None = None
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Step 1: collect email and password."""
"""Step 1: collect email (for display/unique ID)."""
errors: dict[str, str] = {}
if user_input is not None:
self._email = user_input[CONF_EMAIL]
self._password = user_input[CONF_PASSWORD]
return await self.async_step_recaptcha()
return await self.async_step_tokens()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
}
),
errors=errors,
)
async def async_step_recaptcha(
async def async_step_tokens(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Step 2 (fallback): external step — open browser for reCAPTCHA."""
_register_views(self.hass)
"""Step 2: collect UserId and RefreshToken, validate via refresh."""
errors: dict[str, str] = {}
callback_url = f"{RECAPTCHA_CALLBACK_PATH}"
page_url = (
f"{RECAPTCHA_PAGE_PATH}"
f"?callback={callback_url}&flow_id={self.flow_id}"
)
if user_input is not None:
self._user_id = user_input[CONF_USER_ID].strip()
self._refresh_token = user_input[CONF_REFRESH_TOKEN].strip()
return self.async_external_step(step_id="recaptcha", url=page_url)
session = async_get_clientsession(self.hass)
client = PerfectDraftApiClient(session)
async def async_step_recaptcha_done(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Called automatically when the external reCAPTCHA step completes."""
tokens = self.hass.data.get(f"{DOMAIN}_recaptcha_tokens", {})
self._recaptcha_token = tokens.pop(self.flow_id, None)
try:
data = await client.refresh_access_token(
user_id=self._user_id,
refresh_token=self._refresh_token,
)
except AuthenticationError as err:
_LOGGER.error("Token validation failed: %s", err)
errors["base"] = "invalid_auth"
except PerfectDraftConnectionError as err:
_LOGGER.error("Connection failed: %s", err)
errors["base"] = "cannot_connect"
except PerfectDraftApiError as err:
_LOGGER.error("API error during validation: %s", err)
errors["base"] = "unknown"
else:
await self.async_set_unique_id(self._email.lower())
self._abort_if_unique_id_configured()
if not self._recaptcha_token:
return self.async_abort(reason="recaptcha_failed")
return self.async_create_entry(
title=f"PerfectDraft ({self._email})",
data={
CONF_EMAIL: self._email,
CONF_USER_ID: self._user_id,
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: data.get("IdToken"),
CONF_REFRESH_TOKEN: client.refresh_token,
},
)
return self.async_external_step_done(next_step_id="finish")
async def async_step_finish(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Step 3: authenticate with the API and create the config entry."""
session = async_get_clientsession(self.hass)
client = PerfectDraftApiClient(session)
try:
await client.authenticate(
self._email, self._password, self._recaptcha_token
)
except AuthenticationError as err:
_LOGGER.error("Authentication failed: %s", err)
return self.async_abort(reason="invalid_auth")
except PerfectDraftConnectionError as err:
_LOGGER.error("Connection failed: %s", err)
return self.async_abort(reason="cannot_connect")
except PerfectDraftApiError as err:
_LOGGER.error("API error during auth: %s", err)
return self.async_abort(reason="unknown")
try:
profile = await client.get_user_profile()
except (PerfectDraftApiError, PerfectDraftConnectionError):
return self.async_abort(reason="cannot_connect")
machine_id = _extract_machine_id(profile)
await self.async_set_unique_id(self._email.lower())
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"PerfectDraft ({self._email})",
data={
CONF_EMAIL: self._email,
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: client._id_token,
CONF_REFRESH_TOKEN: client.refresh_token,
CONF_MACHINE_ID: machine_id,
},
return self.async_show_form(
step_id="tokens",
data_schema=vol.Schema(
{
vol.Required(CONF_USER_ID): str,
vol.Required(CONF_REFRESH_TOKEN): str,
}
),
errors=errors,
)
async def async_step_reauth(
@@ -217,25 +118,50 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) -> config_entries.ConfigFlowResult:
"""Handle re-authentication when the refresh token expires."""
self._email = entry_data.get(CONF_EMAIL)
self._user_id = entry_data.get(CONF_USER_ID)
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
"""Ask user to re-enter credentials for reauth."""
"""Ask user to re-enter tokens for reauth."""
errors: dict[str, str] = {}
if user_input is not None:
self._email = user_input[CONF_EMAIL]
self._password = user_input[CONF_PASSWORD]
return await self.async_step_recaptcha()
user_id = user_input[CONF_USER_ID].strip()
refresh_token = user_input[CONF_REFRESH_TOKEN].strip()
session = async_get_clientsession(self.hass)
client = PerfectDraftApiClient(session)
try:
await client.refresh_access_token(
user_id=user_id,
refresh_token=refresh_token,
)
except (AuthenticationError, PerfectDraftApiError, PerfectDraftConnectionError) as err:
_LOGGER.error("Reauth failed: %s", err)
errors["base"] = "invalid_auth"
else:
self.hass.config_entries.async_update_entry(
self.context["entry"],
data={
**self.context["entry"].data,
CONF_USER_ID: user_id,
CONF_ACCESS_TOKEN: client.access_token,
CONF_REFRESH_TOKEN: client.refresh_token,
},
)
return self.async_abort(reason="reauth_successful")
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL, default=self._email): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(
CONF_USER_ID, default=self._user_id or ""
): str,
vol.Required(CONF_REFRESH_TOKEN): str,
}
),
errors=errors,
@@ -278,26 +204,3 @@ class PerfectDraftOptionsFlow(config_entries.OptionsFlow):
}
),
)
def _extract_machine_id(profile: dict[str, Any]) -> str | None:
"""Best-effort extraction of the first machine ID from the /api/me response.
The exact shape is unconfirmed; we try several plausible field names.
"""
if "machine_id" in profile:
return profile["machine_id"]
for key in ("machines", "perfectdraft_machines", "machineIds"):
machines = profile.get(key)
if isinstance(machines, list) and machines:
item = machines[0]
if isinstance(item, dict):
return item.get("id") or item.get("machine_id") or item.get("machineId")
return str(item)
_LOGGER.warning(
"Could not extract machine_id from profile response: %s",
list(profile.keys()),
)
return None
+1 -2
View File
@@ -2,8 +2,6 @@ DOMAIN = "perfectdraft"
API_BASE_URL = "https://api.perfectdraft.com"
API_KEY = "cAyzERqthCJXYVExjNAhr9CzE8ncLN2cQK3WGK10"
RECAPTCHA_SITE_KEY = "6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV"
RECAPTCHA_ACTION = "Magento/login"
DEFAULT_SCAN_INTERVAL = 900 # 15 minutes
MIN_SCAN_INTERVAL = 60 # 1 minute
@@ -11,6 +9,7 @@ MIN_SCAN_INTERVAL = 60 # 1 minute
CONF_REFRESH_TOKEN = "refresh_token"
CONF_ACCESS_TOKEN = "access_token"
CONF_ID_TOKEN = "id_token"
CONF_USER_ID = "user_id"
CONF_MACHINE_ID = "machine_id"
CONF_SCAN_INTERVAL = "scan_interval"
@@ -1,85 +0,0 @@
"""Server-side reCAPTCHA v3 token generation for PerfectDraft.
Uses the reCAPTCHA anchor/reload HTTP flow to obtain a token without
requiring a browser on an allowed domain. This works because the
PerfectDraft API uses an Android reCAPTCHA key, and the anchor endpoint
does not enforce domain validation the same way the JS widget does.
If this approach stops working, the fallback is the browser-based
external step flow.
"""
from __future__ import annotations
import logging
import re
import aiohttp
from .const import RECAPTCHA_SITE_KEY
_LOGGER = logging.getLogger(__name__)
ANCHOR_URL = (
"https://www.google.com/recaptcha/api2/anchor"
f"?ar=1&k={RECAPTCHA_SITE_KEY}&co=aHR0cHM6Ly9wZXJmZWN0ZHJhZnQuY29t"
"&hl=en&v=pCoGBhjs9s8EhFOHJFe8BCfw&size=invisible&cb=1"
)
RELOAD_URL = "https://www.google.com/recaptcha/api2/reload"
_TOKEN_RE = re.compile(r'"recaptcha-token"\s+value="([^"]+)"')
_RRESP_RE = re.compile(r'"rresp"\s*,\s*"([^"]+)"')
async def async_generate_recaptcha_token(
session: aiohttp.ClientSession,
) -> str | None:
"""Attempt to generate a reCAPTCHA token server-side.
Returns the token string, or None if generation fails.
"""
try:
async with session.get(ANCHOR_URL) as resp:
if resp.status != 200:
_LOGGER.debug("Anchor request failed: %s", resp.status)
return None
html = await resp.text()
match = _TOKEN_RE.search(html)
if not match:
_LOGGER.debug("Could not find recaptcha-token in anchor response")
return None
anchor_token = match.group(1)
payload = {
"v": "pCoGBhjs9s8EhFOHJFe8BCfw",
"reason": "q",
"c": anchor_token,
"k": RECAPTCHA_SITE_KEY,
"co": "aHR0cHM6Ly9wZXJmZWN0ZHJhZnQuY29t",
"hl": "en",
"size": "invisible",
}
async with session.post(RELOAD_URL, data=payload) as resp:
if resp.status != 200:
_LOGGER.debug("Reload request failed: %s", resp.status)
return None
body = await resp.text()
match = _RRESP_RE.search(body)
if not match:
_LOGGER.debug("Could not find rresp token in reload response")
return None
token = match.group(1)
_LOGGER.debug("Generated reCAPTCHA token server-side (length=%d)", len(token))
return token
except aiohttp.ClientError as exc:
_LOGGER.debug("reCAPTCHA token generation failed: %s", exc)
return None
except Exception:
_LOGGER.exception("Unexpected error generating reCAPTCHA token")
return None
@@ -1,85 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PerfectDraft – Verification</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
display: flex; align-items: center; justify-content: center;
min-height: 100vh; background: #f5f5f5; color: #333;
}
.card {
background: #fff; border-radius: 12px; padding: 2.5rem;
box-shadow: 0 2px 12px rgba(0,0,0,.08); max-width: 420px;
width: 100%; text-align: center;
}
h1 { font-size: 1.25rem; margin-bottom: .75rem; }
.spinner {
width: 40px; height: 40px; margin: 1.5rem auto;
border: 4px solid #e0e0e0; border-top-color: #1976d2;
border-radius: 50%; animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.status { font-size: .95rem; color: #666; }
.error { color: #c62828; display: none; }
.success { color: #2e7d32; }
</style>
</head>
<body>
<div class="card">
<h1>PerfectDraft Verification</h1>
<div id="loading">
<div class="spinner"></div>
<p class="status">Completing verification&hellip;</p>
</div>
<p id="success" class="status success" style="display:none">
Verification complete! You can close this window.
</p>
<p id="error" class="status error">
Verification failed. Please check your network connection and try again.
</p>
</div>
<script src="https://www.google.com/recaptcha/enterprise.js?render=RECAPTCHA_SITE_KEY"></script>
<script>
(function () {
var params = new URLSearchParams(window.location.search);
var callbackUrl = params.get("callback");
var flowId = params.get("flow_id");
if (!callbackUrl || !flowId) {
document.getElementById("loading").style.display = "none";
document.getElementById("error").style.display = "block";
document.getElementById("error").textContent =
"Missing callback parameters. Please restart the setup flow.";
return;
}
grecaptcha.enterprise.ready(function () {
grecaptcha.enterprise
.execute("RECAPTCHA_SITE_KEY", { action: "RECAPTCHA_ACTION" })
.then(function (token) {
return fetch(callbackUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ flow_id: flowId, token: token }),
});
})
.then(function (resp) {
if (!resp.ok) throw new Error("Callback failed: " + resp.status);
document.getElementById("loading").style.display = "none";
document.getElementById("success").style.display = "block";
})
.catch(function (err) {
console.error(err);
document.getElementById("loading").style.display = "none";
document.getElementById("error").style.display = "block";
});
});
})();
</script>
</body>
</html>
+13 -11
View File
@@ -3,29 +3,31 @@
"step": {
"user": {
"title": "PerfectDraft Account",
"description": "Enter your PerfectDraft app credentials.",
"description": "Enter the email address associated with your PerfectDraft account.",
"data": {
"email": "Email",
"password": "Password"
"email": "Email"
}
},
"recaptcha": {
"title": "Complete Verification",
"description": "A browser window will open to complete a quick verification. This only needs to happen once."
"tokens": {
"title": "API Tokens",
"description": "Enter your UserId and RefreshToken from the PerfectDraft app. See the integration documentation for instructions on how to extract these.",
"data": {
"user_id": "User ID",
"refresh_token": "Refresh Token"
}
},
"reauth_confirm": {
"title": "Re-authenticate PerfectDraft",
"description": "Your session has expired. Please re-enter your credentials.",
"description": "Your session has expired. Please enter fresh tokens from the PerfectDraft app.",
"data": {
"email": "Email",
"password": "Password"
"user_id": "User ID",
"refresh_token": "Refresh Token"
}
}
},
"error": {
"invalid_auth": "Invalid email or password.",
"invalid_auth": "Invalid or expired tokens. Please extract fresh tokens from the PerfectDraft app.",
"cannot_connect": "Cannot connect to PerfectDraft service.",
"recaptcha_failed": "Verification failed. Please try again.",
"unknown": "An unexpected error occurred."
},
"abort": {
@@ -3,29 +3,31 @@
"step": {
"user": {
"title": "PerfectDraft Account",
"description": "Enter your PerfectDraft app credentials.",
"description": "Enter the email address associated with your PerfectDraft account.",
"data": {
"email": "Email",
"password": "Password"
"email": "Email"
}
},
"recaptcha": {
"title": "Complete Verification",
"description": "A browser window will open to complete a quick verification. This only needs to happen once."
"tokens": {
"title": "API Tokens",
"description": "Enter your UserId and RefreshToken from the PerfectDraft app. See the integration documentation for instructions on how to extract these.",
"data": {
"user_id": "User ID",
"refresh_token": "Refresh Token"
}
},
"reauth_confirm": {
"title": "Re-authenticate PerfectDraft",
"description": "Your session has expired. Please re-enter your credentials.",
"description": "Your session has expired. Please enter fresh tokens from the PerfectDraft app.",
"data": {
"email": "Email",
"password": "Password"
"user_id": "User ID",
"refresh_token": "Refresh Token"
}
}
},
"error": {
"invalid_auth": "Invalid email or password.",
"invalid_auth": "Invalid or expired tokens. Please extract fresh tokens from the PerfectDraft app.",
"cannot_connect": "Cannot connect to PerfectDraft service.",
"recaptcha_failed": "Verification failed. Please try again.",
"unknown": "An unexpected error occurred."
},
"abort": {
+47 -76
View File
@@ -1,19 +1,16 @@
#!/usr/bin/env python3
"""Local test harness for the PerfectDraft API integration.
Exercises the full auth + data flow without Home Assistant:
1. Server-side reCAPTCHA token generation
2. Authentication (sign-in)
3. Token refresh
4. Fetch user profile (/api/me)
5. Fetch machine details
Exercises the token-refresh + data flow without Home Assistant:
1. Refresh tokens via /auth/renewaccesstokens
2. Fetch user profile (/api/me)
3. Fetch machine details
Reads credentials from .credentials.json (gitignored).
Usage:
python3 test_harness.py
python3 test_harness.py --step auth # stop after auth
python3 test_harness.py --step recaptcha # only test recaptcha token gen
python3 test_harness.py --step refresh # stop after token refresh
python3 test_harness.py --step profile # stop after profile fetch
python3 test_harness.py --dump # dump full API responses as JSON
"""
@@ -28,15 +25,12 @@ from pathlib import Path
import aiohttp
# Import only the standalone modules (no HA dependency)
_pkg = Path(__file__).parent / "custom_components" / "perfectdraft"
sys.path.insert(0, str(Path(__file__).parent / "custom_components"))
# Block homeassistant imports so __init__.py doesn't blow up if accidentally loaded
sys.modules["homeassistant"] = type(sys)("homeassistant")
import importlib.util
def _load_module(name: str, filepath: Path):
spec = importlib.util.spec_from_file_location(name, filepath)
mod = importlib.util.module_from_spec(spec)
@@ -44,17 +38,13 @@ def _load_module(name: str, filepath: Path):
spec.loader.exec_module(mod)
return mod
const = _load_module("perfectdraft.const", _pkg / "const.py")
exceptions = _load_module("perfectdraft.exceptions", _pkg / "exceptions.py")
# api.py imports from .const and .exceptions — those are now in sys.modules
api = _load_module("perfectdraft.api", _pkg / "api.py")
recaptcha = _load_module("perfectdraft.recaptcha", _pkg / "recaptcha.py")
API_BASE_URL = const.API_BASE_URL
API_KEY = const.API_KEY
RECAPTCHA_SITE_KEY = const.RECAPTCHA_SITE_KEY
async_generate_recaptcha_token = recaptcha.async_generate_recaptcha_token
PerfectDraftApiClient = api.PerfectDraftApiClient
AuthenticationError = exceptions.AuthenticationError
PerfectDraftApiError = exceptions.PerfectDraftApiError
@@ -71,11 +61,15 @@ log = logging.getLogger("test_harness")
def load_credentials() -> dict:
if not CRED_FILE.exists():
log.error("Missing %s — copy from template and fill in your creds", CRED_FILE)
log.error("Missing %s — create it with user_id and refresh_token", CRED_FILE)
sys.exit(1)
creds = json.loads(CRED_FILE.read_text())
if creds.get("email", "").startswith("YOUR_"):
log.error("Fill in your real credentials in %s", CRED_FILE)
if not creds.get("user_id") or not creds.get("refresh_token"):
log.error(
"Fill in user_id and refresh_token in %s\n"
"Format: {\"user_id\": \"...\", \"refresh_token\": \"...\", \"email\": \"...\"}",
CRED_FILE,
)
sys.exit(1)
return creds
@@ -96,68 +90,38 @@ def dump_json(label: str, data, *, dump: bool):
async def run(step: str, dump: bool):
creds = load_credentials()
email = creds["email"]
password = creds["password"]
user_id = creds["user_id"]
refresh_token = creds["refresh_token"]
print(f"\n--- PerfectDraft API Test Harness ---")
print(f" Email: {email}")
print(f" User ID: {user_id[:20]}..." if len(user_id) > 20 else f" User ID: {user_id}")
print(f" API base: {API_BASE_URL}")
print(f" API key: {API_KEY[:8]}...{API_KEY[-4:]}")
print(f" Site key: {RECAPTCHA_SITE_KEY[:8]}...{RECAPTCHA_SITE_KEY[-4:]}")
print()
async with aiohttp.ClientSession() as session:
client = PerfectDraftApiClient(session)
# --- Step 1: reCAPTCHA ---
print("[1/5] Generating reCAPTCHA token (server-side)...")
token = await async_generate_recaptcha_token(session)
if token:
print(f" OK — token length: {len(token)}")
print(f" Token prefix: {token[:40]}...")
else:
print(" FAILED — no token generated")
print(" This means the anchor/reload approach didn't work.")
print(" The API call will likely fail without a valid token.")
token = "DUMMY_TOKEN_FOR_TESTING"
print(f" Using dummy token to see what the API says...")
if step == "recaptcha":
print("\n--- Stopping after recaptcha step ---")
return
# --- Step 2: Authenticate ---
print(f"\n[2/5] Authenticating as {email}...")
# --- Step 1: Refresh tokens ---
print("[1/4] Refreshing tokens via /auth/renewaccesstokens...")
try:
auth_data = await client.authenticate(email, password, token)
print(f" OK — got tokens")
print(f" AccessToken: {client.access_token[:20]}..." if client.access_token else " AccessToken: None")
print(f" RefreshToken: {client.refresh_token[:20]}..." if client.refresh_token else " RefreshToken: None")
dump_json("Auth response", auth_data, dump=dump)
except (AuthenticationError, PerfectDraftApiError, PerfectDraftConnectionError) as exc:
print(f" FAILED — {type(exc).__name__}: {exc}")
print("\n If this is an auth error, possible causes:")
print(" - reCAPTCHA token was rejected (invalid/expired/wrong type)")
print(" - Wrong email/password")
print(" - IP rate-limited by Imperva WAF")
return
if step == "auth":
print("\n--- Stopping after auth step ---")
return
# --- Step 3: Refresh token ---
print(f"\n[3/5] Testing token refresh...")
try:
refresh_data = await client.refresh_access_token()
print(f" OK — access token refreshed")
refresh_data = await client.refresh_access_token(
user_id=user_id,
refresh_token=refresh_token,
)
print(f" OK — got fresh tokens")
print(f" AccessToken: {client.access_token[:30]}..." if client.access_token else " AccessToken: None")
print(f" RefreshToken: {client.refresh_token[:30]}..." if client.refresh_token else " RefreshToken: None")
dump_json("Refresh response", refresh_data, dump=dump)
except (AuthenticationError, PerfectDraftApiError, PerfectDraftConnectionError) as exc:
print(f" FAILED — {type(exc).__name__}: {exc}")
print(" (Continuing with original access token...)")
return
# --- Step 4: User profile ---
print(f"\n[4/5] Fetching user profile (/api/me)...")
if step == "refresh":
print("\n--- Stopping after refresh step ---")
return
# --- Step 2: User profile ---
print(f"\n[2/4] Fetching user profile (/api/me)...")
try:
profile = await client.get_user_profile()
print(f" OK — response received")
@@ -170,16 +134,15 @@ async def run(step: str, dump: bool):
print("\n--- Stopping after profile step ---")
return
# --- Step 5: Machine details ---
# --- Step 3: Machine details ---
machine_id = _extract_machine_id(profile)
if not machine_id:
print(f"\n[5/5] Cannot fetch machine details — no machine_id found")
print(f"\n[3/4] Cannot fetch machine details — no machine_id found")
print(f" Profile keys: {list(profile.keys())}")
print(f" Full profile dump needed to find the machine ID field")
dump_json("Full profile", profile, dump=True)
return
print(f"\n[5/5] Fetching machine details for {machine_id}...")
print(f"\n[3/4] Fetching machine details for {machine_id}...")
try:
details = await client.get_machine_details(machine_id)
print(f" OK — response received")
@@ -188,6 +151,15 @@ async def run(step: str, dump: bool):
print(f" FAILED — {type(exc).__name__}: {exc}")
return
# --- Step 4: Try keg endpoint ---
print(f"\n[4/4] Fetching machine kegs...")
try:
kegs = await client._request("GET", "/api/perfectdraft_machine_kegs")
print(f" OK — response received")
dump_json("Machine kegs", kegs, dump=True)
except (PerfectDraftApiError, PerfectDraftConnectionError, AuthenticationError) as exc:
print(f" FAILED — {type(exc).__name__}: {exc}")
print(f"\n--- All steps complete ---")
@@ -202,12 +174,11 @@ def _extract_machine_id(profile: dict) -> str | None:
if isinstance(machines, list) and machines:
item = machines[0]
if isinstance(item, dict):
for id_key in ("id", "machine_id", "machineId", "deviceId", "serial"):
for id_key in ("id", "machine_id", "machineId", "deviceId", "serial", "@id"):
if id_key in item:
return str(item[id_key])
return str(item)
# Brute-force: look for any key containing "machine" or "device"
for key, val in profile.items():
if any(hint in key.lower() for hint in ("machine", "device")):
log.info("Potential machine field: %s = %s", key, val)
@@ -219,7 +190,7 @@ def main():
parser = argparse.ArgumentParser(description="PerfectDraft API test harness")
parser.add_argument(
"--step",
choices=["recaptcha", "auth", "profile", "all"],
choices=["refresh", "profile", "all"],
default="all",
help="Stop after this step (default: all)",
)