Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48434a7af3 | ||
|
|
5a5be12e8a | ||
|
|
43f9410a21 | ||
|
|
a21273c000 | ||
|
|
b2016ce914 | ||
|
|
3a94f6c1cc | ||
|
|
8b2c4418b3 | ||
|
|
b209de0cf2 | ||
|
|
7387bafc0b | ||
|
|
f489b4e915 | ||
|
|
064ee0992b | ||
|
|
6ca1f1ff4e | ||
|
|
b0024c1b74 | ||
|
|
77967e5244 | ||
|
|
5ebdc2c3c1 | ||
|
|
8b2f8ce1c3 | ||
|
|
3fc7faac4e | ||
|
|
fbd299d7c9 | ||
|
|
98c1bd0622 | ||
|
|
fe880f8f72 | ||
|
|
ec9347baac | ||
|
|
f8a9e069a2 | ||
|
|
20ed62b963 | ||
|
|
a526af0088 | ||
|
|
06b625cd83 | ||
|
|
a547afdfde | ||
|
|
6e11d9b2c9 | ||
|
|
7b4edbd390 | ||
|
|
ab206e65a4 | ||
|
|
73ee49ef1d | ||
|
|
3b82df6e83 | ||
|
|
2703328fb5 | ||
|
|
4f82d9a4ac |
@@ -192,10 +192,19 @@ When the user corrects your approach, append a one-line rule here before ending
|
||||
- **`numberOfPoursSinceStartup` resets to 0 on a machine power cycle** (confirmed 2026-06-01: power-cycled the machine at pours=16, reloaded the integration, Pours read 0). It counts since machine startup, NOT since keg insertion. Do not base keg-change detection on the pour counter — a power cycle (outage, unplug, firmware update) would false-trigger it. `kegVolume` (Keg Remaining) was confirmed unchanged across the same power cycle/reload, so a power cycle produces no spurious volume jump — volume-jump signals (b/c) and the manual button are the power-cycle-safe detectors; prefer them.
|
||||
- **TODO — verification debt, do this when the next keg is fitted: confirm the keg-freshness baseline survives a reauth.** `fix-reauth-flow` (archived 2026-09-06) was verified on-device for the reauth flow itself, but the machine had no keg in the tap, so there was no freshness countdown to preserve and task 6.6 could not be checked. The fix uses `async_update_reload_and_abort`, which reloads the config entry — the exact moment a `RestoreEntity` baseline could be lost. After the next keg change, trigger a reauth (or reload the integration) and confirm Keg Freshness keeps its countdown instead of resetting to unknown. If it resets, that is a real regression in `PerfectDraftKegFreshnessSensor`'s restore path, not in the config flow.
|
||||
- **Never add a non-numeric key to `keg_catalog.json`.** `_load_keg_catalog` in `sensor.py` builds `{int(k): v for k, v in raw.items()}` and catches `ValueError` by returning `{}`. A single `_meta` or `_source` key therefore disables the *entire* catalog — every keg reports no name — and says so only at debug level. Recording provenance or attribution inside that file requires changing the loader first. `tests/test_keg_catalog.py::test_keys_are_numeric` guards this.
|
||||
- **A new integration catalog ID is not done until the card maps it.** The companion card joins on `kegId` against `scripts/keg-catalog.reference.json`. Adding a row to `keg_catalog.json` without binding the card entry (and re-syncing that snapshot) ships a named **Keg** sensor that the card still treats as unknown. The card may already have the beer under a slug with no `kegId` — check before adding a duplicate entry.
|
||||
- **TODO — verification debt from `backport-keg-catalog` (archived 2026-09-06), clear this after installing v0.3.2 via HACS: confirm the `Keg` sensor still resolves the fitted keg.** The catalog file was replaced wholesale (86 → 114 entries) and verified statically only: exact diff shape, 114 int keys through the loader, and format guards in `tests/test_keg_catalog.py`. What was never exercised is the live path. On-device checks were impossible at the time — no HA on the dev host, and `.credentials.json`'s refresh token had expired (`NotAuthorizedException: Refresh Token has expired`), so even `test_harness.py` could not reach the API. Task group 5 in the archived change lists the four checks.
|
||||
- **`test_harness.py` is stale: it reads `user_id` from `.credentials.json`, which now holds `email` / `access_token` / `id_token` / `refresh_token`.** It exits before doing anything useful. Fix the key names (and refresh the token per the README's reCAPTCHA step) before relying on it.
|
||||
- **All five files in `openspec/specs/` fail `openspec validate --specs`** for a missing `## Purpose` section. Pre-existing and repo-wide as of 2026-09-06, so a failing spec validation is not necessarily caused by your change — check whether the error is only the Purpose one before chasing it.
|
||||
- **TODO — verification debt from `fix-cognito-signin` (v0.4.4 shipped without on-device checks, maintainer decision 2026-11-07).** The Cognito direct sign-in was verified only by the automated suite (stdlib API tests and pytest config-flow tests) and the README token was checked in Firefox and Chromium; no sign-in reached the live service from Home Assistant. When there is time for a reinstall: (1) add the integration from scratch with a README token and confirm sensors populate; (2) a wrong password must return to the email/password form with `invalid_credentials` and Cognito's reason, and a token older than 2 minutes must stay on the token step with `token_rejected`; (3) trigger a reauth and confirm it succeeds (with a keg fitted, this also clears the Keg Freshness TODO above). Details in the archived change's `tasks.md`, section "Deferred".
|
||||
- **TODO — verification debt from `add-keg-48180` (card 0.4.4 shipped without an on-device check, maintainer decision 2026-11-07).** Do it together with the `fix-cognito-signin` checks above: on a dashboard with card 0.4.4, confirm the card editor's beer picker lists Camden Stout with its artwork; with a 48180 keg fitted, confirm the Keg sensor reads "Camden Stout" and the card brands it.
|
||||
- **TODO — own OpenSpec change: persist Cognito-refreshed tokens back to the config entry.** `PerfectDraftApiClient.refresh_access_token()` updates `_access_token`/`_id_token` in memory only, so every HA restart reloads the stale access token and burns a wasted 401-plus-refresh round trip before the first successful poll. Harmless today because the refresh token is what actually gates reauth and Cognito's `REFRESH_TOKEN_AUTH` never issues a new one, so nothing is lost — just wasteful. Deferred out of `fix-reauth-flow` to keep that diff surgical.
|
||||
- **TODO — housekeeping, after `fix-cognito-signin` / `add-keg-48180` ship: take the GitHub token out of the `github` remote URLs** in both this repo and `Hassio-PerfectDraftPro-Component`. Not a leak (never committed; `.git/` is untracked), but `git remote -v` prints it. Order matters: first change `credential.helper` to an **absolute** path (`store --file=/home/rick/Lab/Dev/<repo>/.git/credentials`) — the current relative `.git/credentials` resolves against the worktree root, where `.git` is a file, so pushes from `.worktree/<topic>` only reach `github` (whose URL carries the token); pushing to `origin` from a worktree fails with "unable to open .git/credentials: Not a directory". Until fixed, push agent branches from the main checkout: `git push origin agent/<topic>` (no branch switch needed). Then strip the URL, run `git ls-remote github` from a worktree to prove auth, and update the `AGENTS.md` helper command to the absolute form.
|
||||
- **Config-flow tests run in `.venv-test` (main checkout) on the system Python 3.14** with `pytest-homeassistant-custom-component==0.13.375` (core 2026.10.4). Run them from a worktree as `../../.venv-test/bin/pytest tests/`. Do not pin a harness that needs Python 3.12: there is no 3.12 and no C compiler on the dev host, so old numpy cannot build.
|
||||
- **DevTools `copy()` cannot copy an async result in any browser.** Chromium removes `copy` once the typed command returns (`undefined` in `.then`/after `await`); Firefox's `copy()` only sets a `helperResult` read when evaluation returns, so a later call silently copies nothing — and a captured `copy` reference "works" in Chromium tests while failing in Firefox. Do not use `prompt(msg, value)` either: Chromium cuts the default value off at 2,000 chars, and reCAPTCHA tokens are ~2,450–2,700. For user-facing snippets, keep one command that adds a page button whose click calls `navigator.clipboard.writeText(value)`. Test console snippets in Firefox too, not only via CDP/Chromium.
|
||||
- **Cursor's embedded browser replaces `alert`/`confirm`/`prompt` with logging stubs** (`[CursorBrowser] Dialog suppressed`, history in `window.__cursorDialogConfig.dialogHistory`). A missing dialog there says nothing about real browsers; read the history to check the arguments, and have a human check the native dialog.
|
||||
- **Version numbering (since 0.4.4, 2026-11-07): integration and card share major.minor; patch may diverge.** A fix to one package bumps only its patch (card 0.4.5 next to integration 0.4.4); a joint release brings both to the same number again. Never use letter suffixes (`0.4.4b`): HACS (PEP 440) and npm (SemVer) treat them as pre-releases that sort *before* 0.4.4, so HACS would not offer the update.
|
||||
- **`gh` is not installed; use the GitHub REST API with `curl`.** Get the token with `printf 'protocol=https\nhost=github.com\n\n' | git credential fill`. The token is fine-grained: since 2026-11-07 it has Issues and Pull requests read/write in addition to admin/push. A `403 Resource not accessible by personal access token` means a permission is missing on the token, not a bad token.
|
||||
- **TODO — own OpenSpec change + release: remove pour-count-based keg detection** from `PerfectDraftKegFreshnessSensor` in `sensor.py`: trigger (a) `pours == 0 && kegVolume > 5.5 && last_pours != 0`, plus the `_last_pours` field and its restore/exposure/rebaseline. It can false-fire on a power cycle while the keg is above ~92% full, and adds nothing the volume triggers (b/c) and the Mark Keg Changed button don't already cover.
|
||||
|
||||
---
|
||||
|
||||
@@ -7,7 +7,7 @@ A Home Assistant custom integration for the [PerfectDraft Pro](https://www.perfe
|
||||
| Sensor | Description | Unit |
|
||||
|--------|-------------|------|
|
||||
| Temperature | Current beer temperature | °C |
|
||||
| Keg | Name of the tapped beer, resolved from a [bundled catalog](#the-keg-name-catalog) of 115 kegs | — |
|
||||
| Keg | Name of the tapped beer, resolved from a [bundled catalog](#the-keg-name-catalog) of 117 kegs | — |
|
||||
| Keg Product | Numeric product ID of the fitted keg | — |
|
||||
| Keg Remaining | Beer left in the keg | % |
|
||||
| Keg Freshness | Days remaining until 30-day freshness expires | days |
|
||||
@@ -45,16 +45,18 @@ The integration needs a one-time verification token from PerfectDraft's website.
|
||||
|
||||
1. Open [perfectdraft.com/en-gb/customer/account/login](https://www.perfectdraft.com/en-gb/customer/account/login) in your browser (Chrome, Firefox, Edge, etc.) — you do **not** need to log in on this page, just open it
|
||||
2. Press **F12** to open Developer Tools, then click the **Console** tab
|
||||
3. Paste this command and press **Enter**:
|
||||
3. Paste this command at the console prompt and press **Enter** — once, not as a "Live expression", which re-runs it over and over:
|
||||
|
||||
```javascript
|
||||
grecaptcha.enterprise.execute('6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV', {action: 'Magento/login'}).then(t => console.log(t))
|
||||
grecaptcha.enterprise.execute('6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV', {action: 'Magento/login'}).then(t => { console.log(t); const b = document.body.appendChild(document.createElement('button')); b.textContent = 'Click THIS BLACK BOX to copy your PerfectDraft token'; b.style = 'position:fixed;top:40%;left:50%;transform:translateX(-50%);z-index:2147483647;padding:20px 40px;font-size:22px;background:#000;color:#fff;border-radius:8px;cursor:pointer'; b.onclick = () => navigator.clipboard.writeText(t).then(() => b.textContent = 'Copied! Paste it into Home Assistant', e => b.textContent = 'Copy failed: ' + e.message) })
|
||||
```
|
||||
|
||||
4. A long string of text will appear in the console — that's your token
|
||||
5. Select it, copy it, and paste it into the Home Assistant setup dialog
|
||||
4. A black box saying **Click THIS BLACK BOX to copy your PerfectDraft token** appears in the middle of the page — click it, and it changes to **Copied!**
|
||||
5. Paste the token into the Home Assistant setup dialog
|
||||
6. Click **Submit** within 2 minutes (the token expires)
|
||||
|
||||
If the button says **Copy failed**, the same token is printed in the console: right-click it there and copy it.
|
||||
|
||||
That's it! The integration will authenticate and start polling your PerfectDraft Pro. Token refresh is automatic — you should not need to repeat this step. If the session does eventually expire, Home Assistant will prompt you to re-authenticate. (This is a new integration, so the exact session lifespan is still being determined — it's at least 30 days and may well be indefinite.)
|
||||
|
||||
### Step 3: Configure polling
|
||||
|
||||
@@ -7,7 +7,14 @@ from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
from .const import API_BASE_URL, API_KEY, COGNITO_CLIENT_ID, COGNITO_REGION
|
||||
from .const import (
|
||||
API_BASE_URL,
|
||||
API_KEY,
|
||||
COGNITO_CLIENT_ID,
|
||||
COGNITO_REGION,
|
||||
RECAPTCHA_ACTION,
|
||||
RECAPTCHA_DOMAIN,
|
||||
)
|
||||
from .exceptions import (
|
||||
AuthenticationError,
|
||||
PerfectDraftApiError,
|
||||
@@ -16,8 +23,33 @@ from .exceptions import (
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
RECAPTCHA_ACTION_SIGN_IN = "Magento/login"
|
||||
COGNITO_IDP_URL = f"https://cognito-idp.{COGNITO_REGION}.amazonaws.com/"
|
||||
COGNITO_HEADERS = {
|
||||
"Content-Type": "application/x-amz-json-1.1",
|
||||
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
|
||||
}
|
||||
|
||||
|
||||
def _parse_cognito_error(body: str) -> tuple[str | None, str | None]:
|
||||
"""Return (error type, message) from a Cognito error body.
|
||||
|
||||
Cognito answers ``{"__type": "...", "message": "..."}``, sometimes with a
|
||||
namespaced type (``com.amazonaws...#NotAuthorizedException``). A body that
|
||||
is not JSON, such as an HTML error page, becomes the message, truncated.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except ValueError:
|
||||
return None, body.strip()[:200] or None
|
||||
if not isinstance(data, dict):
|
||||
return None, None
|
||||
code = data.get("__type")
|
||||
reason = data.get("message")
|
||||
if isinstance(code, str):
|
||||
code = code.rsplit("#", 1)[-1]
|
||||
else:
|
||||
code = None
|
||||
return code, reason if isinstance(reason, str) else None
|
||||
|
||||
|
||||
class PerfectDraftApiClient:
|
||||
@@ -59,42 +91,61 @@ class PerfectDraftApiClient:
|
||||
async def authenticate(
|
||||
self, email: str, password: str, recaptcha_token: str
|
||||
) -> dict[str, str]:
|
||||
"""Sign in via /authentication/sign-in with a reCAPTCHA token.
|
||||
"""Sign in directly against Cognito with a reCAPTCHA token.
|
||||
|
||||
The token must be generated from a real browser on perfectdraft.com
|
||||
using the web reCAPTCHA Enterprise key with action Magento/login.
|
||||
PerfectDraft's PreAuthentication Lambda also requires the shop's
|
||||
origin as ``domain``; the api.perfectdraft.com sign-in gateway does
|
||||
not forward it, so sign-in cannot go through the gateway.
|
||||
"""
|
||||
url = f"{self._base}/authentication/sign-in"
|
||||
payload = {
|
||||
"email": email,
|
||||
"password": password,
|
||||
"recaptchaToken": recaptcha_token,
|
||||
"recaptchaAction": RECAPTCHA_ACTION_SIGN_IN,
|
||||
"AuthFlow": "USER_PASSWORD_AUTH",
|
||||
"ClientId": COGNITO_CLIENT_ID,
|
||||
"AuthParameters": {"USERNAME": email, "PASSWORD": password},
|
||||
"ClientMetadata": {
|
||||
"recaptchaToken": recaptcha_token,
|
||||
"recaptchaAction": RECAPTCHA_ACTION,
|
||||
"domain": RECAPTCHA_DOMAIN,
|
||||
},
|
||||
}
|
||||
headers = {"x-api-key": API_KEY}
|
||||
|
||||
try:
|
||||
async with self._session.post(
|
||||
url, json=payload, headers=headers
|
||||
COGNITO_IDP_URL, json=payload, headers=COGNITO_HEADERS
|
||||
) as resp:
|
||||
if resp.status in (400, 401, 403):
|
||||
body = await resp.text()
|
||||
code, reason = _parse_cognito_error(body)
|
||||
raise AuthenticationError(
|
||||
f"Sign-in rejected ({resp.status}): {body}"
|
||||
f"Sign-in rejected ({resp.status}): {body}",
|
||||
code=code,
|
||||
reason=reason,
|
||||
)
|
||||
if resp.status != 200:
|
||||
body = await resp.text()
|
||||
raise PerfectDraftApiError(resp.status, body)
|
||||
data = await resp.json()
|
||||
data = await resp.json(content_type=None)
|
||||
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"]
|
||||
result = data.get("AuthenticationResult") if isinstance(data, dict) else None
|
||||
if not isinstance(result, dict) or not all(
|
||||
result.get(key) for key in ("AccessToken", "IdToken", "RefreshToken")
|
||||
):
|
||||
challenge = data.get("ChallengeName") if isinstance(data, dict) else None
|
||||
raise AuthenticationError(
|
||||
f"Sign-in returned no tokens (challenge: {challenge})",
|
||||
code=challenge,
|
||||
reason=f"Sign-in requires {challenge}" if challenge else None,
|
||||
)
|
||||
|
||||
self._access_token = result["AccessToken"]
|
||||
self._id_token = result["IdToken"]
|
||||
self._refresh_token = result["RefreshToken"]
|
||||
|
||||
_LOGGER.debug("Authenticated successfully")
|
||||
return data
|
||||
return result
|
||||
|
||||
async def refresh_access_token(self) -> dict[str, Any]:
|
||||
"""Refresh tokens directly via AWS Cognito (bypasses API gateway + reCAPTCHA)."""
|
||||
|
||||
@@ -31,6 +31,12 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_RECAPTCHA_TOKEN = "recaptcha_token"
|
||||
|
||||
_AUTH_ERRORS = {
|
||||
"credentials": "invalid_credentials",
|
||||
"token": "token_rejected",
|
||||
"other": "invalid_auth",
|
||||
}
|
||||
|
||||
|
||||
class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for PerfectDraft."""
|
||||
@@ -40,18 +46,23 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
def __init__(self) -> None:
|
||||
self._email: str | None = None
|
||||
self._password: str | None = None
|
||||
# Fills {reason} in the error strings; every form must pass it.
|
||||
self._auth_reason = ""
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> config_entries.ConfigFlowResult:
|
||||
"""Step 1: collect email and password."""
|
||||
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_token()
|
||||
|
||||
return self._show_user_form({})
|
||||
|
||||
def _show_user_form(
|
||||
self, errors: dict[str, str]
|
||||
) -> config_entries.ConfigFlowResult:
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=vol.Schema(
|
||||
@@ -61,6 +72,7 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
}
|
||||
),
|
||||
errors=errors,
|
||||
description_placeholders={"reason": self._auth_reason},
|
||||
)
|
||||
|
||||
async def async_step_token(
|
||||
@@ -81,7 +93,15 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
except AuthenticationError as err:
|
||||
_LOGGER.error("Authentication failed: %s", err)
|
||||
errors["base"] = "invalid_auth"
|
||||
self._auth_reason = err.display_reason
|
||||
error = _AUTH_ERRORS[err.kind]
|
||||
if error == "invalid_credentials":
|
||||
# A fresh token cannot fix a wrong password, so ask for
|
||||
# the credentials again instead of looping on this step.
|
||||
if self.source == config_entries.SOURCE_REAUTH:
|
||||
return self._show_reauth_confirm_form({"base": error})
|
||||
return self._show_user_form({"base": error})
|
||||
errors["base"] = error
|
||||
except PerfectDraftConnectionError as err:
|
||||
_LOGGER.error("Connection failed: %s", err)
|
||||
errors["base"] = "cannot_connect"
|
||||
@@ -120,6 +140,7 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
}
|
||||
),
|
||||
errors=errors,
|
||||
description_placeholders={"reason": self._auth_reason},
|
||||
)
|
||||
|
||||
async def _async_persist(
|
||||
@@ -168,13 +189,16 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> config_entries.ConfigFlowResult:
|
||||
"""Ask user to re-enter credentials 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_token()
|
||||
|
||||
return self._show_reauth_confirm_form({})
|
||||
|
||||
def _show_reauth_confirm_form(
|
||||
self, errors: dict[str, str]
|
||||
) -> config_entries.ConfigFlowResult:
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
data_schema=vol.Schema(
|
||||
@@ -184,6 +208,7 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
}
|
||||
),
|
||||
errors=errors,
|
||||
description_placeholders={"reason": self._auth_reason},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -5,6 +5,8 @@ API_KEY = "cAyzERqthCJXYVExjNAhr9CzE8ncLN2cQK3WGK10"
|
||||
|
||||
RECAPTCHA_SITE_KEY = "6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV"
|
||||
RECAPTCHA_ACTION = "Magento/login"
|
||||
# PerfectDraft's Cognito PreAuthentication Lambda rejects sign-in without it.
|
||||
RECAPTCHA_DOMAIN = "https://www.perfectdraft.com"
|
||||
|
||||
COGNITO_REGION = "eu-west-1"
|
||||
COGNITO_CLIENT_ID = "57ddq2ppqg2jcpup06r2g1deur"
|
||||
|
||||
@@ -5,8 +5,39 @@ class PerfectDraftError(Exception):
|
||||
"""Base exception for PerfectDraft."""
|
||||
|
||||
|
||||
_CREDENTIAL_ERROR_CODES = frozenset({"NotAuthorizedException", "UserNotFoundException"})
|
||||
_TOKEN_ERROR_CODES = frozenset({"UserLambdaValidationException"})
|
||||
_MAX_REASON_LENGTH = 200
|
||||
|
||||
|
||||
class AuthenticationError(PerfectDraftError):
|
||||
"""Raised when authentication fails (bad credentials, expired refresh token, reCAPTCHA rejection)."""
|
||||
"""Raised when authentication fails (bad credentials, expired refresh token, reCAPTCHA rejection).
|
||||
|
||||
``code`` is the Cognito error type (e.g. ``NotAuthorizedException``) and
|
||||
``reason`` its human-readable message, when the server supplied them.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, message: str, code: str | None = None, reason: str | None = None
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.reason = reason
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
"""Which input was rejected: ``credentials``, ``token`` or ``other``."""
|
||||
if self.code in _CREDENTIAL_ERROR_CODES:
|
||||
return "credentials"
|
||||
if self.code in _TOKEN_ERROR_CODES:
|
||||
return "token"
|
||||
return "other"
|
||||
|
||||
@property
|
||||
def display_reason(self) -> str:
|
||||
"""Server-supplied reason for the config flow, never empty."""
|
||||
text = (self.reason or self.code or "").strip().rstrip(".")
|
||||
return text[:_MAX_REASON_LENGTH] or "no reason given"
|
||||
|
||||
|
||||
class PerfectDraftApiError(PerfectDraftError):
|
||||
|
||||
@@ -97,6 +97,7 @@
|
||||
"47523": "Anosteké Blonde",
|
||||
"47629": "Camden Eazy IPA",
|
||||
"47774": "Old Speckled Hen",
|
||||
"47792": "Camden Eazy",
|
||||
"47816": "Corona Ligera",
|
||||
"47943": "Fuller's London Pride",
|
||||
"47962": "Bass Pale Ale",
|
||||
@@ -113,5 +114,6 @@
|
||||
"48024": "Siren Lumina IPA",
|
||||
"48050": "Anheuser-Busch Bud",
|
||||
"48061": "Northern Monk Faith",
|
||||
"48134": "Kopparberg Crisp Apple"
|
||||
"48134": "Kopparberg Crisp Apple",
|
||||
"48180": "Camden Stout"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"domain": "perfectdraft",
|
||||
"name": "PerfectDraft",
|
||||
"version": "0.3.3",
|
||||
"version": "0.4.4",
|
||||
"documentation": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro",
|
||||
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/issues",
|
||||
"codeowners": ["@Falkvinge"],
|
||||
|
||||
@@ -26,7 +26,9 @@
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"invalid_auth": "Authentication failed. Token may have expired (2 min limit) or credentials are wrong. Try again with a fresh token.",
|
||||
"invalid_auth": "Authentication failed: {reason}. Try again with a fresh token.",
|
||||
"invalid_credentials": "PerfectDraft rejected the email or password: {reason}.",
|
||||
"token_rejected": "PerfectDraft rejected the verification token: {reason}. Generate a fresh token and paste it within 2 minutes.",
|
||||
"cannot_connect": "Cannot connect to PerfectDraft service.",
|
||||
"unknown": "An unexpected error occurred."
|
||||
},
|
||||
|
||||
@@ -26,7 +26,9 @@
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"invalid_auth": "Authentication failed. Token may have expired (2 min limit) or credentials are wrong. Try again with a fresh token.",
|
||||
"invalid_auth": "Authentication failed: {reason}. Try again with a fresh token.",
|
||||
"invalid_credentials": "PerfectDraft rejected the email or password: {reason}.",
|
||||
"token_rejected": "PerfectDraft rejected the verification token: {reason}. Generate a fresh token and paste it within 2 minutes.",
|
||||
"cannot_connect": "Cannot connect to PerfectDraft service.",
|
||||
"unknown": "An unexpected error occurred."
|
||||
},
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-09-26
|
||||
@@ -0,0 +1,53 @@
|
||||
## Context
|
||||
|
||||
The machine reports a numeric product ID. The integration resolves it through `keg_catalog.json`. The companion card (`hassio-component-perfectdraft-pro`) joins on the same ID via `kegId` in `src/beer-catalog.ts`, and only if that misses does it fall through to the sensor's name. `scripts/check-catalog.mjs` fails when an integration ID has no card `kegId`.
|
||||
|
||||
`47792` is absent from both catalogs. Issue #7 names the fitted keg Camden Eazy. The card already has that beer:
|
||||
|
||||
```
|
||||
slug: "camden-eazy", name: "Camden Eazy", imagePath: kegs/camden-eazy.webp, kegId: "47629"
|
||||
```
|
||||
|
||||
The integration lists that other ID as `"47629": "Camden Eazy IPA"`. The card prefers `kegId`, so a machine reporting `47629` already shows Camden Eazy with the existing graphic. `47792` follows Old Speckled Hen `47774` and precedes Corona Ligera `47816`.
|
||||
|
||||
`GET /api/products/{id}` still returns `{id}` only. Provenance is the reporter's fitted keg and the name in the issue title.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
|
||||
- The **Keg** sensor reports Camden Eazy for product ID `47792`.
|
||||
- The card resolves `47792` by `kegId` to that same branding and the existing keg graphic.
|
||||
- `47629` keeps its current integration name and card binding.
|
||||
|
||||
**Non-Goals:**
|
||||
|
||||
- Deciding whether `47629` and `47792` are one recipe or two wraps. Only `47792` was observed for this issue.
|
||||
- A second keg photo.
|
||||
- A card model that stores more than one product ID on a single entry.
|
||||
|
||||
## Decisions
|
||||
|
||||
**List 47792 as "Camden Eazy", and leave 47629 as "Camden Eazy IPA".**
|
||||
The reporter's name is Camden Eazy. Copying the IPA suffix from `47629` would label a different observed ID. Renaming `47629` would change a keg this issue did not report.
|
||||
|
||||
**Add a second card entry that reuses `kegs/camden-eazy.webp`. Do not draw a new graphic.**
|
||||
`camden-eazy` already owns `kegId` `47629`, and the catalog is one ID per entry (`kegIdIndex` and `check-catalog` both assume that). A new slug, `camden-eazy-47792`, carries the same name, brewery, style, ABV, colours, and `imagePath: kegImage("camden-eazy")`. No new asset file.
|
||||
|
||||
Allowing `kegId` to be a list was considered and rejected. It would change the index, the coverage check, and the editor for a case the previous keg addition (`48050`) kept as a separate row.
|
||||
|
||||
**Name-index collision is acceptable.**
|
||||
`nameIndex` keeps the last entry for a given display name, so "Camden Eazy" resolves to whichever row is registered later. That path is unused when a product ID is present: `_updateDetectedBeer` tries `getBeerByKegId` first. The beer picker will list Camden Eazy twice; both rows look the same.
|
||||
|
||||
**Patch releases.**
|
||||
Catalog growth does not change requirements existing users depend on, aside from the floor ratchet. Integration `0.3.4`, card `0.4.2`.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
**47792 is a different wrap than the existing Camden Eazy photo** → The card shows the current Camden Eazy keg until someone supplies a distinct photo. Same bar as every other reused asset.
|
||||
|
||||
**A later keg uses 47792 for a different beer** → Same risk as every catalog row. The ID was observed from a machine.
|
||||
|
||||
**HACS users update only one package** → Integration-only: the **Keg** sensor names it, and the card's name fallback still hits the existing Camden Eazy entry because the names match. Card-only: the sensor stays blank, and the card can brand `47792` once that ID is on an entity. Release notes tell people to update both.
|
||||
|
||||
**Two picker rows named Camden Eazy** → Accepted. Merging them would either drop `47629` or change the one-ID model.
|
||||
@@ -0,0 +1,34 @@
|
||||
## Why
|
||||
|
||||
Issue #7: product ID `47792` is missing from the bundled keg catalog, so the **Keg** sensor stays blank. The reporter identifies the fitted keg as **Camden Eazy**. That name is already on the companion card, but it is bound to a different product ID (`47629`, listed in the integration as Camden Eazy IPA).
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add `"47792": "Camden Eazy"` to `keg_catalog.json` in numeric key order.
|
||||
- Ratchet the catalog floor from 115 to 116 in tests and the `entities` spec.
|
||||
- Patch-bump the integration to 0.3.4.
|
||||
- Companion card: add a catalog entry for `kegId: "47792"` that reuses the existing Camden Eazy colours and `kegs/camden-eazy.webp`. Leave the `47629` entry where it is. Re-sync `scripts/keg-catalog.reference.json`. Patch-bump the card to 0.4.2.
|
||||
|
||||
Not in scope:
|
||||
|
||||
- Renaming `47629` from "Camden Eazy IPA" or moving its card binding.
|
||||
- New keg artwork. The Camden Eazy graphic already exists.
|
||||
- Falling back to the raw product ID when a keg is unmapped.
|
||||
- Allowing one card entry to hold more than one product ID.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `entities`: keg name catalog floor ratchets from 115 to 116 product IDs.
|
||||
|
||||
## Impact
|
||||
|
||||
- Users with keg `47792` see **Camden Eazy** on the **Keg** sensor after updating to 0.3.4, and the existing Camden Eazy branding on the card after 0.4.2.
|
||||
- Users with keg `47629` are unchanged.
|
||||
- No entity churn, no migration, no behaviour change for any other ID.
|
||||
- The name lookup lives in the integration. The card still needs its own `kegId` row: it joins on product ID first, and `check:catalog` treats an unbound integration ID as a gap. The graphic does not.
|
||||
@@ -0,0 +1,29 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Keg name sensor
|
||||
The integration SHALL expose the name of the tapped beer, resolved from the keg product ID through a catalog bundled with the integration at `keg_catalog.json`. The catalog SHALL cover every keg the PerfectDraft app can select, including discontinued kegs that may still be fitted in a machine, and SHALL contain at least 116 product IDs.
|
||||
|
||||
Catalog entries SHALL be observed directly from a machine reporting that product ID rather than inferred from shop listings, because the product IDs cannot be queried in bulk from the API. Entry names SHALL be the beer's name only, excluding shop-listing artefacts such as pack size, "Short Date" prefixes, or best-before dates.
|
||||
|
||||
#### Scenario: Known product ID resolves to a name
|
||||
- **WHEN** the keg product ID is present in the catalog
|
||||
- **THEN** the sensor SHALL report the catalog's name for that ID
|
||||
- **THEN** it SHALL have icon mdi:beer
|
||||
|
||||
#### Scenario: Unknown product ID
|
||||
- **WHEN** the keg product ID is not present in the catalog
|
||||
- **THEN** the sensor SHALL report no value
|
||||
|
||||
#### Scenario: No keg fitted
|
||||
- **WHEN** no keg product ID can be determined
|
||||
- **THEN** the sensor SHALL report no value
|
||||
|
||||
#### Scenario: Catalog unreadable or malformed
|
||||
- **WHEN** `keg_catalog.json` is missing or cannot be parsed
|
||||
- **THEN** the integration SHALL treat the catalog as empty and continue loading
|
||||
- **THEN** the keg name sensor SHALL report no value while every other entity SHALL be unaffected
|
||||
|
||||
#### Scenario: Catalog format
|
||||
- **WHEN** the catalog file is read
|
||||
- **THEN** it SHALL be a flat JSON object mapping the product ID as a string key to the display name as a string value
|
||||
- **THEN** keys SHALL be ordered numerically
|
||||
@@ -0,0 +1,20 @@
|
||||
## 1. Integration catalog
|
||||
|
||||
- [x] 1.1 Add `"47792": "Camden Eazy"` to `keg_catalog.json` in numeric key order, after `47774` and before `47816`
|
||||
- [x] 1.2 Bump `manifest.json` to 0.3.4
|
||||
- [x] 1.3 Ratchet `MINIMUM_ENTRIES` to 116 and assert `catalog["47792"]`
|
||||
- [x] 1.4 Update the README catalog count from 115 to 116
|
||||
|
||||
## 2. Companion card
|
||||
|
||||
Work in `Hassio-PerfectDraftPro-Component`. Do not retarget the existing `camden-eazy` / `47629` entry.
|
||||
|
||||
- [x] 2.1 Add a `camden-eazy-47792` entry with `kegId: "47792"`, the same name, brewery, style, ABV, and colours as `camden-eazy`, and `imagePath: kegImage("camden-eazy")`
|
||||
- [x] 2.2 Re-sync `scripts/keg-catalog.reference.json` to the integration commit that adds `47792`
|
||||
- [x] 2.3 Bump `package.json`, `CARD_VERSION`, and `EDITOR_VERSION` to 0.4.2 and rebuild `dist/`
|
||||
|
||||
## 3. Verify and ship
|
||||
|
||||
- [x] 3.1 `python3 -m unittest tests.test_keg_catalog` — 116 keys, including `47792`
|
||||
- [x] 3.2 In the card repo: `npm run lint`, `npm run check:catalog` (116/116), `npm run build`
|
||||
- [x] 3.3 Publish GitHub releases v0.3.4 and v0.4.2
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-07
|
||||
@@ -0,0 +1,45 @@
|
||||
## Context
|
||||
|
||||
See proposal.md for why. The machine reports a numeric product ID. The integration resolves it through `keg_catalog.json`, and the card joins on the same ID via `kegId` in `src/beer-catalog.ts`. `npm run check:catalog` fails when an integration ID has no card `kegId`.
|
||||
|
||||
`48180` is the highest ID so far, so it goes after `48134` (Kopparberg Crisp Apple). The card has no Camden stout entry and no `camden-stout` artwork. Card PR #2 supplies both: `src/assets/kegs/camden-stout.webp`, and an entry with style Stout, ABV 4.0 and dark colours.
|
||||
|
||||
Two names are in circulation for the same ID:
|
||||
|
||||
| Source | Name |
|
||||
|---|---|
|
||||
| Issue #9 / PR #10 / card PR #2 (MThomas564, keg fitted) | Camden Stout |
|
||||
| brettjenkins fork, commit `3e4a2cc` | Camden Nitro Stout |
|
||||
|
||||
The PerfectDraft shop search did not render product names when checked on 2026-11-07, so it cannot break the tie. It is not authoritative under the catalog rule in any case.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
|
||||
- The **Keg** sensor names `48180`, and the card shows its branding and artwork.
|
||||
- MThomas564's contribution lands under his name.
|
||||
|
||||
**Non-Goals:**
|
||||
|
||||
- Reconciling the rest of the fork's catalog with ours.
|
||||
|
||||
## Decisions
|
||||
|
||||
**Land the change ourselves, crediting the contributor, rather than merging PR #10 and card PR #2.**
|
||||
Both PRs need edits that would amount to rewriting them: key order, the README re-pad, the version clash, and a reference snapshot pinned to an unmerged commit. Asking a first-time contributor for three rounds of fixes costs more goodwill than it saves. Both commits carry `Co-authored-by: MThomas564 <noreply address from his GitHub commits>`. The closing comments on the PRs link the commits and the release.
|
||||
|
||||
**Name: "Camden Stout" unless the contributor says otherwise.**
|
||||
He has the keg fitted, which is the bar the catalog sets. The fork's "Nitro" may well be correct, since Camden does sell a nitro stout. So we ask him once, on PR #10, what the keg or the PerfectDraft app calls it. If he hasn't answered by the time `fix-cognito-signin` is ready to ship, we ship "Camden Stout" rather than hold the sign-in fix. A later rename is a one-line patch with no entity churn.
|
||||
|
||||
**Card entry: take PR #2's artwork and fields, and verify the ABV.**
|
||||
We use slug `camden-stout`, brewery "Camden Town Brewery", style "Stout", colours as in PR #2, `imagePath: kegImage("camden-stout")`, and `kegId: "48180"`. The ABV of 4.0 is checked against Camden's or PerfectDraft's product page before landing. The card displays it, and a stout at exactly the session-pale ABV is worth a second look. The artwork file comes from PR #2's head commit unchanged. `dist/` is rebuilt with our `npm run build`, not taken from the PR.
|
||||
|
||||
**Versions: both packages ship as 0.4.4; no separate integration bump here.**
|
||||
On 2026-11-07 the maintainer synced the two version lines: the integration jumps 0.3.4 → 0.4.4 (owned by `fix-cognito-signin`) and the card 0.4.2 → 0.4.4. From here major.minor moves in lockstep and the patch number may diverge for a fix to only one package (for example card 0.4.5 alongside integration 0.4.4). Letter suffixes such as `0.4.4b` are not used: PEP 440 (HACS) and SemVer (npm) both read them as pre-releases that sort before 0.4.4. The card bumps in `package.json`, `CARD_VERSION` and `EDITOR_VERSION`. PR #2's `package-lock.json` jump from 0.3.1 is a stale lockfile, so we regenerate the lockfile rather than copy it.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **The name is wrong.** A one-line catalog patch fixes it later. Entity IDs do not depend on the name.
|
||||
- **The card snapshot is pinned before the integration commit exists.** Re-sync `_upstreamCommit` after the integration commit is made on its branch, and re-check after any rebase.
|
||||
- **HACS users update only one package.** If they update only the integration, the sensor names the keg and the card falls back to the sensor's name without artwork. If they update only the card, the sensor stays blank, but the card brands `48180` once an entity reports it. The release notes tell people to update both, which they need to anyway for the sign-in fix.
|
||||
@@ -0,0 +1,44 @@
|
||||
## Why
|
||||
|
||||
Issue #9: product ID `48180` is missing from the bundled keg catalog, so the **Keg** sensor stays blank for it. The reporter, MThomas564, has the keg fitted and opened PR #10 against the integration and PR #2 against the companion card. Neither can be merged as-is:
|
||||
|
||||
- PR #10 inserts `48180` between `48061` and `48134`, which fails `test_keys_in_ascending_numeric_order`.
|
||||
- PR #10 also re-pads the whole README sensor table for a one-number change.
|
||||
- PR #10 bumps the integration to 0.3.5, which clashes with the version bump owned by `fix-cognito-signin`, which ships in the same release.
|
||||
- Card PR #2 pins its reference snapshot to PR #10's unmerged commit and ships a `dist/` built outside our toolchain.
|
||||
|
||||
The name is also disputed. PR #10 says "Camden Stout", while brettjenkins' fork maps the same ID as "Camden Nitro Stout".
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add `48180` to `keg_catalog.json` as the last key, after `48134`. The name defaults to "Camden Stout", as reported by the person with the keg fitted. It changes to "Camden Nitro Stout" only if MThomas564 confirms the app or keg reads that way.
|
||||
- Ratchet the catalog floor from 116 to 117 in tests and the `entities` spec. Update the README count without reformatting the table.
|
||||
- No integration version bump of its own. It ships in 0.4.4 with `fix-cognito-signin`.
|
||||
- Companion card:
|
||||
- Add a `camden-stout` entry with `kegId: "48180"` and the keg artwork from card PR #2.
|
||||
- Re-sync `scripts/keg-catalog.reference.json` to the integration commit that adds `48180`.
|
||||
- Bump the card to 0.4.4 and rebuild `dist/`.
|
||||
- Credit MThomas564 as co-author on both commits, then close PR #10, card PR #2 and issue #9 with a pointer to the release.
|
||||
|
||||
Not in scope:
|
||||
|
||||
- brettjenkins' other catalog additions (for example Fada Sunny IPA `48068`). Nobody has reported them here, and each needs its own observation.
|
||||
- Issue #8 (missing Löwenbräu and Spaten artwork on the card). Both IDs are already named.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `entities`: the keg name catalog floor ratchets from 116 to 117 product IDs.
|
||||
|
||||
## Impact
|
||||
|
||||
- Users with keg `48180` see its name on the **Keg** sensor after 0.4.4, and Camden Stout branding and artwork on the card after 0.4.4.
|
||||
- No entity churn, no migration, and no change for any other ID.
|
||||
- Integration: `keg_catalog.json`, `tests/test_keg_catalog.py`, `README.md`.
|
||||
- Card repo (`Hassio-PerfectDraftPro-Component`): `src/beer-catalog.ts`, `src/assets/kegs/camden-stout.webp`, `scripts/keg-catalog.reference.json`, `package.json`, `CARD_VERSION`, `EDITOR_VERSION`, `dist/`.
|
||||
- External: PR #10, card PR #2 and issue #9 close once the joint release ships.
|
||||
@@ -0,0 +1,29 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Keg name sensor
|
||||
The integration SHALL expose the name of the tapped beer, resolved from the keg product ID through a catalog bundled with the integration at `keg_catalog.json`. The catalog SHALL cover every keg the PerfectDraft app can select, including discontinued kegs that may still be fitted in a machine, and SHALL contain at least 117 product IDs.
|
||||
|
||||
Catalog entries SHALL be observed directly from a machine reporting that product ID rather than inferred from shop listings, because the product IDs cannot be queried in bulk from the API. Entry names SHALL be the beer's name only, excluding shop-listing artefacts such as pack size, "Short Date" prefixes, or best-before dates.
|
||||
|
||||
#### Scenario: Known product ID resolves to a name
|
||||
- **WHEN** the keg product ID is present in the catalog
|
||||
- **THEN** the sensor SHALL report the catalog's name for that ID
|
||||
- **THEN** it SHALL have icon mdi:beer
|
||||
|
||||
#### Scenario: Unknown product ID
|
||||
- **WHEN** the keg product ID is not present in the catalog
|
||||
- **THEN** the sensor SHALL report no value
|
||||
|
||||
#### Scenario: No keg fitted
|
||||
- **WHEN** no keg product ID can be determined
|
||||
- **THEN** the sensor SHALL report no value
|
||||
|
||||
#### Scenario: Catalog unreadable or malformed
|
||||
- **WHEN** `keg_catalog.json` is missing or cannot be parsed
|
||||
- **THEN** the integration SHALL treat the catalog as empty and continue loading
|
||||
- **THEN** the keg name sensor SHALL report no value while every other entity SHALL be unaffected
|
||||
|
||||
#### Scenario: Catalog format
|
||||
- **WHEN** the catalog file is read
|
||||
- **THEN** it SHALL be a flat JSON object mapping the product ID as a string key to the display name as a string value
|
||||
- **THEN** keys SHALL be ordered numerically
|
||||
@@ -0,0 +1,39 @@
|
||||
## 1. Name and worktrees
|
||||
|
||||
- [ ] 1.1 Ask MThomas564 on PR #10 whether the keg or the PerfectDraft app calls 48180 "Camden Stout" or "Camden Nitro Stout"; record the answer (or "no reply by release, shipping Camden Stout") in this file
|
||||
- Asked 2026-11-07: https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/pull/10#issuecomment-6706008826 — awaiting reply; implementation proceeds with "Camden Stout"
|
||||
- [x] 1.2 `scripts/agent-worktree.sh create add-keg-48180` in the integration repo, and an equivalent `.worktree/add-keg-48180` on branch `agent/add-keg-48180` in `Hassio-PerfectDraftPro-Component`; confirm `.agent-lock` in both
|
||||
|
||||
## 2. Integration catalog
|
||||
|
||||
- [x] 2.1 Add `"48180": "<name from 1.1>"` to `keg_catalog.json` as the last key, after `48134`
|
||||
- [x] 2.2 Ratchet `MINIMUM_ENTRIES` to 117 in `tests/test_keg_catalog.py` and assert `catalog["48180"]`; verify `python3 -m unittest tests.test_keg_catalog` passes (117 keys, ascending order)
|
||||
- [x] 2.3 Change the README catalog count from 116 to 117 in place, touching no other table cell or padding; verify `git diff README.md` is a single-line change
|
||||
- [x] 2.4 Commit with `Co-authored-by: MThomas564` (address from his PR #10 commit); do not touch `manifest.json`
|
||||
|
||||
## 3. Companion card
|
||||
|
||||
Work in `Hassio-PerfectDraftPro-Component`.
|
||||
|
||||
- [x] 3.1 Take `src/assets/kegs/camden-stout.webp` from card PR #2's head commit unchanged
|
||||
- [x] 3.2 Add the `camden-stout` entry (name from 1.1, Camden Town Brewery, Stout, PR #2 colours, `imagePath: kegImage("camden-stout")`, `kegId: "48180"`) next to the other Camden rows; check the ABV against Camden's or PerfectDraft's product page and use that value
|
||||
- ABV 4.0% confirmed on Camden Town Brewery's "Camden X PerfectDraft Stout" listing (camdentownbrewery.com, 2026-11-07), which also calls the keg "Camden Stout"
|
||||
- [x] 3.3 Re-sync `scripts/keg-catalog.reference.json` from the integration commit in 2.4 and set `_upstreamCommit` to it
|
||||
- [x] 3.4 Bump `package.json`, `CARD_VERSION` and `EDITOR_VERSION` to 0.4.4; regenerate `package-lock.json` with `npm install --package-lock-only` rather than copying PR #2's
|
||||
- [x] 3.5 `npm run lint`, `npm run check:catalog` (117/117), `npm run build`; commit source and `dist/` with `Co-authored-by: MThomas564`
|
||||
|
||||
## 4. Joint verification
|
||||
|
||||
|
||||
## Deferred: shipping without on-device checks
|
||||
|
||||
Maintainer decision, 2026-11-07: ship card 0.4.4 and the 48180 catalog entry without this check (no time for a Home Assistant reinstall), as with `fix-cognito-signin` 5.2–5.4. Coverage at release: catalog unit tests (117 keys, ordering), `npm run lint`, `npm run check:catalog` (117/117) and a clean `npm run build` with the artwork in `dist/`. The open TODO is in `PROJECT_HYGIENE.md`.
|
||||
|
||||
- 4.1 With `fix-cognito-signin` also applied, install integration 0.4.4 and card 0.4.4 on Home Assistant; if a 48180 keg is unavailable, confirm instead that the card editor's beer picker lists the new entry with its artwork, and that `getBeerByKegId("48180")` resolves it in a browser console on the dashboard
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Before archiving this change, archive `add-keg-47792` (complete since v0.3.4, never archived), so the `entities` main spec reads 116 before this delta lifts it to 117.
|
||||
- Joint release: integration v0.4.4 (with `fix-cognito-signin`) and card v0.4.4, published together. The release notes thank MThomas564 and tell users to update both.
|
||||
- After the release, close PR #10, card PR #2 and issue #9, each with a thank-you, the commit links and the release link.
|
||||
- Archive per `AGENTS.md` in both repos (merge, push, sync the `entities` spec, archive, remove worktrees and branches).
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-09-17
|
||||
@@ -0,0 +1,22 @@
|
||||
## Context
|
||||
|
||||
The machine reports a numeric product ID. The integration resolves it through `keg_catalog.json`; the companion card joins on the same ID via `kegId`. `48050` sat in a hole in the 47–48xxx cluster (between Siren Lumina IPA `48024` and Northern Monk Faith `48061`) that the 114-entry snapshot never included.
|
||||
|
||||
`GET /api/products/{id}` still returns `{id}` only. Provenance is the reporter's fitted keg plus their confirmation of the wrap.
|
||||
|
||||
## Decisions
|
||||
|
||||
**List 48050 as "Anheuser-Busch Bud", not "Budweiser".**
|
||||
The two wraps are visually distinct (Budweiser script vs Anheuser-Busch Bud on a white band). The reporter chose the DE/AT option. `31747` stays "Budweiser". Duplicate display names were considered and rejected: the sensor is "what is printed on this keg".
|
||||
|
||||
**Reuse the card's existing `bud` entry rather than adding a second beer.**
|
||||
`src/beer-catalog.ts` already had `name: "Anheuser-Busch Bud"` with `kegs/bud.webp` and no `kegId`. Binding `48050` completes the join. The card's one-ID-per-entry model holds.
|
||||
|
||||
**Patch releases, not a behaviour-contract bump.**
|
||||
Catalog growth does not change requirements existing users depend on. Integration `0.3.3`, card `0.4.1`.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
**A later keg uses 48050 for a different beer** → Same risk as every catalog row. The ID was observed from a machine, which is the established bar.
|
||||
|
||||
**HACS users update only one of the two packages** → Integration-only: the **Keg** sensor names it, the card falls through to name matching and still resolves because the names now match. Card-only: the **Keg** sensor stays blank, the card can still brand `48050` if that sensor exists from an older integration that reports the ID. Release notes tell people to update both.
|
||||
@@ -0,0 +1,32 @@
|
||||
## Why
|
||||
|
||||
Issue #3 (closed after the La Chouffe Blonde backport in v0.3.2) received a follow-up: product ID `48050` is missing from the bundled keg catalog, so the **Keg** sensor stays blank. The reporter confirmed the keg is the DE/AT wrap **Anheuser-Busch Bud**, not the UK Budweiser SKU already listed as `31747`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add `"48050": "Anheuser-Busch Bud"` to `keg_catalog.json` in numeric key order.
|
||||
- Ratchet the catalog floor from 114 to 115 in tests and the `entities` spec.
|
||||
- Patch-bump the integration to 0.3.3.
|
||||
- Companion card: bind the existing `bud` catalog entry (name, colours, keg artwork already present) to `kegId: "48050"` and re-sync `scripts/keg-catalog.reference.json`. Patch-bump the card to 0.4.1.
|
||||
|
||||
Not in scope:
|
||||
|
||||
- Falling back to the raw product ID when a keg is unmapped.
|
||||
- Scraping the PerfectDraft shop for names.
|
||||
- Treating `31747` and `48050` as aliases of one catalog name.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `entities`: keg name catalog floor ratchets from 114 to 115 product IDs.
|
||||
|
||||
## Impact
|
||||
|
||||
- Users with keg `48050` see **Anheuser-Busch Bud** on the **Keg** sensor after updating to 0.3.3, and the matching card branding after 0.4.1.
|
||||
- Users with keg `31747` are unchanged (`Budweiser`).
|
||||
- No entity churn, no migration, no behaviour change for any other ID.
|
||||
@@ -0,0 +1,29 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Keg name sensor
|
||||
The integration SHALL expose the name of the tapped beer, resolved from the keg product ID through a catalog bundled with the integration at `keg_catalog.json`. The catalog SHALL cover every keg the PerfectDraft app can select, including discontinued kegs that may still be fitted in a machine, and SHALL contain at least 115 product IDs.
|
||||
|
||||
Catalog entries SHALL be observed directly from a machine reporting that product ID rather than inferred from shop listings, because the product IDs cannot be queried in bulk from the API. Entry names SHALL be the beer's name only, excluding shop-listing artefacts such as pack size, "Short Date" prefixes, or best-before dates.
|
||||
|
||||
#### Scenario: Known product ID resolves to a name
|
||||
- **WHEN** the keg product ID is present in the catalog
|
||||
- **THEN** the sensor SHALL report the catalog's name for that ID
|
||||
- **THEN** it SHALL have icon mdi:beer
|
||||
|
||||
#### Scenario: Unknown product ID
|
||||
- **WHEN** the keg product ID is not present in the catalog
|
||||
- **THEN** the sensor SHALL report no value
|
||||
|
||||
#### Scenario: No keg fitted
|
||||
- **WHEN** no keg product ID can be determined
|
||||
- **THEN** the sensor SHALL report no value
|
||||
|
||||
#### Scenario: Catalog unreadable or malformed
|
||||
- **WHEN** `keg_catalog.json` is missing or cannot be parsed
|
||||
- **THEN** the integration SHALL treat the catalog as empty and continue loading
|
||||
- **THEN** the keg name sensor SHALL report no value while every other entity SHALL be unaffected
|
||||
|
||||
#### Scenario: Catalog format
|
||||
- **WHEN** the catalog file is read
|
||||
- **THEN** it SHALL be a flat JSON object mapping the product ID as a string key to the display name as a string value
|
||||
- **THEN** keys SHALL be ordered numerically
|
||||
@@ -0,0 +1,18 @@
|
||||
## 1. Integration catalog
|
||||
|
||||
- [x] 1.1 Add `"48050": "Anheuser-Busch Bud"` to `keg_catalog.json` in numeric key order
|
||||
- [x] 1.2 Bump `manifest.json` to 0.3.3
|
||||
- [x] 1.3 Ratchet `MINIMUM_ENTRIES` to 115 and assert `catalog["48050"]`
|
||||
- [x] 1.4 Update README catalog count; leave Brett's 114-entry credit intact as the original mapping
|
||||
|
||||
## 2. Companion card
|
||||
|
||||
- [x] 2.1 Set `kegId: "48050"` on the existing `bud` / Anheuser-Busch Bud entry
|
||||
- [x] 2.2 Re-sync `scripts/keg-catalog.reference.json` to integration commit `fc8a25c4`
|
||||
- [x] 2.3 Bump `package.json`, `CARD_VERSION`, and `EDITOR_VERSION` to 0.4.1 and rebuild `dist/`
|
||||
|
||||
## 3. Verify and ship
|
||||
|
||||
- [x] 3.1 `python3 -m unittest tests.test_keg_catalog` — 9 tests, 115 keys
|
||||
- [x] 3.2 `npm run lint`, `npm run check:catalog` (115/115), `npm run build`
|
||||
- [x] 3.3 Publish GitHub releases v0.3.3 and v0.4.1
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-07
|
||||
@@ -0,0 +1,66 @@
|
||||
## Context
|
||||
|
||||
See proposal.md for why. Current state:
|
||||
|
||||
- `authenticate()` in `api.py` POSTs `{email, password, recaptchaToken, recaptchaAction}` with `x-api-key` to `api.perfectdraft.com/authentication/sign-in`, and reads `AccessToken`/`IdToken`/`RefreshToken` from the top level of the response.
|
||||
- `refresh_access_token()` already calls Cognito `InitiateAuth` directly (`REFRESH_TOKEN_AUTH`, client `57ddq2ppqg2jcpup06r2g1deur`, no client secret). Gateway and refresh share nothing beyond the client ID.
|
||||
- `config_flow.py` maps every `AuthenticationError` to `invalid_auth` on the token form. `exceptions.AuthenticationError` is a bare subclass with no fields.
|
||||
- The perfectdraft.com shop now sends `metadata: { recaptcha: { token, domain: window.location.origin } }`. cesa030's testing in #11 established three things. The gateway drops `domain` whatever field name or header is used. Direct `USER_PASSWORD_AUTH` works with `ClientMetadata {recaptchaToken, recaptchaAction: "Magento/login", domain: "https://www.perfectdraft.com"}`. Action `login` instead of `Magento/login` fails with "Unable to obtain reCAPTCHA site settings".
|
||||
- Re-checked on 2026-11-07 in a browser: the README snippet still yields a token (2,660 characters) on the en-gb login page. The page logs nothing to the console on its own.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
|
||||
- Setup and reauth work again with a token generated per the README.
|
||||
- A failed sign-in names the rejected input and the server's reason, so the next PerfectDraft-side change shows up as a readable message instead of "token may have expired".
|
||||
|
||||
**Non-Goals:**
|
||||
|
||||
- Detecting future PerfectDraft protocol changes automatically.
|
||||
- Localised error text beyond `en`. The integration ships only `translations/en.json`.
|
||||
|
||||
## Decisions
|
||||
|
||||
**Call Cognito directly rather than keep the gateway.**
|
||||
No request shape gets `domain` through the gateway, so it cannot be fixed on our side. Cognito `InitiateAuth` is already a dependency through token refresh, so this adds no new endpoint or trust relationship. The `x-api-key` header is unnecessary for Cognito and is dropped from sign-in only. Data requests still send it.
|
||||
|
||||
**Write our own implementation; do not merge or cherry-pick brettjenkins' fork.**
|
||||
The fork is 48 commits ahead and 64 behind. Its sign-in commit also touches the reauth path we already rewrote in `fix-reauth-flow`, plus versioning and the manifest. We reimplement from the protocol cesa030 documented in #11, which is a few lines, and credit both of them in the release notes. The error classification follows the same idea as the fork. The error key names `token_rejected` and `invalid_credentials` match it, so users moving back from the fork see familiar messages.
|
||||
|
||||
**`domain` is a constant `https://www.perfectdraft.com`, independent of the shop country.**
|
||||
The Lambda validates it as the origin the token was minted for. All country shops share the `www.perfectdraft.com` origin. cesa030 confirmed en-gb and de-de tokens both work with it. It sits in `const.py` next to `RECAPTCHA_SITE_KEY` and `RECAPTCHA_ACTION`. `api.py`'s duplicate `RECAPTCHA_ACTION_SIGN_IN` is dropped in favour of `const.RECAPTCHA_ACTION`.
|
||||
|
||||
**Classification lives on `AuthenticationError`, not in the config flow.**
|
||||
`AuthenticationError(message, code=None, reason=None)` gains a `kind` property (`credentials` / `token` / `other`) and a `display_reason` that is never empty. Existing `AuthenticationError("...")` call sites, including refresh and the coordinator, keep working unchanged. The config flow maps `kind` to an error key and stays free of Cognito vocabulary.
|
||||
|
||||
| Cognito `__type` | kind | Error key | Form shown again |
|
||||
|---|---|---|---|
|
||||
| `NotAuthorizedException`, `UserNotFoundException` | credentials | `invalid_credentials` | user form (setup) or `reauth_confirm` (reauth) |
|
||||
| `UserLambdaValidationException` | token | `token_rejected` | token form |
|
||||
| anything else, a challenge name, or none | other | `invalid_auth` | token form |
|
||||
|
||||
`NotAuthorizedException` also covers "Password attempts exceeded". It still lands on the credentials form, and the reason text says what happened.
|
||||
|
||||
**A credentials failure returns to the credentials form.**
|
||||
reCAPTCHA Enterprise tokens are single-use, so the token is spent either way. Asking for another token on the token form would only lead to the same rejection. The flow re-renders the user form (or `reauth_confirm`) with the error, and submitting it leads back to the token step as usual.
|
||||
|
||||
**The server's reason goes through `{reason}` in the error strings.**
|
||||
Home Assistant fills error placeholders from `description_placeholders`. Every `async_show_form` for `user`, `reauth_confirm` and `token` passes `{"reason": ...}`, with an empty string when there is no error, so no form can render a literal `{reason}`. The reason is the Cognito `message`, with any trailing period removed (the string supplies punctuation) and truncated to 200 characters. It is also logged at error level, as today. The log contains the Cognito error body only, never the request.
|
||||
|
||||
**README: copy to the clipboard instead of printing the token.**
|
||||
`copy()` is a DevTools console utility in Chrome, Edge, Firefox and Safari, but only works while the typed command is still evaluating, and the token arrives asynchronously. In Chromium, `copy` is `undefined` inside a `.then` or after an `await` (verified 2026-11-07). In Firefox, `copy()` only records a `helperResult` that the console reads when evaluation returns (`eval-with-debugger.js`: `helperResult: helpers.getHelperResult()`), so a later call logs nothing and copies nothing (reported by the maintainer 2026-11-07). A two-command version (store in a global, then `copy()` it) works but adds a step for users who rarely open DevTools, so it was rejected. `prompt(msg, token)` was also rejected. Chromium cuts a prompt's default value off at 2,000 characters (the maintainer's test copied exactly 2,000), and tokens run to about 2,450–2,700. The README keeps one command that adds a fixed **Click THIS BLACK BOX to copy your PerfectDraft token** button (the maintainer found plain "Click to copy" unclear about where to click) to the page. Its click handler calls `navigator.clipboard.writeText(token)`: the click is the user activation and page focus the Clipboard API needs, so there is no length cap and no console helper involved. The command also `console.log`s the token as a fallback. In Cursor's embedded browser the write fails with "Document is not focused" because the view never has OS focus. The maintainer's check in real browsers copied full tokens (2,468 characters in Firefox, 2,510 in Chromium). Users no longer have to select a 2,600-character string, and nothing scrolls past. A sentence notes that the command should be run once at the console prompt, not as a "Live expression", which re-runs it continuously. That is the most likely explanation for #13's stream of tokens.
|
||||
|
||||
**Tests: stdlib-only for the client, existing harness for the flow.**
|
||||
`tests/test_api_authenticate.py` loads `api.py` without Home Assistant and drives a fake session. It covers the request shape, success, a challenge, each rejection kind, non-JSON bodies, other statuses and `ClientError`. `tests/test_config_flow.py` gains one test per error key, covering the form each lands on and the placeholder. It also gains a check that every config error key used in `config_flow.py` exists in both translation files, mirroring the existing abort-reason check.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **PerfectDraft changes the Lambda again.** The reason now reaches the UI, so the next break is diagnosable from a user's screenshot. Nothing else changes.
|
||||
- **PerfectDraft disables `USER_PASSWORD_AUTH` on the app client.** Cognito would return `InvalidParameterException`, which surfaces as `invalid_auth` with the reason. There is no mitigation beyond reacting. The shop itself appears to rely on this flow.
|
||||
- **We cannot test against the real service before release.** The stored refresh token on the dev host has expired. The planned mitigation, a manual sign-in through Home Assistant before tagging (tasks 5.2–5.4), was waived by the maintainer on 2026-11-07: v0.4.4 ships with only the automated suite and the browser-verified README token. If live sign-in fails, the `{reason}` placeholder puts the error in front of the reporting user, and the checks are owed as a post-release TODO in `PROJECT_HYGIENE.md`.
|
||||
- **The clipboard write fails in some browser.** The black box then shows "Copy failed: …", and the README tells the user to copy the token from the console, where the command also prints it.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
None. The config entry schema and stored token shape are unchanged. Installs whose refresh token is still valid never call `authenticate()` and see no difference. Rolling back to 0.3.4 restores a sign-in that is already broken, so there is no rollback that helps users. Fixes go forward.
|
||||
@@ -0,0 +1,48 @@
|
||||
## Why
|
||||
|
||||
Nobody can set up the integration or recover from a reauth prompt. Since PerfectDraft's October 2026 frontend update, every sign-in fails with `UserLambdaValidationException: PreAuthentication failed with error 'domain'`. PerfectDraft's Cognito PreAuthentication Lambda now requires a `domain` field in `ClientMetadata`, and the `api.perfectdraft.com/authentication/sign-in` gateway that `authenticate()` posts to does not forward it. Issue #11 has the root cause and a working fix from cesa030. #12 and #13 are the same failure.
|
||||
|
||||
The config flow made this hard to diagnose. Every authentication failure shows the same `invalid_auth` text, "Token may have expired (2 min limit) or credentials are wrong". So in #12 users regenerated tokens over and over for a failure no fresh token could fix.
|
||||
|
||||
## What Changes
|
||||
|
||||
- `PerfectDraftApiClient.authenticate()` signs in by calling Cognito `InitiateAuth` with `USER_PASSWORD_AUTH` directly. This is the endpoint token refresh already uses. `ClientMetadata` carries `recaptchaToken`, `recaptchaAction: Magento/login`, and `domain: https://www.perfectdraft.com`. The API gateway sign-in endpoint is no longer used.
|
||||
- If Cognito answers with a challenge instead of tokens, sign-in fails with `AuthenticationError` rather than a `KeyError`.
|
||||
- `AuthenticationError` carries the Cognito error type and message when the server supplies them.
|
||||
- The config flow tells the user why sign-in failed:
|
||||
- A wrong email or password (`NotAuthorizedException`, `UserNotFoundException`) returns to the credentials form with `invalid_credentials`. This is the user form during setup and `reauth_confirm` during reauth.
|
||||
- A rejected verification token (`UserLambdaValidationException`) stays on the token form with `token_rejected`.
|
||||
- Anything else stays on the token form with `invalid_auth`.
|
||||
- All three show the server's reason.
|
||||
- README step 2: the console snippet copies the token to the clipboard and prints a short confirmation. The user no longer has to select a 2,600-character string by hand. A note says to run it once at the console prompt.
|
||||
- Integration version 0.4.4, synced with the companion card (both 0.4.4; major.minor in lockstep from here). It ships in one joint release with `add-keg-48180` and the companion card release.
|
||||
|
||||
Not in scope:
|
||||
|
||||
- Persisting Cognito-refreshed tokens back to the config entry. This is a separate TODO in `PROJECT_HYGIENE.md`.
|
||||
- Automating token acquisition (an embedded browser, or a reCAPTCHA solver). The user still pastes a token generated on perfectdraft.com.
|
||||
- Any change to token refresh. It already calls Cognito directly and is unaffected.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `api-client`: "Sign-in with reCAPTCHA token" moves from the gateway to Cognito `InitiateAuth`, with the required `ClientMetadata`. Failures carry the Cognito error type and reason, and a challenge response is a failure.
|
||||
- `config-flow`: the "Invalid or expired token" scenario splits into three outcomes (credentials, token, other), each showing the server's reason. The reauth "authentication fails" scenario follows the same split.
|
||||
|
||||
## Impact
|
||||
|
||||
- `custom_components/perfectdraft/api.py`: `authenticate()`.
|
||||
- `custom_components/perfectdraft/exceptions.py`: `AuthenticationError` gains optional `code` and `reason`.
|
||||
- `custom_components/perfectdraft/const.py`: the reCAPTCHA domain constant. The sign-in action constant moves out of `api.py`.
|
||||
- `custom_components/perfectdraft/config_flow.py`: error mapping in `async_step_token`, and a return to the credentials form.
|
||||
- `custom_components/perfectdraft/strings.json`, `translations/en.json`: two new error keys. `invalid_auth` is reworded to include `{reason}`.
|
||||
- `README.md`: the step 2 snippet and wording.
|
||||
- `manifest.json`: 0.4.4.
|
||||
- `tests/`: a new stdlib-only test module for `authenticate()`. `test_config_flow.py` gains tests for the three error paths.
|
||||
- External: issues #11, #12 and #13. #12 and #13 are closed as duplicates of #11. #11 closes once the release ships. Credit goes to cesa030 for the root cause and fix, and to brettjenkins for the fork that confirmed it.
|
||||
- No config entry migration. Stored tokens have the same shape, so existing installs with a valid refresh token are unaffected.
|
||||
@@ -0,0 +1,43 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Sign-in with reCAPTCHA token
|
||||
The client SHALL authenticate by calling AWS Cognito `InitiateAuth` at `https://cognito-idp.eu-west-1.amazonaws.com/` with `AuthFlow: USER_PASSWORD_AUTH`, the Cognito client ID, and the email and password as `USERNAME` and `PASSWORD`. `ClientMetadata` SHALL carry `recaptchaToken`, `recaptchaAction: Magento/login`, and `domain: https://www.perfectdraft.com`, all three of which PerfectDraft's PreAuthentication check requires. The client SHALL NOT sign in through `api.perfectdraft.com/authentication/sign-in`, which does not forward `domain`.
|
||||
|
||||
#### Scenario: Successful sign-in
|
||||
- **WHEN** the client calls `authenticate(email, password, recaptcha_token)`
|
||||
- **THEN** it SHALL POST an `InitiateAuth` request to Cognito with `Content-Type: application/x-amz-json-1.1` and `X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth`
|
||||
- **THEN** the request SHALL carry the `ClientMetadata` fields listed above
|
||||
- **THEN** it SHALL parse the response with `content_type=None` to accept `application/x-amz-json-1.1`
|
||||
- **THEN** it SHALL store the `AccessToken`, `IdToken`, and `RefreshToken` from `AuthenticationResult`
|
||||
|
||||
#### Scenario: Challenge instead of tokens
|
||||
- **WHEN** Cognito answers 200 without a complete `AuthenticationResult`, for example with a `ChallengeName`
|
||||
- **THEN** the client SHALL raise `AuthenticationError`, carrying the challenge name as its error type when present
|
||||
- **THEN** no stored token SHALL change
|
||||
|
||||
#### Scenario: Sign-in failure
|
||||
- **WHEN** Cognito returns 400, 401, or 403
|
||||
- **THEN** the client SHALL raise `AuthenticationError` with the status and response body
|
||||
- **THEN** the error SHALL expose the Cognito error type (`__type`, without any namespace prefix) and the human-readable message, when the body supplies them
|
||||
|
||||
#### Scenario: Rejection is classified
|
||||
- **WHEN** a sign-in is rejected with error type `NotAuthorizedException` or `UserNotFoundException`
|
||||
- **THEN** the error SHALL classify as a credentials failure
|
||||
- **WHEN** a sign-in is rejected with error type `UserLambdaValidationException`
|
||||
- **THEN** the error SHALL classify as a verification token failure
|
||||
- **WHEN** a sign-in is rejected with any other error type, or none
|
||||
- **THEN** the error SHALL classify as an other failure
|
||||
|
||||
#### Scenario: Unreadable rejection body
|
||||
- **WHEN** a rejection body is not JSON, such as an HTML error page
|
||||
- **THEN** the client SHALL still raise `AuthenticationError`, with no error type and a reason truncated to at most 200 characters
|
||||
|
||||
#### Scenario: Other sign-in failures
|
||||
- **WHEN** Cognito returns any other non-200 status
|
||||
- **THEN** the client SHALL raise `PerfectDraftApiError`
|
||||
- **WHEN** the request fails due to `aiohttp.ClientError`
|
||||
- **THEN** the client SHALL raise `PerfectDraftConnectionError`
|
||||
|
||||
#### Scenario: Secrets are not logged
|
||||
- **WHEN** sign-in succeeds or fails
|
||||
- **THEN** the password, the verification token, and the issued tokens SHALL NOT be logged
|
||||
@@ -0,0 +1,85 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Token step collects verification token
|
||||
The config flow SHALL present a form requesting a reCAPTCHA verification token as the second step, with instructions linking to the README. When authentication fails, the flow SHALL tell the user which input was rejected and show the server's reason.
|
||||
|
||||
#### Scenario: Token step display
|
||||
- **WHEN** the user reaches the token step
|
||||
- **THEN** the description SHALL render without translation errors (no curly braces or newlines)
|
||||
- **THEN** the description SHALL contain a clickable link to the setup instructions on GitHub
|
||||
- **THEN** the description SHALL mention the 2-minute token expiry
|
||||
|
||||
#### Scenario: Valid token submitted
|
||||
- **WHEN** the user submits a valid token
|
||||
- **THEN** the flow SHALL call `authenticate()` with the email, password, and token
|
||||
- **THEN** on success, it SHALL fetch the user profile to discover the machine ID
|
||||
- **THEN** it SHALL create a config entry storing email, access token, ID token, refresh token, and machine ID
|
||||
|
||||
#### Scenario: Invalid or expired token
|
||||
- **WHEN** authentication fails as a verification token failure
|
||||
- **THEN** the flow SHALL show the token form again with the `token_rejected` error, including the server's reason
|
||||
- **THEN** the user SHALL be able to retry with a fresh token
|
||||
|
||||
#### Scenario: Wrong email or password
|
||||
- **WHEN** authentication fails as a credentials failure
|
||||
- **THEN** the flow SHALL show the credentials form again with the `invalid_credentials` error, including the server's reason
|
||||
- **THEN** that form SHALL be the email and password form during setup, and the `reauth_confirm` form during reauth
|
||||
- **THEN** after the user resubmits credentials, the flow SHALL ask for a fresh token
|
||||
|
||||
#### Scenario: Other authentication failure
|
||||
- **WHEN** authentication fails for any other reason
|
||||
- **THEN** the flow SHALL show the token form again with the `invalid_auth` error, including the server's reason
|
||||
- **THEN** the user SHALL be able to retry with a fresh token
|
||||
|
||||
#### Scenario: Failure without a server reason
|
||||
- **WHEN** authentication fails and the server supplied no reason
|
||||
- **THEN** the error message SHALL still render, with a fixed fallback in place of the reason and no unfilled placeholder
|
||||
|
||||
#### Scenario: API unreachable
|
||||
- **WHEN** the API is unreachable
|
||||
- **THEN** the flow SHALL show a connection error
|
||||
|
||||
### Requirement: Reauth flow
|
||||
The integration SHALL support Home Assistant's reauth mechanism when the refresh token expires. A successful reauth SHALL update the existing config entry in place, reload it, and abort with `reauth_successful`. It SHALL NOT create a second config entry, and it SHALL NOT abort with `already_configured`.
|
||||
|
||||
#### Scenario: Reauth triggered
|
||||
- **WHEN** the coordinator raises `ConfigEntryAuthFailed` because token refresh has failed
|
||||
- **THEN** Home Assistant SHALL start a reauth flow for the affected entry
|
||||
- **THEN** the flow SHALL show the `reauth_confirm` form pre-filled with the stored email
|
||||
- **THEN** submitting credentials SHALL advance to the token step
|
||||
|
||||
#### Scenario: Reauth succeeds and persists new tokens
|
||||
- **WHEN** the user submits a valid verification token during reauth and authentication succeeds
|
||||
- **THEN** the existing config entry's access token, ID token, and refresh token SHALL be replaced with the newly issued values
|
||||
- **THEN** the entry's stored email and machine ID SHALL be preserved unchanged
|
||||
- **THEN** the entry SHALL be reloaded
|
||||
- **THEN** the flow SHALL abort with reason `reauth_successful`
|
||||
- **THEN** no additional config entry SHALL be created
|
||||
|
||||
#### Scenario: Reauth does not abort as already configured
|
||||
- **WHEN** reauth authentication succeeds for the same account as the entry under repair
|
||||
- **THEN** the flow SHALL NOT abort with reason `already_configured`
|
||||
- **THEN** the "authentication failed, please re-authenticate" condition SHALL clear once the reloaded entry polls successfully
|
||||
|
||||
#### Scenario: Reauth with a different account is rejected
|
||||
- **WHEN** the user submits credentials during reauth for an email whose lowercased value differs from the entry's unique ID, and authentication succeeds
|
||||
- **THEN** the flow SHALL abort with reason `reauth_account_mismatch`
|
||||
- **THEN** the existing config entry's tokens SHALL be left unchanged
|
||||
|
||||
#### Scenario: Reauth accepts the same account in different letter case
|
||||
- **WHEN** the user re-enters the entry's email with different capitalisation during reauth
|
||||
- **THEN** the flow SHALL treat it as the same account and complete successfully
|
||||
|
||||
#### Scenario: Reauth authentication fails
|
||||
- **WHEN** the verification token or the credentials are rejected during reauth
|
||||
- **THEN** the flow SHALL show the same error, on the same form, as the matching failure during setup (`token_rejected`, `invalid_credentials` on the `reauth_confirm` form, or `invalid_auth`)
|
||||
- **THEN** the existing config entry's tokens SHALL be left unchanged
|
||||
|
||||
#### Scenario: Machine ID lookup is skipped when already known
|
||||
- **WHEN** reauth authentication succeeds and the existing entry already records a machine ID
|
||||
- **THEN** the flow SHALL NOT call the user profile endpoint
|
||||
- **THEN** the entry SHALL retain its recorded machine ID
|
||||
|
||||
#### Scenario: Machine ID recovered when absent
|
||||
- **WHEN** reauth authentication succeeds and the existing entry has no machine ID recorded
|
||||
- **THEN** the flow SHALL fetch the user profile and store the discovered machine ID on the entry
|
||||
@@ -0,0 +1,41 @@
|
||||
## 1. Worktree
|
||||
|
||||
- [x] 1.1 `scripts/agent-worktree.sh create fix-cognito-signin` and confirm `.worktree/fix-cognito-signin/.agent-lock` exists on branch `agent/fix-cognito-signin`
|
||||
|
||||
## 2. API client sign-in
|
||||
|
||||
- [x] 2.1 Add `RECAPTCHA_DOMAIN = "https://www.perfectdraft.com"` to `const.py`; drop `RECAPTCHA_ACTION_SIGN_IN` from `api.py` in favour of `const.RECAPTCHA_ACTION`, and move `COGNITO_IDP_URL` alongside if it reads better; verify `rg RECAPTCHA_ACTION_SIGN_IN` finds nothing
|
||||
- [x] 2.2 Give `AuthenticationError` optional `code` and `reason`, a `kind` property (`credentials` / `token` / `other`, per the design table) and a never-empty `display_reason` (trailing period stripped, at most 200 chars); existing single-argument raises still work
|
||||
- [x] 2.3 Rewrite `authenticate()` as Cognito `InitiateAuth` `USER_PASSWORD_AUTH` with `ClientMetadata {recaptchaToken, recaptchaAction, domain}`; parse with `content_type=None`; read tokens from `AuthenticationResult`; raise `AuthenticationError` (code = `ChallengeName`) when the result is missing or incomplete; parse `__type` / `message` from rejection bodies, tolerating namespaced types and non-JSON bodies; log no secrets
|
||||
- [x] 2.4 Add `tests/test_api_authenticate.py` (stdlib-only, loads `api.py` without Home Assistant, fake session) covering every scenario in the `api-client` delta; verify `python3 -m unittest tests.test_api_authenticate` passes
|
||||
|
||||
## 3. Config flow errors
|
||||
|
||||
- [x] 3.1 In `async_step_token`, map `err.kind` to `token_rejected` / `invalid_credentials` / `invalid_auth`; on `invalid_credentials` re-show the `user` form (setup) or `reauth_confirm` form (reauth) with the error instead of the token form
|
||||
- [x] 3.2 Pass `description_placeholders={"reason": ...}` on every `async_show_form` for `user`, `reauth_confirm` and `token` (empty string when there is no error)
|
||||
- [x] 3.3 In `strings.json` and `translations/en.json`, reword `invalid_auth` to include `{reason}` and add `invalid_credentials` and `token_rejected`; verify the two files stay identical (`diff`)
|
||||
- [x] 3.4 Extend `tests/test_config_flow.py`: one test per error key (setup and reauth), asserting the form step, the error key and the `reason` placeholder; update `test_reauth_bad_token_keeps_old_tokens` for the new key; add a check that every `errors["base"]` value in `config_flow.py` exists in both translation files; verify `.venv-test/bin/pytest tests/` passes (harness bumped to 0.13.375 / core 2026.10.4, see branch commit)
|
||||
|
||||
## 4. README
|
||||
|
||||
- [x] 4.1 Keep step 2 to one command that logs the token and adds a "Click THIS BLACK BOX to copy" button using `navigator.clipboard.writeText` (DevTools `copy()` cannot copy an async result in Firefox or Chromium, and Chromium truncates `prompt()` defaults at 2,000 chars); test in Firefox and Chrome/Edge that the clipboard receives the full token; reword steps 4–5 to "paste it"; add one sentence to run it once at the console prompt (not as a Live expression) and a fallback line using `console.log(t)`; verify the snippet runs in a browser console on the en-gb login page and the clipboard holds a ~2,600-char token
|
||||
|
||||
## 5. On-device verification and version
|
||||
|
||||
- [x] 5.1 Bump `manifest.json` to 0.4.4 (shared with `add-keg-48180`, which must not bump it again)
|
||||
- [x] 5.5 Run the full suite (`.venv-test/bin/pytest tests/` and `python3 -m unittest discover -s tests`) and confirm green
|
||||
|
||||
## Deferred: shipping without on-device checks
|
||||
|
||||
Maintainer decision, 2026-11-07: ship v0.4.4 without these on-device checks (no time for a Home Assistant reinstall). Coverage at release is the automated suite plus the README token verified in Firefox and Chromium; sign-in against the live service is untested. Run them after release; the open TODO is in `PROJECT_HYGIENE.md`.
|
||||
|
||||
- 5.2 Install the branch build on Home Assistant and add the integration from scratch with a fresh README token; confirm the entry is created and sensors populate
|
||||
- 5.3 With a deliberately wrong password, confirm the flow returns to the credentials form showing `invalid_credentials` and Cognito's reason; with a stale (>2 min) token, confirm `token_rejected` on the token form
|
||||
- 5.4 Trigger a reauth on the existing entry and confirm it succeeds; if a keg is fitted, also confirm Keg Freshness keeps its countdown and clear that TODO in `PROJECT_HYGIENE.md`
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Release jointly with `add-keg-48180`: integration v0.4.4 and card v0.4.4, published together. Release notes credit cesa030 (root cause and fix in #11) and brettjenkins (fork that confirmed it).
|
||||
- After the release is live, comment on #11 with the release link and close it.
|
||||
- #12 and #13 are closed as duplicates of #11 (each with a thank-you comment) ahead of the release; post the release link there too.
|
||||
- Archive per `AGENTS.md` (merge, push, sync `api-client` and `config-flow` specs, archive, remove worktree and branch).
|
||||
@@ -59,7 +59,7 @@ The integration SHALL expose the numeric product ID of the keg currently fitted
|
||||
- **THEN** the sensor SHALL report no value and SHALL NOT raise
|
||||
|
||||
### Requirement: Keg name sensor
|
||||
The integration SHALL expose the name of the tapped beer, resolved from the keg product ID through a catalog bundled with the integration at `keg_catalog.json`. The catalog SHALL cover every keg the PerfectDraft app can select, including discontinued kegs that may still be fitted in a machine, and SHALL contain at least 114 product IDs.
|
||||
The integration SHALL expose the name of the tapped beer, resolved from the keg product ID through a catalog bundled with the integration at `keg_catalog.json`. The catalog SHALL cover every keg the PerfectDraft app can select, including discontinued kegs that may still be fitted in a machine, and SHALL contain at least 115 product IDs.
|
||||
|
||||
Catalog entries SHALL be observed directly from a machine reporting that product ID rather than inferred from shop listings, because the product IDs cannot be queried in bulk from the API. Entry names SHALL be the beer's name only, excluding shop-listing artefacts such as pack size, "Short Date" prefixes, or best-before dates.
|
||||
|
||||
|
||||
@@ -3,16 +3,11 @@
|
||||
# config-flow behaviour cannot be exercised without a real Home Assistant.
|
||||
#
|
||||
# pytest-homeassistant-custom-component releases track core one-to-one.
|
||||
# 0.13.205 is the newest release that still supports Python 3.12 and it
|
||||
# pins core 2025.1.4 — above the 2024.11 floor the reauth helpers need.
|
||||
# 0.13.375 pins core 2026.10.4 and requires Python 3.14, the interpreter on
|
||||
# the dev host. Older pins (0.13.205 / core 2025.1.4) need Python 3.12:
|
||||
# their numpy has no 3.14 wheel and will not build without a C compiler.
|
||||
#
|
||||
# python3 -m venv .venv-test
|
||||
# .venv-test/bin/pip install -r requirements-test.txt
|
||||
# .venv-test/bin/pytest tests/
|
||||
pytest-homeassistant-custom-component==0.13.205
|
||||
|
||||
# Core pins aiodns==3.2.0 but leaves pycares floating. pycares 4.6+ starts a
|
||||
# daemon shutdown thread that the harness's verify_cleanup fixture flags as a
|
||||
# leak, failing every test at teardown. 4.5.0 is contemporaneous with core
|
||||
# 2025.1.4 and has no such thread.
|
||||
pycares==4.5.0
|
||||
pytest-homeassistant-custom-component==0.13.375
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Tests for PerfectDraftApiClient.authenticate() against Cognito.
|
||||
|
||||
Stdlib only, like ``test_keg_detection.py``: ``api.py`` is loaded as part of
|
||||
a stub ``perfectdraft`` package so the integration's ``__init__.py`` (which
|
||||
needs Home Assistant) never runs, and a fake session replays canned
|
||||
responses instead of touching the network.
|
||||
"""
|
||||
import asyncio
|
||||
import importlib
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
PKG_DIR = Path(__file__).resolve().parent.parent / "custom_components" / "perfectdraft"
|
||||
|
||||
try:
|
||||
import aiohttp
|
||||
except ImportError: # the client only needs aiohttp.ClientError at runtime
|
||||
aiohttp = types.ModuleType("aiohttp")
|
||||
aiohttp.ClientError = type("ClientError", (Exception,), {})
|
||||
aiohttp.ClientSession = object
|
||||
sys.modules["aiohttp"] = aiohttp
|
||||
|
||||
_pkg = types.ModuleType("_perfectdraft_stub")
|
||||
_pkg.__path__ = [str(PKG_DIR)]
|
||||
sys.modules["_perfectdraft_stub"] = _pkg
|
||||
|
||||
api = importlib.import_module("_perfectdraft_stub.api")
|
||||
exceptions = importlib.import_module("_perfectdraft_stub.exceptions")
|
||||
|
||||
EMAIL = "drinker@example.com"
|
||||
PASSWORD = "hunter2"
|
||||
TOKEN = "recaptcha-token"
|
||||
TOKENS = {"AccessToken": "access-jwt-1", "IdToken": "id-jwt-1", "RefreshToken": "refresh-jwt-1"}
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self, status, body):
|
||||
self.status = status
|
||||
self._body = body if isinstance(body, str) else json.dumps(body)
|
||||
|
||||
async def text(self):
|
||||
return self._body
|
||||
|
||||
async def json(self, content_type="application/json"):
|
||||
if content_type is not None:
|
||||
raise AssertionError("Cognito replies x-amz-json; parse with content_type=None")
|
||||
return json.loads(self._body)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, status=200, body=None, raises=None):
|
||||
self._response = FakeResponse(status, body if body is not None else {})
|
||||
self._raises = raises
|
||||
self.calls = []
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
self.calls.append((url, kwargs))
|
||||
if self._raises:
|
||||
raise self._raises
|
||||
return self._response
|
||||
|
||||
|
||||
def sign_in(session):
|
||||
client = api.PerfectDraftApiClient(session)
|
||||
result = asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
|
||||
return client, result
|
||||
|
||||
|
||||
def rejection(session):
|
||||
client = api.PerfectDraftApiClient(session)
|
||||
client.set_tokens("old-access", "old-id", "old-refresh")
|
||||
with unittest.TestCase().assertRaises(exceptions.AuthenticationError) as ctx:
|
||||
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
|
||||
return client, ctx.exception
|
||||
|
||||
|
||||
class SuccessfulSignIn(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.session = FakeSession(200, {"AuthenticationResult": {**TOKENS, "ExpiresIn": 3600}})
|
||||
self.client, self.result = sign_in(self.session)
|
||||
self.url, self.kwargs = self.session.calls[0]
|
||||
|
||||
def test_posts_to_cognito_not_the_gateway(self):
|
||||
self.assertEqual(self.url, "https://cognito-idp.eu-west-1.amazonaws.com/")
|
||||
self.assertEqual(
|
||||
self.kwargs["headers"],
|
||||
{
|
||||
"Content-Type": "application/x-amz-json-1.1",
|
||||
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
|
||||
},
|
||||
)
|
||||
|
||||
def test_payload_carries_credentials_and_recaptcha_metadata(self):
|
||||
self.assertEqual(
|
||||
self.kwargs["json"],
|
||||
{
|
||||
"AuthFlow": "USER_PASSWORD_AUTH",
|
||||
"ClientId": "57ddq2ppqg2jcpup06r2g1deur",
|
||||
"AuthParameters": {"USERNAME": EMAIL, "PASSWORD": PASSWORD},
|
||||
"ClientMetadata": {
|
||||
"recaptchaToken": TOKEN,
|
||||
"recaptchaAction": "Magento/login",
|
||||
"domain": "https://www.perfectdraft.com",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
def test_stores_tokens_from_authentication_result(self):
|
||||
self.assertEqual(self.client.access_token, "access-jwt-1")
|
||||
self.assertEqual(self.client.id_token, "id-jwt-1")
|
||||
self.assertEqual(self.client.refresh_token, "refresh-jwt-1")
|
||||
self.assertEqual(self.result["AccessToken"], "access-jwt-1")
|
||||
|
||||
|
||||
class Challenge(unittest.TestCase):
|
||||
def test_challenge_raises_and_keeps_tokens(self):
|
||||
client, err = rejection(FakeSession(200, {"ChallengeName": "NEW_PASSWORD_REQUIRED", "Session": "s"}))
|
||||
self.assertEqual(err.code, "NEW_PASSWORD_REQUIRED")
|
||||
self.assertEqual(err.kind, "other")
|
||||
self.assertIn("NEW_PASSWORD_REQUIRED", err.display_reason)
|
||||
self.assertEqual(client.access_token, "old-access")
|
||||
self.assertEqual(client.refresh_token, "old-refresh")
|
||||
|
||||
def test_incomplete_result_raises(self):
|
||||
_, err = rejection(FakeSession(200, {"AuthenticationResult": {"AccessToken": "a"}}))
|
||||
self.assertIsNone(err.code)
|
||||
self.assertEqual(err.display_reason, "no reason given")
|
||||
|
||||
|
||||
class Rejections(unittest.TestCase):
|
||||
def test_wrong_password_is_a_credentials_failure(self):
|
||||
_, err = rejection(FakeSession(400, {"__type": "NotAuthorizedException", "message": "Incorrect username or password."}))
|
||||
self.assertEqual(err.code, "NotAuthorizedException")
|
||||
self.assertEqual(err.kind, "credentials")
|
||||
self.assertEqual(err.display_reason, "Incorrect username or password")
|
||||
self.assertIn("400", str(err))
|
||||
|
||||
def test_unknown_user_is_a_credentials_failure(self):
|
||||
_, err = rejection(FakeSession(400, {"__type": "UserNotFoundException", "message": "User does not exist."}))
|
||||
self.assertEqual(err.kind, "credentials")
|
||||
|
||||
def test_lambda_rejection_is_a_token_failure(self):
|
||||
_, err = rejection(FakeSession(400, {
|
||||
"__type": "UserLambdaValidationException",
|
||||
"message": "PreAuthentication failed with error 'domain'.",
|
||||
}))
|
||||
self.assertEqual(err.kind, "token")
|
||||
self.assertEqual(err.display_reason, "PreAuthentication failed with error 'domain'")
|
||||
|
||||
def test_namespaced_type_is_stripped(self):
|
||||
_, err = rejection(FakeSession(400, {
|
||||
"__type": "com.amazonaws.cognito.identity.idp.model#NotAuthorizedException",
|
||||
"message": "x",
|
||||
}))
|
||||
self.assertEqual(err.code, "NotAuthorizedException")
|
||||
|
||||
def test_other_type_is_an_other_failure(self):
|
||||
for status in (401, 403):
|
||||
_, err = rejection(FakeSession(status, {"__type": "InvalidParameterException", "message": "USER_PASSWORD_AUTH flow not enabled"}))
|
||||
self.assertEqual(err.kind, "other")
|
||||
self.assertEqual(err.display_reason, "USER_PASSWORD_AUTH flow not enabled")
|
||||
|
||||
def test_non_json_body_becomes_truncated_reason(self):
|
||||
_, err = rejection(FakeSession(403, "<html>" + "x" * 500 + "</html>"))
|
||||
self.assertIsNone(err.code)
|
||||
self.assertEqual(err.kind, "other")
|
||||
self.assertLessEqual(len(err.reason), 200)
|
||||
self.assertTrue(err.reason.startswith("<html>"))
|
||||
|
||||
def test_empty_body_has_fallback_reason(self):
|
||||
_, err = rejection(FakeSession(400, ""))
|
||||
self.assertEqual(err.display_reason, "no reason given")
|
||||
|
||||
def test_rejection_keeps_existing_tokens(self):
|
||||
client, _ = rejection(FakeSession(400, {"__type": "NotAuthorizedException", "message": "x"}))
|
||||
self.assertEqual(client.access_token, "old-access")
|
||||
|
||||
|
||||
class OtherFailures(unittest.TestCase):
|
||||
def test_server_error_is_an_api_error(self):
|
||||
client = api.PerfectDraftApiClient(FakeSession(500, "boom"))
|
||||
with self.assertRaises(exceptions.PerfectDraftApiError) as ctx:
|
||||
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
|
||||
self.assertEqual(ctx.exception.status, 500)
|
||||
|
||||
def test_network_failure_is_a_connection_error(self):
|
||||
client = api.PerfectDraftApiClient(FakeSession(raises=aiohttp.ClientError("down")))
|
||||
with self.assertRaises(exceptions.PerfectDraftConnectionError):
|
||||
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
|
||||
|
||||
|
||||
class SecretsAreNotLogged(unittest.TestCase):
|
||||
def test_no_secret_reaches_the_log(self):
|
||||
cases = [
|
||||
FakeSession(200, {"AuthenticationResult": TOKENS}),
|
||||
FakeSession(400, {"__type": "NotAuthorizedException", "message": "Incorrect username or password."}),
|
||||
]
|
||||
for session in cases:
|
||||
with self.assertLogs(api._LOGGER, level="DEBUG") as logs:
|
||||
api._LOGGER.debug("marker")
|
||||
client = api.PerfectDraftApiClient(session)
|
||||
try:
|
||||
asyncio.run(client.authenticate(EMAIL, PASSWORD, TOKEN))
|
||||
except exceptions.AuthenticationError:
|
||||
pass
|
||||
text = "\n".join(logs.output)
|
||||
for secret in (PASSWORD, TOKEN, *TOKENS.values()):
|
||||
self.assertNotIn(secret, text)
|
||||
|
||||
|
||||
class LegacyRaises(unittest.TestCase):
|
||||
def test_single_argument_raise_still_works(self):
|
||||
err = exceptions.AuthenticationError("No refresh token available")
|
||||
self.assertIsNone(err.code)
|
||||
self.assertEqual(err.kind, "other")
|
||||
self.assertEqual(str(err), "No refresh token available")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+159
-3
@@ -57,6 +57,24 @@ STORED_DATA = {
|
||||
}
|
||||
|
||||
|
||||
WRONG_PASSWORD = AuthenticationError(
|
||||
"Sign-in rejected (400)",
|
||||
code="NotAuthorizedException",
|
||||
reason="Incorrect username or password.",
|
||||
)
|
||||
TOKEN_REJECTED_REASON = "PreAuthentication failed with error 'domain'"
|
||||
TOKEN_REJECTED = AuthenticationError(
|
||||
"Sign-in rejected (400)",
|
||||
code="UserLambdaValidationException",
|
||||
reason=f"{TOKEN_REJECTED_REASON}.",
|
||||
)
|
||||
OTHER_FAILURE = AuthenticationError(
|
||||
"Sign-in rejected (400)",
|
||||
code="InvalidParameterException",
|
||||
reason="USER_PASSWORD_AUTH flow not enabled for this client",
|
||||
)
|
||||
|
||||
|
||||
def _mock_client(*, authenticate_error=None, machines=((MACHINE_ID,))):
|
||||
"""An API client that hands back recognisably new tokens."""
|
||||
client = AsyncMock()
|
||||
@@ -182,16 +200,60 @@ async def test_reauth_accepts_same_account_different_case(
|
||||
|
||||
async def test_reauth_bad_token_keeps_old_tokens(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
client = _mock_client(authenticate_error=AuthenticationError("token expired"))
|
||||
client = _mock_client(authenticate_error=TOKEN_REJECTED)
|
||||
result = await _run_reauth(hass, entry, client)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "token"
|
||||
assert result["errors"] == {"base": "invalid_auth"}
|
||||
assert result["errors"] == {"base": "token_rejected"}
|
||||
assert result["description_placeholders"]["reason"] == TOKEN_REJECTED_REASON
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
|
||||
assert entry.data[CONF_REFRESH_TOKEN] == "old-refresh"
|
||||
|
||||
|
||||
async def test_reauth_wrong_password_returns_to_reauth_confirm(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
entry = _entry(hass)
|
||||
client = _mock_client(authenticate_error=WRONG_PASSWORD)
|
||||
result = await _run_reauth(hass, entry, client)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
assert result["errors"] == {"base": "invalid_credentials"}
|
||||
assert result["description_placeholders"]["reason"] == "Incorrect username or password"
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
|
||||
|
||||
# Corrected credentials lead to a fresh token, then success.
|
||||
client.authenticate.side_effect = None
|
||||
with (
|
||||
patch(CLIENT_PATH, return_value=client),
|
||||
patch(SETUP_PATH, return_value=True),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
assert result["step_id"] == "token"
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": TOKEN}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "new-access"
|
||||
|
||||
|
||||
async def test_reauth_other_failure_is_invalid_auth(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
client = _mock_client(authenticate_error=AuthenticationError("token expired"))
|
||||
result = await _run_reauth(hass, entry, client)
|
||||
|
||||
assert result["step_id"] == "token"
|
||||
assert result["errors"] == {"base": "invalid_auth"}
|
||||
assert result["description_placeholders"]["reason"] == "no reason given"
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
|
||||
|
||||
|
||||
async def test_reauth_skips_profile_when_machine_id_known(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
@@ -240,8 +302,11 @@ async def test_add_integration_while_reauth_pending(hass: HomeAssistant) -> None
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Core up to 2025.x aborts in async_set_unique_id; 2026.x no longer
|
||||
# counts the parked reauth flow as in progress and reaches the
|
||||
# duplicate guard instead. Both reasons are translated.
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_in_progress"
|
||||
assert result["reason"] in ("already_in_progress", "already_configured")
|
||||
|
||||
|
||||
# --- User setup: must be unchanged by this fix ---
|
||||
@@ -318,6 +383,49 @@ async def test_user_setup_connection_error(hass: HomeAssistant) -> None:
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
|
||||
async def _run_user_setup(hass, client):
|
||||
"""Drive user then token, returning the token step's result."""
|
||||
with patch(CLIENT_PATH, return_value=client):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
assert result["description_placeholders"]["reason"] == ""
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
assert result["description_placeholders"]["reason"] == ""
|
||||
return await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": TOKEN}
|
||||
)
|
||||
|
||||
|
||||
async def test_user_setup_wrong_password_returns_to_user_form(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
result = await _run_user_setup(hass, _mock_client(authenticate_error=WRONG_PASSWORD))
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["errors"] == {"base": "invalid_credentials"}
|
||||
assert result["description_placeholders"]["reason"] == "Incorrect username or password"
|
||||
|
||||
|
||||
async def test_user_setup_token_rejected(hass: HomeAssistant) -> None:
|
||||
result = await _run_user_setup(hass, _mock_client(authenticate_error=TOKEN_REJECTED))
|
||||
|
||||
assert result["step_id"] == "token"
|
||||
assert result["errors"] == {"base": "token_rejected"}
|
||||
assert result["description_placeholders"]["reason"] == TOKEN_REJECTED_REASON
|
||||
|
||||
|
||||
async def test_user_setup_other_auth_failure(hass: HomeAssistant) -> None:
|
||||
result = await _run_user_setup(hass, _mock_client(authenticate_error=OTHER_FAILURE))
|
||||
|
||||
assert result["step_id"] == "token"
|
||||
assert result["errors"] == {"base": "invalid_auth"}
|
||||
assert result["description_placeholders"]["reason"] == "USER_PASSWORD_AUTH flow not enabled for this client"
|
||||
|
||||
|
||||
# --- Translations must cover every reachable abort reason ---
|
||||
|
||||
COMPONENT_DIR = Path(__file__).parent.parent / "custom_components" / "perfectdraft"
|
||||
@@ -383,3 +491,51 @@ def test_every_abort_reason_is_translated(filename: str) -> None:
|
||||
)["config"]["abort"]
|
||||
missing = sorted(_abort_reasons_in_source() - set(declared))
|
||||
assert not missing, f"{filename} is missing abort reasons: {missing}"
|
||||
|
||||
|
||||
# --- ...and every error key the forms can show ---
|
||||
|
||||
|
||||
def _error_keys_in_source() -> set[str]:
|
||||
"""String constants assigned to ``errors["base"]`` or listed in ``_AUTH_ERRORS``."""
|
||||
tree = ast.parse((COMPONENT_DIR / "config_flow.py").read_text(encoding="utf-8"))
|
||||
keys: set[str] = set()
|
||||
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Assign):
|
||||
continue
|
||||
target = node.targets[0]
|
||||
if (
|
||||
isinstance(target, ast.Subscript)
|
||||
and isinstance(target.slice, ast.Constant)
|
||||
and target.slice.value == "base"
|
||||
and isinstance(node.value, ast.Constant)
|
||||
):
|
||||
keys.add(node.value.value)
|
||||
if (
|
||||
isinstance(target, ast.Name)
|
||||
and target.id == "_AUTH_ERRORS"
|
||||
and isinstance(node.value, ast.Dict)
|
||||
):
|
||||
keys.update(v.value for v in node.value.values if isinstance(v, ast.Constant))
|
||||
|
||||
return keys
|
||||
|
||||
|
||||
def test_error_key_scanner_sees_the_known_keys() -> None:
|
||||
assert {
|
||||
"cannot_connect",
|
||||
"unknown",
|
||||
"invalid_auth",
|
||||
"invalid_credentials",
|
||||
"token_rejected",
|
||||
} <= _error_keys_in_source()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filename", ["strings.json", "translations/en.json"])
|
||||
def test_every_error_key_is_translated(filename: str) -> None:
|
||||
declared = json.loads(
|
||||
(COMPONENT_DIR / filename).read_text(encoding="utf-8")
|
||||
)["config"]["error"]
|
||||
missing = sorted(_error_keys_in_source() - set(declared))
|
||||
assert not missing, f"{filename} is missing error keys: {missing}"
|
||||
|
||||
@@ -23,7 +23,7 @@ CATALOG_PATH = os.path.join(
|
||||
|
||||
# Floor ratchets when the catalog grows. A drop below this means entries were
|
||||
# lost; the catalog is only ever meant to grow.
|
||||
MINIMUM_ENTRIES = 115
|
||||
MINIMUM_ENTRIES = 117
|
||||
|
||||
# Shop-listing artefacts that are not part of a beer's name.
|
||||
LISTING_ARTEFACTS = ("6L", "Short Date", "BBE")
|
||||
@@ -105,6 +105,8 @@ class TestKegCatalogContent(unittest.TestCase):
|
||||
self.assertEqual(catalog["44331"], "Ninkasi Flower Lager")
|
||||
self.assertEqual(catalog["44536"], "Tiny Rebel Stay Puft")
|
||||
self.assertEqual(catalog["48050"], "Anheuser-Busch Bud")
|
||||
self.assertEqual(catalog["47792"], "Camden Eazy")
|
||||
self.assertEqual(catalog["48180"], "Camden Stout")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user