9 Commits
Author SHA1 Message Date
rickandCursor 20ed62b963 Sign in via Cognito directly so PerfectDraft gets the domain
PerfectDraft's Cognito PreAuthentication Lambda now requires a "domain"
field in ClientMetadata. The api.perfectdraft.com /authentication/sign-in
gateway does not forward it, so every setup and reauth failed with
"PreAuthentication failed with error 'domain'" (#11, #12, #13).
authenticate() now calls Cognito InitiateAuth (USER_PASSWORD_AUTH)
itself, the endpoint token refresh already uses.

A failed sign-in now says what was rejected and why. A wrong email or
password returns to the credentials form; a rejected token stays on the
token step; both show Cognito's reason instead of the old blanket "token
may have expired", which hid this outage.

The README snippet copies the token to the clipboard. It captures copy()
up front because Chromium removes it once the console command returns.

Root cause and fix by @cesa030 in #11; confirmed in @brettjenkins' fork.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-07 11:20:47 +01:00
rickandCursor 0f3b4c20af fix: make reauth update the existing entry instead of aborting
async_step_token is shared by the user and reauth sources but was written
only for the former. It called _abort_if_unique_id_configured() on every
path, and during reauth the unique ID belongs to the entry being repaired,
so the duplicate guard fired by design: authentication succeeded, the flow
aborted with already_configured, the new tokens were discarded, and the
coordinator's next poll re-raised the reauth repair. The integration was
unrecoverable through the UI short of delete-and-re-add, which costs entity
history and the restored keg-freshness baseline.

Branch on self.source at the terminal step, per HA's documented pattern for
flows shared between setup and reauth: reauth now guards with
_abort_if_unique_id_mismatch() and persists through
async_update_reload_and_abort(), which merges the new tokens into the
existing entry, keeps email and machine ID, reloads, and aborts with
reauth_successful. The user path keeps _abort_if_unique_id_configured()
unchanged.

Reauth also stops re-fetching /api/me when the entry already records a
machine ID, removing a round trip from a flow the user waits on and a
failure mode where a transient /api/me error turned a successful sign-in
into cannot_connect.

The helpers require core 2024.11, so declare that floor in hacs.json —
otherwise older cores would AttributeError mid-flow, which is worse than
the bug being fixed.

Adds the repo's first HA test harness (requirements-test.txt, opt-in) with
regression tests covering token persistence, entry reload, account
mismatch, case-insensitive email, and the explicit assertion that reauth
never aborts as already_configured. tests/test_keg_detection.py still runs
standalone under python3 -m unittest.

Version set to 0.3.1 rather than the 0.4.0 that PR #2 introduced; no
v0.4.0 tag was ever cut, so nothing was released under that number.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:26:48 +02:00
rick 56ea7711f0 Simplify config flow: paste-token instead of external step
The reCAPTCHA external step has domain validation issues (HA's
hostname isn't in the allowed list for any reCAPTCHA key). Instead,
the config flow now asks the user to:

1. Open perfectdraft.com/en-gb/customer/account/login
2. Run one console command to generate a token
3. Paste the token into the HA config flow

Clear instructions are shown in the flow description. The token
expires in 2 minutes, and the error message tells the user to
try again with a fresh token if it fails.

Removed the external step, HTML page, and HTTP views entirely.
Much simpler code, no moving parts.

Made-with: Cursor
2026-04-12 17:27:29 +02:00
rick 34a23a2814 Working integration with real API data
Breakthrough: discovered the web reCAPTCHA Enterprise key
(6LcZQiUo...) from perfectdraft.com with action "Magento/login"
is accepted by the /authentication/sign-in API endpoint when
generated from a real browser. Token refresh works via direct
AWS Cognito InitiateAuth (bypasses API gateway, no reCAPTCHA).

Cognito details extracted from JWT:
  Pool: eu-west-1_UXWVyvlHR
  Client: 57ddq2ppqg2jcpup06r2g1deur

Real API response fields mapped:
  /api/me → perfectdraftMachines[].id
  /api/perfectdraft_machines/{id} → details.temperature,
    details.kegVolume, details.connectedState, details.doorClosed,
    details.numberOfPoursSinceStartup, details.volumeOfLastPour,
    details.firmwareVersion, details.serialNumber, setting.mode

Changes:
- api.py: Cognito direct refresh, correct sign-in endpoint
- config_flow.py: external step with web reCAPTCHA on HA page
- const.py: Cognito config, web reCAPTCHA key
- coordinator.py: real field name extraction
- sensor.py: 8 sensors with real field mappings (temperature,
  keg remaining %, connection, door, pours, last pour, firmware, mode)
- Removed image.py (API doesn't expose keg images)
- Restored static/recaptcha.html with Enterprise JS

Made-with: Cursor
2026-04-12 17:18:03 +02:00
rick fcba32fecd Replace reCAPTCHA auth with token-bootstrap flow
The Android reCAPTCHA Enterprise key cannot be used from any
non-Android context (browser, server, headless). Certificate
pinning prevents MITM token capture. Every approach to bypass
reCAPTCHA has been exhausted.

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

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

Made-with: Cursor
2026-04-12 12:26:12 +02:00
rick 17c0551711 Switch to PerfectDraft web reCAPTCHA key
The Android key (6LdrqmAp...) only works with the Android SDK —
it rejects all web-based token generation with "Invalid domain."

Discovered that perfectdraft.com's web login uses a separate
Enterprise web key (6LcZQiUo...) with action "Magento/login".
Testing confirmed the API at api.perfectdraft.com accepts tokens
from this web key. The only remaining requirement is a high
reCAPTCHA score, which a real user's browser will provide.

The external step flow now uses:
- Enterprise JS (recaptcha/enterprise.js)
- Web site key: 6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV
- Action: Magento/login

Removed server-side token generation attempt from config flow
since it cannot produce high-score tokens.

Made-with: Cursor
2026-04-11 21:04:56 +02:00
rick 74163b1ff1 Add server-side reCAPTCHA token generation
The browser-based reCAPTCHA approach fails with "Invalid domain"
because PerfectDraft's site key is registered for their domains,
not for the HA instance hostname.

New approach: generate the token server-side via the reCAPTCHA
anchor/reload HTTP endpoints, bypassing domain validation entirely.
Falls back to browser-based external step if server-side fails.

Also adds better error logging in the auth step.

Made-with: Cursor
2026-04-11 20:47:29 +02:00
rick 1706a10ccb Fix config flow external step for reCAPTCHA
The external step mechanism requires a specific flow:
1. async_external_step() pauses the flow
2. Callback stashes token in hass.data and calls async_configure()
   with no user_input to signal completion
3. HA calls async_step_recaptcha_done() which picks up the token
4. async_external_step_done() transitions to async_step_finish()
5. async_step_finish() does the actual API authentication

Previously tried to resume the flow by passing user_input directly
to async_configure(), which doesn't work with external steps.

Made-with: Cursor
2026-04-11 20:32:46 +02:00
rick c24e3678a7 Implement PerfectDraft Pro HA integration (tasks 1–7)
Complete custom_components/perfectdraft/ with:
- Async API client (auth, refresh, machine polling)
- Config flow with reCAPTCHA v3 external step
- DataUpdateCoordinator for shared polling
- Sensor entities (temperature, % remaining, days to expiry, keg name)
- Image entity for keg artwork
- HACS-compliant packaging (manifest.json, hacs.json, translations)
- Configurable polling interval via OptionsFlow
- Reauth flow for expired refresh tokens

Group 8 (manual testing) deferred — requires live HA instance.

Made-with: Cursor
2026-04-11 19:09:44 +02:00