From cc30cedde81194a4dd3a1f78bba486894eca6f78 Mon Sep 17 00:00:00 2001 From: Jasper Delahaije Date: Sat, 17 Oct 2026 00:41:56 +0200 Subject: [PATCH 1/2] Add separate live app-validation scripts and per-cat weight probes --- README.md | 14 + docs/app-validation.md | 209 ++++++++++++ scripts/app_actions.py | 384 ++++++++++++++++++++++ scripts/app_validation.py | 512 ++++++++++++++++++++++++++++++ scripts/login_validation.py | 85 +++++ scripts/probe_weights.py | 321 +++++++++++++++++++ scripts/validate_alias.py | 13 + scripts/validate_associations.py | 13 + scripts/validate_cleaning.py | 13 + scripts/validate_dnd.py | 13 + scripts/validate_firmware.py | 13 + scripts/validate_lock.py | 13 + scripts/validate_login.py | 18 ++ scripts/validate_memos.py | 13 + scripts/validate_notifications.py | 13 + scripts/validate_pets.py | 13 + scripts/validate_reminders.py | 13 + scripts/validate_schedules.py | 13 + scripts/validate_settings.py | 13 + scripts/validate_statistics.py | 13 + scripts/validate_timezone.py | 13 + scripts/weight_report.py | 270 ++++++++++++++++ tests/test_app_validation.py | 160 ++++++++++ tests/test_weight_probe.py | 163 ++++++++++ 24 files changed, 2318 insertions(+) create mode 100644 docs/app-validation.md create mode 100644 scripts/app_actions.py create mode 100644 scripts/app_validation.py create mode 100644 scripts/login_validation.py create mode 100755 scripts/probe_weights.py create mode 100755 scripts/validate_alias.py create mode 100755 scripts/validate_associations.py create mode 100755 scripts/validate_cleaning.py create mode 100755 scripts/validate_dnd.py create mode 100755 scripts/validate_firmware.py create mode 100755 scripts/validate_lock.py create mode 100755 scripts/validate_login.py create mode 100755 scripts/validate_memos.py create mode 100755 scripts/validate_notifications.py create mode 100755 scripts/validate_pets.py create mode 100755 scripts/validate_reminders.py create mode 100755 scripts/validate_schedules.py create mode 100755 scripts/validate_settings.py create mode 100755 scripts/validate_statistics.py create mode 100755 scripts/validate_timezone.py create mode 100644 scripts/weight_report.py create mode 100644 tests/test_app_validation.py create mode 100644 tests/test_weight_probe.py diff --git a/README.md b/README.md index 314ba42..ca26710 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,20 @@ uv run scripts/compare_datapoints.py probe-output/before.json probe-output/after Reports contain JSON paths and observed types, not values. Review reports before sharing: backend-generated object keys can themselves contain identifiers. Raw captures contain personal/device data, are created with owner-only permissions, and must end in `.private.json`. Both that suffix and `probe-output/` are ignored by Git. Output files must be new, so captures are not accidentally overwritten. A top-level read failure yields exit 1 with partial results; authentication or local input/output failure yields exit 2. Optional endpoints omitted by the API client's fallbacks are not individually reported as errors. +## Validate live behavior against the NOTTY app + +Separate feature scripts cover lock/DND, commands, settings/reminders, schedules, +timezone, aliases, pets/associations, notifications, memos, firmware, statistics +and authentication. They save private before/after evidence and compare values +independently observed in the phone app. Emptying is blocked; reversible writes +support an explicit restore-and-check test. See [commands and examples](docs/app-validation.md). + +`uv run python scripts/probe_weights.py --session-file probe-output/session.private.json` +checks both cats' profile/daily weight fields and scoped litter-box statistics. +Use private before/after captures to check changes after a normal visit. Unit +codes, per-visit attribution and history remain unverified until compared with +the app; API success alone is not validation. + ## Development ```sh diff --git a/docs/app-validation.md b/docs/app-validation.md new file mode 100644 index 0000000..0f8d752 --- /dev/null +++ b/docs/app-validation.md @@ -0,0 +1,209 @@ +# Live API and NOTTY phone-app validation + +These developer scripts use the integration's request builders and a saved NOTTY +session. Run `uv sync --frozen --group dev` first. They do not need a running HA +server. `probe_weights.py` also runs with only Python and aiohttp installed. + +**Emptying is prohibited.** The shared write transport rejects one-key code 2, +unknown/Boolean/string motor codes and unsupported methods. There is no empty +operation. Clean and level remain explicit physical actions. + +## Separate commands + +Each command starts with read-only collection. Use a new filename on every run; +captures, app values, requests and reports use `.private.json` and mode 0600. +Keep these files in ignored `probe-output/`. They can contain personal data. + +| Script | Evidence / outstanding checks | +| --- | --- | +| `probe_weights.py` | Profile versus daily/other weight candidates; units, timestamp fields, potential historical rows and before/after changes | +| `validate_login.py` | Existing-session read; explicit fresh email-code request/exchange modes | +| `validate_lock.py` | Child lock state and set_key writes | +| `validate_dnd.py` | DND switch, both clocks, preserved LED and reported timezone; edits are device-local times | +| `validate_cleaning.py` | Clean/level acknowledgement and subsequent device/messages readback; record the physical effect yourself | +| `validate_settings.py` | Auto delay, mode and screen language; Scheduled requires an enabled plan | +| `validate_reminders.py` | Enabled flags, configured intervals, remaining counters; action-3 reset and interval writes | +| `validate_schedules.py` | Plan IDs/times/enable state; explicit add/edit/toggle/delete | +| `validate_timezone.py` | Server catalog, device zone and plans; explicit catalog-selected changes | +| `validate_alias.py` | Cloud alias, refreshed discovery; does not test HA's separate name override | +| `validate_pets.py` | Existing pet profile/breed catalog, preserved fields and bindings | +| `validate_associations.py` | One selected pet's profile and physical-box association list | +| `validate_notifications.py` | Account-wide litter-box categories and block state | +| `validate_memos.py` | Pet memo list; add `--memo-id ID` for scoped detail; explicit create/edit | +| `validate_firmware.py` | Installed/offered versions and raw task status; explicit offered-task installation | +| `validate_statistics.py` | Device info, daily counts/messages before/after an explicitly requested irreversible clear | + +The old `validate_commands.py` remains available for its original child-lock/DND +workflow. The new physical-command script is `validate_cleaning.py`. + +Example for each feature (replace `lock` in the filenames/script): + +```sh +uv run python scripts/validate_lock.py \ + --session-file probe-output/session.private.json \ + --device-id YOUR_PHYSICAL_BOX_ID \ + --capture-raw probe-output/lock.before.private.json \ + --template probe-output/lock.app.private.json \ + --output probe-output/lock.report.private.json +``` + +Pet/memo/association scripts also accept `--pet-id YOUR_PET_ID`. A sole box/pet +can be selected automatically; ambiguous targets require an explicit selection. +IDs must come from your account. No feeder/water device is eligible. + +Read the corresponding value in the NOTTY phone app. Edit the generated app +file, entering `equals` with the API field's type, then change +`confirmed_from_app` to `true`. Templates deliberately contain **null pending +placeholders**, not copied API values. Example: + +```json +{ + "checks": [ + {"source": "info", "path": ["switch_key"], "equals": 1, + "confirmed_from_app": true} + ] +} +``` + +The app's On label maps to the integer expected by the field; enum meaning must +be checked independently. For lists, use literal indexes/keys such as +`"path": [0, "blocked"]`, verifying the row's ID in the private capture first. +You may add more checks, including preserved profile/binding fields. A missing +field does not match null, and Boolean true does not match integer 1. + +Compare offline without contacting NOTTY: + +```sh +uv run python scripts/validate_lock.py \ + --from-file probe-output/lock.before.private.json \ + --expect probe-output/lock.app.private.json +``` + +Add `--show-values` to inspect private API/app values locally. Default console +reports omit them. Exit codes: **0** supplied app values match, **1** failed +reads/mismatches/restoration, **2** input/auth/request failure (a write may be +uncertain), **3** app observations pending. API acknowledgement alone is never +marked as app or physical verification. + +## Explicit writes and reversible tests + +The owner authorized API testing except emptying. The scripts require a selected +request file so running a feature reader does not accidentally operate hardware. +Use `--execute request.private.json` plus `--capture-raw before.private.json`. +A baseline journal is saved **before** the operation. The after snapshot is saved +as `before.after.private.json`; a roundtrip also saves +`before.restored.private.json`. Nothing is automatically retried. + +Example lock request: + +```json +{"operation": "set_key", "changes": {"switch": 1}} +``` + +```sh +uv run python scripts/validate_lock.py \ + --session-file probe-output/session.private.json \ + --device-id YOUR_PHYSICAL_BOX_ID \ + --execute probe-output/lock.request.private.json --roundtrip \ + --capture-raw probe-output/lock-test.before.private.json \ + --output probe-output/lock-test.report.private.json +``` + +`--roundtrip` restores and checks the original lock, mode/delay/language, alias, +pet edited fields or notification category. It attempts restoration even after +an uncertain write failure. Inspect the restoration file and app before retrying +an interrupted test. Immediate readback may lag; a mismatch needs investigation, +not a blind repeat. Roundtrips are deliberately rejected for motor commands, +reminder countdowns, schedules, timezone changes, associations, memos, firmware +and deleted history because their original effect cannot be generically restored. +Those operations can be selected explicitly without `--roundtrip`. + +| Feature | Operation | `changes` example | +| --- | --- | --- | +| Lock | `set_key` | `{"switch": 1}` | +| DND | `set_dnd` | `{"switch_dnd": 0}` or device-local clock fields `dnd_begin_time`, `dnd_end_time` | +| Settings | `set_auto_delay` / `set_mode` / `set_language` | `{"delay": 5}` / `{"mode": 1}` / `{"language": 1}` | +| Reminders | `set_litter_remind` / `set_garbage_bag_remind` | `{"action": 1, "cycle_time": CURRENT_CYCLE}` (2 disables) | +| Reminders | `reset_litter_reminder` / `reset_garbage_bag_reminder` | `{"cycle_time": CURRENT_CYCLE}` (reset preserves cycle) | +| Reminders | `set_litter_reminder_days` / `set_garbage_bag_reminder_days` | `{"cycle_time": NEW_CYCLE}` | +| Alias | `set_alias` | `{"alias": "Test box"}` | +| Pets | `update` | `{"name": "Milo"}`; supported birthday/sex/neutered/breed fields follow the integration | +| Associations | `associate` / `disassociate` | `{}`; explicit `--pet-id` selects the pet | +| Notifications | `block` / `unblock` | `{"message_type_id": SERVER_LISTED_ID}` | +| Schedules | `add_plan` / `edit_plan` / `open_plan` / `delete_plan` | `{"time":"06:30"}` / `{"plan_id":ID,"time":"06:30"}` / `{"plan_id":ID,"open":false}` / `{"plan_id":ID}` | +| Timezone | `change` | `{"catalog_id":"EXACT_CATALOG_ID","confirm_schedule_change":true}` | +| Memos | `create` / `update` | `{"fields":{"title":"Visit","content":"Check","date":"2026-10-17 15:00"}}`; update also requires `memo_id` | +| Cleaning | `clean` / `level` | `{}`; empty is never supported | +| Firmware | `install` | `{}`; confirms only a freshly eligible offered task | +| Statistics | `clear` | `{"confirm_irreversible":true}`; data cannot be restored | + +JSON examples containing uppercase placeholders must be filled before use. No +bulk write/sweep command is provided. Firmware percentage/realtime events, +installation across restarts, actual timed firing/DST and physical cleaning +behavior require observation beyond a one-shot HTTP test. Statistics clearing's +exact affected history must be established from before/after evidence. HA entity +identity/name overrides must be checked in a running HA instance separately. + +Fresh login is separate from checking an existing session: + +```sh +export NOTTY_EMAIL='your-account-email' +uv run python scripts/validate_login.py --request-code +# Read the fresh email code, then provide it through the environment: +export NOTTY_VERIFICATION_CODE='your-new-code' +uv run python scripts/validate_login.py --exchange-code \ + --new-session-file probe-output/session-new.private.json +unset NOTTY_VERIFICATION_CODE +``` + +Code exchange uses the integration's current APK-backed metadata and saves the +session before its authenticated read. It does not test expiry/reauthentication +in a running HA instance or claim automatic refresh-token support. + +## Weight before/after evidence + +```sh +uv run python scripts/probe_weights.py \ + --session-file probe-output/session.private.json \ + --capture-raw probe-output/weight-before.private.json \ + --output probe-output/weight-before.json + +# After a normal visit, take a second snapshot and compare private stable IDs: +uv run python scripts/probe_weights.py \ + --session-file probe-output/session.private.json \ + --capture-raw probe-output/weight-after.private.json \ + --compare probe-output/weight-before.private.json \ + --output probe-output/weight-after.json + +# Inspect actual values locally, or reanalyse entirely offline: +uv run python scripts/probe_weights.py \ + --from-file probe-output/weight-after.private.json --show-values +``` + +Weight reports distinguish profile `weight` from daily/other measurement +candidates, reject nonpositive/nonfinite/Boolean values, preserve unverified unit +codes, and show available timestamp field types. Comparing responses is not +per-visit event deduplication. Numeric-series rows are candidates, not historical +measurements proven to have a known date, unit and cat attribution. This tool +does not import past records into HA. + +## Development run, 17 October 2026 + +All fifteen feature readbacks completed without endpoint errors using the owner's +saved session. Phone-app observations remain pending. Lock, one notification +category, device alias and one pet name were tested with temporary changes and +restoration. Notification/alias/pet changes appeared in API readback; restoration +matched the baselines. The pet's weight, unit, image path, collar and device +bindings were unchanged. The child-lock request was acknowledged, but immediate +readback did not change; its effect is **unverified**, not a passed test. + +Both pets returned positive profile weight plus today_weight/yesterday_weight, +unit code 1 and no measurement timestamp. The scoped litter-box responses had no +recognized weight fields. This does not establish the enum meaning, per-visit +sampling, missing history, or which daily value the app displays. + +No motor command, reminder reset, schedule/timezone change, firmware installation +or history deletion was performed in this development run. Those scripts exist +for explicit owner-selected tests with app/physical observations. No empty command +was sent. Raw captures and editable app-value templates remain private under +`probe-output/app-validation-20261017/`; they are not published in GitHub. diff --git a/scripts/app_actions.py b/scripts/app_actions.py new file mode 100644 index 0000000..1b878d4 --- /dev/null +++ b/scripts/app_actions.py @@ -0,0 +1,384 @@ +"""Explicit feature writes for live validation; emptying is blocked at transport.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TypedDict, cast, override + +from custom_components.notty.api import ( + JsonObject, + JsonValue, + NottyApi, + NottyApiError, + alias_payload, + dnd_payload, + plan_enabled, +) +from custom_components.notty.device_features import FirmwareApi, NotificationApi, clear_statistics, owned_litter +from custom_components.notty.device_timezone import change_with_readback +from custom_components.notty.feature_contracts import identifier, profile_changes +from custom_components.notty.pet_api import MemoApi, PetApi + +POST = "POST" +GET = "GET" +ONE_KEY_PATH = "/device/litter_box/one_key" +SET_MODE = "set_mode" +SET_DND = "set_dnd" +SET_ALIAS = "set_alias" +SET_KEY = "set_key" +SET_DELAY = "set_auto_delay" +ASSOCIATE = "associate" +BLOCK = "block" +CREATE = "create" +UPDATE = "update" +ALIAS = "alias" +PETS = "pets" +NOTIFICATIONS = "notifications" + + +@dataclass +class Target: + """An account-validated physical box and/or pet.""" + + box: str + pet: str + device: JsonObject + + +class DndEdits(TypedDict, total=False): + """Only writable DND fields, excluding builder clock/context parameters.""" + + switch_dnd: JsonValue + dnd_begin_time: JsonValue + dnd_end_time: JsonValue + + +OPERATIONS = { + "lock": {SET_KEY}, + "dnd": {SET_DND}, + "settings": {SET_DELAY, SET_MODE, "set_language"}, + "reminders": { + "set_litter_remind", + "set_garbage_bag_remind", + "reset_litter_reminder", + "reset_garbage_bag_reminder", + "set_litter_reminder_days", + "set_garbage_bag_reminder_days", + }, + ALIAS: {SET_ALIAS}, + "commands": {"clean", "level"}, + "schedules": {"add_plan", "edit_plan", "open_plan", "delete_plan"}, + "timezone": {"change"}, + PETS: {UPDATE}, + "associations": {ASSOCIATE, "disassociate"}, + NOTIFICATIONS: {BLOCK, "unblock"}, + "memos": {CREATE, UPDATE}, + "firmware": {"install"}, + "statistics": {"clear"}, +} + + +class ValidationApi(NottyApi): + """Enforce the owner's no-empty rule even if a higher-level caller is wrong.""" + + writes_enabled = False + + @override + async def request(self, method: str, path: str, *, data: JsonObject | None = None) -> JsonValue: + """Reject writes in read mode and all unrecognized motor operations. + + Returns: + The normal API response. + + Raises: + NottyApiError: If a write is disabled or could empty the litter box. + """ + if method not in {GET, POST} or (method != GET and not self.writes_enabled): + msg = "Validation writes require an explicit selected operation" + raise NottyApiError(msg) + if path.split("?", 1)[0].rstrip("/") == ONE_KEY_PATH and method == POST: + operation = (data or {}).get("one_key") + if type(operation) is not int or operation not in {1, 3}: + msg = "Empty-litter and unknown motor commands are forbidden" + raise NottyApiError(msg) + return await super().request(method, path, data=data) + + +async def apply(api: ValidationApi, feature: str, target: Target, operation: str, changes: JsonObject) -> JsonValue: + """Dispatch one allowlisted feature operation with account-scoped validation. + + Returns: + Acknowledgement/readback, never evidence of a physical effect. + + Raises: + NottyApiError: If the feature, operation or field set is unsupported. + """ + require_operation(operation, OPERATIONS.get(feature, set())) + if feature not in {"pets", "memos", "notifications", "login"}: + await owned_litter(api, target.box) + handlers = { + "lock": setting, + "dnd": setting, + "settings": setting, + "reminders": setting, + "alias": alias, + "commands": command, + "schedules": schedule, + "timezone": timezone, + "pets": pet, + "associations": association, + "notifications": notification, + "memos": memo, + "firmware": firmware, + "statistics": statistics, + } + handler = handlers.get(feature) + if handler is None: + msg = "This validation feature has no write operation" + raise NottyApiError(msg) + return await handler(api, target.box, target.pet, operation, changes) + + +def require_fields(changes: JsonObject, expected: set[str]) -> None: + """Reject silent extra fields, missing values and target overrides. + + Raises: + NottyApiError: If fields do not match the selected operation. + """ + if set(changes) != expected: + msg = "Write fields do not match the selected operation" + raise NottyApiError(msg) + + +async def setting(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Validate and apply the integration's existing setting builders. + + Returns: + Server acknowledgement. + + Raises: + NottyApiError: If setting fields or values are unsupported. + """ + fields = {"set_key": {"switch"}, "set_auto_delay": {"delay"}, SET_MODE: {"mode"}, "set_language": {"language"}} + if operation == SET_DND: + allowed = {"switch_dnd", "dnd_begin_time", "dnd_end_time"} + if not changes or set(changes) - allowed: + msg = "DND accepts switch_dnd and device-local start/end clock edits" + raise NottyApiError(msg) + payload = dnd_payload(await api.litter_info(box), **cast("DndEdits", changes)) + elif operation in api_reminders(): + payload = changes + elif operation in fields: + require_fields(changes, fields[operation]) + payload = changes + if operation == SET_KEY and (type(changes["switch"]) is not int or changes["switch"] not in {0, 1}): + msg = "Child lock requires integer switch 0 or 1" + raise NottyApiError(msg) + if operation == SET_DELAY and (await api.litter_info(box)).get("mode") != 1: + msg = "Automatic delay requires Auto mode" + raise NottyApiError(msg) + else: + msg = "Unsupported setting operation" + raise NottyApiError(msg) + return await api.litter_action(box, operation, payload) + + +def api_reminders() -> set[str]: + """Known reminder write operations. + + Returns: + Explicit reset, interval and toggle actions. + """ + return { + "set_litter_remind", + "set_garbage_bag_remind", + "reset_litter_reminder", + "reset_garbage_bag_reminder", + "set_litter_reminder_days", + "set_garbage_bag_reminder_days", + } + + +async def alias(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Set one cloud alias. + + Returns: + Server acknowledgement. + """ + require_fields(changes, {"alias"}) + require_operation(operation, {SET_ALIAS}) + return await api.set_device_alias(box, changes["alias"]) + + +async def command(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Clean or level only; emptying is never a supported operation. + + Returns: + Server acknowledgement, requiring physical observation. + """ + require_fields(changes, set()) + require_operation(operation, {"clean", "level"}) + return await api.command(box, operation) + + +async def schedule(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Use the integration's fresh plan membership/payload validation. + + Returns: + Server acknowledgement. + """ + require_operation(operation, {"add_plan", "edit_plan", "open_plan", "delete_plan"}) + return await api.manage_litter_plan(box, operation, changes) + + +async def timezone(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Change one exact catalog ID with schedule snapshots. + + Returns: + Before/after schedule readback. + """ + require_operation(operation, {"change"}) + return await change_with_readback(api, box, changes) + + +async def pet(api: ValidationApi, _box: str, pet_id: str, operation: str, changes: JsonObject) -> JsonValue: + """Edit an owned existing pet with all current bindings preserved. + + Returns: + Fresh profile readback. + """ + require_operation(operation, {"update"}) + return await PetApi(api).update(pet_id, changes) + + +async def association(api: ValidationApi, box: str, pet_id: str, operation: str, changes: JsonObject) -> JsonValue: + """Change one association without affecting other pets. + + Returns: + Fresh association rows. + """ + require_operation(operation, {"associate", "disassociate"}) + require_fields(changes, set()) + return list(await PetApi(api).associate(box, pet_id, enabled=operation == ASSOCIATE)) + + +async def notification(api: ValidationApi, _box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Block/unblock one current account category. + + Returns: + Fresh category readback. + """ + require_operation(operation, {"block", "unblock"}) + require_fields(changes, {"message_type_id"}) + return list(await NotificationApi(api).set_blocked(changes["message_type_id"], blocked=operation == BLOCK)) + + +async def memo(api: ValidationApi, _box: str, pet_id: str, operation: str, changes: JsonObject) -> JsonValue: + """Create or edit one text memo; no deletion contract is invented. + + Returns: + The cloud acknowledgement. + + Raises: + NottyApiError: If memo fields are malformed. + """ + require_operation(operation, {"create", "update"}) + fields = {"fields"} if operation == CREATE else {"fields", "memo_id"} + require_fields(changes, fields) + values = changes["fields"] + if not isinstance(values, dict): + msg = "Memo fields must be an object" + raise NottyApiError(msg) + memo_id = identifier(changes["memo_id"]) if operation == UPDATE else None + return await MemoApi(api).save(pet_id, values, memo_id=memo_id) + + +async def firmware(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Confirm only a fresh currently offered task. + + Returns: + The requested version; completion needs later readback. + """ + require_operation(operation, {"install"}) + require_fields(changes, set()) + return await FirmwareApi(api).install(box) + + +async def statistics(api: ValidationApi, box: str, _pet: str, operation: str, changes: JsonObject) -> JsonValue: + """Clear selected-device statistics only through the explicit irreversible action. + + Returns: + Server acknowledgement. + """ + require_operation(operation, {"clear"}) + require_fields(changes, {"confirm_irreversible"}) + return await clear_statistics(api, box, confirmed=changes["confirm_irreversible"] is True) + + +def require_operation(operation: str, allowed: set[str]) -> None: + """Reject unknown actions, particularly empty-litter aliases. + + Raises: + NottyApiError: If the selected operation is outside this feature's scope. + """ + if operation not in allowed: + msg = "Unsupported validation operation; emptying is prohibited" + raise NottyApiError(msg) + + +def restore_request(feature: str, operation: str, changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject]: + """Prepare restoration only where the exact original state is available. + + Returns: + An operation and original values for supported reversible settings. + + Raises: + NottyApiError: If automatic restoration cannot preserve the original state. + """ + if feature in {"lock", "settings"} and operation in {SET_KEY, SET_DELAY, SET_MODE, "set_language"}: + return _setting_restore(operation, changes, before) + if feature == ALIAS: + device = before.get("device") + if isinstance(device, dict): + value = device.get("alias") + alias_payload(str(device.get("user_device_id")), value) + return SET_ALIAS, {"alias": value} + if feature == PETS: + profile = before.get("profile") + if isinstance(profile, dict) and all(key in profile for key in changes): + return "update", profile_changes({key: profile[key] for key in changes}) + if feature == NOTIFICATIONS: + restored = _notification_restore(changes, before) + if restored is not None: + return restored + msg = "Automatic restoration is supported only for lock, mode/delay/language, alias, pet fields and notifications" + raise NottyApiError(msg) + + +def _notification_restore(changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject] | None: + categories = before.get("categories") + if isinstance(categories, list): + for row in categories: + if isinstance(row, dict) and row.get("message_type_id") == changes.get("message_type_id"): + blocked = plan_enabled(row.get("blocked")) + if blocked is not None: + return BLOCK if blocked else "unblock", changes + return None + + +def _setting_restore(operation: str, changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject]: + info = before.get("info") + if not isinstance(info, dict): + info = {} + keys = {SET_KEY: "switch_key", SET_DELAY: "auto_delay", SET_MODE: "mode", "set_language": "language"} + field = {SET_KEY: "switch", SET_DELAY: "delay", SET_MODE: "mode", "set_language": "language"}[operation] + require_fields(changes, {field}) + value = info.get(keys[operation]) + if type(value) is not int: + msg = "Original setting must be a known integer before a roundtrip" + raise NottyApiError(msg) + ranges = {SET_KEY: {0, 1}, SET_DELAY: set(range(1, 16)), SET_MODE: {1, 2, 3}, "set_language": {0, 1, 2, 3}} + if value not in ranges[operation]: + msg = "Original setting is outside the restorable write range" + raise NottyApiError(msg) + return operation, {field: value} diff --git a/scripts/app_validation.py b/scripts/app_validation.py new file mode 100644 index 0000000..3b9cc66 --- /dev/null +++ b/scripts/app_validation.py @@ -0,0 +1,512 @@ +"""Shared live NOTTY/phone-app comparison runner for separate feature commands.""" + +from __future__ import annotations + +import argparse +import asyncio +from dataclasses import dataclass +from datetime import UTC, datetime +import json +from pathlib import Path +import sys +from typing import cast + +import aiohttp + +from custom_components.notty.api import JsonObject, JsonValue, NottyApiError, NottyAuthError +from custom_components.notty.feature_contracts import identifier +from custom_components.notty.pet_api import MemoApi +from scripts import app_actions +from scripts.console import console +from scripts.probe_datapoints import write_json +from scripts.validate_commands import ValidationError, load_session + +INFO = "/device/litter_box/get_info/{box}" +FEATURE_PATHS = { + "login": {"pets": "/pet/list"}, + "lock": {"info": INFO}, + "dnd": {"info": INFO}, + "commands": {"info": INFO, "messages": "/device/get_message/{box}"}, + "settings": {"info": INFO}, + "reminders": {"info": INFO}, + "schedules": {"info": INFO, "plans": "/device/litter_box/plans/{box}"}, + "timezone": {"info": INFO, "plans": "/device/litter_box/plans/{box}", "catalog": "/entity/get_time_zones"}, + "alias": {"info": INFO}, + "pets": {"profile": "/pet/info/{pet}", "breeds": "/pet/breeds"}, + "associations": {"associations": "/device/get_associated_pets/{box}", "profile": "/pet/info/{pet}"}, + "notifications": {"categories": "/message/get_type_block_stats_list?message_group_id=3"}, + "memos": {"memos": "/pet/memos/{pet}"}, + "firmware": {"upgrade": "/device/check_upgrade/{box}"}, + "statistics": { + "info": INFO, + "daily_counts": "/device/get_daily_event_counts/{box}", + "messages": "/device/get_message/{box}", + }, +} +FEATURE_FIELDS = { + "lock": ("info", ("switch_key",)), + "dnd": ("info", ("switch_dnd", "led", "dnd_begin_time", "dnd_end_time", "time_zone_iana")), + "settings": ("info", ("mode", "auto_delay", "language")), + "reminders": ( + "info", + ( + "open_litter_remind", + "default_remaining_days", + "remaining_days", + "open_garbagebag_remind", + "garbage_bag_cycle_time", + "garbage_bag_remaining_days", + ), + ), + "timezone": ("info", ("time_zone_iana",)), + "alias": ("device", ("alias",)), + "pets": ("profile", ("name", "sex", "birthday", "breed_id", "is_sterilization", "weight", "weight_unit")), + "firmware": ("upgrade", ("src_version", "dest_version", "task_status")), + "statistics": ("info", ("today_clean_count",)), +} +PET_FEATURES = {"pets", "associations", "memos"} +ACCOUNT_FEATURES = {"login", "notifications"} +SOURCE_INFO = "info" +FIELD_CHECKS = "checks" +MISMATCH = "mismatch" +PENDING = "pending" +MATCHED = "matches_supplied_phone_app_values" +MEMOS = "memos" +ALIAS = "alias" +LITTER_KIND = "litter_box" +LITTER_WORD = "litter" +PET_SOURCE = "pet" +LITTER_ID = 2 + + +@dataclass +class Options: + """Selected validation inputs and explicitly named local evidence files.""" + + session_file: Path | None = None + from_file: Path | None = None + device_id: str | None = None + pet_id: str | None = None + memo_id: str | None = None + expect: Path | None = None + template: Path | None = None + capture_raw: Path | None = None + execute: Path | None = None + roundtrip: bool = False + output: Path | None = None + show_values: bool = False + + +def private_json(path: Path) -> JsonObject: + """Read an object from an explicitly private input file. + + Returns: + Parsed JSON object. + + Raises: + ValueError: If the input name is invalid. + TypeError: If the input is not an object. + """ + if not path.name.endswith(".private.json"): + msg = "App values, requests and captures must use .private.json filenames" + raise ValueError(msg) + value = cast("JsonValue", json.loads(path.read_text(encoding="utf-8"))) + if not isinstance(value, dict): + msg = "Expected an object in the private input file" + raise TypeError(msg) + return value + + +def follow(data: JsonValue, path: list[JsonValue]) -> tuple[bool, JsonValue]: + """Resolve literal keys/list indexes without evaluating code or expressions. + + Returns: + Presence and value, distinguishing a missing field from null. + """ + current = data + for key in path: + if isinstance(current, dict) and isinstance(key, str) and key in current: + current = current[key] + continue + if isinstance(current, list) and type(key) is int and 0 <= key < len(current): + current = current[key] + continue + return False, None + return True, current + + +def app_comparison(data: JsonObject, expected: JsonObject | None, *, show_values: bool) -> JsonObject: + """Evaluate independently entered phone-app values; pending is never success. + + Returns: + Per-check status and a separate app-verification verdict. + + Raises: + ValueError: If the expectation schema is malformed. + """ + if expected is None: + return {"status": "pending_phone_app_values", "checks": []} + checks = expected.get("checks") + if not isinstance(checks, list) or not checks: + msg = "Expectations require a nonempty checks list" + raise ValueError(msg) + result: list[JsonValue] = [] + for index, check in enumerate(checks, 1): + if not isinstance(check, dict) or set(check) != {"source", "path", "equals", "confirmed_from_app"}: + msg = "Each app check requires source, path, equals and confirmed_from_app" + raise ValueError(msg) + source, path = check["source"], check["path"] + if not isinstance(source, str) or source not in data or not isinstance(path, list): + msg = "App check source or path is invalid" + raise ValueError(msg) + present, actual = follow(data[source], path) + matches = present and type(actual) is type(check["equals"]) and actual == check["equals"] + status = "pending" if check["confirmed_from_app"] is not True else "match" if matches else "mismatch" + item: JsonObject = {"check": index, "status": status, "field_present": present} + if show_values: + item.update({"source": source, "path": path, "api_value": actual, "app_value": check["equals"]}) + result.append(item) + statuses = {item["status"] for item in result if isinstance(item, dict)} + return { + "status": "mismatch" + if MISMATCH in statuses + else "pending_phone_app_values" + if PENDING in statuses + else "matches_supplied_phone_app_values", + "checks": result, + } + + +def template(feature: str, data: JsonObject) -> JsonObject: + """Generate blank app observations rather than copying API values as evidence. + + Returns: + A private editable expectation template with every check pending. + """ + source, fields = FEATURE_FIELDS.get(feature, (next(iter(data)), ())) + checks: list[JsonValue] = [ + {"source": source, "path": [field], "equals": None, "confirmed_from_app": False} for field in fields + ] + if not checks: + checks.append({"source": source, "path": [], "equals": None, "confirmed_from_app": False}) + return { + "checks": checks, + "instructions": "Read the phone app, enter each exact API-typed equals value and set confirmed_from_app true. Adjust list indexes/fields from the private capture; do not copy the API response and call it independent app evidence.", + } + + +async def targets(api: app_actions.ValidationApi, feature: str, options: Options) -> app_actions.Target: + """Resolve explicit account targets; never guess among multiple cats or boxes. + + Returns: + Physical ID, pet ID and selected discovery metadata. + + Raises: + ValueError: If a target is ambiguous or outside the account. + """ + pets = await api.pets() + pet_id = str(identifier(options.pet_id)) if options.pet_id else "" + if feature in PET_FEATURES: + available = {str(identifier(row.get("pet_id"))) for row in pets} + if not pet_id and len(available) == 1: + pet_id = next(iter(available)) + if pet_id not in available: + msg = "Select an account pet with --pet-id" + raise ValueError(msg) + if feature in ACCOUNT_FEATURES or feature in {"pets", "memos"}: + return app_actions.Target("", pet_id, {}) + devices = await api.user_devices(pets) + available_devices = {str(identifier(row.get("user_device_id"))): row for row in devices if _is_box(row)} + device_id = str(identifier(options.device_id)) if options.device_id else "" + if not device_id and len(available_devices) == 1: + device_id = next(iter(available_devices)) + if device_id not in available_devices: + msg = "Select an account physical litter box with --device-id" + raise ValueError(msg) + return app_actions.Target(device_id, pet_id, available_devices[device_id]) + + +def _is_box(row: JsonObject) -> bool: + return row.get("_notty_source") != PET_SOURCE and ( + row.get("device_type") == LITTER_KIND + or row.get("device_id") == LITTER_ID + or LITTER_WORD in str(row.get("product_name", "")).lower() + ) + + +async def collect( + api: app_actions.ValidationApi, feature: str, target: app_actions.Target, memo_id: str | None +) -> tuple[JsonObject, list[JsonValue]]: + """Read fixed feature routes and report optional failures without error bodies. + + Returns: + Named responses and redacted failed-read records. + + Raises: + NottyAuthError: If the saved session expires; stop without replay. + """ + device = target.device + if feature == ALIAS: + devices = await api.user_devices(await api.pets()) + device = next((row for row in devices if str(row.get("user_device_id")) == target.box), {}) + data: JsonObject = {"device": device} if device else {} + errors: list[JsonValue] = [] + for source, path in FEATURE_PATHS[feature].items(): + try: + data[source] = await api.request("GET", path.format(box=target.box, pet=target.pet)) + except NottyAuthError: + raise + except NottyApiError: + errors.append({"source": source, "error": "read_failed"}) + if feature == MEMOS and memo_id: + data["detail"] = await MemoApi(api).detail(target.pet, identifier(memo_id)) + return data, errors + + +def _output_paths(options: Options) -> list[Path]: + paths = [path for path in (options.capture_raw, options.output, options.template) if path] + if options.execute and options.capture_raw: + paths.extend([phase_path(options.capture_raw, "after"), phase_path(options.capture_raw, "restored")]) + return paths + + +def phase_path(path: Path, phase: str) -> Path: + """Choose a separate private file for each write phase. + + Returns: + A sibling filename without replacing the before capture. + """ + return path.with_name(path.name.removesuffix(".private.json") + f".{phase}.private.json") + + +def validate_options(options: Options) -> None: + """Validate private outputs before any API calls. + + Raises: + ValueError: If modes conflict, paths exist or write evidence would be absent. + """ + if (options.session_file is None) == (options.from_file is None): + msg = "Choose exactly one saved session or offline capture" + raise ValueError(msg) + if options.execute and (not options.capture_raw or options.from_file): + msg = "Executing requires live mode and a new --capture-raw before.private.json journal" + raise ValueError(msg) + if options.roundtrip and not options.execute: + msg = "--roundtrip requires an explicit --execute request file" + raise ValueError(msg) + paths = _output_paths(options) + if len(set(paths)) != len(paths): + msg = "Every evidence output must use a separate file" + raise ValueError(msg) + for path in paths: + if path.exists() or path.is_symlink() or not path.name.endswith(".private.json"): + msg = "Evidence outputs must be new .private.json files" + raise ValueError(msg) + + +async def _live(feature: str, options: Options) -> JsonObject: + if options.session_file is None: + msg = "Saved session required" + raise ValueError(msg) + saved = load_session(options.session_file) + token, user = saved.get("access_token"), saved.get("user_id") + if not isinstance(token, str) or not isinstance(user, str): + msg = "Session credentials must be strings" + raise TypeError(msg) + async with aiohttp.ClientSession() as session: + api = app_actions.ValidationApi( + session, token=token, user_id=user, region_code=str(saved.get("region_code") or "NL") + ) + target = await targets(api, feature, options) + before, errors = await collect(api, feature, target, options.memo_id) + capture: JsonObject = { + "feature": feature, + "captured_at": datetime.now(UTC).isoformat(), + "data": before, + "errors": errors, + } + if options.capture_raw: + write_json(options.capture_raw, capture) + if options.execute: + return await execute(api, feature, target, capture, options) + return capture + + +async def execute( + api: app_actions.ValidationApi, feature: str, target: app_actions.Target, baseline: JsonObject, options: Options +) -> JsonObject: + """Journal and execute one selected change, restoring supported settings on exit. + + Returns: + After-readback capture and an explicit restoration result. + + Raises: + ValueError: If preflight reads or write-request fields are invalid. + NottyApiError: If the write/readback fails; journal uncertainty and attempt restoration. + """ + before, errors = baseline.get("data"), baseline.get("errors") + if not isinstance(before, dict) or errors or options.execute is None or options.capture_raw is None: + msg = "Every baseline read must succeed before a write" + raise ValueError(msg) + request = private_json(options.execute) + operation, changes = request.get("operation"), request.get("changes") + if set(request) != {"operation", "changes"} or not isinstance(operation, str) or not isinstance(changes, dict): + msg = "Write request requires exactly operation and changes" + raise ValueError(msg) + restore = app_actions.restore_request(feature, operation, changes, before) if options.roundtrip else None + api.writes_enabled = True + result: JsonObject = { + "feature": feature, + "data": {}, + "errors": [], + "write_status": "not_attempted", + "request": request, + } + result["write_status"] = "attempted" + try: + await app_actions.apply(api, feature, target, operation, changes) + result["write_status"] = "acknowledged_not_physically_verified" + data, after_errors = await collect(api, feature, target, options.memo_id) + result.update({"data": data, "errors": after_errors, "captured_at": datetime.now(UTC).isoformat()}) + write_json(phase_path(options.capture_raw, "after"), result) + except NottyApiError: + result["write_status"] = "failed_or_uncertain_do_not_blindly_retry" + write_json(phase_path(options.capture_raw, "after"), result) + raise + finally: + if restore: + restored_result = await restore_state(api, feature, target, restore, options) + result["restore_status"] = restored_result["restore_status"] + write_json(phase_path(options.capture_raw, "restored"), restored_result) + return result + + +async def run(feature: str, options: Options) -> JsonObject: + """Collect evidence and compare independently supplied phone-app observations. + + Returns: + Redacted report; API acknowledgement and phone-app verification stay separate. + + Raises: + ValueError: If a capture is from another feature or has malformed data. + """ + validate_options(options) + expected = private_json(options.expect) if options.expect else None + capture = private_json(options.from_file) if options.from_file else await _live(feature, options) + data, errors = capture.get("data"), capture.get("errors") + if capture.get("feature") != feature or not isinstance(data, dict) or not isinstance(errors, list): + msg = "Capture does not match this feature or is malformed" + raise ValueError(msg) + if options.template: + write_json(options.template, template(feature, data)) + result: JsonObject = { + "feature": feature, + "api_reads": "partial_failure" if errors else "completed", + "failed_reads": len(errors), + "sources": list(data), + "app_comparison": app_comparison(data, expected, show_values=options.show_values), + "write_status": capture.get("write_status", "not_attempted"), + "api_write_readback": write_readback(feature, capture, data), + "restore_status": capture.get("restore_status", "not_requested"), + "remaining": "Phone-app observations, physical effects, schedule firing/DST and firmware completion are not proved by HTTP success. Login uses an existing session; fresh code login and expiry need a separate auth test.", + } + if options.show_values: + result["values"] = data + if options.output: + write_json(options.output, result) + return result + + +def main(feature: str) -> int: + """Run one feature's separate command. + + Returns: + 0 for supplied app values matching, 1 for failures/mismatches, 2 for errors, 3 pending app observations. + """ + parser = argparse.ArgumentParser( + description=f"Validate NOTTY {feature} against independently observed phone-app values. Emptying is prohibited." + ) + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--session-file", type=Path) + mode.add_argument("--from-file", type=Path) + for name in ("device-id", "pet-id", "memo-id"): + parser.add_argument(f"--{name}") + for name in ("expect", "template", "capture-raw", "execute", "output"): + parser.add_argument(f"--{name}", type=Path) + parser.add_argument("--roundtrip", action="store_true") + parser.add_argument("--show-values", action="store_true", help="Print private API values locally") + options = cast("Options", parser.parse_args()) + try: + result = asyncio.run(run(feature, options)) + console(json.dumps(result, indent=2, allow_nan=False)) + except NottyApiError, ValidationError, OSError, TypeError, ValueError: + console( + "Validation failed or a write is uncertain. Inspect private before/after/restoration evidence and the app before retrying. Emptying is prohibited.", + file=sys.stderr, + ) + return 2 + comparison = result["app_comparison"] + status = comparison.get("status") if isinstance(comparison, dict) else None + if ( + result["failed_reads"] + or status == MISMATCH + or result["restore_status"] not in {"not_requested", "readback_matches_baseline"} + ): + return 1 + return 0 if status == MATCHED else 3 + + +async def restore_state( + api: app_actions.ValidationApi, + feature: str, + target: app_actions.Target, + restore: tuple[str, JsonObject], + options: Options, +) -> JsonObject: + """Restore a reversible change once, preserving evidence of failures. + + Returns: + Original-value comparison and raw restoration evidence. + """ + try: + return await _restore(api, feature, target, restore, options) + except NottyApiError: + return {"feature": feature, "restore_status": "failed_or_uncertain_check_app_and_before_capture"} + + +async def _restore( + api: app_actions.ValidationApi, + feature: str, + target: app_actions.Target, + restore: tuple[str, JsonObject], + options: Options, +) -> JsonObject: + await app_actions.apply(api, feature, target, restore[0], restore[1]) + fresh_devices = await api.user_devices(await api.pets()) if feature == ALIAS else [] + fresh_device = next((row for row in fresh_devices if str(row.get("user_device_id")) == target.box), target.device) + restored_target = app_actions.Target(target.box, target.pet, fresh_device) + restored, errors = await collect(api, feature, restored_target, options.memo_id) + restored_values = app_actions.restore_request(feature, restore[0], restore[1], restored) + status = ( + "readback_matches_baseline" if not errors and restored_values == restore else "readback_mismatch_or_unavailable" + ) + return {"feature": feature, "data": restored, "errors": errors, "restore_status": status} + + +def write_readback(feature: str, capture: JsonObject, data: JsonObject) -> str: + """Check supported requested fields separately from independent app evidence. + + Returns: + Match/mismatch for directly comparable writes; otherwise an explicit unknown. + """ + request = capture.get("request") + if not isinstance(request, dict): + return "not_requested_or_request_not_captured" + operation, changes = request.get("operation"), request.get("changes") + if not isinstance(operation, str) or not isinstance(changes, dict): + return "unreadable_request" + try: + actual = app_actions.restore_request(feature, operation, changes, data) + except NottyApiError: + return "not_interpreted_verify_in_app" + return "match" if actual == (operation, changes) else MISMATCH diff --git a/scripts/login_validation.py b/scripts/login_validation.py new file mode 100644 index 0000000..9f8cc49 --- /dev/null +++ b/scripts/login_validation.py @@ -0,0 +1,85 @@ +"""Explicit NOTTY email-code request/exchange using the integration login contract.""" + +from __future__ import annotations + +import argparse +import asyncio +from dataclasses import dataclass +import json +import os +from pathlib import Path +import sys +from typing import cast + +import aiohttp + +from scripts import probe_datapoints +from scripts.console import console + + +@dataclass +class LoginOptions: + """Explicit one-time login operation and optional new private session path.""" + + request_code: bool = False + exchange_code: bool = False + new_session_file: Path | None = None + + +async def run(options: LoginOptions) -> dict[str, str]: + """Request a code or exchange a supplied code once, without publishing secrets. + + Returns: + Authentication acknowledgement only; no credentials or email address. + + Raises: + ValueError: If inputs are missing or a session could be overwritten. + """ + email = os.environ.get("NOTTY_EMAIL") + code = os.environ.get("NOTTY_VERIFICATION_CODE") + if not email or options.request_code == options.exchange_code: + msg = "Set NOTTY_EMAIL and choose one login operation" + raise ValueError(msg) + path = options.new_session_file + if options.exchange_code and (not code or path is None): + msg = "Code exchange requires NOTTY_VERIFICATION_CODE and --new-session-file" + raise ValueError(msg) + if path and (not path.name.endswith(".private.json") or path.exists() or path.is_symlink()): + msg = "Use a new .private.json session path" + raise ValueError(msg) + async with aiohttp.ClientSession() as session: + api = probe_datapoints.load_api.NottyApi( + session, email=email, verification_code=code, region_code=os.environ.get("NOTTY_REGION_CODE", "NL") + ) + if options.request_code: + await api.request_email_code() + return {"status": "code_request_acknowledged_check_inbox", "contract": "integration_email_code_request"} + await api.login() + if not api.token or not api.user_id or path is None: + msg = "Login returned incomplete credentials" + raise ValueError(msg) + probe_datapoints.write_json( + path, {"access_token": api.token, "user_id": api.user_id, "email": email, "region_code": api.region_code} + ) + await api.pets() + return {"status": "code_exchange_and_authenticated_read_succeeded", "contract": "integration_email_login_metadata"} + + +def main() -> int: + """Run an explicit auth test; rejected/used codes are never retried. + + Returns: + Zero on acknowledgement, two for a failed operation or local validation. + """ + parser = argparse.ArgumentParser(description=__doc__) + operation = parser.add_mutually_exclusive_group(required=True) + operation.add_argument("--request-code", action="store_true") + operation.add_argument("--exchange-code", action="store_true") + parser.add_argument("--new-session-file", type=Path) + options = cast("LoginOptions", parser.parse_args()) + try: + console(json.dumps(asyncio.run(run(options)), indent=2)) + except probe_datapoints.load_api.NottyApiError, OSError, ValueError: + console("Login validation failed. Codes are not retried; credentials were not printed.", file=sys.stderr) + return 2 + return 0 diff --git a/scripts/probe_weights.py b/scripts/probe_weights.py new file mode 100755 index 0000000..d7d3402 --- /dev/null +++ b/scripts/probe_weights.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +"""Read NOTTY pet/profile and litter-box weight evidence; never change settings. + +Default output omits weights, names, IDs and timestamp values. --show-values +prints weight/timestamp values for local comparison with the app. Save raw +captures before and after a normal visit, then compare them offline. +""" + +from __future__ import annotations + +import argparse +import asyncio +from dataclasses import dataclass +from datetime import UTC, datetime +import json +from pathlib import Path +import sys +from typing import TYPE_CHECKING, cast + +import aiohttp + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts import probe_datapoints, weight_report +from scripts.console import console +from scripts.validate_commands import ValidationError, load_session + +if TYPE_CHECKING: + from custom_components.notty.api import JsonObject, JsonValue + +SOURCE_PET = "pet" +LITTER_WORD = "litter" +SAND_WORD = "sand" +LIST_FIELDS = ("list", "data", "rows", "items") +LITTER_PRODUCT_ID = 2 + + +def rows(value: JsonValue) -> list[JsonObject]: + """Require a supported record-list shape instead of hiding malformed reads. + + Returns: + Explicit object records. + + Raises: + ValueError: If the response is absent or malformed. + """ + if isinstance(value, dict): + value = next((value[key] for key in LIST_FIELDS if key in value), None) + if not isinstance(value, list) or any(not isinstance(row, dict) for row in value): + msg = "Unreadable NOTTY record list" + raise ValueError(msg) + return [row for row in value if isinstance(row, dict)] + + +def numeric_id(value: JsonValue) -> str: + """Validate IDs before interpolation into a read URL. + + Returns: + Canonical positive decimal text. + + Raises: + ValueError: If a target has an ambiguous or unsafe identity. + """ + if type(value) is int and value > 0: + return str(value) + if isinstance(value, str) and value.isascii() and value.isdecimal() and int(value) > 0: + return str(int(value)) + msg = "A positive numeric account target is required" + raise ValueError(msg) + + +def litter_box(device: JsonObject) -> bool: + """Recognize physical litter boxes without accepting feeder/water devices. + + Returns: + Whether discovery explicitly identifies a litter box. + """ + kind = " ".join( + str(device.get(key, "")) for key in ("device_type", "type", "device_name", "product_name", "model") + ).lower() + return device.get("_notty_source") != SOURCE_PET and ( + LITTER_WORD in kind + or SAND_WORD in kind + or (type(device.get("device_id")) is int and device["device_id"] == LITTER_PRODUCT_ID) + ) + + +class WeightCollector: + """Collect fixed GET endpoints and retain failures in a private snapshot.""" + + def __init__(self, api: probe_datapoints.load_api.NottyApi) -> None: + self.api = api + self.sources: list[JsonValue] = [] + self.errors: list[JsonValue] = [] + + async def read(self, label: str, kind: str, identity: str, path: str) -> JsonValue: + """Read one fixed route, keeping raw error bodies out of every output. + + Returns: + Server data or None on an explicitly recorded endpoint failure. + + Raises: + NottyAuthError: If the saved session expires; collection stops without retry. + """ + try: + data = await self.api.request("GET", path) + except probe_datapoints.load_api.NottyAuthError: + raise + except probe_datapoints.load_api.NottyApiError: + self.errors.append({"source": label, "error": "request_failed"}) + return None + self.sources.append({"label": label, "kind": kind, "identity": identity, "data": data}) + return data + + async def box(self, device_id: str, label: str, pets: dict[str, str]) -> None: + """Inspect one box, and scoped detail/history for explicitly associated account pets.""" + identity = f"box:{device_id}" + await self.read(f"{label}.info", "info", f"{identity}:info", f"/device/litter_box/get_info/{device_id}") + await self.read( + f"{label}.pet_list", "pet_list", f"{identity}:pet_list", f"/device/litter_box/pet_data_list/{device_id}" + ) + associated = await self.read( + f"{label}.associations", + "associations", + f"{identity}:associations", + f"/device/get_associated_pets/{device_id}", + ) + if associated is None: + return + try: + candidates = rows(associated) + selected = {numeric_id(row.get("pet_id")): row for row in candidates} + except ValueError: + self.errors.append({"source": f"{label}.associations", "error": "malformed_list_or_identity"}) + return + for pet_id, pet_label in pets.items(): + row = selected.get(pet_id) + if row is None: + continue + state = probe_datapoints.load_api.plan_enabled(row.get("is_associated")) + if state is None: + self.errors.append({"source": f"{label}.{pet_label}", "error": "unknown_association_state"}) + if state is not True: + continue + for kind, endpoint in (("statistics", "pet_data_statistics"), ("detail", "pet_data_detail")): + await self.read( + f"{label}.{pet_label}.{kind}", + kind, + f"{identity}:pet:{pet_id}:{kind}", + f"/device/litter_box/{endpoint}/{device_id}?pet_id={pet_id}", + ) + + async def collect(self, device_ids: list[str], pet_ids: list[str]) -> JsonObject: + """Resolve selected targets from current account discovery before reading data. + + Returns: + A private weight snapshot with identities preserved only for offline joining. + + Raises: + ValueError: If a requested target is outside current account discovery. + """ + pets = rows(await self.api.request("GET", "/pet/list")) + account_pets = {numeric_id(pet.get("pet_id")): pet for pet in pets} + selected_pets = {numeric_id(value) for value in pet_ids} if pet_ids else set(account_pets) + if selected_pets - account_pets.keys(): + msg = "Requested pet is not in the current account" + raise ValueError(msg) + devices = await self.api.user_devices(pets) + boxes = {numeric_id(device.get("user_device_id")): device for device in devices if litter_box(device)} + selected_boxes = {numeric_id(value) for value in device_ids} if device_ids else set(boxes) + if selected_boxes - boxes.keys(): + msg = "Requested physical litter box is not in the current account" + raise ValueError(msg) + labels = {pet_id: f"pet[{index}]" for index, pet_id in enumerate(sorted(selected_pets, key=int), 1)} + for pet_id, label in labels.items(): + await self.read(f"{label}.profile", "profile", f"pet:{pet_id}:profile", f"/pet/info/{pet_id}") + for index, device_id in enumerate(sorted(selected_boxes, key=int), 1): + await self.box(device_id, f"box[{index}]", labels) + if not selected_boxes or not selected_pets: + self.errors.append({"source": "discovery", "error": "no_litter_boxes_or_pets"}) + return { + "schema_version": 1, + "captured_at": datetime.now(UTC).isoformat(), + "sources": self.sources, + "errors": self.errors, + } + + +@dataclass +class WeightProbeOptions: + """CLI inputs; every write is an explicitly named local output file.""" + + session_file: Path | None = None + from_file: Path | None = None + compare: Path | None = None + output: Path | None = None + capture_raw: Path | None = None + show_values: bool = False + device_id: list[str] | None = None + pet_id: list[str] | None = None + + +def load_capture(path: Path) -> JsonObject: + """Load a versioned private capture for offline analysis. + + Returns: + A validated capture object. + + Raises: + ValueError: If the filename or JSON schema is invalid. + TypeError: If the capture root is not an object. + """ + if not path.name.endswith(".private.json"): + msg = "Weight capture inputs must end in .private.json" + raise ValueError(msg) + value = cast("JsonValue", json.loads(path.read_text(encoding="utf-8"))) + if not isinstance(value, dict): + msg = "Expected a weight capture object" + raise TypeError(msg) + weight_report.capture_sources(value) + return value + + +def validate_options(options: WeightProbeOptions) -> None: + """Check all output paths before credentials are read or network calls begin. + + Raises: + ValueError: If input modes conflict or private/output paths are unsafe. + """ + if (options.session_file is None) == (options.from_file is None): + msg = "Choose exactly one of --session-file and --from-file" + raise ValueError(msg) + if options.from_file and (options.capture_raw or options.device_id or options.pet_id): + msg = "Offline mode does not accept live selection or raw-capture options" + raise ValueError(msg) + for path in (options.capture_raw, options.output): + if path and (path.exists() or path.is_symlink()): + msg = "Output files must be new and must not be symlinks" + raise ValueError(msg) + if options.capture_raw and not options.capture_raw.name.endswith(".private.json"): + msg = "Raw captures must end in .private.json" + raise ValueError(msg) + if options.show_values and options.output and not options.output.name.endswith(".private.json"): + msg = "Reports showing weight/timestamp values must end in .private.json" + raise ValueError(msg) + if options.capture_raw and options.capture_raw == options.output: + msg = "Report and raw capture must use separate paths" + raise ValueError(msg) + for value in (*(options.device_id or []), *(options.pet_id or [])): + numeric_id(value) + + +async def run(options: WeightProbeOptions) -> JsonObject: + """Collect live GET evidence or analyse saved data without network access. + + Returns: + The report, including explicit failed-read counts and optional comparison. + + Raises: + ValueError: If session credentials are malformed or input modes conflict. + """ + validate_options(options) + before = load_capture(options.compare) if options.compare else None + if options.from_file: + capture = load_capture(options.from_file) + else: + if options.session_file is None: + msg = "A saved session is required for live reads" + raise ValueError(msg) + saved = load_session(options.session_file) + token, user_id = saved.get("access_token"), saved.get("user_id") + if not isinstance(token, str) or not isinstance(user_id, str): + msg = "Saved session credentials must be strings" + raise ValueError(msg) + async with aiohttp.ClientSession() as session: + api = probe_datapoints.load_api.NottyApi( + session, token=token, user_id=user_id, region_code=str(saved.get("region_code") or "NL") + ) + capture = await WeightCollector(api).collect(options.device_id or [], options.pet_id or []) + if options.capture_raw: + probe_datapoints.write_json(options.capture_raw, capture) + result = weight_report.report(capture, show_values=options.show_values, before=before) + if options.output: + probe_datapoints.write_json(options.output, result) + return result + + +def main() -> int: + """Run fixed read routes only; failures never trigger a login or write retry. + + Returns: + Zero for complete reads, one for partial reads, two for authentication/input failures. + """ + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--session-file", type=Path) + mode.add_argument("--from-file", type=Path) + parser.add_argument("--compare", type=Path, help="Previous private weight capture; compare by private stable IDs") + parser.add_argument("--capture-raw", type=Path) + parser.add_argument("--output", type=Path) + parser.add_argument( + "--show-values", action="store_true", help="Reveal weight/timestamp values locally; never prints names or IDs" + ) + parser.add_argument("--device-id", action="append") + parser.add_argument("--pet-id", action="append") + options = cast("WeightProbeOptions", parser.parse_args()) + try: + result = asyncio.run(run(options)) + console(json.dumps(result, indent=2, allow_nan=False)) + except probe_datapoints.load_api.NottyApiError, ValidationError, OSError, TypeError, ValueError, RecursionError: + console( + "Weight validation failed; check saved session and input/output files. No device changes were attempted.", + file=sys.stderr, + ) + return 2 + return 1 if result["failed_reads"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validate_alias.py b/scripts/validate_alias.py new file mode 100755 index 0000000..1c9cc01 --- /dev/null +++ b/scripts/validate_alias.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY alias against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("alias")) diff --git a/scripts/validate_associations.py b/scripts/validate_associations.py new file mode 100755 index 0000000..1bc1a92 --- /dev/null +++ b/scripts/validate_associations.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY associations against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("associations")) diff --git a/scripts/validate_cleaning.py b/scripts/validate_cleaning.py new file mode 100755 index 0000000..168730a --- /dev/null +++ b/scripts/validate_cleaning.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY cleaning commands against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("commands")) diff --git a/scripts/validate_dnd.py b/scripts/validate_dnd.py new file mode 100755 index 0000000..79cdb7b --- /dev/null +++ b/scripts/validate_dnd.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY dnd against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("dnd")) diff --git a/scripts/validate_firmware.py b/scripts/validate_firmware.py new file mode 100755 index 0000000..de8cfaf --- /dev/null +++ b/scripts/validate_firmware.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY firmware against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("firmware")) diff --git a/scripts/validate_lock.py b/scripts/validate_lock.py new file mode 100755 index 0000000..428b3f6 --- /dev/null +++ b/scripts/validate_lock.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY lock against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("lock")) diff --git a/scripts/validate_login.py b/scripts/validate_login.py new file mode 100755 index 0000000..ed80d5f --- /dev/null +++ b/scripts/validate_login.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Validate NOTTY login against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main +from scripts.login_validation import main as login_main + +AUTH_FLAGS = {"--request-code", "--exchange-code"} + +if __name__ == "__main__": + if AUTH_FLAGS.intersection(sys.argv): + raise SystemExit(login_main()) + raise SystemExit(main("login")) diff --git a/scripts/validate_memos.py b/scripts/validate_memos.py new file mode 100755 index 0000000..0f3725e --- /dev/null +++ b/scripts/validate_memos.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY memos against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("memos")) diff --git a/scripts/validate_notifications.py b/scripts/validate_notifications.py new file mode 100755 index 0000000..f8edacd --- /dev/null +++ b/scripts/validate_notifications.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY notifications against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("notifications")) diff --git a/scripts/validate_pets.py b/scripts/validate_pets.py new file mode 100755 index 0000000..0498434 --- /dev/null +++ b/scripts/validate_pets.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY pets against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("pets")) diff --git a/scripts/validate_reminders.py b/scripts/validate_reminders.py new file mode 100755 index 0000000..389dbc2 --- /dev/null +++ b/scripts/validate_reminders.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY reminders against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("reminders")) diff --git a/scripts/validate_schedules.py b/scripts/validate_schedules.py new file mode 100755 index 0000000..62d9e9e --- /dev/null +++ b/scripts/validate_schedules.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY schedules against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("schedules")) diff --git a/scripts/validate_settings.py b/scripts/validate_settings.py new file mode 100755 index 0000000..f4a348c --- /dev/null +++ b/scripts/validate_settings.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY settings against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("settings")) diff --git a/scripts/validate_statistics.py b/scripts/validate_statistics.py new file mode 100755 index 0000000..f58cf39 --- /dev/null +++ b/scripts/validate_statistics.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY statistics against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("statistics")) diff --git a/scripts/validate_timezone.py b/scripts/validate_timezone.py new file mode 100755 index 0000000..f0e33bd --- /dev/null +++ b/scripts/validate_timezone.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Validate NOTTY timezone against live API and phone-app observations.""" + +from pathlib import Path +import sys + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.app_validation import main + +if __name__ == "__main__": + raise SystemExit(main("timezone")) diff --git a/scripts/weight_report.py b/scripts/weight_report.py new file mode 100644 index 0000000..2fbb66f --- /dev/null +++ b/scripts/weight_report.py @@ -0,0 +1,270 @@ +"""Conservative analysis of private NOTTY weight captures, without HA imports.""" + +from __future__ import annotations + +from datetime import UTC, datetime +import math +import re +from typing import TYPE_CHECKING, cast + +if TYPE_CHECKING: + from custom_components.notty.api import JsonObject, JsonValue + +WEIGHT_FIELDS = { + "weight", + "today_weight", + "yesterday_weight", + "total_weight", + "average_weight", + "avg_weight", + "last_weight", + "latest_weight", + "body_weight", + "weight_value", +} +UNIT_FIELDS = ("weight_unit", "weight_unit_name", "unit") +TIME_FIELDS = ( + "date", + "time", + "datetime", + "timestamp", + "measured_at", + "weight_time", + "weight_date", + "utc_create", + "utc_modified", + "created_at", +) +STRUCTURE_FIELDS = { + "data", + "list", + "rows", + "items", + "statistics", + "detail", + "weights", + "weight_list", + "weight_data", + *WEIGHT_FIELDS, +} +PROFILE = "profile" +FIELD_WEIGHT = "weight" +MAX_FINDINGS = 500 +MAX_DEPTH = 16 +CAPTURE_VERSION = 1 +FIELD_DATA = "data" +SOURCE_PATTERN = re.compile( + r"(?:pet\[[1-9][0-9]*\]\.profile|box\[[1-9][0-9]*\]\.(?:info|pet_list|associations|pet\[[1-9][0-9]*\]\.(?:statistics|detail)))" +) + + +def positive_number(value: JsonValue) -> float | None: + """Parse finite positive measurements without accepting Booleans or units. + + Returns: + A numeric candidate, otherwise None. + """ + if isinstance(value, bool) or not isinstance(value, (str, int, float)): + return None + try: + number = float(value) + except ValueError, OverflowError: + return None + return number if math.isfinite(number) and number > 0 else None + + +def unit_evidence(row: JsonObject) -> JsonObject: + """Keep explicit unit text separate from unverified numeric enum mappings. + + Returns: + A safe description, never an assumed kilogram conversion. + """ + for key in UNIT_FIELDS: + value = row.get(key) + if isinstance(value, str) and value.strip().lower() in {"kg", "lb", "lbs", "g"}: + return {"field": key, "reported": value.strip().lower(), "status": "explicit_text"} + if type(value) is int or (isinstance(value, str) and value.isascii() and value.isdecimal()): + return {"field": key, "reported": value, "status": "unverified_enum"} + return {"status": "missing_or_unknown"} + + +def _find_weights( + value: JsonValue, *, path: str = "$", depth: int = 0 +) -> tuple[list[tuple[str, str, JsonValue, JsonObject]], bool]: + if depth > MAX_DEPTH: + return [], True + result: list[tuple[str, str, JsonValue, JsonObject]] = [] + truncated = False + children: list[tuple[str, JsonValue]] = [] + if isinstance(value, dict): + for key, child in value.items(): + safe_key = key if key in STRUCTURE_FIELDS else "*" + child_path = f"{path}.{safe_key}" + if key in WEIGHT_FIELDS and not isinstance(child, (dict, list)): + result.append((child_path, key, child, value)) + elif isinstance(child, (dict, list)): + children.append((child_path, child)) + elif isinstance(value, list): + if path.rsplit(".", 1)[-1] in WEIGHT_FIELDS | {"weights", "weight_list"}: + result.extend( + (f"{path}[{index}]", "weight", child, {}) + for index, child in enumerate(value) + if not isinstance(child, (dict, list)) + ) + children = [(f"{path}[{index}]", child) for index, child in enumerate(value) if isinstance(child, (dict, list))] + for child_path, child in children: + found, limited = _find_weights(child, path=child_path, depth=depth + 1) + result.extend(found) + truncated |= limited + if len(result) >= MAX_FINDINGS: + return result[:MAX_FINDINGS], True + return result, truncated + + +def _timestamp_context(row: JsonObject, *, show_values: bool) -> JsonObject: + context: JsonObject = {} + for key in TIME_FIELDS: + value = row.get(key) + if isinstance(value, (str, int, float)) and not isinstance(value, bool): + context[key] = value if show_values else type(value).__name__ + return context + + +def source_report(source: JsonObject, *, show_values: bool) -> JsonObject: + """Inventory candidate fields without claiming profile weight was measured. + + Returns: + Pseudonymous source metadata, field evidence and explicit limitations. + """ + found, truncated = _find_weights(source.get("data")) + fields: list[JsonValue] = [] + for path, field, value, context in found: + entry: JsonObject = { + "path": path, + "field": field, + "role": "profile_setting" + if source.get("kind") == PROFILE and field == FIELD_WEIGHT + else "unverified_measurement_candidate", + "value_type": type(value).__name__, + "positive_finite_number": positive_number(value) is not None, + "unit": unit_evidence(context), + "timestamp_context": _timestamp_context(context, show_values=show_values), + } + if show_values: + entry["reported_value"] = value + fields.append(entry) + return { + "source": source["label"], + "kind": source["kind"], + "response_type": type(source.get("data")).__name__, + "fields": fields, + "truncated": truncated, + } + + +def capture_sources(capture: JsonObject) -> list[JsonObject]: + """Validate this tool's capture schema before analysing or comparing it. + + Returns: + Captured source objects. + + Raises: + ValueError: If this is not a complete compatible weight-probe capture. + """ + sources = capture.get("sources") + if ( + type(capture.get("schema_version")) is not int + or capture["schema_version"] != CAPTURE_VERSION + or not isinstance(sources, list) + or not isinstance(capture.get("errors"), list) + ): + msg = "Expected a version-1 weight-probe capture" + raise ValueError(msg) + result: list[JsonObject] = [] + seen: set[str] = set() + for source in sources: + if ( + not isinstance(source, dict) + or not all(isinstance(source.get(key), str) for key in ("label", "kind", "identity")) + or FIELD_DATA not in source + ): + msg = "Malformed weight-probe source" + raise ValueError(msg) + # Labels and kinds are generated by this tool; arbitrary capture text is not printed. + label = source["label"] + kind = source["kind"] + if ( + not isinstance(label, str) + or SOURCE_PATTERN.fullmatch(label) is None + or not isinstance(kind, str) + or kind not in {PROFILE, "info", "pet_list", "associations", "statistics", "detail"} + ): + msg = "Unknown weight-probe source label or kind" + raise ValueError(msg) + identity = str(source["identity"]) + if identity in seen: + msg = "Duplicate weight-probe source identity" + raise ValueError(msg) + seen.add(identity) + result.append(source) + return result + + +def compare_captures(before: JsonObject, after: JsonObject) -> JsonObject: + """Join snapshots by private stable IDs, never by potentially reordered labels. + + Returns: + Change counts and current pseudonyms; no values or identifiers. + """ + previous = {str(source["identity"]): source for source in capture_sources(before)} + changes: list[JsonValue] = [] + for source in capture_sources(after): + old = previous.pop(str(source["identity"]), None) + if old is None: + changes.append({"source": source["label"], "status": "new_source"}) + continue + old_fields, _ = _find_weights(old["data"]) + new_fields, _ = _find_weights(source["data"]) + # List positions may change; this is a response comparison, not event deduplication. + changed = [(path, field, value) for path, field, value, _ in old_fields] != [ + (path, field, value) for path, field, value, _ in new_fields + ] + context_changed = [ + (path, _timestamp_context(row, show_values=True), unit_evidence(row)) for path, _, _, row in old_fields + ] != [(path, _timestamp_context(row, show_values=True), unit_evidence(row)) for path, _, _, row in new_fields] + changes.append({ + "source": source["label"], + "weight_response_changed": changed, + "timestamp_or_unit_context_changed": context_changed, + }) + return { + "sources": changes, + "missing_previous_sources": len(previous), + "interpretation": "Response changes do not prove a new weigh-in; list order and aggregates can change.", + } + + +def report(capture: JsonObject, *, show_values: bool = False, before: JsonObject | None = None) -> JsonObject: + """Produce a conservative discovery report rather than a production-readiness verdict. + + Returns: + Weight field evidence, source coverage and optional before/after differences. + """ + sources = capture_sources(capture) + errors = capture.get("errors") + result: JsonObject = { + "schema_version": CAPTURE_VERSION, + "analysed_at": datetime.now(UTC).isoformat(), + "sources": cast("list[JsonValue]", [source_report(source, show_values=show_values) for source in sources]), + "failed_reads": len(errors) if isinstance(errors, list) else 0, + "limitations": [ + "All device/pet weight fields are candidates until compared with the official app after a normal visit.", + "Profile weight is an editable setting, not evidence of a litter-box measurement.", + "Numeric unit codes are not converted; verify the enum against APK and app settings.", + "Timestamps are reported as supplied; their timezone and meaning are unverified.", + "Historical response rows are not imported into Home Assistant history.", + ], + } + if before is not None: + result["comparison"] = compare_captures(before, capture) + return result diff --git a/tests/test_app_validation.py b/tests/test_app_validation.py new file mode 100644 index 0000000..a9aed23 --- /dev/null +++ b/tests/test_app_validation.py @@ -0,0 +1,160 @@ +"""No-empty enforcement, independent app evidence and reversible write journals.""" + +from __future__ import annotations + +import asyncio +from copy import deepcopy +import json +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError +from scripts import app_actions, app_validation +from scripts.probe_datapoints import write_json + +EXPECTED_MATCH = "matches_supplied_phone_app_values" +EXPECTED_MISMATCH = "mismatch" +EXPECTED_PENDING = "pending_phone_app_values" +EXPECTED_RESTORED = "readback_matches_baseline" +PRIVATE_MODE = 0o600 +GET = "GET" +PRIVATE_MARKER = "do-not-print" +POST = "POST" + + +@pytest.mark.parametrize("operation", [2, "2", True, 0, None, "empty", -1, 4]) +async def test_empty_and_unknown_motor_commands_are_blocked_at_transport(operation: JsonValue) -> None: + """Even a mistaken caller with writes enabled cannot send the empty code.""" + api = app_actions.ValidationApi(MagicMock()) + api.writes_enabled = True + with patch.object(NottyApi, "request", AsyncMock()) as request, pytest.raises(NottyApiError, match="forbidden"): + await api.request(POST, "/device/litter_box/one_key", data={"one_key": operation}) + request.assert_not_awaited() + + +async def test_read_mode_blocks_every_post() -> None: + """The default transport is incapable of making a settings change.""" + api = app_actions.ValidationApi(MagicMock()) + with patch.object(NottyApi, "request", AsyncMock()) as request, pytest.raises(NottyApiError, match="explicit"): + await api.request(POST, "/device/litter_box/set_key", data={"switch": 1}) + request.assert_not_awaited() + + +async def test_feature_cannot_route_another_features_write() -> None: + """The lock script cannot disguise an unrelated command as a setting.""" + api = MagicMock() + with pytest.raises(NottyApiError, match="Unsupported"): + await app_actions.apply(api, "lock", app_actions.Target("123", "", {}), "set_mode", {"mode": 3}) + api.devices.assert_not_called() + + +def test_pending_or_api_copied_expectation_is_not_independent_app_verification() -> None: + """Templates contain blanks and remain pending until explicitly filled from the app.""" + data: JsonObject = {"info": {"switch_key": 1}} + expected = app_validation.template("lock", data) + assert expected["checks"][0]["equals"] is None + assert app_validation.app_comparison(data, expected, show_values=False)["status"] == EXPECTED_PENDING + expected["checks"][0].update({"equals": 1, "confirmed_from_app": True}) + assert app_validation.app_comparison(data, expected, show_values=False)["status"] == EXPECTED_MATCH + expected["checks"][0]["equals"] = True + assert app_validation.app_comparison(data, expected, show_values=False)["status"] == EXPECTED_MISMATCH + + +def test_missing_field_never_matches_an_expected_null() -> None: + """Missing API fields must not be confused with an actual null value.""" + expected: JsonObject = { + "checks": [{"source": "info", "path": ["absent"], "equals": None, "confirmed_from_app": True}] + } + assert app_validation.app_comparison({"info": {}}, expected, show_values=False)["status"] == EXPECTED_MISMATCH + + +async def test_roundtrip_records_changed_readback_and_restores_original_on_success(tmp_path: Path) -> None: + """A lock test stores separate phases and validates the original switch readback.""" + api = MagicMock() + api.pets = AsyncMock(return_value=[]) + api.user_devices = AsyncMock(return_value=[]) + state: JsonObject = {"switch_key": 0} + + async def apply(_api: object, _feature: str, _target: object, _operation: str, changes: JsonObject) -> None: + state["switch_key"] = changes["switch"] + await asyncio.sleep(0) + + async def collect( + _api: object, _feature: str, _target: object, _memo: object + ) -> tuple[JsonObject, list[JsonValue]]: + snapshot = deepcopy(state) + await passthrough() + return {"info": snapshot}, [] + + request = tmp_path / "request.private.json" + before = tmp_path / "before.private.json" + write_json(request, {"operation": "set_key", "changes": {"switch": 1}}) + options = app_validation.Options( + session_file=tmp_path / "session.private.json", execute=request, capture_raw=before, roundtrip=True + ) + with ( + patch.object(app_actions, "apply", side_effect=apply), + patch.object(app_validation, "collect", side_effect=collect), + ): + result = await app_validation.execute( + api, "lock", app_actions.Target("123", "", {}), {"data": {"info": {"switch_key": 0}}, "errors": []}, options + ) + assert state["switch_key"] == 0 + assert result["restore_status"] == EXPECTED_RESTORED + after = app_validation.private_json(app_validation.phase_path(before, "after")) + assert after["data"]["info"]["switch_key"] == 1 + restored_file = app_validation.phase_path(before, "restored") + assert restored_file.stat().st_mode & 0o777 == PRIVATE_MODE + + +async def passthrough() -> None: + """Yield to exercise asynchronous readback and restoration sequencing.""" + await asyncio.sleep(0) + + +async def test_roundtrip_restores_after_an_uncertain_write_failure(tmp_path: Path) -> None: + """A timeout may follow an accepted write; restoration still runs once.""" + api = MagicMock() + request = tmp_path / "request.private.json" + write_json(request, {"operation": "set_key", "changes": {"switch": 1}}) + options = app_validation.Options(execute=request, capture_raw=tmp_path / "before.private.json", roundtrip=True) + with ( + patch.object(app_actions, "apply", AsyncMock(side_effect=[NottyApiError("timeout"), None])) as apply, + patch.object(app_validation, "collect", AsyncMock(return_value=({"info": {"switch_key": 0}}, []))), + pytest.raises(NottyApiError, match="timeout"), + ): + await app_validation.execute( + api, "lock", app_actions.Target("123", "", {}), {"data": {"info": {"switch_key": 0}}, "errors": []}, options + ) + assert apply.await_args_list[-1].args[-1] == {"switch": 0} + assert app_validation.phase_path(options.capture_raw, "restored").exists() + + +@pytest.mark.parametrize("feature", ["firmware", "statistics", "commands", "memos", "timezone"]) +def test_nonrestorable_operations_cannot_start_a_roundtrip(feature: str) -> None: + """History deletion, motor actions and firmware cannot be presented as reversible.""" + with pytest.raises(NottyApiError, match="restoration"): + app_actions.restore_request(feature, "install", {}, {}) + + +async def test_offline_comparison_uses_no_session_and_hides_private_values(tmp_path: Path) -> None: + """A phone-app comparison can be rerun later without contacting NOTTY.""" + capture = tmp_path / "lock.private.json" + expected = tmp_path / "app.private.json" + write_json(capture, {"feature": "lock", "data": {"info": {"switch_key": 1, "token": "do-not-print"}}, "errors": []}) + write_json( + expected, {"checks": [{"source": "info", "path": ["switch_key"], "equals": 1, "confirmed_from_app": True}]} + ) + with patch.object(app_validation.aiohttp, "ClientSession", side_effect=AssertionError("network")): + result = await app_validation.run("lock", app_validation.Options(from_file=capture, expect=expected)) + assert result["app_comparison"]["status"] == EXPECTED_MATCH + assert PRIVATE_MARKER not in json.dumps(result) + + +def test_acknowledged_but_unchanged_api_write_is_a_mismatch() -> None: + """HTTP success cannot hide a lock value that never changed in readback.""" + capture: JsonObject = {"request": {"operation": "set_key", "changes": {"switch": 1}}} + assert app_validation.write_readback("lock", capture, {"info": {"switch_key": 0}}) == EXPECTED_MISMATCH + assert app_validation.write_readback("lock", capture, {"info": {"switch_key": 1}}) != EXPECTED_MISMATCH diff --git a/tests/test_weight_probe.py b/tests/test_weight_probe.py new file mode 100644 index 0000000..7c02b08 --- /dev/null +++ b/tests/test_weight_probe.py @@ -0,0 +1,163 @@ +"""Read-only weight probing, private output and conservative evidence checks.""" + +from __future__ import annotations + +from copy import deepcopy +import json +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from custom_components.notty.api import JsonObject, JsonValue +from scripts import probe_datapoints, probe_weights, weight_report + +PRIVATE_MODE = 0o600 +EXPECTED_ENUM = "unverified_enum" +EXPECTED_SETTING = "profile_setting" +GET = "GET" +FIELD_VALUE = "reported_value" +SERIES_COUNT = 2 +EXPECTED_DETAIL_PATH = "/device/litter_box/pet_data_detail/123?pet_id=7" +FORBIDDEN_PATH_PARTS = ("pet_id=8", "pet_id=99", "/456") +PRIVATE_MARKER = "secret-token" + + +def capture() -> JsonObject: + """Return invented profile and measured-series candidates. + + Returns: + A synthetic private weight capture. + """ + return { + "schema_version": 1, + "errors": [], + "sources": [ + { + "label": "pet[1].profile", + "kind": "profile", + "identity": "pet:7:profile", + "data": {"name": "Secret cat", "pet_id": 7, "weight": 4.8, "weight_unit": 1}, + }, + { + "label": "box[1].pet[1].detail", + "kind": "detail", + "identity": "box:123:pet:7:detail", + "data": { + "private-person-key": [{"weight": 4.1, "weight_unit": "kg", "date": "2026-10-17", "time": "08:00"}] + }, + }, + ], + } + + +def test_report_separates_profile_and_candidate_without_leaking_values() -> None: + """Default reports keep personal keys, names, measurements and IDs private.""" + result = weight_report.report(capture()) + text = json.dumps(result) + for secret in ("Secret cat", "private-person-key", "4.8", "4.1", "2026-10-17", "08:00", "pet:7", "box:123"): + assert secret not in text + sources = result["sources"] + assert sources[0]["fields"][0]["role"] == EXPECTED_SETTING + assert sources[0]["fields"][0]["unit"]["status"] == EXPECTED_ENUM + assert sources[1]["fields"][0]["timestamp_context"] == {"date": "str", "time": "str"} + assert FIELD_VALUE not in sources[1]["fields"][0] + + +@pytest.mark.parametrize("value", [True, False, 0, -1, "nan", "inf", "4 kg", None, float("inf")]) +def test_invalid_weight_is_not_a_measurement(value: JsonValue) -> None: + """Nonfinite, missing and Boolean weights never count as valid samples.""" + assert weight_report.positive_number(value) is None + + +def test_series_and_changed_timestamp_are_detected_without_claiming_a_new_visit() -> None: + """A same-weight new timestamp is visible independently of numeric changes.""" + before = capture() + after = deepcopy(before) + after["sources"][1]["data"]["private-person-key"][0]["time"] = "09:00" + comparison = weight_report.compare_captures(before, after) + assert comparison["sources"][1]["weight_response_changed"] is False + assert comparison["sources"][1]["timestamp_or_unit_context_changed"] is True + after["sources"][1]["data"] = {"weight": [4.0, 4.1], "duration": [90, 100]} + fields = weight_report.report(after)["sources"][1]["fields"] + assert len(fields) == SERIES_COUNT + + +async def test_collector_calls_get_only_and_scopes_history_to_bound_account_pets() -> None: + """No write, login, unbound-pet or foreign-account history endpoint is invoked.""" + api = MagicMock() + api.user_devices = AsyncMock( + return_value=[ + {"user_device_id": 123, "device_type": "litter_box"}, + {"user_device_id": 456, "device_type": "feeder"}, + ] + ) + replies: dict[str, JsonValue] = { + "/pet/list": [{"pet_id": 7}, {"pet_id": 8}], + "/device/get_associated_pets/123": [ + {"pet_id": 7, "is_associated": True}, + {"pet_id": 8, "is_associated": False}, + {"pet_id": 99, "is_associated": True}, + ], + } + api.request = AsyncMock(side_effect=lambda _method, path: replies.get(path, {})) + result = await probe_weights.WeightCollector(api).collect([], []) + assert result["errors"] == [] + paths = [call.args[1] for call in api.request.await_args_list] + assert all(call.args[0] == GET for call in api.request.await_args_list) + assert EXPECTED_DETAIL_PATH in paths + assert not any(part in path for path in paths for part in FORBIDDEN_PATH_PARTS) + + +async def test_foreign_target_prevents_data_reads() -> None: + """A CLI target cannot bypass account discovery.""" + api = MagicMock(request=AsyncMock(return_value=[{"pet_id": 7}])) + with pytest.raises(ValueError, match="current account"): + await probe_weights.WeightCollector(api).collect([], ["99"]) + api.request.assert_awaited_once_with(GET, "/pet/list") + + +async def test_optional_failure_is_recorded_without_echoing_error_body() -> None: + """A failed history route is not silently reported as an empty history.""" + api = MagicMock(request=AsyncMock(side_effect=probe_datapoints.load_api.NottyApiError("secret-token"))) + collector = probe_weights.WeightCollector(api) + await collector.read("pet[1].profile", "profile", "pet:7:profile", "/pet/info/7") + assert len(collector.errors) == 1 + assert PRIVATE_MARKER not in json.dumps(collector.errors) + + +async def test_offline_analysis_never_opens_a_network_session_and_outputs_owner_only(tmp_path: Path) -> None: + """Private captures can be reanalysed without tokens or Home Assistant.""" + source = tmp_path / "weight.private.json" + output = tmp_path / "report.json" + probe_datapoints.write_json(source, capture()) + with patch.object(probe_weights.aiohttp, "ClientSession", side_effect=AssertionError("network")): + await probe_weights.run(probe_weights.WeightProbeOptions(from_file=source, output=output)) + assert output.stat().st_mode & 0o777 == PRIVATE_MODE + + +@pytest.mark.parametrize( + "options", + [ + probe_weights.WeightProbeOptions(session_file=Path("session.private.json"), capture_raw=Path("unsafe.json")), + probe_weights.WeightProbeOptions( + session_file=Path("session.private.json"), output=Path("unsafe.json"), show_values=True + ), + probe_weights.WeightProbeOptions(from_file=Path("capture.private.json"), device_id=["123"]), + ], +) +async def test_bad_paths_and_modes_fail_before_network(options: probe_weights.WeightProbeOptions) -> None: + """Sensitive captures and value-bearing reports cannot use a public filename.""" + with ( + patch.object(probe_weights.aiohttp, "ClientSession", side_effect=AssertionError("network")), + pytest.raises(ValueError, match=r"private|Offline"), + ): + await probe_weights.run(options) + + +def test_daily_weight_in_profile_response_is_still_a_measurement_candidate() -> None: + """Endpoint origin does not make today/yesterday values editable profile settings.""" + value = capture() + value["sources"][0]["data"]["today_weight"] = 4.1 + fields = weight_report.report(value)["sources"][0]["fields"] + assert fields[-1]["role"] != EXPECTED_SETTING From 09204b6a9009ec2aaa35e729fb69319ee35d1300 Mon Sep 17 00:00:00 2001 From: Jasper Delahaije Date: Sat, 17 Oct 2026 00:43:26 +0200 Subject: [PATCH 2/2] Reject mismatched cat identities in weight evidence --- scripts/probe_weights.py | 23 +++++++++++++++++++++-- tests/test_weight_probe.py | 11 +++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/scripts/probe_weights.py b/scripts/probe_weights.py index d7d3402..a35cc14 100755 --- a/scripts/probe_weights.py +++ b/scripts/probe_weights.py @@ -86,6 +86,20 @@ def litter_box(device: JsonObject) -> bool: ) +def profile_identity_matches(value: JsonValue, pet_id: str) -> bool: + """Require profile identity before attributing its weights to a selected cat. + + Returns: + Whether explicit response identity matches the requested account pet. + """ + if not isinstance(value, dict): + return False + try: + return numeric_id(value.get("pet_id")) == pet_id + except ValueError: + return False + + class WeightCollector: """Collect fixed GET endpoints and retain failures in a private snapshot.""" @@ -94,7 +108,7 @@ def __init__(self, api: probe_datapoints.load_api.NottyApi) -> None: self.sources: list[JsonValue] = [] self.errors: list[JsonValue] = [] - async def read(self, label: str, kind: str, identity: str, path: str) -> JsonValue: + async def read(self, label: str, kind: str, identity: str, path: str, *, pet_id: str | None = None) -> JsonValue: """Read one fixed route, keeping raw error bodies out of every output. Returns: @@ -110,6 +124,9 @@ async def read(self, label: str, kind: str, identity: str, path: str) -> JsonVal except probe_datapoints.load_api.NottyApiError: self.errors.append({"source": label, "error": "request_failed"}) return None + if pet_id is not None and not profile_identity_matches(data, pet_id): + self.errors.append({"source": label, "error": "profile_identity_mismatch_or_missing"}) + return None self.sources.append({"label": label, "kind": kind, "identity": identity, "data": data}) return data @@ -174,7 +191,9 @@ async def collect(self, device_ids: list[str], pet_ids: list[str]) -> JsonObject raise ValueError(msg) labels = {pet_id: f"pet[{index}]" for index, pet_id in enumerate(sorted(selected_pets, key=int), 1)} for pet_id, label in labels.items(): - await self.read(f"{label}.profile", "profile", f"pet:{pet_id}:profile", f"/pet/info/{pet_id}") + await self.read( + f"{label}.profile", "profile", f"pet:{pet_id}:profile", f"/pet/info/{pet_id}", pet_id=pet_id + ) for index, device_id in enumerate(sorted(selected_boxes, key=int), 1): await self.box(device_id, f"box[{index}]", labels) if not selected_boxes or not selected_pets: diff --git a/tests/test_weight_probe.py b/tests/test_weight_probe.py index 7c02b08..4201932 100644 --- a/tests/test_weight_probe.py +++ b/tests/test_weight_probe.py @@ -94,6 +94,8 @@ async def test_collector_calls_get_only_and_scopes_history_to_bound_account_pets ) replies: dict[str, JsonValue] = { "/pet/list": [{"pet_id": 7}, {"pet_id": 8}], + "/pet/info/7": {"pet_id": 7}, + "/pet/info/8": {"pet_id": 8}, "/device/get_associated_pets/123": [ {"pet_id": 7, "is_associated": True}, {"pet_id": 8, "is_associated": False}, @@ -161,3 +163,12 @@ def test_daily_weight_in_profile_response_is_still_a_measurement_candidate() -> value["sources"][0]["data"]["today_weight"] = 4.1 fields = weight_report.report(value)["sources"][0]["fields"] assert fields[-1]["role"] != EXPECTED_SETTING + + +async def test_profile_for_a_different_pet_never_becomes_weight_evidence() -> None: + """A server identity mismatch cannot silently assign another cat's weight.""" + api = MagicMock(request=AsyncMock(return_value={"pet_id": 8, "today_weight": 5.1})) + collector = probe_weights.WeightCollector(api) + await collector.read("pet[1].profile", "profile", "pet:7:profile", "/pet/info/7", pet_id="7") + assert not collector.sources + assert collector.errors