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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Strava requires an active subscription to create an API application and keep it
1. Create a Strava API app at <https://www.strava.com/settings/api>.
2. Set **Authorization Callback Domain** to `localhost`.
3. Run `eufy-sync --setup-strava` and enter the Client ID and Secret.
4. Authorize eufy-sync in the browser when it opens.
4. Authorize eufy-sync in the browser when it opens. Leave the permission to edit your profile ticked: Strava lets you untick it, but eufy-sync needs it to update your weight, and setup stops if it is missing.

## Adding Zwift (experimental)

Expand Down
2 changes: 1 addition & 1 deletion eufy_sync/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Sync Eufy smart scale body composition data to Garmin Connect and Strava."""

__version__ = "1.15.3"
__version__ = "1.15.4"

# Public API for programmatic use
from eufy_sync.eufy_client import EufyClient, EufyMeasurement
Expand Down
67 changes: 65 additions & 2 deletions eufy_sync/strava_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
2. Tokens stored in keychain (file fallback).
3. Access tokens expire after 6 hours; refresh tokens are indefinite.
4. On each sync, we PUT /athlete with the latest weight.
5. The API host follows Strava's published move to api-v3.strava.com
5. Strava lets the athlete untick individual permissions on the consent
screen. Since 2026-04-23 the token response lists the scopes actually
granted; we refuse a grant without profile:write and keep the list so a
later 403 can name the real cause.
6. The API host follows Strava's published move to api-v3.strava.com
(see _api_bases).
"""
from __future__ import annotations
Expand Down Expand Up @@ -39,6 +43,35 @@
CALLBACK_PORT = 8089
REDIRECT_URI = f"http://localhost:{CALLBACK_PORT}/callback"
REFRESH_SAFETY_MARGIN = 300 # seconds before expiry to trigger refresh
REQUESTED_SCOPES = ("profile:write", "profile:read_all")
WRITE_SCOPE = "profile:write"
MISSING_WRITE_SCOPE_MESSAGE = (
"Strava did not grant permission to edit your profile, which eufy-sync "
"needs to update your weight. Run eufy-sync --setup-strava and leave the "
"profile permission ticked."
)


def _parse_scopes(raw) -> list[str] | None:
"""Turn a granted-scope value into a list, or None when Strava sent none.

The token response uses spaces; the callback query string uses commas.
"""
if raw is None:
return None
if isinstance(raw, (list, tuple)):
return [str(s) for s in raw if s]
return [s for s in str(raw).replace(",", " ").split() if s]


def _lacks_write_scope(tokens: dict | None) -> bool:
"""True only when we know the granted scopes and profile:write is absent.

Grants saved before Strava returned scopes have no list; treat those as
unknown rather than missing.
"""
scopes = (tokens or {}).get("scope")
return scopes is not None and WRITE_SCOPE not in scopes


def _utc_today() -> date:
Expand All @@ -63,7 +96,7 @@ def _auth_url(client_id: str, state_value: str) -> str:
"client_id": client_id,
"response_type": "code",
"redirect_uri": REDIRECT_URI,
"scope": "profile:write,profile:read_all",
"scope": ",".join(REQUESTED_SCOPES),
"approval_prompt": "force",
"state": state_value,
})
Expand All @@ -79,6 +112,7 @@ def authorize_strava(config: StravaConfig) -> dict:
Returns the token dict (access_token, refresh_token, expires_at).
"""
captured_code: list[str] = []
captured_scope: list[str] = []
captured_error: list[str] = []
state_value = secrets.token_urlsafe(32)

Expand All @@ -94,6 +128,8 @@ def do_GET(self):
self.wfile.write(b"<html><body><h2>Invalid state parameter</h2></body></html>")
return
captured_code.append(query["code"][0])
if "scope" in query:
captured_scope.append(query["scope"][0])
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
Expand Down Expand Up @@ -179,6 +215,14 @@ def _serve_until_done():
"refresh_token": data["refresh_token"],
"expires_at": data.get("expires_at", now + data.get("expires_in", 21600)),
}
granted = _parse_scopes(data.get("scope"))
if granted is None and captured_scope:
granted = _parse_scopes(captured_scope[0])
if granted is not None:
tokens["scope"] = granted
if _lacks_write_scope(tokens):
# A grant that can't write the weight would only fail on every sync.
raise RuntimeError(MISSING_WRITE_SCOPE_MESSAGE)

_save_tokens(tokens)
logger.info("Strava authorization complete")
Expand Down Expand Up @@ -246,16 +290,25 @@ def _refresh_access_token(self) -> None:
)

data = resp.json()
previous_scope = self._tokens.get("scope")
self._tokens = {
"access_token": data["access_token"],
"refresh_token": data["refresh_token"],
"expires_at": data.get("expires_at", time.time() + data.get("expires_in", 21600)),
}
granted = _parse_scopes(data.get("scope"))
if granted is None:
granted = previous_scope
if granted is not None:
self._tokens["scope"] = granted
_save_tokens(self._tokens)
logger.info("Refreshed Strava access token")

def check_connection(self) -> None:
"""Verify the saved session with a read-only athlete request."""
if _lacks_write_scope(self._tokens):
from eufy_sync.sync import PermanentSyncError
raise PermanentSyncError(MISSING_WRITE_SCOPE_MESSAGE)
resp = self._api_request("GET", "/athlete")
if resp.status_code == 401:
from eufy_sync.sync import PermanentSyncError
Expand Down Expand Up @@ -289,6 +342,16 @@ def update_weight(self, weight_kg: float) -> dict:
# 4xx (except 429) won't recover by retrying; signal that to _retry.
if resp.status_code == 403:
from eufy_sync.sync import PermanentSyncError
if _lacks_write_scope(self._tokens):
raise PermanentSyncError(
f"Failed to update Strava weight (HTTP 403). {MISSING_WRITE_SCOPE_MESSAGE}"
)
if (self._tokens or {}).get("scope") is not None:
raise PermanentSyncError(
"Failed to update Strava weight (HTTP 403). Profile edits are allowed, "
"so the account that owns the API app likely needs its Strava "
"subscription renewed. Signing in again won't fix it."
)
raise PermanentSyncError(
"Failed to update Strava weight (HTTP 403). The account that owns the "
"API app may need its Strava subscription renewed. If the subscription "
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "eufy-sync"
version = "1.15.3"
version = "1.15.4"
description = "Sync Eufy smart scale data to Garmin Connect, Strava, and Zwift"
readme = "README.md"
license = "MIT"
Expand Down
146 changes: 146 additions & 0 deletions tests/test_strava_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,149 @@ def test_update_weight_403_names_both_causes(mock_load, mock_save):
assert "subscription" in message
assert "eufy-sync --setup-strava" in message
client.close()


# --- Granted scopes (Strava changelog 2026-04-23: the token response lists them) ---


def _run_authorize(token_body: dict, callback_scope: str | None = None):
"""Drive authorize_strava end to end: the 'browser' hits the local
callback, and the token exchange returns ``token_body``."""
import threading
from urllib.parse import parse_qs, urlparse

from eufy_sync.strava_client import REDIRECT_URI, authorize_strava

def fake_browser(url):
state = parse_qs(urlparse(url).query)["state"][0]
params = {"code": "abc", "state": state}
if callback_scope is not None:
params["scope"] = callback_scope

def hit():
httpx.get(REDIRECT_URI, params=params, timeout=5)

threading.Thread(target=hit, daemon=True).start()
return True

token_resp = MagicMock()
token_resp.status_code = 200
token_resp.json.return_value = {
"access_token": "a", "refresh_token": "r", "expires_at": time.time() + 21600,
**token_body,
}
with patch("eufy_sync.strava_client.webbrowser.open", side_effect=fake_browser), \
patch("eufy_sync.strava_client.httpx.post", return_value=token_resp), \
patch("eufy_sync.strava_client._save_tokens") as mock_save:
try:
result = authorize_strava(_make_config())
except RuntimeError as e:
return e, mock_save
return result, mock_save


def test_auth_url_still_requests_profile_write():
from urllib.parse import parse_qs, urlparse

from eufy_sync.strava_client import _auth_url
scope = parse_qs(urlparse(_auth_url("1", "s")).query)["scope"][0]
assert scope.split(",") == ["profile:write", "profile:read_all"]


def test_authorize_saves_the_granted_scopes_from_the_token_response():
result, mock_save = _run_authorize({"scope": "profile:write profile:read_all"})
assert result["scope"] == ["profile:write", "profile:read_all"]
mock_save.assert_called_once()


def test_authorize_refuses_a_grant_without_profile_write():
result, mock_save = _run_authorize({"scope": "read profile:read_all"})
assert isinstance(result, RuntimeError)
assert "--setup-strava" in str(result)
mock_save.assert_not_called()


def test_authorize_falls_back_to_the_callback_scope():
result, _ = _run_authorize({}, callback_scope="read,profile:read_all")
assert isinstance(result, RuntimeError)
result, _ = _run_authorize({}, callback_scope="read,profile:write")
assert result["scope"] == ["read", "profile:write"]


def test_authorize_without_any_scope_info_keeps_working():
result, mock_save = _run_authorize({})
assert "scope" not in result
mock_save.assert_called_once()


@patch("eufy_sync.strava_client._save_tokens")
@patch("eufy_sync.strava_client._load_tokens")
def test_refresh_keeps_known_scopes_when_strava_omits_them(mock_load, mock_save):
mock_load.return_value = {**_make_tokens(expired=True), "scope": ["profile:write"]}
client = StravaClient(_make_config())
with patch.object(client._client, "post", return_value=_ok({
"access_token": "n", "refresh_token": "r2", "expires_at": time.time() + 21600,
})):
client.authenticate()
assert client._tokens["scope"] == ["profile:write"]
client.close()


@patch("eufy_sync.strava_client._save_tokens")
@patch("eufy_sync.strava_client._load_tokens")
def test_refresh_takes_the_scopes_strava_returns(mock_load, mock_save):
mock_load.return_value = {**_make_tokens(expired=True), "scope": ["profile:write"]}
client = StravaClient(_make_config())
with patch.object(client._client, "post", return_value=_ok({
"access_token": "n", "refresh_token": "r2", "expires_at": time.time() + 21600,
"scope": "read",
})):
client.authenticate()
assert client._tokens["scope"] == ["read"]
client.close()


@patch("eufy_sync.strava_client._save_tokens")
@patch("eufy_sync.strava_client._load_tokens")
def test_check_connection_flags_a_grant_without_profile_write(mock_load, mock_save):
from eufy_sync.sync import PermanentSyncError
mock_load.return_value = {**_make_tokens(), "scope": ["read"]}
client = _client_on(date(2026, 11, 2))
client.authenticate()
with patch.object(client._client, "request", return_value=_ok()) as mock_request:
with pytest.raises(PermanentSyncError, match="--setup-strava"):
client.check_connection()
mock_request.assert_not_called()
client.close()


@patch("eufy_sync.strava_client._save_tokens")
@patch("eufy_sync.strava_client._load_tokens")
def test_update_weight_403_without_write_scope_asks_for_a_new_sign_in(mock_load, mock_save):
from eufy_sync.sync import PermanentSyncError
mock_load.return_value = {**_make_tokens(), "scope": ["read"]}
client = StravaClient(_make_config())
client.authenticate()
with patch.object(client._client, "request", return_value=_status(403)):
with pytest.raises(PermanentSyncError) as excinfo:
client.update_weight(86.2)
message = str(excinfo.value)
assert "--setup-strava" in message
assert "subscription" not in message
client.close()


@patch("eufy_sync.strava_client._save_tokens")
@patch("eufy_sync.strava_client._load_tokens")
def test_update_weight_403_with_write_scope_points_at_the_subscription(mock_load, mock_save):
from eufy_sync.sync import PermanentSyncError
mock_load.return_value = {**_make_tokens(), "scope": ["profile:write"]}
client = StravaClient(_make_config())
client.authenticate()
with patch.object(client._client, "request", return_value=_status(403)):
with pytest.raises(PermanentSyncError) as excinfo:
client.update_weight(86.2)
message = str(excinfo.value)
assert "subscription" in message
assert "--setup-strava" not in message
client.close()
Loading