Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ..plugin.common import snapshot_plugin_catalog_data

from ..user.homes.service import home_payload
from .v1.agreement import product_agreements


def build_product_response(ctx: ServerContext) -> dict[str, Any]:
Expand Down Expand Up @@ -57,8 +58,10 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]:
"ncMode": "global",
"status": 10,
# Read by PluginSDKModule.getProductAgreements; a missing field is
# null and the device plugin's privacy check never completes.
"agreements": [],
# null and the device plugin's privacy check never completes. An
# empty list fails the check and sends the plugin to its privacy
# dialog path before it requests the map.
"agreements": product_agreements(),
}
icon_url = product.get("iconUrl")
if isinstance(icon_url, str) and icon_url:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ def _home_device_ids(ctx: ServerContext) -> list[str]:
return device_ids


def product_agreements() -> list[dict[str, Any]]:
"""Latest agreement versions of a product, as in /api/v5/product.

The device plugin compares these with the signed versions from
plugin_agreements(). It opens without a privacy dialog only if both lists
name both types and no signed version is lower than the latest version.
"""
return [
{"type": agreement_type, "version": PLUGIN_AGREEMENT_VERSION, "minorVersion": 0}
for agreement_type in PLUGIN_AGREEMENT_TYPES
]


def plugin_agreements(ctx: ServerContext) -> list[dict[str, Any]]:
"""One accepted plugin agreement per agreement type and home device.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import Any

from shared.constants import region_country
from shared.context import ServerContext
from shared.data_helpers import as_bool, get_value

Expand All @@ -10,16 +11,6 @@
from ...auth.service import ok

_DEFAULT_AVATAR_URL = "https://files.roborock.com/iot/default_avatar.png"
_REGION_COUNTRY_CODE = {
"US": "1",
"CN": "86",
"EU": "49",
"RU": "7",
}


def _default_country_code_for_region(region: str) -> str:
return _REGION_COUNTRY_CODE.get(region.upper(), "1")


def match_get_url_by_email(path: str) -> bool:
Expand All @@ -44,12 +35,12 @@ def build_get_url_by_email(
_body_params: dict[str, list[str]],
_clean_path: str,
) -> dict[str, Any]:
region_upper = ctx.region.upper()
country, countrycode = region_country(ctx.region)
return ok(
{
"url": ctx.api_url(),
"countrycode": _default_country_code_for_region(region_upper),
"country": region_upper,
"countrycode": countrycode,
"country": country,
}
)

Expand All @@ -76,16 +67,9 @@ def build_user_info(
if not mobile and username.isdigit():
mobile = username

region_upper = ctx.region.upper()
country = str(get_value(cloud_user_data, "country", default=region_upper) or region_upper)
countrycode = str(
get_value(
cloud_user_data,
"countrycode",
default=_default_country_code_for_region(region_upper),
)
or _default_country_code_for_region(region_upper)
)
default_country, default_countrycode = region_country(ctx.region)
country = str(get_value(cloud_user_data, "country", default=default_country) or default_country)
countrycode = str(get_value(cloud_user_data, "countrycode", default=default_countrycode) or default_countrycode)
nickname = str(get_value(cloud_user_data, "nickname", default="Local User") or "Local User")
avatarurl = str(get_value(cloud_user_data, "avatarurl", "avatarUrl", default="") or "")
if not avatarurl:
Expand Down
16 changes: 16 additions & 0 deletions src/roborock_local_server/bundled_backend/shared/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,22 @@
"roborock.vacuum.sc05": 10001,
}

# The login and user answers name a country and its dialing code. "EU" is no
# country, so the EU cloud answers "DE", which fits the dialing code 49.
REGION_COUNTRY = {
"US": ("US", "1"),
"CN": ("CN", "86"),
"EU": ("DE", "49"),
"RU": ("RU", "7"),
}


def region_country(region: str) -> tuple[str, str]:
"""Return the country and its dialing code for a cloud region."""
region_upper = str(region or "").upper()
return REGION_COUNTRY.get(region_upper, (region_upper, "1"))


MQTT_TYPES = {
1: "CONNECT",
2: "CONNACK",
Expand Down
23 changes: 9 additions & 14 deletions src/roborock_local_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware

from .certs import CertificateManager
from .bundled_backend.shared.constants import DEFAULT_PRODUCT_SCHEMA
from .bundled_backend.shared.constants import DEFAULT_PRODUCT_SCHEMA, region_country
from .bundled_backend.shared.data_helpers import utcnow_iso
from .product_registry import resolve_product_metadata
from .bundled_backend.shared.runtime_state import ONBOARDING_STEP_LABELS, REQUIRED_ONBOARDING_STEPS
Expand Down Expand Up @@ -73,12 +73,6 @@
ALL_HTTP_METHODS = ("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
PROTOCOL_AUTH_SYNC_PATH = "/internal/protocol/user-data"
PROTOCOL_AUTH_SYNC_SECRET_HEADER = "x-local-sync-secret"
_REGION_COUNTRY_CODE = {
"US": "1",
"CN": "86",
"EU": "49",
"RU": "7",
}
PROJECT_SUPPORT = {
"title": "Support This Project",
"text": (
Expand Down Expand Up @@ -613,22 +607,23 @@ def _protocol_login_pin_matches(self, pin: str) -> bool:
self.config.admin.protocol_login_pin_hash,
)

@staticmethod
def _default_country_code_for_region(region: str) -> str:
return _REGION_COUNTRY_CODE.get(str(region or "").upper(), "1")

def _local_protocol_identity(self) -> dict[str, Any]:
email = self._protocol_login_email()
normalized_email = email.casefold()
digest = hashlib.sha256(normalized_email.encode("utf-8")).hexdigest()
uid = (int(digest[:12], 16) % 900_000_000) + 100_000_000
region_upper = self.config.network.region.upper()
region = self.config.network.region.lower()
region_upper = region.upper()
country, countrycode = region_country(region)
return {
"uid": uid,
"rruid": f"rrls-{digest[:20]}",
"email": email,
"country": region_upper,
"countrycode": self._default_country_code_for_region(region_upper),
# The app keeps "region" as RRUser.region. The device plugin needs
# it in fetchCountryInfo and retries forever without it.
"region": region,
"country": country,
"countrycode": countrycode,
"nickname": "Local User",
"hasPassword": True,
"rriot": {
Expand Down
2 changes: 2 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def write_release_config(
tmp_path: Path,
*,
stack_fqdn: str = "api-roborock.example.com",
region: str = "us",
listener_mode: str = "local_tls",
https_port: int = 443,
mqtt_tls_port: int = 8883,
Expand All @@ -38,6 +39,7 @@ def write_release_config(
f"""
[network]
stack_fqdn = "{stack_fqdn}"
region = "{region}"
listener_mode = "{listener_mode}"
https_port = {https_port}
mqtt_tls_port = {mqtt_tls_port}
Expand Down
39 changes: 38 additions & 1 deletion tests/test_product_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,22 @@ def _products_v5(tmp_path: Path, devices: list[dict[str, object]]) -> dict:
return payload["data"]


def _plugin_agreements(tmp_path: Path) -> list[dict]:
_route, payload = resolve_route(
rules=default_endpoint_rules(),
context=_make_context(tmp_path),
clean_path="/api/v1/checkAppAgreement",
query_params={},
body_params={},
method="GET",
)
return payload["data"]["userPluginAgreementList"]


def _versions_by_type(agreements: list[dict]) -> dict[str, int]:
return {agreement["type"]: agreement["version"] for agreement in agreements}


_DEVICE = {
"duid": "device-a",
"name": "Vacuum A",
Expand All @@ -74,7 +90,28 @@ def test_product_entry_carries_rriotid_category_id_and_agreements(tmp_path: Path
# Product.rriotid is what the app joins the home data device's productId on.
assert product["rriotid"] == "iot-product-a"
assert product["categoryId"] == category["id"]
assert product["agreements"] == []
assert [agreement["type"] for agreement in product["agreements"]] == [
"USER_AGREEMENT",
"PRIVACY_POLICY",
]


def test_product_agreements_are_signed_in_plugin_agreements(tmp_path: Path) -> None:
device = dict(_DEVICE, model="roborock.vacuum.a307")
data = _products_v5(tmp_path, [device])
plugin_agreements = _plugin_agreements(tmp_path)

[product] = data["categoryDetailList"][0]["productList"]
latest = _versions_by_type(product["agreements"])
signed = _versions_by_type(
[agreement for agreement in plugin_agreements if agreement["deviceId"] == "device-a"]
)

# hasSignLastestPluginPrivacyAgreement in the device plugin returns true
# only if both lists name both types and every signed version is at least
# the latest version. Otherwise the plugin goes to its privacy dialog path.
for agreement_type in ("USER_AGREEMENT", "PRIVACY_POLICY"):
assert signed[agreement_type] >= latest[agreement_type]


def test_product_category_carries_code(tmp_path: Path) -> None:
Expand Down
81 changes: 79 additions & 2 deletions tests/test_protocol_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from pathlib import Path

from fastapi.testclient import TestClient
import pytest

from conftest import write_release_config
from roborock_local_server.config import load_config, resolve_paths
Expand Down Expand Up @@ -72,8 +73,13 @@ def _token_headers(login_payload: dict[str, object]) -> dict[str, str]:
}


def _build_supervisor(tmp_path: Path, *, with_snapshot: bool = True) -> tuple[ReleaseSupervisor, object]:
config_file = write_release_config(tmp_path)
def _build_supervisor(
tmp_path: Path,
*,
with_snapshot: bool = True,
region: str = "us",
) -> tuple[ReleaseSupervisor, object]:
config_file = write_release_config(tmp_path, region=region)
config = load_config(config_file)
paths = resolve_paths(config_file, config)
_write_json(paths.inventory_path, {"home": {"id": 12345, "name": "Test Home"}, "devices": []})
Expand Down Expand Up @@ -228,6 +234,77 @@ def test_local_pin_login_succeeds_without_imported_cloud_snapshot(tmp_path: Path
assert user_info.json()["data"]["email"] == "user@example.com"


@pytest.mark.parametrize(
("region", "country", "countrycode"),
[("eu", "DE", "49"), ("us", "US", "1")],
)
def test_local_pin_login_names_the_region_and_country_of_the_config(
tmp_path: Path,
region: str,
country: str,
countrycode: str,
) -> None:
supervisor, _paths = _build_supervisor(tmp_path, with_snapshot=False, region=region)
client = TestClient(supervisor.app)

login_response = client.post(
"/api/v5/auth/email/login/code",
data={"country": "DE", "countryCode": "49", "email": "user@example.com", "code": "123456"},
)
assert login_response.status_code == 200
login_payload = login_response.json()["data"]
# The app stores "region" as RRUser.region, and the device plugin reads it
# as serverCode in fetchCountryInfo. Without it, the plugin looks the
# country up in its own server map, fails, and retries forever.
assert login_payload["region"] == region
assert login_payload["country"] == country
assert login_payload["countrycode"] == countrycode


@pytest.mark.parametrize(("region", "country", "countrycode"), [("eu", "DE", "49"), ("us", "US", "1")])
def test_url_and_user_info_routes_name_the_country_of_the_login_answer(
tmp_path: Path,
region: str,
country: str,
countrycode: str,
) -> None:
supervisor, _paths = _build_supervisor(tmp_path, with_snapshot=False, region=region)
client = TestClient(supervisor.app)

login_response = client.post(
"/api/v5/auth/email/login/code",
data={"email": "user@example.com", "code": "123456"},
)
assert login_response.status_code == 200
login_payload = login_response.json()["data"]
assert (login_payload["country"], login_payload["countrycode"]) == (country, countrycode)

url_response = client.post("/api/v1/getUrlByEmail", data={"email": "user@example.com"})
assert url_response.status_code == 200
url_data = url_response.json()["data"]
assert (url_data["country"], url_data["countrycode"]) == (country, countrycode)

user_info = client.get("/api/v1/userInfo", headers=_token_headers(login_payload))
assert user_info.status_code == 200
user_data = user_info.json()["data"]
assert (user_data["country"], user_data["countrycode"]) == (country, countrycode)


def test_user_info_prefers_the_country_of_the_cloud_snapshot(tmp_path: Path) -> None:
supervisor, paths = _build_supervisor(tmp_path, region="eu")
snapshot = json.loads(paths.cloud_snapshot_path.read_text(encoding="utf-8"))
snapshot["user_data"]["country"] = "AT"
_write_json(paths.cloud_snapshot_path, snapshot)
client = TestClient(supervisor.app)

user_info = client.get(
"/api/v1/userInfo",
headers={"Authorization": "local-token-123", "header_username": "local-rruid-123"},
)
assert user_info.status_code == 200
assert user_info.json()["data"]["country"] == "AT"


def test_protected_routes_skip_protocol_auth_when_disabled(tmp_path: Path) -> None:
supervisor, _paths = _build_supervisor_with_protocol_toggle(tmp_path, protocol_auth_enabled=False)
client = TestClient(supervisor.app)
Expand Down