diet-guard/scripts/probe_kuchnia_shape.py
Krzysztof kuhy Rudnicki 26f1770090 feat: import Kuchnia Wikinga catering deliveries into the food bank
Pulls the day's delivered dishes and their real per-portion macros out of
panel.kuchniavikinga.pl, so a catering meal is one keypress instead of five
retyped numbers.

A delivered meal is not an eaten meal, so nothing is ever logged unattended:
dishes land in the *curated* bank, and entries are written only after an
explicit confirmation. Auto-logging would let the gate satisfy its own
checkpoint from a delivery note, and would record what the courier dropped off
rather than what was eaten.

Three surfaces:
  - `diet-guard kuchnia [--log] [--yes]`
  - the lock screen's "Today's delivery" button, which prefills the meal form
    dish by dish (the user still clicks Log & Continue)
  - a warm-up after each logged meal, on the existing background thread

All event-driven; no new systemd timer. The two automatic paths go through
`refresh_delivery_once`, guarded to one fetch per day.

The panel is an undocumented white-labelled Dietly API; the endpoint map was
recovered from its JS bundles and confirmed against live responses. Notes,
including the traps, are in docs/kuchnia-wikinga.md.

Load-bearing details:

* Macros are per portion and `weight` is that portion in grams -- proven, not
  assumed: 4P+4C+9F reproduces the stated calories within ~1% on every meal of
  the captured day. `_energy_is_consistent` re-runs that check per dish and
  drops any that fails; a per-100g mix-up is invisible in a payload and would
  silently skew every logged meal by a factor of several.
* `bank_dishes` compares nutritional fields before calling `add_manual_entry`,
  which restamps `t` unconditionally. Without the compare, every refresh
  republishes the whole curated bank to every peer. Tests assert on call count.
* Duplicate log suppression reads today's synced log, not a local marker:
  `log_meal` mints a fresh uuid, so a re-import after marker loss would merge
  as duplicates on every peer.
* The gate hook is in `on_focus_ready`, not `_cli_gate._should_lock`:
  `gate_is_due()` never reads the food bank, so a refresh there could not
  change the lock decision while adding a third-party round trip to the ~105ms
  `gate --check` fast path.
* `requests` is lazy-imported so the gate's not-due tick does not pay for it.
* Credentials and the cached session cookie live in ~/.config/diet_guard at
  mode 600, outside the synced tree. The credentials file is written by hand,
  never by the package -- the same contract as sync_token.

`_GateDashboard` is merged into `_GateMealFlow`, and both "pull it in from
elsewhere" flows share one `_PullFlows` mixin: pylint's max-parents counts
every MRO entry, so the gate's controller chain had no room for a new class.

Also adds a side-by-side row for the two pull buttons -- stacking them cost
42px and pushed the tab past the viewport at 1366x768.

989 tests, 100% branch coverage, pre-commit clean.
2026-08-22 23:04:22 +02:00

97 lines
3.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Payload shaping for :mod:`probe_kuchnia`: redaction and delivery-id search.
Split out of ``probe_kuchnia.py`` to keep both files under the repo's 250-line
cap. Nothing here performs I/O, which also makes the redaction rule -- the
part with a real security consequence -- readable on its own.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
import requests
#: Keys whose *values* never reach the dump. Names are kept: knowing a cookie is
#: called ``XSRF-TOKEN`` is the point; knowing its value is a liability, and the
#: capture is a plain file the operator may well paste into a chat window.
SECRET_KEYS = frozenset(
{"password", "token", "accesstoken", "refreshtoken", "authorization", "cookie"},
)
REDACTED = "<redacted>"
#: How much of a non-JSON body to keep -- enough to recognise an HTML error page
#: or a proxy banner without pasting an entire document into the capture.
BODY_EXCERPT_CHARS = 500
def redact(value: object) -> object:
"""Return ``value`` with any secret-looking field replaced by a placeholder.
Args:
value: Arbitrary decoded JSON.
Returns:
The same structure with secret values masked.
"""
if isinstance(value, dict):
return {
key: REDACTED if str(key).casefold() in SECRET_KEYS else redact(item)
for key, item in value.items()
}
if isinstance(value, list):
return [redact(item) for item in value]
return value
def describe(response: requests.Response) -> dict[str, Any]:
"""Summarise ``response`` for the dump, body included when it is JSON.
Args:
response: The response to describe.
Returns:
A JSON-serialisable record of status, cookie names and body.
"""
try:
body: object = redact(response.json())
except ValueError:
# Not JSON: an HTML login redirect or an error page. Keep an excerpt --
# which of those it is answers "did the session actually authenticate?".
body = response.text[:BODY_EXCERPT_CHARS]
return {
"url": response.url,
"status": response.status_code,
"set_cookie_names": sorted({cookie.name for cookie in response.cookies}),
"body": body,
}
def find_delivery_id(payload: object) -> object:
"""Return the first ``deliveryId`` found anywhere in ``payload``.
The bundles treat this id as opaque and never derive it from a date, so it
is located by searching the order payload rather than constructed from
today's date -- which is exactly the assumption that would break the walk.
Args:
payload: Decoded order JSON.
Returns:
The first delivery id encountered, or None.
"""
if isinstance(payload, dict):
for key, value in payload.items():
if key == "deliveryId" and value is not None:
return value
found = find_delivery_id(value)
if found is not None:
return found
elif isinstance(payload, list):
for item in payload:
found = find_delivery_id(item)
if found is not None:
return found
return None