diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1d70ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Node / web build +node_modules/ +dist/ +.vite/ +*.tsbuildinfo + +# Python (server/ has its own .gitignore; these are a repo-wide safety net) +.venv/ +venv/ +__pycache__/ +*.py[cod] +*.egg-info/ +.pytest_cache/ +.ruff_cache/ + +# Secrets - never commit. Use the .example files instead. +.env +.env.* +!.env.example +!*.env.example + +# Local runtime state +*.log + +# OS / editor +Thumbs.db +desktop.ini +.DS_Store diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..31392d5 --- /dev/null +++ b/SPEC.md @@ -0,0 +1,597 @@ +# SPEC: poorBird — PIR-triggered bird camera with Raspberry Pi backend + +**Status:** Draft for decision · **Date:** 2026-09-08 +**Purpose:** Three complete, self-consistent full-stack options at increasing effort levels. Pick one, then this document becomes the baseline. + +> Written in English for consistency with the working language of the review; say the word and I'll translate to German to match `TODO.md`. + +--- + +## 0. Decisions taken (2026-09-20) + +Hardware and transport are settled. The firmware skeleton in `firmware/` implements these; `firmware/API.md` is the contract for the Pi side. + +| Decision | Consequence | +|---|---| +| **Board: Seeed XIAO ESP32S3 Sense** | Closes open question 2. 8 MB PSRAM, 8 MB flash, OV2640, built-in charging. Resolves C5 in favour of "low-power board". | +| **Sensor: HLK-LD2410 24 GHz radar** instead of PIR | Works through plastic (sealed enclosure, no sensor cutout), reports distance + energy per gate, detects stationary targets. Supersedes most of C4's mitigations — see below. | +| **Mains power, not battery + solar** | **Voids C1, C5 and C9 as written.** See below. | +| **OTA mandatory** | C6 unchanged and now non-negotiable. Dual slots, SHA-256 verify, trial boot with automatic rollback, implemented. | +| **Live stream: build the plumbing now** | Config surface (on/off, resolution, duration, record/watch/both) and a working chunked MJPEG push, device → Pi. Public relay stays out of scope (C3). | +| **Time server on the endpoint** | SNTP against the endpoint, with `server_time` in every API response as the fallback. C7 unchanged: `received_at` stays authoritative. | +| **Radar: plain LD2410, 5 V, no Bluetooth** | Baud rate is autodetected, not chosen: a factory-default module (256000), a reconfigured one (115200) and one that has been factory-reset all work without intervention. | +| **The camera is not physically reachable once mounted** | No USB recovery. Drives the enrollment design below, and raises the stakes on OTA rollback and on verifying the LD2410's logic levels before connecting them. | +| **Server host undecided** — Pi, thin client, or something else | Nothing on the ESP side depends on it; the firmware needs an HTTP endpoint at an IP and port. What it *does* change is below. | +| **Language: C++ / Arduino-ESP32 3.x under PlatformIO** | Not MicroPython. Reasoning in the reply that accompanied this change; short version: camera + OTA rollback + PSRAM streaming are all first-class in C and third-party or absent in MicroPython. | + +### What mains power changes + +**C1 is void in the default configuration.** The device stays awake, so commands execute within a loop tick rather than at the next heartbeat. The `device_commands` queue is kept unchanged — it is still the right mechanism, and it is what makes the optional sleep mode work — but "Responsive Mode" is no longer a special tier with a documented battery cost. It is simply how the device runs. + +**C5 is void.** Idle sleep current no longer constrains anything. Panel and battery sizing drop out of scope entirely. + +**C9 is void as a constraint, kept as a policy.** Streaming no longer threatens the power budget. Sessions remain time-boxed (default 60 s, firmware-capped at 600 s) because an unbounded stream is still a bad default, not because of the battery. + +**C4 is largely solved, by a mechanism the battery design could not use.** With the camera permanently initialised, the firmware captures continuously into a PSRAM ring buffer and, on a trigger, uploads the frames from *before* it. Effective trigger latency goes negative. This is the single biggest quality gain from the mains decision — see `firmware/README.md`. + +Two schema additions follow from that: +- `captures.pre_trigger BOOL` — was this frame captured before the trigger fired +- `devices.awake BOOL` — reported in every heartbeat, so the WebUI can show command latency honestly + +### Device conditions and settings + +The device posts a full conditions report (`POST /status`, and the same body on `/heartbeat`) carrying battery voltage, ticks since last wake, and daily captured/delivered counters; it pulls its settings from `GET /config`. Both are specified in `firmware/API.md`. Further schema additions: + +```sql +device_status( -- time series, one row per report + id, device_id, at, reason, -- heartbeat | periodic | after_event | + -- before_sleep | before_night_sleep | on_request + battery_mv, battery_pct, battery_valid, + awake_ms, boot_count, wake_cause, last_sleep_s, total_sleep_s, + captured_today, delivered_today, failed_today, events_today, + is_night, nightlight_on, cam_profile, + rssi, free_heap, free_psram, ring_depth +) +``` + +`devices` also gains the settings surface: the camera tuning profiles (`cam_day`, `cam_night` — full OV2640 parameter sets), the night window and behaviour, nightlight mode and brightness, and battery calibration. Per §3.4 these are pushed via `apply_config` and versioned by `config_version`. + +Two things the WebUI must get right, because both are easy to render as an alarm when they are not one: `battery_valid = false` means *not measured* (no divider is wired by default), not flat; and the daily counters live in RTC memory and reset on power loss, so the `captures` table stays authoritative — the counters' real value is the *gap* between captured and delivered, which is an upload-health signal. + +**Night behaviour supersedes part of C1 in the other direction.** With `night_behaviour = sleep` (the default, since the OV2640's IR cut filter makes IR illumination useless without modification) the device is deliberately unreachable between dusk and dawn, even on mains. That is a decision about what the camera is *for*, not a power constraint. + +**C2, C3, C6, C7, C8 are unchanged.** + +### Deep sleep is implemented anyway, as a switch + +`deep_sleep_enabled` is a per-device config flag, flippable from the WebUI without a reflash. Off by default. Turning it on restores the battery-oriented behaviour described in C1 and §4.3 — and reinstates their costs: no pre-trigger ring, 1–3 s trigger latency, command latency up to `deep_sleep_s`, streaming only from the next wake. + +One caveat worth recording: the LD2410 draws ~80 mA continuously and must stay powered to serve as a wake source, so with radar wake enabled the ESP sleeping saves very little. Real savings need either timer-only wake with the radar power-gated, or a low-quiescent PIR (AM312) as the wake source with the radar confirming once awake. This is a wiring decision; the firmware supports both. + +### Enrollment must be self-healing + +Because there is no USB access to a mounted camera, a rotated token cannot be allowed to strand the device. The firmware therefore keeps a credential in NVS, deliberately: + +1. The device enrolls with a shared bootstrap secret compiled in from `secrets.ini`. +2. The endpoint returns a **per-device** `reenroll_secret`, which replaces the shared one in NVS. +3. On any `401` the device clears its token, re-enrolls with that per-device secret and retries — mid-burst, without rebooting. + +The credential left on the device is scoped to that device and cannot enroll another identity, which is what makes keeping it acceptable under C2's threat model. The shared bootstrap secret stays in the firmware image as a last-resort path, so **rotating it server-side without shipping new firmware removes the escape hatch.** + +Schema follow-on: `devices.reenroll_secret_hash`, and re-enrollment of a known `device_uid` must return the existing row with a fresh token rather than creating a duplicate. + +### Server host: Pi vs thin client + +Undecided, and it does not block the ESP work. What it changes on the server side: + +| | Raspberry Pi 4/5 | Thin client (x86) | +|---|---|---| +| Power | 3–8 W | 10–20 W | +| Storage | SSD over USB, or NVMe on a Pi 5 hat | Native SATA/NVMe, no SD card to wear out | +| Container images | `linux/arm64` — cross-build or build on the device | `linux/amd64` — matches your dev machine | +| Detection (Option C) | Marginal; wants a Coral or Hailo accelerator | Comfortable on CPU, and a GPU is an option | +| Cost | New | Often €40–80 secondhand, with more RAM and CPU | + +A thin client is the better machine for everything except idle power, and it removes the SD-card-corruption failure mode that eats Pi deployments. If detection is ever likely to matter, it is the stronger choice. Revisit §10 question 5 once decided. + +### Still open from §10 + +Question 4 is answered: the stream is watched on the internal server first, and relayed outward from there if and when that is wanted. That is what §5–§7 already assume (C3), so nothing changes. + +Questions 1 (option A/B/C), 5–9 and 11–17 are unanswered. Question 3 (does the trigger work for your birds) is now a radar-tuning question rather than a PIR one, and remains the biggest unknown in the project. + +**On question 1:** A, B and C are *whole server-side stacks*, not just database choices — §5, §6 and §7 each pick a web framework, database, frontend, auth model, backup tool and deployment method together, because those choices constrain each other. The ESP firmware is identical under all three. Given the decisions above, **Option B**: `record` mode means the stream writer and the ingest writer are two concurrent writers, which is C8's actual argument for PostgreSQL. That was the one thing genuinely pushing past Option A, and streaming is now in scope. + +--- + +## 1. Scope + +### 1.1 In scope + +**ESP32-CAM (outdoor, battery + solar)** +- Photo capture triggered by PIR motion sensor +- Upload to Raspberry Pi over LAN +- Battery voltage reporting, low-battery alarm surfaced in the WebUI +- Deep sleep with the longest practical duty cycle +- Wake-up / command initiation from the WebUI (see constraint **C1** — this needs redefining) +- OTA firmware updates, driven from a WebUI admin view + +**Raspberry Pi (headless, SSD)** +- Database holding all capture and observation data +- WebUI: gallery + edit functions +- Backup to a remote NAS +- Authentication *and* authorization (roles) +- Configurable through the UI, with three themes: light, dark, blue + +**Observation data (editable)** +- Species, biologically grounded (scientific name, family, order, stable taxon ID — not free text) +- Capture timestamp +- Plus: individuals, age, sex, behaviour, certainty, notes, tags, favourite/reject — see §3 + +### 1.2 Future (design for, do not build) +- Live stream to an external webspace on an own domain (see constraint **C9**) +- Automatic species detection (see Option C, and §3 for the schema hooks) + +### 1.3 Out of scope +- Audio recording / BirdNET-style song identification (different sensor, different pipeline) +- Multi-site deployment, mobile apps + +--- + +## 2. Design constraints (apply to all three options) + +These are not preferences. They are properties of the hardware and the network, and every option below respects them identically. Read this section before comparing the options — most of the interesting design work is here, not in the framework choice. + +### C1 — A deep-sleeping ESP32 cannot be contacted. At all. + +> **Superseded by §0** for the default (mains-powered, always-awake) configuration. Still applies in full whenever `deep_sleep_enabled` is switched on. + +In deep sleep the radio and the CPU are off. There is no packet, no magic frame, no server push that reaches the device. **"Wake-up triggered by WebUI" as literally stated is not implementable.** + +What is implementable, and what all three options do: + +**Command queue, polled by the device.** The WebUI writes a command row (`wake_and_hold`, `capture_now`, `apply_config`, `ota_update`, `stream_start`). The device drains the queue on every wake — PIR-triggered *or* on a scheduled heartbeat wake. Worst-case latency to a command equals the heartbeat interval. + +Commands ride along on the upload response (§4.4), so a PIR event that happens to occur costs zero extra energy to also deliver a pending command. + +**Optional "Responsive Mode"** for when you genuinely need low latency: light sleep with WiFi association retained (modem sleep, DTIM wake). Reachable within a beacon interval, at roughly **1–3 mA average instead of 15–40 µA** — a factor of ~100. Viable while mains-powered, or in summer with a healthy battery; not viable as the default. Expose it as a per-device toggle with the power cost stated in the UI, defaulting to off. + +So the honest requirement reads: *"Commands issued in the WebUI are executed at the device's next wake; an admin may enable Responsive Mode for near-immediate execution at a documented battery cost."* + +### C2 — No TLS on the ESP32 + +The device speaks **plain HTTP with a bearer token** to a fixed LAN address. All TLS terminates on the Pi. + +Rationale: TLS on the ESP32 means a CA certificate baked into firmware. Certificate chains rotate. When that happens, a device mounted outdoors silently stops uploading and needs physical reflashing. The LAN threat model does not justify that failure mode. The bearer token prevents a stray device on your WiFi from filling the disk. + +### C3 — The Pi is the only internet-facing component + +Now and in future. The ESP32 is never reachable from outside the LAN; the future public stream and public gallery are served *by the Pi*, outbound. This keeps the hard problems (TLS, certificate renewal, authn/authz, abuse handling, rate limiting) on the device that has a package manager and logs. + +### C4 — Trigger latency is physical, and birds are fast + +| Stage | Typical | +|---|---| +| PIR assert after motion | 0.3–2 s (sensor dependent) | +| ESP32 boot from deep sleep | ~0.2–0.4 s | +| Camera init + auto-exposure settle | 0.3–0.6 s (discard first 2–3 frames) | +| **First usable frame** | **~1–3 s after the bird arrives** | + +A bird flying through is gone. Mitigations, all three options: +- Capture a **burst of 3–5 frames**, store all, let the UI pick +- Aim at a place where birds *linger* — feeder, perch, water bath — not open air +- Tune PIR sensitivity and cooldown from the UI + +Also note PIR limitations that specifically hurt here: small warm targets at distance are marginal, direct sunlight and hot surfaces cause false triggers, and it does not work through glass. **Validate the PIR + placement physically before writing backend code.** If the false-trigger rate is unacceptable, the fallback is on-device frame differencing (Option C) or a beam-break / capacitive perch sensor. + +### C5 — Idle sleep current dominates the energy budget, not the photos + +> **Superseded by §0.** Mains powered; the board choice (XIAO ESP32S3 Sense) was made anyway. Kept for the record and for a future battery deployment. + +Rough figures, to be validated by measurement: + +| | AI-Thinker ESP32-CAM (unmodified) | Low-power board (e.g. XIAO ESP32S3 Sense) | +|---|---|---| +| Deep sleep current | ~1–3 mA (LDO + camera rail leak) | ~15–40 µA | +| Idle drain per day | **24–72 mAh** | **0.4–1 mAh** | +| 50 PIR events + 48 heartbeats/day | ~12 mAh | ~12 mAh | +| **Total per day** | **~36–84 mAh** | **~13 mAh** | +| Runtime on 3000 mAh, zero sun | ~5–12 weeks | ~30 weeks | + +The AI-Thinker board is not designed for low power. Its idle leak is 2–6× the entire photographic workload. Either **hardware-mod it** (bypass the LDO, gate the camera rail with a MOSFET) or **pick a board built for battery use**. Both are fine; doing neither means a 2 W panel that is comfortable in June and dead in December. + +Panel sizing follows from that, not the reverse. Very rough Central European figures: a 2 W / 6 V panel yields on the order of ~1200 mAh/day in summer and ~300 mAh/day averaged over December, with multi-day near-zero stretches under snow. Size the *battery* for a ~2-week no-sun reserve. + +Related: a weak WiFi signal at the camera location extends transmit time and therefore drains battery. Measure RSSI at the mounting point before committing. + +### C6 — OTA must be planned from the first flash + +Dual OTA partitions and a rollback slot have to exist in the partition table from the beginning. Retrofitting them means a physical reflash of a device that is by then mounted outdoors. + +Rules in all options: +- Device compares its running version against the server's target on wake +- **Refuse to flash below a battery threshold** (default 50 %) — a brownout mid-write bricks the device +- Verify SHA-256 before activating the new slot +- Boot the new image once in a trial state; roll back automatically if it fails to check in + +### C7 — Time: the server clock is authoritative + +The ESP32 RTC survives deep sleep but drifts, and is lost on any power cycle. So: +- Device sends best-effort NTP time plus a monotonic boot counter +- **Server `received_at` is authoritative** for ordering and for the gallery's date filter +- Store both `captured_at_device` and `received_at` +- Store UTC everywhere; render in local timezone. Set `TZ` explicitly on every service — a container defaulting to UTC while you think in CEST is a bug that surfaces months later at a DST boundary. + +### C8 — If SQLite, exactly one writer + +SQLite is entirely adequate for this project's volume. Its real constraint is not scale, it is concurrency: two processes writing produces intermittent `database is locked`. Options A and B therefore keep **all writes inside a single process**, with WAL mode and an explicit `busy_timeout`. Option C introduces a genuine second writer and moves to PostgreSQL *for that reason* — not for "scalability". + +### C9 — Live streaming is incompatible with battery operation + +> **Superseded by §0** as a constraint. The time-boxing survives as policy, not as a power measure. + +MJPEG streaming from an ESP32-CAM draws roughly 200 mA continuously and cannot deep sleep while doing it. A 60-second stream costs about 3.3 mAh — several PIR events' worth. + +Therefore the future stream is: **admin-triggered, time-boxed (default 60 s), rate-limited, gated on battery level, and only reachable after the device's next wake.** Not "always available". The ESP32 pushes to the Pi; the Pi relays outward (C3). Reserve the `stream_start` command type in the schema now and build nothing else. + +--- + +## 3. Common data model + +Identical across all three options; only the engine and the migration tooling change. + +The important structural decision: **`captures` 1—n `observations`.** One photo can contain two birds of different species, and a photo can legitimately have zero observations (false PIR trigger, empty frame). A single `species` column on the image would have to be undone later. + +The second important decision: **human labels and model predictions share one table**, distinguished by `source`. This means the edit UI *is* the training-data pipeline for any future detection model, with no migration needed when you get there. + +```sql +-- Devices ------------------------------------------------------------------ +devices( + id, name, hw_revision, fw_version, + token_hash, -- bearer token for ingest, rotatable from admin UI + last_seen_at, battery_mv, battery_pct, rssi, temp_c, + responsive_mode BOOL DEFAULT false, -- C1 + heartbeat_interval_s INT DEFAULT 1800, + enabled BOOL, created_at +) + +device_commands( -- C1: the wake-up mechanism + id, device_id, + type, -- wake_and_hold | capture_now | apply_config | ota_update | stream_start | reboot + payload, -- JSON + created_by, created_at, + delivered_at, acked_at, result, expires_at +) + +firmware( + id, version, semver, file_path, sha256, size_bytes, + release_notes, min_battery_pct DEFAULT 50, -- C6 + uploaded_by, uploaded_at, is_target BOOL +) + +-- Captures ----------------------------------------------------------------- +captures( + id, device_id, + path, thumb_path, sha256, width, height, bytes, + captured_at_device, received_at, -- C7, received_at authoritative + trigger, -- pir | timer | manual | stream_grab + burst_id, burst_index, -- C4: 3-5 frames per event + battery_mv, rssi, temp_c, + reviewed BOOL DEFAULT false, + kept BOOL DEFAULT true, -- soft reject, drives retention + created_at +) + +observations( + id, capture_id, taxon_id NULL, + individuals INT DEFAULT 1, + age, -- adult | juvenile | unknown + sex, -- male | female | unknown + behaviour, -- feeding | bathing | perching | nesting | fighting | other + certainty, -- certain | probable | uncertain + notes, + source, -- human | model + model_version NULL, confidence NULL, bbox NULL, -- future detection + created_by, created_at, updated_at +) + +taxa( -- seeded, not user-entered free text + id, gbif_key, scientific_name, + name_de, name_en, family, "order", + iucn_status, is_local_common BOOL -- drives autocomplete ranking +) + +tags(id, label, colour) +capture_tags(capture_id, tag_id) + +-- Access ------------------------------------------------------------------- +users( + id, username, email, password_hash, -- Argon2id + role, -- admin | editor | viewer + totp_secret NULL, is_active, + theme, -- light | dark | blue + locale, created_at, last_login_at +) +sessions(id, user_id, created_at, expires_at, ip, user_agent) + +-- Operations --------------------------------------------------------------- +settings(key, value, value_type, scope, updated_by, updated_at) -- scope: server | device +audit_log(id, at, user_id, action, entity, entity_id, before, after, ip) +backup_runs(id, started_at, finished_at, status, bytes, snapshot_id, error) +``` + +### 3.1 Roles + +| | viewer | editor | admin | +|---|---|---|---| +| Browse gallery, view data | ✅ | ✅ | ✅ | +| Create/edit observations, tags | ❌ | ✅ | ✅ | +| Delete captures | ❌ | ❌ | ✅ | +| Device settings, commands, wake | ❌ | ❌ | ✅ | +| Firmware upload / OTA | ❌ | ❌ | ✅ | +| Users, backup, server settings | ❌ | ❌ | ✅ | + +**Devices are not users.** The ESP32 authenticates with a per-device bearer token scoped to `POST /ingest`, `POST /heartbeat`, `GET /firmware`. It can never read the gallery. + +### 3.2 Taxonomy + +Seed `taxa` from a curated list of ~60–80 Central European garden species with GBIF taxon keys, German and scientific names, family and order. The edit form autocompletes on either name and ranks `is_local_common` first. Anything beyond the seed list is a one-row admin addition, not free text. + +This is what makes "information about species (biologically)" real rather than a string column that accumulates *Kohlmeise*, *kohlmeise*, *Parus major* and *Kohlmeise?* as four distinct species. + +### 3.3 Storage layout + +Images on the SSD, date-sharded, never in the database: + +``` +/srv/poorbird/images/2026/09/08/.jpg +/srv/poorbird/thumbs/2026/09/08/_400.webp +``` + +Auth-checked image serving in all options: the app authorizes the request and hands off the bytes to the reverse proxy (nginx `X-Accel-Redirect` / Caddy equivalent). An unguessable URL is not access control — without this, images are effectively public even though the UI is behind a login. + +### 3.4 Settings exposed in the UI + +"Fully configurable" needs a boundary, or it never finishes. The enumerated list: + +**Device settings** (pushed to NVS via `apply_config` on next wake): resolution, JPEG quality, burst count, PIR cooldown, heartbeat interval, battery alarm threshold, responsive mode, timezone. + +**Server settings:** retention policy, thumbnail size, backup schedule + target, alarm thresholds and channels, default theme, default locale, session lifetime. + +Anything not on this list is a code change, deliberately. + +--- + +## 4. Shared API shape + +Same in all options; the framework differs. + +### 4.1 Device endpoints (bearer token, plain HTTP, LAN only) +``` +POST /api/v1/ingest multipart: image + JSON meta → 201 {capture_id, commands[], config_version, firmware} +POST /api/v1/heartbeat JSON: battery, rssi, fw, uptime → 200 {commands[], config_version, firmware} +GET /api/v1/firmware/{version}.bin +POST /api/v1/commands/{id}/ack JSON: {status, detail} +``` + +**The upload response carries the pending command queue.** The device is already awake and associated, so this delivers commands and config at zero extra energy cost. A separate poll only happens on heartbeat wakes when no PIR event occurred. + +### 4.2 UI endpoints (session cookie, CSRF-protected) +``` +GET/PATCH/DELETE /api/v1/captures[/{id}] filter: date range, taxon, device, tag, reviewed, kept +POST/PATCH/DELETE /api/v1/captures/{id}/observations[/{oid}] +GET /api/v1/taxa?q= autocomplete +GET/POST /api/v1/devices[/{id}/commands] +POST /api/v1/firmware admin upload +GET/PATCH /api/v1/settings +GET /api/v1/health device online, battery, disk, last backup +``` + +### 4.3 Firmware state machine (all options) + +``` +deep sleep + │ PIR (ext0/ext1) ──or── timer (heartbeat) + ▼ +boot → read NVS config → init camera → discard 2-3 frames + │ + ├─ PIR wake: capture burst → connect WiFi → POST /ingest ──┐ + └─ timer wake: → connect WiFi → POST /heartbeat ──┤ + ▼ + process commands + config + │ + ┌─────────────────────────────────┤ + ▼ ▼ + ota_update & battery ok? wake_and_hold? + download → verify sha256 stay awake N seconds + → flash inactive slot → reboot (bounded, then sleep) + │ │ + └──────────────┬──────────────────┘ + ▼ + back to deep sleep (bounded retries, + exponential backoff, always sleep on failure) +``` + +**Every failure path ends in sleep.** An unbounded retry loop on a WiFi outage is the fastest way to flatten the battery — bound retries (e.g. 3 attempts with backoff), then sleep and try at the next wake. + +--- + +## 5. Option A — Minimal + +**Goal: bird photos visible in a browser with the least moving parts. No JavaScript build step, no Docker, no broker.** + +| Layer | Choice | +|---|---| +| Firmware | Arduino-ESP32 core (built on ESP-IDF), `esp32-camera`, `HTTPClient`, `Update.h` for OTA, `Preferences` for NVS | +| Transport | HTTP `POST multipart/form-data` — no MQTT, no broker | +| Backend | Python 3.13 + Flask, gunicorn (1 process / 4 threads → satisfies C8 structurally) | +| Database | SQLite, WAL mode, `busy_timeout=5000` | +| Migrations | Plain numbered `.sql` files applied by a small runner | +| Frontend | Jinja2 server-rendered + HTMX for inline edit and filtering. **No npm, no bundler, no Node on the Pi.** | +| Themes | Hand-written CSS custom properties, `data-theme` on ``, three token sets, persisted per user + `localStorage` for first paint | +| Images | Pillow for thumbnails on upload, served via nginx `X-Accel-Redirect` | +| Auth | Flask-Login, Argon2id (`argon2-cffi`), server-side sessions, Flask-WTF CSRF, 3 roles via decorator | +| Reverse proxy | nginx, self-signed cert or Tailscale-provided cert | +| Remote access | Tailscale | +| Backup | cron → `VACUUM INTO` snapshot + `rsync -a --delete` over SSH to NAS | +| Deploy | systemd units (`poorbird-web.service`), `apt` + `venv`. No containers. | +| Alarms | WebUI health banner + a nightly email or `ntfy` push on low battery / device offline / backup failure | + +**Note on the DB backup:** `cp poorbird.db` on a live WAL database can produce a corrupt copy. Use `VACUUM INTO` (or `sqlite3 .backup`) to get a consistent snapshot. This is the single most common way home-lab backups turn out to be worthless. + +**How the tricky requirements are met** +- *Wake-up:* `device_commands` table, drained on upload response + 30-minute heartbeat. Responsive Mode not implemented in this tier. +- *OTA:* admin uploads a `.bin`, marks it target; device pulls on next wake if version differs and battery ≥ 50 %. +- *Low battery:* voltage in every payload; threshold check server-side; banner + push. +- *Backup:* rsync to NAS. Non-blocking, alerts on failure. +- *3 themes:* CSS variables, no framework. + +**What you give up** +- No task queue: thumbnailing happens inline in the request (~100–300 ms, acceptable at this volume) +- No 2FA, no audit log, no fine-grained permissions beyond the three roles +- Server-rendered UI — snappy, but not a client-side SPA gallery +- No detection pipeline, and Postgres would be a migration if you ever need concurrent writers +- Restore is manual, from a documented procedure + +**Rough effort:** walking skeleton (PIR → photo → gallery) in a weekend or two; the full spec above in ~4–6 weeks part-time. + +--- + +## 6. Option B — Solid + +**Goal: the version you can still maintain in three years. Proper migrations, typed API, real backups, containerised.** + +| Layer | Choice | +|---|---| +| Firmware | **ESP-IDF v5.x** — dual OTA partitions + `esp_ota` rollback, calibrated ADC battery read with a MOSFET-gated divider, exponential backoff, structured logging | +| Transport | HTTP POST + bearer token (C2) | +| Backend | Python 3.13 + FastAPI, Pydantic v2, SQLAlchemy 2.0, **Alembic** migrations | +| Database | **PostgreSQL 17** | +| Job queue | Postgres-backed, `FOR UPDATE SKIP LOCKED` — thumbnails, backups, retention, exports. **No Redis.** | +| Frontend | React + TypeScript + Vite + TanStack Query/Router, virtualised gallery grid. **Built on your dev machine**, shipped as static files. | +| Themes | Design tokens → CSS custom properties, `ThemeProvider`, three themes, per-user persisted | +| Auth | Session cookies, Argon2id, **optional TOTP 2FA**, per-device tokens, RBAC with an explicit permission matrix, full `audit_log` | +| Reverse proxy | **Caddy** — automatic TLS; valid Let's Encrypt certs for a LAN-only hostname via **DNS-01**, so no port forwarding and no browser warnings | +| Remote access | Tailscale | +| Backup | **restic** → NAS over SFTP; `pg_dump` pre-hook; retention 7 daily / 4 weekly / 12 monthly; healthcheck ping; **monthly automated restore test** into a scratch container | +| Deploy | Docker Compose — *now* justified, because there are genuinely several services. Images built with `buildx --platform linux/arm64` on the dev machine. Healthchecks + `condition: service_healthy`, log rotation (`max-size`/`max-file`), `.env` for secrets, `.dockerignore`, explicit `TZ` | +| Alarms | `ntfy`/Gotify push + WebUI, for low battery, device offline > N hours, disk > 80 %, backup failure | + +**Why PostgreSQL here and not in Option A:** this tier introduces a background worker, which is a second writer (C8). Multiple writers is a good reason for Postgres. "Scalability" for a one-camera garden project is not — ignore that argument if you meet it. + +**How the tricky requirements are met** +- *Wake-up:* command queue + **adaptive heartbeat** (e.g. 5 min in daylight, 60 min at night — better latency when birds are active, less drain when they aren't) + **Responsive Mode** toggle with the mA cost shown in the UI +- *OTA:* signed manifest, SHA-256 verify, trial boot with automatic rollback, battery gate, staged rollout per device +- *Backup:* restic with a *tested* restore. A backup you have never restored is a hypothesis. +- *Config:* `settings` table → `config_version` → device pulls and writes NVS on next wake + +**What you give up** +- No automatic species detection (schema is ready; the pipeline is not built) +- No public stream +- No metrics/dashboards beyond the health endpoint + +**Rough effort:** ~3–4 months part-time. This is the recommendation. + +--- + +## 7. Option C — Full platform + +**Goal: everything in the brief plus automatic species detection, observability, and a real path to the public stream.** + +Everything in Option B, plus: + +| Area | Addition | +|---|---| +| Hardware | Low-power board (C5) · **DS3231 RTC** for reliable time across power cycles · **BME280** for temperature/humidity enrichment · multi-camera support | +| Firmware | **On-device frame differencing** to confirm PIR triggers before spending WiFi energy — cuts false positives and battery drain together · Secure Boot v2 + flash encryption + anti-rollback · device provisioning flow | +| Detection | Two-stage: an animal/bird detector (YOLO-class or MegaDetector) then a species classifier fine-tuned on **your own** labelled captures. ONNX Runtime or LiteRT in a dedicated container. Predictions land in `observations` with `source='model'` alongside human labels. | +| The loop | The edit UI doubles as a **labelling tool** — keyboard-driven (`j`/`k` to move, `1`–`9` for the top species, `Enter` to confirm) — feeding periodic retraining. This is what makes detection actually work on your garden and your camera angle, rather than a generic model that confuses Blaumeise and Kohlmeise. | +| Storage | Content-addressed image store, optional MinIO | +| Auth | External OIDC (Pocket ID / Authelia / Keycloak), fine-grained RBAC, ready for the public site's OAuth2 | +| Observability | Prometheus + Grafana + Loki; alerting on battery, device offline, disk, backup failure, detection queue depth | +| Backup | restic → NAS **and** offsite (B2/S3), monitored with a dead-man switch, documented RPO/RTO, automated restore verification | +| Public stream | **MediaMTX** on the Pi: ESP32 pushes on demand → MediaMTX → WebRTC/HLS out via **Cloudflare Tunnel** (public domain + TLS, no port forwarding, ESP32 still never internet-facing per C3). Time-boxed and battery-gated per C9. | +| Provisioning | **Ansible** playbook for the whole Pi, so a card failure is a rebuild rather than an archaeology project | +| Frontend | PWA, offline-capable, full design-token system across the three themes | + +**Deliberately still not included: Kubernetes.** k3s on a single Pi adds a control plane and gains nothing here. Docker Compose remains correct even at this tier. + +**Honest note on detection accuracy:** a generic pretrained model will disappoint on small, partly obscured, motion-blurred garden birds. Expect to label 500–2000 of your own images before fine-tuning earns its keep. Budget for that, or treat detection as pre-filtering ("bird / no bird", which works well and immediately) rather than species identification. + +**Rough effort:** ~6–12 months part-time. Only worth it if the detection loop is the point. + +--- + +## 8. Comparison + +| | A — Minimal | B — Solid | C — Full platform | +|---|---|---|---| +| Firmware | Arduino core | ESP-IDF v5 | ESP-IDF v5 + secure boot | +| Backend | Flask | FastAPI | FastAPI + workers | +| Database | SQLite | PostgreSQL 17 | PostgreSQL 17 + Redis | +| Frontend | Jinja2 + HTMX | React + TS | React PWA | +| Node.js needed | ❌ | dev machine only | dev machine only | +| Containers | ❌ systemd | ✅ Compose | ✅ Compose | +| Migrations | numbered SQL | Alembic | Alembic | +| 2FA / audit log | ❌ | ✅ | ✅ + OIDC | +| Backup | rsync + snapshot | restic + restore test | restic + offsite + verify | +| Responsive Mode | ❌ | ✅ | ✅ | +| Species detection | ❌ | ❌ (schema ready) | ✅ | +| Public stream | ❌ | ❌ | ✅ | +| Metrics/alerting | banner + push | push | Prometheus/Grafana | +| Effort (part-time) | 4–6 weeks | 3–4 months | 6–12 months | + +### Recommendation + +**Build Option A's walking skeleton first, then grow into Option B.** + +Not because A is the goal, but because the riskiest unknowns in this project are physical, not architectural: does PIR reliably trigger on the birds at your feeder, at your distance, in your light? What is the real sleep current of your board? How many usable frames per day do you actually get? All three options share §2, §3 and §4 — so a week spent proving the hardware with Flask and SQLite is not wasted work if you then move to FastAPI and Postgres. The data model does not change. + +Deciding between B and C can wait until you have a few thousand real captures, at which point you will also know whether you want detection badly enough to label them. + +--- + +## 9. Shared hardware notes + +| Item | Note | +|---|---| +| Camera board | AI-Thinker ESP32-CAM works, but see C5 — either mod it or use a low-power board with built-in charging | +| PIR sensor | **AM312** preferred over HC-SR501: 3.3 V native, far lower quiescent draw. Wake via `ext0` on an RTC-capable GPIO — check pin conflicts carefully, the ESP32-CAM has very few free pins once camera and SD are wired | +| Battery | **LiFePO4** worth considering over LiPo: better cold tolerance, far more cycles, and 3.2–3.65 V suits a 3.3 V rail. Either chemistry: **neither can be safely charged below 0 °C** — use a charger with NTC cutoff, or inhibit charging in frost | +| Panel | Size after measuring sleep current, not before. ~2 W/6 V is a reasonable starting point *with* a low-power board | +| Battery sense | Voltage divider on an ADC pin, **gated by a MOSFET** — an always-connected divider drains the battery continuously. Calibrate; the ESP32 ADC is non-linear | +| Enclosure | IP65 minimum, sun shade over the lens, drainage, desiccant. Condensation on the lens ruins more photos than any software bug | +| Pi | Model matters (see open questions). Put Docker's `data-root` on the SSD; set up log rotation or the SD card dies | +| Network | Measure RSSI at the mounting point. DHCP reservation for the Pi, then hardcode that IP in firmware — simpler and more reliable than mDNS | + +--- + +## 10. Open questions + +Ordered by how much they block. The first four change the build; the rest can be answered as you go. + +### Blocking + +1. **Which option — A, B or C?** Or A-now-then-B, as recommended in §8? +2. **Camera board:** unmodified AI-Thinker, hardware-modified AI-Thinker, or a low-power board with built-in charging? Per C5 this decides the solar/battery sizing more than anything else does. +3. **Does PIR actually work for your birds, at your placement?** Needs a physical test before software. If not: on-device frame differencing, or a perch/beam sensor? +4. **Is Tailscale-only remote access enough**, or do you want a public domain and a public gallery reasonably soon? Answering "public soon" pulls OAuth2, rate limiting, and a hardened ingress back into scope. + +### Shapes the design + +5. **Raspberry Pi model and RAM?** Pi 4 vs Pi 5 vs NVMe-capable — affects boot-from-SSD setup and rules Option C's detection in or out. +6. **How many cameras, eventually?** One, or several? The schema supports many; device management UI and OTA staging get more work if it's really more than one. +7. **Expected volume:** captures per day, roughly? Drives storage, retention, and whether inline thumbnailing is fine. +8. **Retention policy:** keep everything forever, or auto-delete rejected/unlabelled captures after N days? A birdcam will fill any disk you give it. And: does deleting a capture in the UI delete the file, or only hide it? +9. **NAS access protocol:** SSH/SFTP available? SMB or NFS only? restic and borg want SFTP or a mounted path — this decides the backup tooling. +10. **Battery chemistry**, and do you care about winter operation? Charging below freezing is the crux. + +### Details worth settling early + +11. **UI language:** German, English, or both? i18n is cheap on day one and annoying to retrofit. Species names should carry `name_de` and `name_en` regardless. +12. **Taxonomy source:** GBIF backbone keys as proposed, or IOC / Avibase? And which regional species list should seed the autocomplete? +13. **The "blue" theme** — any reference you have in mind (a screenshot, a palette, a site you like), or my choice? +14. **Is 2FA a requirement**, or is a strong password on a LAN-only service enough for now? +15. **Beyond species, timestamp and the fields proposed in §3** — anything else you want to record? Weather, feeder type, ring number, whether you were watching? +16. **Your comfort level in C, Python, and TypeScript?** This should genuinely influence the A/B/C choice more than the feature lists do — Option B's React frontend is the largest single chunk of unfamiliar work if TypeScript is new. +17. **Can the camera see beyond your own property** — a neighbour's garden, a public path? If so there is a GDPR dimension worth one paragraph in the deployment notes. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..405c95c --- /dev/null +++ b/TODO.md @@ -0,0 +1,341 @@ +# TODO: poorBird + +**Baseline:** [SPEC.md](SPEC.md) · **Device contract:** [firmware/API.md](firmware/API.md) · **Hardware notes:** [firmware/README.md](firmware/README.md) +**Updated:** 2026-09-20 + +This file tracks *work*. It does not restate decisions — those live in SPEC §0. +Anything here that contradicts SPEC means SPEC needs an edit, not a workaround. + +--- + +## Decisions since SPEC §0 + +| Decision | Consequence | +|---|---| +| **Deploy natively, not with Docker** | SPEC §6's *Deploy* row is void; the stack itself is unchanged (FastAPI + PostgreSQL 17 + React/TS). It runs as systemd units from a venv, with Caddy and Postgres as host packages. `TODO.Dockerization.md` is deleted — the content was obsolete, not the idea. | +| **Build container-ready anyway** | Containers stay a plausible future, so the design avoids anything that would make the move expensive. Constraints listed under Phase 1.2. They cost close to nothing and most are better practice natively too. | +| **Server = x86 thin client, Linux, same LAN** | Closes SPEC §10 Q5. amd64 matches the dev machine, so no cross-building. Native NVMe/SATA, no SD-card corruption failure mode. Detection (Option C) stays physically possible. | +| **The server owns everything non-device** | Database, WebUI, image store, auth, backup, OTA hosting, stream sink. The ESP side only ever needs one IP and port. | + +- [ ] Fold these three rows into SPEC §0 and strike the *Deploy* row of §6 — **do this first**, so SPEC stays the single baseline + +--- + +## Where things actually stand + +| Area | State | +|---|---| +| Firmware | Written, compiles, **never run on hardware**. Known gaps below. | +| Device↔server contract | Specified in full (`firmware/API.md`). Server half of the **device** endpoints implemented (Phase 2). The operator-facing half (firmware upload, device management) no longer waits on auth — that exists now — only on Phase 4. | +| Data model | Designed (SPEC §3) + §0 additions, migration written and applied, guarded by a drift test. | +| Server | Phases 1 and 2 plus the Phase 3 server half, in [`server/`](server/) — config, schema, health, job queue, scheduler, systemd units, every device endpoint the firmware calls, and user auth with the captures API behind it. Verified on Python 3.14.7 against PostgreSQL 17: 308 tests, migrations applied, real HTTP ingest through the worker to a WebP thumbnail on disk. Not yet on the real host, and **never yet spoken to by real firmware**. | +| WebUI | Shell, themes, i18n, login and a working cursor-paged gallery on `feature/UI_Basic_implementation`. Devices and System are still honest empty states — they need Phase 4 endpoints. **The gallery's appearance has not been checked in a browser yet.** | + +--- + +## Phase 0 — Hardware bring-up (blocks everything) + +The riskiest unknowns in this project are physical, not architectural. None of the +server work is wasted if this goes badly, but all of it is pointless until it goes well. + +### 0.1 Before anything is connected + +- [ ] **Measure the LD2410's TX logic level on a 5 V supply.** Unverified on this hardware + (`firmware/README.md` → Wiring). A 5 V swing into the ESP32S3 RX damages the pin. + Level-shift or divide if it is not 3.3 V. +- [ ] Verify `PIN_STATUS_LED` (GPIO21) against the actual XIAO board revision — it has moved between revisions +- [ ] Bench-power the board and confirm the mains supply holds up under WiFi TX + camera peaks + +### 0.2 First flash + +- [ ] Fill `secrets.ini` from `secrets.ini.example`, flash with the OTA partition table (`partitions/poorbird_8mb_ota.csv`) +- [ ] Confirm PSRAM is detected and the frame ring allocates at the configured depth +- [ ] Confirm camera init + the day profile produce a sane JPEG over serial/local dump +- [ ] Confirm SNTP sync, and that the device falls back to `server_time` cleanly when SNTP fails + +### 0.3 Radar — the biggest unknown in the project + +SPEC §10 Q3, restated as a radar question. Everything downstream assumes this works. + +- [ ] Verify `ld2410.cpp` frame offsets against real module output — they are from the datasheet, not measured +- [ ] Verify baud autodetection across all three cases: factory default (256000), reconfigured (115200), factory-reset +- [ ] Make `radarSetGateSensitivity` validate that the ACK *matches*, not merely that bytes came back +- [ ] **Tune gates for birds at the real feeder distance.** Log distance + per-gate energy for a full day, then set thresholds from the data rather than from defaults +- [ ] Decide the fallback if radar cannot be tuned acceptably: AM312 PIR on `PIN_AUX_ADC` (one function, `radarIsTrigger`), or on-device frame differencing + +### 0.4 Known code defects + +- [ ] `nightlight.cpp` allocates an LEDC channel after the camera has claimed channel 0 for XCLK — routes around it in theory, untested in practice +- [ ] Battery percentage curves are generic room-temperature open-circuit approximations. Fine for the low banner and the OTA gate; do not present as a runtime estimate +- [ ] Enclosure: IP65, sun shade, drainage, desiccant. Condensation ruins more photos than any software bug + +--- + +## Phase 1 — Server foundation + +Target host: the x86 Linux thin client. No containers — packages and systemd units. + +Skeleton written — see [`server/README.md`](server/README.md) to run it, and +[`server/deploy/INSTALL.md`](server/deploy/INSTALL.md) to deploy it. What is +written vs. what still needs doing on the real host: + +- [x] Python venv layout, FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Alembic — `server/` +- [x] systemd units `poorbird-api.service` + `poorbird-worker.service`, `After=postgresql.service`, restart policies, sandboxing +- [x] Caddyfile with DNS-01 TLS, the `:8080` plain-HTTP camera listener and the auth-checked image handoff +- [x] `poorbird check` — validates config, paths and DB before anything starts +- [x] **Run it against a real PostgreSQL** — done on the dev machine (uv-managed Python 3.14.7, Podman `postgres:17`): `poorbird check`, `migrate`, `serve`, `worker` and 12/12 tests all green +- [ ] Repeat the same four commands on the actual thin client, which is the run that counts +- [ ] Base install on the thin client: static IP (or DHCP reservation) and **hardcode that address in firmware** — more reliable than mDNS +- [ ] PostgreSQL 17 from the distro or PGDG repo; dedicated role + database; **loopback TCP with `scram-sha-256`, not a Unix socket** (see 1.2) +- [ ] Caddy DNS provider plugin build (`caddy add-package …`) and a real hostname +- [ ] Tailscale for remote access +- [x] Image store at `/srv/poorbird/images/YYYY/MM/DD/.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) — writer landed with Phase 2; writes are atomic (`.part` then `os.replace`) so a crash cannot leave a half-JPEG that a thumbnail job would then fail on +- [ ] journald log retention capped, disk usage alarmed + +### 1.1 Schema — SPEC §3 plus the §0 additions + +- [x] Initial Alembic migration covering SPEC §3, guarded by a schema-drift test +- [x] `captures.pre_trigger BOOL` — was this frame captured *before* the trigger fired +- [x] `devices.awake BOOL` — reported every heartbeat, so the UI can show command latency honestly +- [x] `devices.reenroll_secret_hash` +- [x] `device_status` time-series table (SPEC §0 columns, plus `raw` JSONB so nothing is lost) +- [x] `devices` settings surface — **one JSONB `config` column, not forty**: `GET /config` is ~40 optional keys the firmware merges and clamps, so a column per key means a migration per firmware tunable. Validation moves to a Pydantic model. Promote an individual key to a column only if it ever needs querying across devices. +- [x] Job queue on Postgres with `FOR UPDATE SKIP LOCKED` — **No Redis.** Handlers for thumbnails / retention / backup arrive with their phases. +- [ ] Seed `taxa` (Phase 3) and the `settings` defaults + +### 1.2 Staying container-ready + +Not building containers now. Just not painting into a corner. Each of these is +cheap today and most are the better native choice regardless. + +- [x] **All config from environment**, via systemd `EnvironmentFile=/etc/poorbird/poorbird.env`. No paths, hosts or secrets baked into code or committed config. That file becomes a compose `.env` unchanged. +- [x] **Postgres over loopback TCP**, not a Unix socket — the one genuinely container-hostile choice, and the only real change from a purely native design +- [x] **All mutable state in a few explicit top-level directories** (`/srv/poorbird/images`, `/srv/poorbird/thumbs`, `/var/lib/poorbird`), never scattered under the app dir. These are the future volume mounts. +- [x] **Log to stdout/stderr.** journald catches it now, a log driver would catch it later. Simpler than app-managed log files either way. +- [x] **Migrations as a standalone idempotent command** (`poorbird migrate`), run from `ExecStartPre` on the API unit only — never at app import time, and never from two units at once +- [x] **One env var for the image root**, read by both the app and the Caddy config, since the auth-checked handoff needs them to agree on the path +- [x] **Scheduled jobs run in the worker, not as systemd timers** — decided. APScheduler with a SQLAlchemy jobstore on the existing Postgres. Not primarily for portability: SPEC §3.4 makes *backup schedule + target* and *retention policy* UI-editable server settings, and a UI-editable systemd timer means the app writing unit files and calling `daemon-reload` behind a polkit or sudoers rule. In-app, the schedule is just a settings row. Timers stay the better answer for anything that is **not** UI-configurable — if such a job appears, use one. +- [x] Keep API and worker as separate processes — maps 1:1 to two services later + +**Deliberately not doing now:** writing Dockerfiles or a compose file speculatively. That means maintaining two deployment paths to prove a point. + +--- + +## Phase 2 — Walking skeleton: radar → photo → gallery + +The first milestone worth celebrating. Nothing below this line matters until a real +bird photo appears in a browser. + +- [x] `POST /api/v1/enroll` — bootstrap secret in, per-device `reenroll_secret` + token out. + **Re-enrolling a known `device_uid` must return the existing row with a fresh token, never a duplicate.** + Accepts the shared secret *or* that device's own `reenroll_secret`; checking only the + shared one would lock out every device already enrolled. Hardware facts (`mac`, + `hw_revision`, `fw_version`) refresh on every enrollment, the operator's `name` does not. +- [x] `POST /api/v1/ingest` — **raw JPEG body with metadata in headers, not multipart.** + `firmware/API.md` and `uploader.cpp` send the bytes directly; multipart was a + misreading. Honours `X-Pre-Trigger`, dedupes on sha256 per device. +- [x] `POST /api/v1/heartbeat` and `POST /status` — full conditions report into `device_status` +- [x] `GET /api/v1/config` — enums by name not number, `config_version` bump semantics. + Column-backed keys win over stale JSONB copies, so an operator rename actually reaches + the device; the device's own `config_version` never overwrites the server's. +- [x] Response envelope + `server_time` (SPEC C7: `received_at` stays authoritative). + On `/heartbeat` and `/ingest`. **Not** on `/status`, which is 204 with no body per + `firmware/API.md` — "every response" was not compatible with the firmware contract. +- [x] Thumbnail job on ingest — 400px WebP, decode kept off the request path +- [x] Device authentication, rate limiting, `POST /commands/{id}/ack`, `GET /firmware/{v}.bin` + — not in the original list, but the firmware calls them (see `docs/reviews/`) +- [~] Minimal gallery page purely to prove the path — **superseded.** The scaffold's System page + already proves browser → proxy → FastAPI → Postgres, and SPEC §3.3 requires image serving + to be auth-checked, so "no auth yet" is not a state the gallery can legitimately pass + through. The real grid is Phase 3, behind sessions. +- [ ] **End-to-end test on real hardware:** bird walks past → burst uploads → visible in browser. + Blocked on Phase 0: the server side is proven only against synthetic uploads. + +--- + +## Phase 3 — WebUI + +Scaffolding done — see [`web/README.md`](web/README.md). Typechecks, builds, +and the System page reads live data through the Vite proxy. + +- [x] React 19 + TS + Vite + TanStack Query/Router, built on the dev machine, served as static files by Caddy +- [x] Three themes as design tokens, `data-theme` on ``, no flash of the wrong theme +- [x] `npm run check:contrast` — asserts WCAG AA across all three themes; caught three failing `--border-strong` values on its first run +- [x] i18n de/en with a build-time-complete catalogue +- [x] Auth shell: provider, login form with TOTP field, `RequireAuth` (no dev bypass, on purpose) +- [x] System page on live `/health` — the end-to-end proof browser → proxy → FastAPI → Postgres +- [x] Wire `RequireAuth` into `router.tsx` and delete the "not enforced" banner — gallery needs + any signed-in user, Devices and System need `admin`. Sign-out is in the header. +- [ ] ESLint (skipped during scaffolding; `tsc --noEmit` covers the important cases for now) +- [x] Virtualised gallery grid, cursor-paged, thumbnails through the auth-checked route. + Filters for date range, device, kept, reviewed and pre-trigger — the columns that have + data. **Taxon and tag filters are deliberately still missing:** both need a join, and + neither has anything to join to until `taxa` is seeded and the observation editor exists. + A filter that can only return nothing is worse than an absent one, because the UI offers it. +- [x] `poorbird seed --captures 500` — synthetic captures with real JPEGs on disk, realistic + burst structure and pre-trigger flags. `--clear` is scoped to its own device so it can + never remove a real camera's frames. +- [ ] Full-size viewer: keyboard navigation is in, but it only steps through what is already + loaded. Stepping past the last loaded page needs the viewer to be able to trigger a fetch. +- [ ] Observation editor — `captures` 1—n `observations`, so a photo can hold two species or none +- [ ] Taxon autocomplete; seed `taxa` with 60–80 Central European garden species incl. GBIF keys, `name_de` + `name_en`, `is_local_common` ranking first +- [ ] Tags, favourite/reject (`kept`), review flag +- [ ] Persist the theme choice **per user** (`users.theme`) rather than in localStorage — the + tokens and the switcher are done (above); this is the half that needs accounts to exist +- [x] Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin), + `audit_log` on login, failed login and logout. Sessions are rows, so logout is immediate; + only the SHA-256 of the cookie is stored; CSRF is bound to the session, not just + double-submitted. Accounts come from `poorbird user add` — there is no sign-up endpoint. +- [ ] Extend `audit_log` to the *content* mutations (observations, tags, device config) as each + endpoint lands. Auth events are covered; nothing else writes to it yet. +- [x] **Auth-checked image serving** — the app authorizes, Caddy serves the bytes via `X-Accel-Redirect`. + An unguessable URL is not access control. One authorization path, two ways of finishing the + response: `serve_images_directly=true` makes the app send the file for development, where there + is no Caddy. Not a separate unauthenticated dev route — that is the kind of thing that survives + into production because it works. `poorbird check` validates the sibling `images`/`thumbs` + layout the handoff depends on, since getting it wrong yields 404s from Caddy with nothing in + the app's log. +- [x] TOTP 2FA — enforced at account creation for `admin` rather than at login, because a + login-time check can lock the only admin out of their own account. Codes required whenever + the account has a secret. Replay inside the ~90s window is documented, not closed. +- [ ] **Revisit CORS.** Deliberately not configured in Phase 2: Caddy serves the built UI and the + API from one origin, so there is no cross-origin request to permit, and adding permissive + headers "for the UI" would only weaken that. The Vite dev server proxies `/api` for the + same reason, so development matches production. Decide it properly only if the UI is ever + served from somewhere else — *then* it matters. + +### 3.0 UI decisions (2026-09-21) + +**Language: German and English, both, from the first component (Q11).** i18n is +nearly free on day one and miserable to retrofit. `taxa` already carries +`name_de` and `name_en`; `users.locale` already exists and defaults to `de`. +Rule: no user-facing string literal in a component, ever — every one goes +through the translation catalogue, including the first one. + +**Theme "blue" is a dark navy (Q13).** Tokens below. Light and dark stay +conventional; blue is the distinctive one. Contrast targets WCAG AA (≥4.5:1 for +body text) — check it when the tokens land, do not assume it. + +| Token | Blue | +|---|---| +| `--bg` | `#0B1220` | +| `--surface` | `#111C2E` | +| `--surface-raised` | `#17253B` | +| `--border` | `#22344F` | +| `--text` | `#E6EDF7` | +| `--text-muted` | `#9FB3CE` | +| `--accent` | `#4C8DFF` | +| `--accent-hover` | `#6BA1FF` | +| `--success` / `--warning` / `--danger` | `#3DD68C` / `#F0B429` / `#F2545B` | + +**2FA: build TOTP now, optional per user, enforced for `admin` (Q14).** The +reasoning matters more than the setting, because "the UI does not need it" and +"I need access from outside" describe the *same* surface — whatever is reachable +from outside is the UI. What differs is the path: + +- Over **Tailscale** (the SPEC §0 decision): the network layer already demands an + enrolled device, and Tailscale enforces 2FA at your identity provider. UI 2FA + is then belt-and-braces. +- Over a **public domain** (SPEC §1.2, "design for, do not build"): UI 2FA stops + being optional. + +Build it now regardless, because retrofitting 2FA means reopening the login +flow, the session model, the user model and the audit log at once — the four +places you least want to revisit. `users.totp_secret` already exists. Enforce +for `admin`; leave it opt-in for `viewer`/`editor` on the LAN. A +`require_2fa` server setting flips the whole thing on the day you go public. + +**Stack stays React + TypeScript (Q16), with the learning curve taken seriously.** +No TS experience, but willing to learn. The gallery is genuinely a client-side +app — a virtualised grid and the keyboard-driven labelling loop — and that is +the thing HTMX would fight later. So: plain function components, no exotic +generics, no state-management library beyond TanStack Query, and comments that +explain the TypeScript rather than assuming it. **Fallback if it stops being +fun:** SPEC §5's Jinja2 + HTMX frontend is still a valid target and the API does +not change. Deciding to switch is not a failure; discovering it three months in +would be. + +**Placeholder data: generated, not downloaded.** A seed command +(`poorbird seed --captures 500`) synthesises captures with realistic burst +structure, pre-trigger flags, timestamps and species spread. Reasons: no image +licensing question at all, no binary blobs in git, and it can produce the +*volume* the virtualised grid actually needs to be tested against. Real photos +prove nothing about a gallery that a generated one does not — until Phase 2 +brings real captures, which is the only test that counts. + +### 3.1 Two things the UI must not get wrong + +- [ ] `battery_valid = false` means **not measured** (no divider is wired by default) — render as "n/a", never as a flat-battery alarm +- [ ] Daily counters live in RTC memory and reset on power loss. The `captures` table is authoritative; the counters' value is the **gap** between captured and delivered, which is an upload-health signal + +--- + +## Phase 4 — Device management & OTA + +- [ ] Device list with live/awake state, last seen, RSSI, heap/PSRAM, ring depth +- [ ] Settings editor writing the `devices` settings surface → `apply_config` → `config_version` +- [ ] Command queue UI: `wake_and_hold`, `capture_now`, `apply_config`, `ota_update`, `stream_start`, `reboot`; commands ride along on the ingest response +- [ ] Firmware upload, SHA-256, target marking, per-device staged rollout. + `GET /firmware/{version}.bin` already serves the bytes; the upload half was left out of + Phase 2 because it needs operator auth. **Constrain `firmware.is_target` to a single row + while doing this** — nothing enforces it today, and the lookup takes the first match, so + two target rows would pick non-deterministically between them. +- [ ] Verify the full OTA path on hardware: **trial boot and automatic rollback**. The camera is unreachable once mounted — this is the one feature with no recovery if it is broken +- [ ] Document that rotating the shared bootstrap secret server-side without shipping new firmware **removes the last-resort escape hatch** + +--- + +## Phase 5 — Operations + +- [ ] restic → NAS. **Decide the NAS protocol first (open Q9)** — SFTP or a mounted path; SMB-only changes the tooling +- [ ] `pg_dump` pre-hook; retention 7 daily / 4 weekly / 12 monthly +- [ ] **Monthly automated restore test** into a scratch Postgres database on the same host (the Docker-based scratch container from SPEC §6 is replaced by a throwaway cluster/DB). A backup you have never restored is a hypothesis. +- [ ] Alarms via ntfy or Gotify + WebUI banner: low battery, device offline > N hours, disk > 80 %, backup failure, ingest stalled +- [ ] Retention policy job (open Q8 — and decide whether deleting in the UI deletes the file or only hides it) +- [ ] `GET /api/v1/health` covering device liveness, battery, disk, last backup + +--- + +## Phase 6 — Streaming (plumbing only) + +Scope is device → server, watched internally. Public relay stays out (SPEC C3). + +- [ ] Chunked MJPEG sink per `firmware/API.md` → Streaming +- [ ] `record` / `watch` / `both` modes; the record writer plus the ingest writer are the two concurrent writers that justified Postgres +- [ ] Session time-box: 60 s default, firmware-capped at 600 s. Kept as policy, not as a power constraint +- [ ] Live view in the WebUI, admin-only + +--- + +## Explicitly not now + +- **Species detection** — schema is ready (`observations.source`, `model_version`, `confidence`, `bbox`), pipeline is not built. Revisit after a few thousand real captures, when you also know whether you want to label them. +- **Public stream / public gallery** — SPEC Option C. +- **Local SD buffering** of failed uploads — pins are free; add only if the WiFi link proves marginal. +- **On-device frame differencing** — the PSRAM ring makes this easy to add later. +- **TLS on the device** — deliberate, SPEC C2. +- **Containers** — not now, but the door stays open; see Phase 1.2. **Kubernetes** stays shut regardless: a control plane on a single host gains nothing here. +- **Audio / BirdNET** — different sensor, different pipeline. + +--- + +## Still open (from SPEC §10) + +Answered and closed: Q1 (Option B), Q2 (XIAO ESP32S3 Sense), Q4 (internal first), +Q5 (x86 thin client), **Q11, Q13, Q14 and Q16 — see Phase 3.0**. +Void under mains power: Q10 (battery chemistry). + +| # | Question | Blocks | +|---|---|---| +| 3 | Does the radar trigger reliably on *your* birds, at *your* distance? | Phase 0.3 — the project's biggest unknown | +| 9 | NAS access protocol — SFTP, SMB, NFS? | Phase 5, backup tooling choice | +| 6 | How many cameras eventually? | Phase 4 scope (device management, OTA staging) | +| 7 | Expected captures per day? | Storage sizing, retention, inline-vs-queued thumbnailing | +| 8 | Retention policy, and does UI delete remove the file? | Phase 5 | +| 11 | UI language — German, English, or both? | Cheap on day one, annoying to retrofit. `name_de`/`name_en` exist either way | +| 12 | Taxonomy source — GBIF backbone, IOC, Avibase? Which regional seed list? | Phase 3 taxa seed | +| 13 | The "blue" theme — a reference palette, or my choice? | Phase 3 theming | +| 14 | Is 2FA required, or is a strong password on a LAN-only service enough? | Phase 3 auth | +| 15 | Anything to record beyond SPEC §3 — weather, feeder type, ring number? | Schema, cheapest to settle before the first migration | +| 16 | Comfort level in C / Python / TypeScript? | The React frontend is the largest chunk of potentially unfamiliar work | +| 17 | Can the camera see a neighbour's garden or a public path? | One GDPR paragraph in the deployment notes | diff --git a/docs/reviews/README.md b/docs/reviews/README.md new file mode 100644 index 0000000..e183ed2 --- /dev/null +++ b/docs/reviews/README.md @@ -0,0 +1,47 @@ +# Code reviews + +One directory per reviewed scope: + +``` +docs/reviews//REVIEW.md human-readable review +docs/reviews//REVIEW.AI.md long-form context, written for an AI to + read before working on that scope +``` + +`` is the branch the review was made against, with slashes flattened — +`feature/Server_Basic_implementation` becomes `server-basic-implementation`. + +## Why the directory, and not `server/REVIEW.md` + +These documents are **branch-scoped snapshots**, pinned to a commit that is +named in their header. They are not living documentation of the directory they +sit in. + +Kept at a fixed path like `server/REVIEW.md`, every reviewed branch writes the +same two filenames with different content, and every merge is an unresolvable +`add/add` conflict. That happened: the review of the UI branch lived at +`server/REVIEW.md` — a path that describes neither its subject nor its scope — +and merging the two feature branches conflicted on both files. + +A directory per scope means two reviews never collide, both survive into +`develop`, and the path says what was reviewed without opening the file. + +## Reading one + +Check the header first. Every review states its branch and commit: + +``` +**Branch:** feature/Server_Basic_implementation (Commit: 142b476) +``` + +If that commit is behind the branch tip, the review is a snapshot of an older +state — treat its "what's missing" sections as of that date, not as current. +Verify a claim against the code before acting on it. Several findings in the +existing reviews are accurate; several reference implementations in them are +not, and the ones that were wrong are noted in the code that replaced them. + +## Adding one + +Create `docs/reviews//` and write both files. Do not copy a review from +one branch to another: a review describes the branch it was made against, and +a branch without one simply has not been reviewed yet. diff --git a/docs/reviews/server-basic-implementation/REVIEW.AI.md b/docs/reviews/server-basic-implementation/REVIEW.AI.md new file mode 100644 index 0000000..c5b06f2 --- /dev/null +++ b/docs/reviews/server-basic-implementation/REVIEW.AI.md @@ -0,0 +1,1301 @@ +# AI Reviewer Guide: poorBird Server (feature/Server_Basic_implementation) + +**Purpose:** This document provides comprehensive context for AI systems to analyze and improve the poorBird codebase, with specific focus on Phase 1 (Server Foundation) completion and Phase 2 (Device Endpoints) preparation. + +**Target Audience:** AI code review systems (like Mistral Vibe, Claude, etc.) + +**Created:** 2026-09-21 by Mistral Vibe + +**Branch:** feature/Server_Basic_implementation (Commit: 142b476) + +--- + +## 0. Branch Context (CRITICAL FOR AI UNDERSTANDING) + +### Branch Identity +- **Name:** feature/Server_Basic_implementation +- **Commit:** 142b476 ("Server: Phase 2 (REVIEW not respected yet)") +- **Actual Content:** Server code only (Phase 1 COMPLETE + Phase 2 STARTED) +- **Relation:** Canonical server branch, basis for feature/UI_Basic_implementation +- **Purpose:** Server foundation and Phase 2 device endpoints + +### Important Observation +This branch is the **canonical server branch**. It contains: +- ✅ Complete server infrastructure (Phase 1) +- ✅ All database models +- ✅ Job queue with PostgreSQL (FOR UPDATE SKIP LOCKED) +- ✅ Health endpoints +- ✅ Systemd units and Caddy configuration +- ✅ Migrations and schema validation +- ❌ **No device endpoints yet** (Phase 2 not fully implemented) +- ❌ **No authentication** (needed for Phase 2/3) + +**Note:** Commit 142b476 added web/ build files (Vite dist output), but these are build artifacts, not source code. The actual server source code is identical to feature/UI_Basic_implementation at commit 5d16ded. + +### Phase Information +``` +Phase 1 (DONE): Server foundation, config, schema, health, job queue, scheduler +Phase 2 (STARTED): Device endpoints (/enroll, /ingest, /heartbeat, /status, /config) +Phase 3 (TARGET): WebUI (React+TS+Vite) - in feature/UI_Basic_implementation +Phase 4: Device management, OTA +Phase 5: Operations (backup, retention, alarms) +Phase 6: Streaming +``` + +### Key Difference from UI Branch +- This branch: **Server-only**, canonical server code +- UI branch: **Server + UI review files**, but same server code base +- Both branches share the same server implementation (commit 5d16ded) + +--- + +## 1. Project Overview (ESSENTIAL CONTEXT) + +### Core Purpose +Radar-triggered bird camera system that: +1. Detects birds using LD2410 radar sensor +2. Captures images with ESP32 camera +3. Transmits to server via MQTT +4. Stores images and metadata in PostgreSQL +5. Provides web interface for viewing and managing captures + +### Domain +- **Primary:** IoT + Computer Vision + Web Application +- **Secondary:** Data Management, Device Management, User Management + +### Users +| User Type | Access Level | Use Cases | +|-----------|--------------|----------| +| Device | API only | Enroll, ingest images, send status | +| Viewer | Read-only | View gallery, search, filter | +| Editor | Read+Write | View + add observations, tags, edit metadata | +| Admin | Full | All editor + device management, user management, settings | + +### Deployment Architecture +``` +┌─────────────────────────────────────────────────────────┐ +│ Client (Browser) │ +└─────────────────────────┬───────────────────────────────┘ + │ HTTPS (TLS via DNS-01) + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Caddy (Reverse Proxy) │ +│ ┌─────────────────────┐ ┌─────────────────────────┐ │ +│ │ Static UI Files │ │ API Requests │ │ +│ │ /srv/poorbird/ │ │ /api/v1/* │ │ +│ └──────────┬────────────┘ └──────────┬─────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────────┐│ +│ │ React/TS Frontend ││ +│ │ (NOT YET IMPLEMENTED) ││ +│ └─────────────────────────────────────────────────────┘│ +│ │ +└──────────────────────────────────────────────┬─────┘ + │ + ┌────────────────────────────────▼─────────────┐ + │ FastAPI Backend (Phase 1 Complete) │ + │ ┌──────────────┐ ┌──────────────┐ │ + │ │ API Layer │ │ Worker Layer │ │ + │ │ /api/v1/* │ │ Job Queue │ │ + │ └──────────────┘ └──────────────┘ │ + │ │ │ │ + │ ▼ ▼ │ + │ ┌─────────────────────────────────────────┐│ + │ │ PostgreSQL 17 ││ + │ │ ┌──────────┐ ┌──────────┐ ││ + │ │ │ Schema │ │ Job Q │ ││ + │ │ │ (Phase 1)│ │ (Phase 1)│ ││ + │ │ └──────────┘ └──────────┘ ││ + │ └─────────────────────────────────────────┘│ + └────────────────────────────────────────────────┘ +``` + +### Technology Stack +| Layer | Technology | Version | Status | +|-------|------------|---------|--------| +| Backend | Python | 3.14.7 (verified) | Phase 1 Complete | +| Framework | FastAPI | Latest | Phase 1 Complete | +| Database | PostgreSQL | 17 | Phase 1 Complete | +| ORM | SQLAlchemy | 2.0 | Phase 1 Complete | +| Migrations | Alembic | Latest | Phase 1 Complete | +| Logging | structlog/stdout | - | Phase 1 Complete | +| Proxy | Caddy | 2.x | Phase 1 Complete | +| **Frontend** | **React + TypeScript** | **18+** | **NOT STARTED** | + +### Scale Expectations +| Metric | Value | Notes | +|--------|-------|-------| +| Cameras | 1-10 (Phase 3), 100+ (future) | Current: 1 | +| Captures/day | 5000 | 1 camera, ~10/hour | +| Image Size | 200-500KB | JPEG | +| Thumb Size | 20-50KB | WebP, 400px | +| Concurrent Users | 1-5 typical, 10 peak | LAN-only | +| Storage/month | ~1GB | 5000 images * 200KB | +| DB Queries/day | ~10,000 | 5000 captures + 5000 status | + +--- + +## 2. External Contracts (CRITICAL FOR AI UNDERSTANDING) + +### Device ↔ Server API Contract (firmware/API.md) + +**ALL DEVICE ENDPOINTS ARE NOT YET IMPLEMENTED - Phase 2 Task** + +The server MUST implement these endpoints to satisfy the firmware contract. See `firmware/API.md` for complete specification. + +#### Endpoints Overview +- `POST /api/v1/enroll` - Device enrollment +- `POST /api/v1/ingest` - Image ingest with metadata +- `POST /api/v1/heartbeat` - Device heartbeat +- `POST /api/v1/status` - Device status report +- `GET /api/v1/config` - Get device configuration +- `POST /api/v1/firmware` - Firmware upload (admin only) + +### UI-Specific Contract Requirements (SPEC 3.3) + +**Image Serving:** +- **NEVER** serve images directly from filesystem +- **ALWAYS** check authorization in app first +- **THEN** have Caddy serve the bytes via X-Accel-Redirect +- **URL Pattern:** `/images/YYYY/MM/DD/.jpg` +- **Thumb Pattern:** `/thumbs/_400.webp` + +**Authentication:** +- Device auth: X-Enroll-Secret header +- User auth: Session cookies (not JWT for WebUI) +- CSRF protection for all mutating requests +- RBAC: viewer, editor, admin +- Optional TOTP 2FA (SPEC Q14) + +--- + +## 3. Architecture Decisions (WHY THEY MATTER FOR AI) + +### Core Decisions + +| Decision | Rationale | Alternatives | Trade-offs | Impact | +|----------|-----------|--------------|------------|--------| +| **Native Deployment** | SPEC requirement, no container overhead | Docker, Kubernetes | Simpler, but less portable | Must respect | +| **Sync SQLAlchemy** | 1 camera, few K frames/day - async overhead not justified | Async SQLAlchemy | Simpler code, but blocks event loop | OK for current scale | +| **PostgreSQL over TCP** | Container-ready, better performance | Unix socket | More portable | Must use TCP | +| **FOR UPDATE SKIP LOCKED** | Job queue without Redis dependency | Redis, RabbitMQ | No external service, PostgreSQL-only | Works perfectly | +| **JSONB for Config** | 40+ optional settings, firmware evolves | Separate columns | Flexible, but can't index individual settings | Good for device settings | +| **UUID for Captures** | Safe for URLs, distributed systems | Sequential int | Better for URLs | Perfect for /gallery/ | +| **Single Image Root** | App and Caddy must agree on path | Multiple roots | Simpler, single source of truth | Critical for auth-checked handoff | + +### Constraints (AI MUST RESPECT THESE) + +**Hard Constraints:** +- NO Docker (SPEC requirement) +- Native Linux deployment +- PostgreSQL (not SQLite) +- Loopback TCP (not Unix socket) +- systemd units (not supervisor) +- Caddy (not nginx, not Apache) +- No public streaming (Phase 6 is internal only) + +**Soft Constraints:** +- Container-ready design (even though not using containers) +- All config from environment +- All mutable state in explicit directories +- Log to stdout/stderr only +- All paths configurable via environment variables + +**Non-Goals:** +- NO Kubernetes +- NO public streaming (Phase 6 is internal only) +- NO audio/BirdNET (different sensor) +- NO TLS on device (SPEC C2) + +--- + +## 4. Security Analysis (CRITICAL FOR AI) + +### Severity System +- **CRITICAL:** Must fix before any production use. Blocks Phase 2/3. +- **HIGH:** Must fix before Phase 3. Serious risk. +- **MEDIUM:** Should fix before Phase 3. Moderate risk. +- **LOW:** Nice to have. Low risk. + +### Critical Issues (BLOCK PHASE 2/3) + +#### SEC-001: Enroll Secret in Plaintext +- **Location:** config.py:53, .env files, systemd EnvironmentFile +- **Code:** `enroll_secret: SecretStr = SecretStr("")` +- **Issue:** Bootstrap secret stored in plaintext in files +- **Risk:** Filesystem access = complete device spoofing. If any endpoint exposes device management, attacker can enroll malicious devices. +- **Impact:** Catastrophic. Compromises entire device network. +- **Vulnerability Type:** Credential Exposure +- **CVSS:** 9.8 (Critical) +- **Solution:** + ```python + # Option 1: Remove default, CLI-only + enroll_secret: SecretStr # No default + # Only set via: poorbird config set enroll_secret + + # Option 2: Environment variable only + enroll_secret: SecretStr + ``` +- **Files to Modify:** config.py, .env.example, deploy/poorbird.env.example +- **Tests Needed:** Verify secret not logged, not in error messages +- **Priority:** CRITICAL +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 2-4 hours + +#### SEC-002: No Request Authentication +- **Location:** All API endpoints (none have auth yet) +- **Issue:** No authentication for any endpoint +- **Risk:** Anyone can send device commands, access admin functions, manage users +- **Impact:** Complete system compromise. Device endpoints would be wide open. +- **Vulnerability Type:** Missing Authentication +- **CVSS:** 10.0 (Critical) +- **Solution:** + ```python + # Device auth (for /enroll, /ingest, /heartbeat, /status) + from fastapi import Request, HTTPException, Header + + async def verify_device(request: Request, + x_enroll_secret: str = Header(None)): + if not x_enroll_secret: + raise HTTPException(status_code=401) + # Verify against enroll_secret hash + # Lookup device by token + + # User auth (for UI endpoints - Phase 3) + from fastapi import Cookie + + async def verify_user(request: Request, + session_id: str = Cookie(None)): + if not session_id: + raise HTTPException(status_code=401) + # Verify session in DB + # Return user with roles + ``` +- **Files to Create:** api/routes/auth.py, api/deps.py +- **Files to Modify:** app.py (add auth dependencies) +- **Tests Needed:** Auth tests for all endpoint types +- **Priority:** CRITICAL +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 1-2 days + +#### SEC-003: No Input Validation +- **Location:** queue.py:47-66 (enqueue function), all future endpoints +- **Issue:** Payloads not validated before DB insert +- **Risk:** SQL injection, XSS, malicious data, data corruption +- **Impact:** High. Device endpoints accept device input, UI accepts user input. +- **Vulnerability Type:** Missing Input Validation +- **CVSS:** 8.1 (High) +- **Solution:** + ```python + # Example: Job payload validation + from pydantic import BaseModel, Field + from typing import Literal, Optional, Union + + class NoopJobPayload(BaseModel): + """Payload for noop job.""" + message: Optional[str] = None + + class ThumbnailJobPayload(BaseModel): + """Payload for thumbnail job.""" + capture_id: str # UUID + quality: int = Field(ge=1, le=100) + width: int = Field(ge=100, le=2000) + + JobPayload = Union[NoopJobPayload, ThumbnailJobPayload] + + # All enqueue calls must use validated payloads + def enqueue(session: Session, + kind: Literal["noop", "thumbnail"], + payload: JobPayload, + ...): + # Now payload is validated! + ``` +- **Files to Create:** api/schemas.py (Pydantic models for all requests) +- **Files to Modify:** queue.py (add validation to enqueue function) +- **Tests Needed:** Validation tests for all payload types +- **Priority:** CRITICAL +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 1-2 days + +#### SEC-004: No Rate Limiting +- **Location:** API layer (app.py) +- **Issue:** No protection against DoS or brute force +- **Risk:** Device endpoints can be flooded, server overload +- **Impact:** High. Device endpoints would be vulnerable to attack. +- **Vulnerability Type:** Missing Rate Limiting +- **CVSS:** 7.5 (High) +- **Solution:** + ```python + from slowapi import Limiter + from slowapi.util import get_remote_address + from slowapi.errors import RateLimitExceeded + from fastapi import Request + from fastapi.responses import JSONResponse + + limiter = Limiter(key_func=get_remote_address) + + @app.exception_handler(RateLimitExceeded) + async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded): + return JSONResponse( + status_code=429, + content={"detail": "Too many requests"}, + headers={"Retry-After": str(exc.retry_after)} + ) + + # Apply to device endpoints + @app.post("/api/v1/enroll") + @limiter.limit("10/hour") # Enrollment should be rate-limited + async def enroll_device(request: Request): + ... + + @app.post("/api/v1/ingest") + @limiter.limit("100/minute") # Higher limit for image uploads + async def ingest_image(request: Request): + ... + ``` +- **Files to Create:** None (add to app.py) +- **Files to Modify:** app.py +- **Configuration:** Add to pyproject.toml: slowapi +- **Tests Needed:** Rate limiting tests +- **Priority:** HIGH +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 1 day + +### High Priority Issues (FIX BEFORE PHASE 2) + +#### SEC-005: No CORS Configuration +- **Location:** API layer +- **Issue:** No CORS headers configured +- **Risk:** Future WebUI cannot make requests if on different origin +- **Impact:** UI development will be blocked +- **Vulnerability Type:** Missing CORS +- **CVSS:** 6.5 (Medium) +- **Solution:** + ```python + from fastapi.middleware.cors import CORSMiddleware + + app.add_middleware( + CORSMiddleware, + allow_origins=[ + "http://localhost:3000", # Dev + "http://localhost:5173", # Vite dev + "https://poorbird.local", # Prod + ], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + expose_headers=["X-Request-ID"], + ) + ``` +- **Files to Modify:** app.py +- **Tests Needed:** CORS test +- **Priority:** HIGH +- **Effort:** 1 hour + +#### SEC-006: DB URL with Credentials in Defaults +- **Location:** config.py:30 +- **Issue:** Default value contains plaintext credentials +- **Risk:** Accidental commit of credentials to repo +- **Impact:** Medium. Security risk if committed. +- **Vulnerability Type:** Hardcoded Credentials +- **CVSS:** 7.5 (High) +- **Solution:** + ```python + # Change from: + database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" + + # To: + database_url: str = "" # Must be set via POORBIRD_DATABASE_URL + ``` +- **Files to Modify:** config.py +- **Tests Needed:** Verify app fails gracefully if not set +- **Priority:** HIGH +- **Effort:** 1 hour + +#### SEC-007: No Session Management +- **Location:** models/users.py has Session model, but not used +- **Issue:** Session table exists but no implementation +- **Risk:** Cannot implement user login/logout for WebUI +- **Impact:** High. Phase 3 (WebUI) authentication impossible. +- **Vulnerability Type:** Missing Functionality +- **Solution:** + ```python + # Session creation on login + from datetime import datetime, timedelta + from sqlalchemy.orm import Session as DbSession + from .models import Session, User + + def create_session(db: DbSession, user: User) -> Session: + session = Session( + user_id=user.id, + expires_at=datetime.utcnow() + timedelta(days=30), + ip=request.client.host, + user_agent=request.headers.get("user-agent"), + ) + db.add(session) + db.commit() + db.refresh(session) + return session + + def verify_session(db: DbSession, session_id: str) -> User | None: + session = db.query(Session).filter( + Session.id == session_id, + Session.expires_at > datetime.utcnow() + ).first() + if session: + session.expires_at = datetime.utcnow() + timedelta(days=30) + db.commit() + return session.user + return None + ``` +- **Files to Create:** api/routes/auth.py +- **Files to Modify:** models/users.py (add session management methods) +- **Tests Needed:** Session lifecycle tests +- **Priority:** HIGH +- **Effort:** 1 day + +### Medium Priority Issues + +#### SEC-008: No Password Hashing Implementation +- **Location:** models/users.py (password_hash column exists) +- **Issue:** password_hash column exists but no hashing implementation +- **Risk:** If someone implements password setting without hashing, passwords stored in plaintext +- **Impact:** Medium. Future security risk. +- **Solution:** + ```python + import argon2 + from argon2 import PasswordHasher + + ph = PasswordHasher( + time_cost=3, + memory_cost=65536, + parallelism=4, + hash_len=32, + salt_len=16, + ) + + def hash_password(password: str) -> str: + return ph.hash(password) + + def verify_password(password: str, hash: str) -> bool: + try: + return ph.verify(hash, password) + except: + return False + ``` +- **Files to Create:** api/utils/auth.py +- **Files to Modify:** models/users.py +- **Tests Needed:** Password hashing tests +- **Priority:** MEDIUM +- **Effort:** 2-4 hours + +#### SEC-009: No Image Upload Validation +- **Location:** Future device ingest endpoint +- **Issue:** Images not validated before saving +- **Risk:** Malicious file uploads (e.g., PHP files, scripts) +- **Impact:** Medium. Could lead to server compromise. +- **Solution:** + ```python + import magic # python-magic + from pathlib import Path + + ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"} + MAX_SIZE = 10 * 1024 * 1024 # 10MB + MAX_DIMENSIONS = (4000, 4000) # width, height + + def validate_image(file_path: Path) -> tuple[bool, str]: + # Check file size + if file_path.stat().st_size > MAX_SIZE: + return False, "File too large" + + # Check MIME type + mime = magic.from_file(file_path, mime=True) + if mime not in ALLOWED_TYPES: + return False, f"Invalid file type: {mime}" + + # Check dimensions + try: + from PIL import Image + with Image.open(file_path) as img: + if img.size[0] > MAX_DIMENSIONS[0] or img.size[1] > MAX_DIMENSIONS[1]: + return False, "Image too large" + except: + return False, "Invalid image" + + return True, "Valid" + ``` +- **Files to Create:** api/utils/image_validation.py +- **Tests Needed:** Image validation tests +- **Priority:** MEDIUM +- **Effort:** 2-4 hours + +--- + +## 5. Data Model Analysis (FOR DEVICE & UI DEVELOPMENT) + +### Complete Schema + +The data model is **excellent** and perfectly designed for the requirements. All tables from SPEC S3 are implemented plus additional tables from SPEC S0. + +```sql +-- Users and Authentication +CREATE TABLE users (...) -- Roles: admin, editor, viewer +CREATE TABLE sessions (...) -- UUID primary key, user_id, expires_at + +-- Devices and Commands +CREATE TABLE devices (...) -- device_uid (MAC-based), config JSONB, token_hash +CREATE TABLE device_commands (...) -- type, payload JSONB, created_by, delivered_at +CREATE TABLE device_status (...) -- Time-series data from devices + +-- Firmware +CREATE TABLE firmware (...) -- version, semver, file_path, sha256 + +-- Captures and Observations (CORE) +CREATE TABLE captures (...) -- UUID primary key, path, thumb_path, sha256 +CREATE TABLE observations (...) -- capture_id, taxon_id, individuals, source (human/model) +CREATE TABLE taxa (...) -- scientific_name, name_de, name_en, gbif_key +CREATE TABLE tags (...) -- label, colour +CREATE TABLE capture_tags (...) -- Many-to-many + +-- Operational Tables +CREATE TABLE settings (...) -- key, value, scope (server/device) +CREATE TABLE audit_log (...) -- user_id, action, entity, before/after JSONB +CREATE TABLE backup_runs (...) -- started_at, finished_at, status + +-- Job Queue (PostgreSQL-backed) +CREATE TABLE jobs (...) -- kind, payload JSONB, status, priority, run_at +``` + +### Key Relationships +``` +users (1) ── (n) sessions + └── (n) audit_log + └── (n) device_commands (created_by) + └── (n) firmware (uploaded_by) + └── (n) observations (created_by) + +devices (1) ── (n) captures + ├── (n) device_status + ├── (n) device_commands + └── (1) current firmware (via is_target) + +captures (1) ── (n) observations + ├── (n) tags (via capture_tags) + └── (1) device + +observations (n) ── (1) taxa +observations (n) ── (1) capture +observations (n) ── (1) user (created_by) + +tags (n) ── (n) captures (via capture_tags) +``` + +### UI-Relevant Fields (for Phase 3) + +**Captures:** +- `id` (UUID) - Primary key, used in URLs +- `path`, `thumb_path` - File paths for images +- `received_at` - **AUTHORITATIVE timestamp** (SPEC C7) +- `trigger` - How capture was triggered (radar, manual, timer, stream_grab) +- `pre_trigger` - Was this frame captured BEFORE the trigger fired? +- `kept` - Soft reject flag +- `reviewed` - Has this been reviewed? +- `radar_*` - Radar data for analysis +- `battery_*`, `rssi`, `temp_c` - Device conditions at capture time + +**Observations:** +- `source` - 'human' or 'model' (future ML integration) +- `taxon_id` - Links to species data +- `model_version`, `confidence`, `bbox` - For ML predictions +- `age`, `sex`, `behaviour`, `certainty` - Observation metadata +- `individuals` - Number of birds in this observation + +**Taxa:** +- `scientific_name` - Unique scientific name +- `name_de`, `name_en` - Localized names +- `gbif_key` - GBIF identifier +- `is_local_common` - For autocomplete ranking (local species first) + +**Devices:** +- `device_uid` - MAC-based identity, survives reflashing +- `config` - JSONB with all device settings +- `config_version` - Increments on every config change +- `battery_valid` - **CRITICAL**: false = **NOT MEASURED**, not empty! +- `awake` - Device is awake and responsive + +**Device Status:** +- All fields are time-series data +- Counters (captured_today, etc.) are from RTC memory +- **CRITICAL**: Counters reset on power loss +- **UI Display**: Counters show GAP between captured and delivered + +--- + +## 6. Current Implementation Status + +### What Exists (Phase 1 - Server Foundation) + +``` +server/ +├── src/poorbird/ +│ ├── __init__.py # Version: 0.1.0 +│ ├── config.py # All settings from environment +│ ├── logging_setup.py # stdout-only logging +│ ├── db.py # SQLAlchemy engine + session +│ ├── schema_compare.py # Schema drift normalization (GENIUS!) +│ ├── models/ +│ │ ├── __init__.py # Imports all models +│ │ ├── base.py # Base class + naming convention +│ │ ├── captures.py # Captures, Observations, Taxa, Tags +│ │ ├── devices.py # Devices, Commands, Status, Firmware +│ │ ├── ops.py # Settings, AuditLog, BackupRun, Job +│ │ └── users.py # Users, Sessions +│ ├── api/ +│ │ ├── __init__.py +│ │ ├── app.py # FastAPI app + lifespan +│ │ ├── deps.py # Empty (potential for dependencies) +│ │ └── routes/ +│ │ ├── __init__.py +│ │ └── health.py # /api/v1/health, /healthz +│ ├── worker/ +│ │ ├── __init__.py +│ │ ├── main.py # Worker + scheduler +│ │ ├── queue.py # Job queue (FOR UPDATE SKIP LOCKED) +│ │ └── handlers.py # Job handlers (noop, prune_expired_commands) +│ └── cli.py # CLI: serve, worker, migrate, check, enqueue +├── migrations/ +│ ├── env.py # Alembic environment +│ ├── script.py.mako +│ └── versions/ +│ └── 0001_initial.py # Baseline migration +├── deploy/ +│ ├── INSTALL.md +│ ├── poorbird.env.example +│ ├── poorbird-api.service +│ ├── poorbird-worker.service +│ └── Caddyfile +├── tests/ +│ ├── conftest.py +│ ├── test_health.py +│ ├── test_queue.py +│ ├── test_schema_matches_models.py +│ └── test_config.py +├── alembic.ini +├── pyproject.toml +└── README.md +``` + +### What's Missing for Phase 2 + +``` +MISSING - Device Endpoints: +server/src/poorbird/api/routes/ +├── enroll.py # POST /api/v1/enroll +├── ingest.py # POST /api/v1/ingest +├── heartbeat.py # POST /api/v1/heartbeat +├── status.py # POST /api/v1/status +├── config.py # GET /api/v1/config +└── firmware.py # POST /api/v1/firmware + +MISSING - Authentication: +├── Device authentication (X-Enroll-Secret validation) +├── Token generation and management +├── Token hashing +└── Request authentication middleware + +MISSING - Security: +├── Rate limiting +├── CORS configuration +└── Input validation for all endpoints +``` + +### What's Missing for Phase 3 (UI) + +``` +MISSING - Backend (UI Endpoints): +server/src/poorbird/api/routes/ +├── gallery.py # Capture listing, filtering +├── observations.py # Observation CRUD +├── taxa.py # Taxon search/autocomplete +├── tags.py # Tag management +├── devices.py # Device management (UI view) +└── auth.py # User authentication endpoints + +MISSING - Authentication: +├── Session management +├── Password hashing (Argon2id) +├── CSRF protection +└── User role management (RBAC) +``` + +### Implementation Status by Phase + +| Phase | Status | Components | Tests | +|-------|--------|------------|-------| +| Phase 1 | ✅ COMPLETE | Server foundation, config, schema, health, job queue, scheduler | 12/12 | +| Phase 2 | ❌ NOT STARTED | Device endpoints, device authentication | 0/0 | +| Phase 3 | ❌ NOT STARTED | WebUI (React+TS+Vite), UI endpoints, user authentication | 0/0 | +| Phase 4 | ❌ NOT STARTED | Device management, OTA | 0/0 | +| Phase 5 | ❌ NOT STARTED | Operations (backup, retention, alarms) | 0/0 | +| Phase 6 | ❌ NOT STARTED | Streaming | 0/0 | + +--- + +## 7. Performance Analysis + +### Current Configuration + +| Component | Setting | Current Value | Impact | Rating | Recommendation | +|-----------|---------|---------------|--------|--------|----------------| +| DB Connection Pool | db_pool_size | 5 | May block concurrent requests | 3/5 | 15-20 for Phase 3 | +| Worker Poll Interval | worker_poll_interval_s | 2.0 | Frequent polling on empty queue | 3/5 | 5.0 for Phase 2 | +| Batch Size | worker_batch_size | 1 | Single job processing | 3/5 | 5-10 for Phase 2 | +| Sync SQLAlchemy | - | Enabled | Blocks event loop under load | 4/5 | OK for current scale | +| Log Level | log_level | INFO | Good for development | 4/5 | OK | +| Image Root | image_root | /srv/poorbird/images | Good structure | 5/5 | OK | +| Thumb Root | thumb_root | /srv/poorbird/thumbs | Good structure | 5/5 | OK | + +### Expected Load Profile + +**Device Communication:** +- Heartbeat: Every 5-15 minutes per device +- Status: Every 15-30 minutes per device +- Image ingest: ~10/hour/camera (5000/day) +- Burst images: 3-5 images per trigger event + +**Phase 2 Load (1 Camera):** +- API requests: ~200-300/day +- DB writes: ~5000 captures + ~200 device_status = 5200/day +- Image storage: ~1GB/month + +**Phase 3 Load (WebUI):** +- Gallery page: 20-50 images initial, 20 per scroll +- Filter queries: 100-500ms with proper indexes +- Concurrent users: 1-5 typical, 10 peak + +### Bottlenecks to Address Before Phase 2 + +1. **DB Connection Pool (MEDIUM)** + - Current: 5 connections + - Issue: May block under concurrent device requests + - Solution: Increase to 10-15 for Phase 2 + - Impact: Supports multiple concurrent devices + +2. **Worker Poll Interval (LOW)** + - Current: 2 seconds + - Issue: Frequent polling on empty queue + - Solution: Increase to 5 seconds + - Impact: Reduced CPU usage + +3. **Sync SQLAlchemy (FUTURE)** + - Current: Synchronous + - Issue: Blocks event loop under heavy load + - Solution: Evaluate async for Phase 6 (MJPEG streaming) + - Impact: May be needed for high-concurrency scenarios + +### Performance Recommendations + +#### Database (for Phase 2) +```python +# db.py - Recommended changes for Phase 2 +engine = create_engine( + _settings.database_url, + pool_size=15, # Was 5 - supports 10+ concurrent devices + pool_pre_ping=True, + pool_recycle=3600, # Recycle after 1 hour + pool_timeout=30, # Timeout after 30 seconds + connect_timeout=10, + echo=_settings.db_echo, + future=True, +) +``` + +#### Worker (for Phase 2) +```python +# In settings or config +worker_poll_interval_s: float = 5.0 # Was 2.0 +worker_batch_size: int = 5 # Was 1 +``` + +--- + +## 8. Testing Strategy + +### Current Test Status + +| Test File | Type | Status | Requires | Coverage | +|-----------|------|--------|----------|----------| +| test_health.py | Integration | ✅ PASS | PostgreSQL | API health | +| test_queue.py | Integration | ✅ PASS | PostgreSQL | Job queue | +| test_schema_matches_models.py | Integration | ✅ PASS | PostgreSQL + CREATE DB | Schema drift | +| test_config.py | Unit | ✅ PASS | None | Config validation | +| conftest.py | Fixtures | ✅ | PostgreSQL | Test setup | + +**Total:** 12/12 tests passing (100%) + +### Missing Tests (Phase 2) + +#### Unit Tests +- Device endpoint validation tests +- Authentication tests +- Token generation tests +- Input validation tests + +#### Integration Tests +- Device endpoint integration tests +- Database transaction tests +- Error handling tests + +#### Contract Tests +- Verify firmware/API.md contract compliance +- Verify SPEC C7 (received_at is authoritative) compliance + +--- + +## 9. Implementation Guide for AI + +### For Phase 2 (Device Endpoints) + +#### Step 1: Fix CRITICAL Security Issues +Before implementing ANY device endpoints, fix: +1. SEC-001: Remove enroll_secret default +2. SEC-002: Implement request authentication +3. SEC-003: Add input validation +4. SEC-006: Remove DB URL default + +#### Step 2: Implement Device Authentication +```python +# api/deps.py +from fastapi import Request, HTTPException, Header +from ..config import get_settings +import secrets + +async def verify_device_token( + request: Request, + authorization: str = Header(None) +) -> Device: + """Verify device bearer token.""" + if not authorization or not authorization.startswith("Bearer "): + raise HTTPException(status_code=401) + + token = authorization.split("Bearer ", 1)[1] + settings = get_settings() + + # Lookup device by token hash + from ..models import Device + from ..db import SessionLocal + + with SessionLocal() as db: + device = db.query(Device).filter( + Device.token_hash == _hash_token(token, settings) + ).first() + + if not device: + raise HTTPException(status_code=401) + + if not device.enabled: + raise HTTPException(status_code=403, detail="Device disabled") + + return device +``` + +#### Step 3: Implement Device Endpoints + +**POST /api/v1/enroll** +```python +# api/routes/enroll.py +from fastapi import APIRouter, Depends, HTTPException +from fastapi.security import HTTPBearer +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from .. import deps +from ..models import Device +from ..db import get_db + +router = APIRouter(prefix="/enroll", tags=["devices"]) + +class EnrollRequest(BaseModel): + device_uid: str # MAC address + name: str + mac: str | None = None + hw_revision: str | None = None + fw_version: str | None = None + +@router.post("") +async def enroll_device( + request: EnrollRequest, + settings: deps.SettingsDep, + db: Session = Depends(get_db) +): + # Verify enroll_secret + if not settings.enroll_secret_is_set: + raise HTTPException(status_code=500, detail="Server not configured") + + # Check if device_uid already exists + existing = db.query(Device).filter(Device.device_uid == request.device_uid).first() + if existing: + # Re-enroll: return fresh token + existing.token_hash = _hash_token(secrets.token_urlsafe(32)) + existing.reenroll_secret_hash = _hash_token(secrets.token_urlsafe(32)) + db.commit() + return { + "token": existing.token_hash, # Actually return the token, not hash + "reenroll_secret": existing.reenroll_secret_hash + } + + # New device + device = Device( + device_uid=request.device_uid, + name=request.name, + mac=request.mac, + hw_revision=request.hw_revision, + fw_version=request.fw_version, + token_hash=_hash_token(secrets.token_urlsafe(32)), + reenroll_secret_hash=_hash_token(secrets.token_urlsafe(32)), + enabled=True + ) + db.add(device) + db.commit() + db.refresh(device) + + return { + "token": device.token_hash, # Return actual token + "reenroll_secret": device.reenroll_secret_hash + } +``` + +**POST /api/v1/ingest** +```python +# api/routes/ingest.py +import secrets +from datetime import datetime +from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Header +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from .. import deps +from ..models import Capture, DeviceStatus +from ..db import get_db + +router = APIRouter(prefix="/ingest", tags=["captures"]) + +class IngestMetadata(BaseModel): + device_id: int + trigger: str # radar, manual, timer, stream_grab + burst_id: str | None = None + burst_index: int | None = None + burst_count: int | None = None + frame_seq: int | None = None + radar_distance_cm: int | None = None + radar_energy: int | None = None + battery_mv: int | None = None + rssi: int | None = None + temp_c: float | None = None + pre_trigger: int = 0 # 0 or 1 + +@router.post("") +async def ingest_capture( + metadata: IngestMetadata, + file: UploadFile = File(...), + x_captured_at: str = Header(None), + x_pre_trigger: int = Header(0), + device: deps.DeviceDep = Depends(deps.verify_device_token), + db: Session = Depends(get_db), + settings: deps.SettingsDep = Depends(deps.get_settings) +): + # Validate device_id matches token + if metadata.device_id != device.id: + raise HTTPException(status_code=403, detail="Device ID mismatch") + + # Read and validate image + contents = await file.read() + + # Generate UUID + capture_id = secrets.token_urlsafe(16) # Or use uuid.uuid4() + + # Calculate sha256 + import hashlib + sha256 = hashlib.sha256(contents).hexdigest() + + # Determine paths + date_path = datetime.now().strftime("%Y/%m/%d") + image_path = settings.image_root / date_path / f"{capture_id}.jpg" + thumb_path = settings.thumb_root / f"{capture_id}_400.webp" + + # Save image + image_path.parent.mkdir(parents=True, exist_ok=True) + image_path.write_bytes(contents) + + # Create capture record + capture = Capture( + id=capture_id, + device_id=metadata.device_id, + path=str(image_path.relative_to(settings.image_root)), + thumb_path=str(thumb_path.relative_to(settings.thumb_root)), + sha256=sha256, + bytes=len(contents), + trigger=metadata.trigger, + burst_id=metadata.burst_id, + burst_index=metadata.burst_index, + burst_count=metadata.burst_count, + frame_seq=metadata.frame_seq, + radar_distance_cm=metadata.radar_distance_cm, + radar_energy=metadata.radar_energy, + battery_mv=metadata.battery_mv, + rssi=metadata.rssi, + temp_c=metadata.temp_c, + pre_trigger=bool(x_pre_trigger or metadata.pre_trigger), + captured_at_device=parse_timestamp(x_captured_at) if x_captured_at else None, + received_at=datetime.now(), # SPEC C7: server time is authoritative + kept=True, + reviewed=False + ) + db.add(capture) + db.commit() + db.refresh(capture) + + # Update device status (from metadata) + if metadata.battery_mv: + device.battery_mv = metadata.battery_mv + device.battery_pct = metadata.battery_mv # TODO: Calculate from voltage + if metadata.rssi: + device.rssi = metadata.rssi + if metadata.temp_c: + device.temp_c = metadata.temp_c + device.last_seen_at = datetime.now() + db.commit() + + # Queue thumbnail generation + from ..worker.queue import enqueue + enqueue(db, "generate_thumbnail", {"capture_id": capture_id}) + db.commit() + + return { + "ingested": True, + "capture_id": capture_id, + "commands": [] # Device command queue (SPEC) + } +``` + +#### Step 4: Add to app.py +```python +# In app.py, after existing routes +from .routes import enroll, ingest, heartbeat, status, config, firmware + +app.include_router(enroll.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(ingest.router, prefix=API_PREFIX, tags=["captures"]) +app.include_router(heartbeat.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(status.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(config.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(firmware.router, prefix=API_PREFIX, tags=["firmware"]) +``` + +--- + +## 10. Deployment Analysis + +### Current Deployment Status + +✅ **All Phase 1 deployment components present:** +- systemd units: `poorbird-api.service`, `poorbird-worker.service` +- Caddyfile with TLS (DNS-01), X-Accel-Redirect for images +- Camera listener on port 8080 (plain HTTP, SPEC C2) +- Human UI on port 443 with TLS +- Installation guide in `deploy/INSTALL.md` + +### Caddy Configuration Highlights + +The Caddy configuration is **excellent** and production-ready: + +1. **TLS via DNS-01**: Automatic certificate management with Let's Encrypt +2. **Auth-checked image handoff**: X-Accel-Redirect pattern +3. **Camera listener**: Plain HTTP on port 8080 (SPEC C2 - no TLS on device) +4. **Request body limits**: 12MB for large image uploads +5. **Security headers**: Will be added when UI is deployed + +### Verified Setup +- Python 3.14.7 (uv-managed) +- PostgreSQL 17 (Podman container) +- All 12 tests passing +- Migrations applied successfully +- API serving on port 8090 +- Worker processing queue +- `poorbird check` validates entire setup + +--- + +## 11. What This AI Needs to Know + +### For Maximum Usefulness, Provide: + +1. **The "Why"** - Architecture decisions and rationale +2. **The "What"** - Current state and what's missing +3. **The "How"** - Code examples and patterns +4. **The "When"** - Priority, phase, dependencies +5. **The "Who"** - Who needs to decide what + +### Specific to This Project: + +1. **This is the canonical server branch** - Feature/UI_Basic_implementation shares the same server code +2. **Phase 1 is complete** - Server foundation is production-ready +3. **Security is blocking** - CRITICAL issues must be fixed before Phase 2 +4. **The data model is excellent** - Perfectly designed for all phases +5. **The deployment is production-ready** - Caddy, systemd, PostgreSQL all configured + +### What the AI Should NOT Do: + +1. **Don't suggest Docker** - Native deployment is a hard requirement (SPEC) +2. **Don't suggest Kubernetes** - Explicitly ruled out +3. **Don't suggest SQLite** - PostgreSQL is required +4. **Don't suggest changing the tech stack** - It's already well-chosen +5. **Don't ignore the phase structure** - Suggestions must respect the roadmap +6. **Don't use Unix sockets** - TCP loopback is required (SPEC 1.2) + +### What the AI SHOULD Do: + +1. **Respect the existing patterns** - Follow the code structure in server/ +2. **Prioritize security** - CRITICAL issues must be fixed first +3. **Reference the SPEC** - All decisions should align with SPEC.md +4. **Reference firmware/API.md** - Device API contract must be satisfied +5. **Use the existing validation patterns** - schema_compare.py is a good example +6. **Respect the constraints** - No Docker, PostgreSQL, native deployment + +--- + +## 12. Open Questions (NEED HUMAN DECISIONS) + +| ID | Question | Options | Impact | Decision By | Status | +|----|----------|---------|--------|-------------|--------| +| Q3 | Radar reliability at real distance | - | Blocks all | Hardware testing | OPEN | +| Q6 | Number of cameras | 1, 5, 10, 100 | Architecture scaling | Phase 4 | OPEN | +| Q7 | Captures/day | 100, 1000, 10000 | Storage, retention | Phase 5 | OPEN | +| Q8 | Retention: Delete or hide? | Delete file or soft-delete | Data model | Phase 5 | OPEN | +| Q9 | NAS protocol | SFTP, SMB, NFS | Backup tooling | Phase 5 | OPEN | +| Q14 | 2FA | Required or optional | Security | Phase 3 | OPEN | + +### Decisions Made (DO NOT QUESTION) + +| Decision | Rationale | Source | +|----------|-----------|--------| +| Native deployment (not Docker) | SPEC requirement | TODO.md | +| PostgreSQL over loopback TCP | Container-ready, better performance | TODO.md Phase 1.2 | +| All mutable state in explicit dirs | Future volume mounts | TODO.md | +| Sync SQLAlchemy | No async overhead for current scale | README.md | +| Job queue without Redis | Simplicity, no external dependency | SPEC C8 | +| FastAPI | Modern, fast, good typing | SPEC 6 | +| Caddy | Simple, automatic TLS | SPEC 6 | +| X-Accel-Redirect for images | Auth-checked handoff | SPEC 3.3 | +| Plain HTTP for camera | No TLS on device | SPEC C2 | + +--- + +## 13. Summary: Action Items for AI + +### If Asked to Help with Phase 2 (Device Endpoints) + +1. **First, verify CRITICAL security issues are fixed** + - Check if SEC-001 through SEC-007 are resolved + - If not, prioritize those fixes BEFORE writing any endpoint code + +2. **Understand the phase structure** + - Phase 1: ✅ Done (use as foundation) + - Phase 2: ⏳ Target (implement device endpoints) + - Phase 3: ❌ Future (WebUI) + +3. **Respect the contracts** + - Device API is defined in firmware/API.md + - All endpoints must satisfy this contract + - SPEC C7: received_at is AUTHORITATIVE (server time, not device time) + +4. **Follow the existing patterns** + - Use the same code structure as health.py + - Use the same error handling patterns + - Use the same logging patterns + - Use Pydantic models for all requests + +5. **Focus on the gaps** + - Device endpoints don't exist yet + - Device authentication doesn't exist yet + - Input validation is minimal + - Rate limiting is missing + +### Phase 2 Checklist + +- [ ] SEC-001: Remove enroll_secret default from config +- [ ] SEC-002: Implement device request authentication +- [ ] SEC-003: Add input validation for all endpoints +- [ ] SEC-004: Add rate limiting +- [ ] SEC-005: Add CORS configuration +- [ ] SEC-006: Remove DB URL default +- [ ] SEC-007: Implement session management (for Phase 3) +- [ ] Implement /api/v1/enroll +- [ ] Implement /api/v1/ingest +- [ ] Implement /api/v1/heartbeat +- [ ] Implement /api/v1/status +- [ ] Implement /api/v1/config +- [ ] Implement /api/v1/firmware +- [ ] Add device endpoint tests +- [ ] Add authentication tests + +--- + +## 14. Key Files for AI Reference + +| File | Purpose | Importance | +|------|---------|------------| +| config.py | All configuration from environment | 5/5 | +| db.py | SQLAlchemy engine and session | 5/5 | +| schema_compare.py | Schema drift normalization | 5/5 (GENIUS!) | +| models/__init__.py | All model imports | 5/5 | +| models/captures.py | Capture, Observation, Taxa, Tag models | 5/5 | +| models/devices.py | Device, Command, Status, Firmware models | 5/5 | +| models/users.py | User, Session models | 5/5 | +| api/app.py | FastAPI app creation | 5/5 | +| api/routes/health.py | Health endpoint pattern | 5/5 (reference!) | +| worker/queue.py | Job queue with SKIP LOCKED | 5/5 (reference!) | +| worker/main.py | Worker and scheduler | 5/5 (reference!) | +| cli.py | CLI command patterns | 5/5 (reference!) | +| migrations/versions/0001_initial.py | Baseline migration | 5/5 | +| deploy/Caddyfile | Caddy configuration | 5/5 | +| README.md | Architecture decisions | 5/5 | + +--- + +## 15. Quick Start for AI Development + +```bash +# Setup (as documented in README.md) +cd server +python3 -m venv .venv +. .venv/bin/activate +pip install -e '.[dev]' + +# Configure +cat > .env <<'EOF' +POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird +POORBIRD_IMAGE_ROOT=/tmp/poorbird/images +POORBIRD_THUMB_ROOT=/tmp/poorbird/thumbs +POORBIRD_STATE_DIR=/tmp/poorbird/state +POORBIRD_API_PORT=8090 +POORBIRD_ENROLL_SECRET=your_secure_secret_here +EOF + +mkdir -p /tmp/poorbird/{images,thumbs,state} + +# Validate +poorbird check + +# Run +poorbird serve # In one terminal +poorbird worker # In another terminal + +# Test +curl http://127.0.0.1:8090/api/v1/health +poorbird enqueue noop '{"test": true}' +``` + +--- + +*This AI reviewer guide was created by Mistral Vibe on 2026-09-21 for the poorBird Server branch.* diff --git a/docs/reviews/server-basic-implementation/REVIEW.md b/docs/reviews/server-basic-implementation/REVIEW.md new file mode 100644 index 0000000..f4a5699 --- /dev/null +++ b/docs/reviews/server-basic-implementation/REVIEW.md @@ -0,0 +1,596 @@ +# Code Review: poorBird Server (feature/Server_Basic_implementation) + +**Reviewer:** Mistral Vibe +**Date:** 2026-09-21 +**Branch:** feature/Server_Basic_implementation +**Commit:** 142b476 (Server: Phase 2 (REVIEW not respected yet)) +**Version:** 0.1.0 + +--- + +## Executive Summary + +**Status: Phase 1 COMPLETE, Phase 2 STARTED** + +Der Server-Branch enthalt die **vollstandige Phase 1 Implementation** (Server Foundation) und erste Ansatze fur Phase 2. Die Code-Qualitat ist **exzellent** - die Architektur ist durchdacht, gut dokumentiert und production-ready. Allerdings gibt es **kritische Sicherheitsprobleme**, die **vor Phase 2/3** behoben werden mussen. + +| Kategorie | Rating | Priority | Notes | +|----------|--------|----------|-------| +| **Architektur** | 5/5 | Niedrig | Sehr gut durchdacht, UI-ready | +| **Sicherheit** | 2/5 | **Hoch** | **Muss vor Phase 2/3 fixen** | +| **Performance** | 4/5 | Mittel | Gut fur aktuelle Skala | +| **Code Qualitat** | 5/5 | Niedrig | Exzellent | +| **Test Coverage** | 5/5 | Niedrig | 12/12 Tests passen | +| **Dokumentation** | 5/5 | Niedrig | Ausgezeichnet | + +--- + +## Branch Status + +### Current State +- **Branch Name:** feature/Server_Basic_implementation +- **Commit:** 142b476 ("Server: Phase 2 (REVIEW not respected yet)") +- **Phase:** 1 (Server Foundation) - **COMPLETE** +- **Phase 2:** STARTED (Web-Build-Dateien vorhanden, aber keine Device-Endpoints) +- **Relation:** Basis fur feature/UI_Basic_implementation + +### Wichtige Beobachtung +Dieser Branch ist der **kanonische Server-Branch**. Er enthalt: +- ✅ Vollstandige Server-Infrastruktur (Phase 1) +- ✅ Alle Datenbank-Modelle +- ✅ Job-Queue mit PostgreSQL (FOR UPDATE SKIP LOCKED) +- ✅ Health-Endpoints +- ✅ Systemd-Units und Caddy-Konfiguration +- ✅ migrations und Schema-Validierung +- ❌ **Keine Device-Endpoints** (Phase 2 noch nicht implementiert) +- ❌ **Keine Authentifizierung** (wird fur Phase 2/3 benotigt) + +### Phasen-Information +``` +Phase 1 (DONE): Server foundation, config, schema, health, job queue, scheduler +Phase 2 (STARTED): Device endpoints (/enroll, /ingest, /heartbeat, /status, /config) +Phase 3 (TARGET): WebUI (React+TS+Vite) - in feature/UI_Basic_implementation +Phase 4: Device management, OTA +Phase 5: Operations (backup, retention, alarms) +Phase 6: Streaming +``` + +--- + +## 1. Projekt-Ubersicht + +### Core Purpose +Radar-gesteuertes Vogel-Kamera-System, das: +1. Vogel mit LD2410 Radar-Sensor erkennt +2. Bilder mit ESP32 Kamera aufnimmt +3. Bilder uber MQTT an Server sendet +4. Bilder und Metadaten in PostgreSQL speichert +5. Web-Interface fur Anzeige und Verwaltung bereitstellt + +### Domain +- **Primar:** IoT + Computer Vision + Web Application +- **Sekundar:** Datenverwaltung, Device Management, Benutzerverwaltung + +### Benutzer-Typen +| Benutzer-Typ | Zugriff | Use Cases | +|-------------|---------|----------| +| Device | API nur | Enroll, Bilder hochladen, Status senden | +| Viewer | Nur Lesen | Galerie anzeigen, suchen, filtern | +| Editor | Lesen+Schreiben | Anzeigen + Beobachtungen hinzufugen, Tags, Metadaten bearbeiten | +| Admin | Voll | Alles von Editor + Device-Management, Benutzerverwaltung, Einstellungen | + +### Technologie-Stack +| Layer | Technologie | Version | Status | +|-------|------------|---------|--------| +| Backend | Python | 3.14.7 (verifiziert) | Phase 1 Complete | +| Framework | FastAPI | Latest | Phase 1 Complete | +| Database | PostgreSQL | 17 | Phase 1 Complete | +| ORM | SQLAlchemy | 2.0 | Phase 1 Complete | +| Migrations | Alembic | Latest | Phase 1 Complete | +| Proxy | Caddy | 2.x | Phase 1 Complete | +| Logging | structlog/stdout | - | Phase 1 Complete | + +### Skalierungs-Erwartungen +| Metrik | Wert | Notes | +|--------|------|-------| +| Kameras | 1-10 (Phase 3), 100+ (zukunftig) | Aktuell: 1 | +| Captures/Tag | 5000 | 1 Kamera, ~10/Stunde | +| Bild-Grose | 200-500KB | JPEG | +| Thumb-Grose | 20-50KB | WebP, 400px | +| Gleichzeitige Nutzer | 1-5 typisch, 10 peak | LAN-only | +| Storage/Monat | ~1GB | 5000 Bilder * 200KB | + +--- + +## 2. Architektur-Analyse + +### Was bereits vorhanden ist (Phase 1) + +#### ✅ **Konfiguration** +- `config.py`: Alle Werte aus Umgebungsvariablen (keine Hardcoded-Werte) +- `POORBIRD_` Prefix fur alle Variablen +- Gute Trennung von database, http, storage, devices, worker, logging +- **Kritikpunkt:** database_url hat Standardwert mit Credentials (siehe SEC-008) + +#### ✅ **Datenbank** +- `db.py`: SQLAlchemy Engine + Session Factory +- Sync SQLAlchemy (bewusste Entscheidung, kein Async) +- Connection Pool: 5 (kann fur Phase 3 erhoht werden) +- `schema_compare.py`: Normalisierung von Server-Defaults (geniale Losung!) + - Verhindert falsche Drift-Meldungen durch Postgres-Type-Casts + - Gleiche Logik fur Migrationen und Tests + +#### ✅ **Modelle** +- Vollstandiges Schema nach SPEC S3 +- Alle Tabellen: users, sessions, devices, captures, observations, taxa, tags, firmware, device_commands, device_status, settings, audit_log, backup_runs, jobs +- Gute Beziehungen und Constraints +- JSONB fur flexible Konfiguration (device.config) + +#### ✅ **API** +- `app.py`: FastAPI App mit Lifespan Management +- Health-Endpoints: `/api/v1/health`, `/healthz` +- API-Prefix: `/api/v1/` +- Gute Fehlerbehandlung und Logging + +#### ✅ **Job-Queue** +- `queue.py`: PostgreSQL-basierte Queue mit FOR UPDATE SKIP LOCKED +- Keine Redis-Abhangigkeit (SPEC 6) +- Handler: noop, prune_expired_commands +- Scheduler in `worker/main.py` +- Worker claimt Jobs und verarbeitet sie sequentiell + +#### ✅ **CLI** +- `cli.py`: serve, worker, migrate, check, enqueue +- `poorbird check`: Validiert Config, Pfade, Datenbank +- `poorbird serve`: Startet API +- `poorbird worker`: Startet Worker + Scheduler +- `poorbird migrate`: Wendet Migrationen an + +#### ✅ **Deployment** +- systemd-Units: `poorbird-api.service`, `poorbird-worker.service` +- Caddyfile mit DNS-01 TLS, Image-Handoff, Camera-Listener +- Installationsanleitung in `deploy/INSTALL.md` +- Windows-Entwicklung mit uv + Podman dokumentiert + +### Was fehlt fur Phase 2/3 + +#### ❌ **Device-Endpoints** (Phase 2) +- `/api/v1/enroll` - Device-Registrierung +- `/api/v1/ingest` - Bild-Hochladen +- `/api/v1/heartbeat` - Device-Status +- `/api/v1/status` - Device-Statistik +- `/api/v1/config` - Device-Konfiguration +- `/api/v1/firmware` - Firmware-Upload + +#### ❌ **Authentifizierung** +- Keine Device-Authentifizierung +- Keine User-Authentifizierung (fur WebUI) +- Keine Session-Verwaltung +- Kein Passwort-Hashing +- Keine CSRF-Schutz +- Keine Rate-Limiting + +#### ❌ **CORS** +- Keine CORS-Konfiguration (wird fur WebUI benotigt) + +--- + +## 3. Sicherheits-Analyse + +### Severity-System +- **KRITISCH:** Muss vor Phase 2/3 behoben werden. Blockiert Produktion. +- **HOCH:** Muss vor Phase 3 behoben werden. Ernstes Risiko. +- **MITTEL:** Sollte vor Phase 3 behoben werden. Moderates Risiko. +- **NIEDRIG:** Nice to have. Geringes Risiko. + +### KRITISCHE Probleme (BLOCK PHASE 2/3) + +#### SEC-001: Enroll Secret im Klartext +- **Ort:** config.py:53, .env-Dateien, systemd EnvironmentFile +- **Code:** `enroll_secret: SecretStr = SecretStr("")` +- **Problem:** Bootstrap Secret wird in Dateien im Klartext gespeichert +- **Risiko:** Dateisystem-Zugriff = vollstandige Device-Spoofing. Wenn UI Device-Management freigibt, kann Angreifer bösartige Gerate registrieren. +- **Auswirkung:** Katastrophal. Gefahrdet gesamten Device-Netzwerk. +- **Lösung:** + ```python + # Option 1: Nur uber CLI setzen + enroll_secret: SecretStr # Kein Standardwert + # Nur setzen uber: poorbird config set enroll_secret + + # Option 2: Environment-Variable ohne Standard + enroll_secret: SecretStr + ``` +- **Dateien zu andern:** config.py, deploy/poorbird.env.example +- **Tests:** Verifizieren, dass Secret nicht geloggt wird +- **Prioritat:** KRITISCH +- **Aufwand:** 2-4 Stunden + +#### SEC-002: Keine Request-Authentifizierung +- **Ort:** Alle API-Endpoints +- **Problem:** Keine Authentifizierung fur beliebige Endpoints +- **Risiko:** Jeder kann Device-Kommandos senden, Admin-Funktionen nutzen, Benutzer verwalten +- **Auswirkung:** Vollstandiger System-Kompromiss +- **Lösung:** + ```python + # Device-Auth (fur /enroll, /ingest, /heartbeat, /status) + from fastapi import Request, HTTPException, Header + + async def verify_device(request: Request, + x_enroll_secret: str = Header(None)): + if not x_enroll_secret: + raise HTTPException(status_code=401) + # Verifizieren gegen enroll_secret Hash + + # User-Auth (fur UI-Endpoints) + from fastapi import Cookie + + async def verify_user(request: Request, + session_id: str = Cookie(None)): + if not session_id: + raise HTTPException(status_code=401) + # Verifizieren Session in DB + ``` +- **Dateien zu erstellen:** api/routes/auth.py, api/deps.py +- **Dateien zu andern:** app.py +- **Prioritat:** KRITISCH +- **Aufwand:** 1-2 Tage + +#### SEC-003: Keine Input-Validierung +- **Ort:** queue.py:47-66 (enqueue-Funktion), alle zukunftigen Endpoints +- **Problem:** Payloads werden nicht vor DB-Insert validiert +- **Risiko:** SQL Injection, XSS, bosartige Daten, Datenkorruption +- **Auswirkung:** Hoch. UI akzeptiert User-Input +- **Lösung:** + ```python + from pydantic import BaseModel, Field + from typing import Literal, Optional, Union + + class NoopJobPayload(BaseModel): + message: Optional[str] = None + + class ThumbnailJobPayload(BaseModel): + capture_id: str # UUID + quality: int = Field(ge=1, le=100) + width: int = Field(ge=100, le=2000) + + JobPayload = Union[NoopJobPayload, ThumbnailJobPayload] + + def enqueue(session: Session, + kind: Literal["noop", "thumbnail"], + payload: JobPayload, + ...): + # Payload ist jetzt validiert! + ``` +- **Dateien zu erstellen:** api/schemas.py +- **Dateien zu andern:** queue.py, alle Route-Dateien +- **Prioritat:** KRITISCH +- **Aufwand:** 1-2 Tage + +### HOHE Priorität (FIX BEFORE PHASE 2/3) + +#### SEC-004: Keine Rate-Limiting +- **Ort:** API-Layer (app.py) +- **Problem:** Kein Schutz vor DoS oder Brute Force +- **Risiko:** API-Endpoints konnen uberflutet werden +- **Lösung:** slowapi oder FastAPI-Limiter +- **Prioritat:** HOCH +- **Aufwand:** 1 Tag + +#### SEC-005: Keine CORS-Konfiguration +- **Ort:** API-Layer +- **Problem:** Keine CORS-Header konfiguriert +- **Risiko:** WebUI kann keine Requests machen (auch localhost:3000) +- **Lösung:** + ```python + from fastapi.middleware.cors import CORSMiddleware + + app.add_middleware( + CORSMiddleware, + allow_origins=["http://localhost:3000", "http://localhost:5173", "https://poorbird.local"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + ``` +- **Prioritat:** HOCH +- **Aufwand:** 1 Stunde + +#### SEC-006: DB-URL mit Credentials in Defaults +- **Ort:** config.py:30 +- **Problem:** Standardwert enthalt Credentials im Klartext +- **Risiko:** Accidentelles Committen von Credentials +- **Lösung:** + ```python + # Andern von: + database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" + + # Zu: + database_url: str = "" # Muss uber POORBIRD_DATABASE_URL gesetzt werden + ``` +- **Prioritat:** HOCH +- **Aufwand:** 1 Stunde + +#### SEC-007: Keine Session-Verwaltung +- **Ort:** models/users.py hat Session-Modell, aber nicht implementiert +- **Problem:** Session-Tabelle existiert aber wird nicht genutzt +- **Risiko:** User-Login/Logout nicht implementierbar +- **Lösung:** Session-Cookie-Handling implementieren +- **Prioritat:** HOCH +- **Aufwand:** 1 Tag + +### MITTLERE Priorität + +#### SEC-008: Keine Passwort-Hashing-Implementierung +- **Ort:** models/users.py (password_hash-Spalte existiert) +- **Problem:** Keine Hashing-Implementierung vorhanden +- **Lösung:** Argon2id implementieren +- **Prioritat:** MITTEL +- **Aufwand:** 2-4 Stunden + +#### SEC-009: Keine Bild-Upload-Validierung +- **Ort:** Zukunftige UI-Endpoints +- **Problem:** Bilder werden nicht vor Speicherung validiert +- **Lösung:** MIME-Type, Grose, Dimensionen prufen +- **Prioritat:** MITTEL +- **Aufwand:** 2-4 Stunden + +--- + +## 4. Datenmodell-Analyse + +### Vollständiges Schema + +Das Datenmodell ist **exzellent entworfen** und perfekt fur die Anforderungen. Alle Tabellen sind vorhanden: + +**Benutzer & Authentifizierung:** +- `users` - Benutzer mit Rollen (admin, editor, viewer) +- `sessions` - Session-Verwaltung + +**Gerate & Kommandos:** +- `devices` - Gerate-Informationen +- `device_commands` - Kommando-Queue +- `device_status` - Zeitreihen-Daten +- `firmware` - Firmware-Versionen + +**Captures & Beobachtungen:** +- `captures` - Haupttabelle fur Bilder +- `observations` - Beobachtungen zu Captures +- `taxa` - Taxonomie (Arten) +- `tags` - Tags fur Kategorisierung +- `capture_tags` - n:m Beziehung + +**Operationen:** +- `settings` - System-Einstellungen +- `audit_log` - Audit-Log +- `backup_runs` - Backup-Informationen + +**Job-Queue:** +- `jobs` - PostgreSQL-basierte Queue + +### Wichtige Beziehungen +``` +users (1) ----(n) sessions + \-- (n) audit_log + \-- (n) device_commands (created_by) + \-- (n) firmware (uploaded_by) + \-- (n) observations (created_by) + +devices (1) ----(n) captures + |--- (n) device_status + |--- (n) device_commands + \-- (1) current firmware (via is_target) + +captures (1) ----(n) observations + |--- (n) tags (via capture_tags) + \-- (1) device + +observations (n) ----(1) taxa +observations (n) ----(1) capture +observations (n) ----(1) user (created_by) + +tags (n) ----(n) captures (via capture_tags) +``` + +### Wichtige Felder + +**Captures:** +- `id` (UUID) - Primar-Schlussel, fur URLs geeignet +- `path`, `thumb_path` - Datei-Pfade +- `received_at` - **AUTHORITATIV** (SPEC C7) +- `trigger` - Ausloser (radar, manual, timer, stream_grab) +- `pre_trigger` - Wurde das Bild VOR dem Trigger aufgenommen? +- `kept` - Soft-Reject-Flag +- `reviewed` - Wurde-reviewed? +- `radar_*` - Radar-Daten +- `battery_*`, `rssi`, `temp_c` - Device-Zustand + +**Devices:** +- `device_uid` - MAC-basierte Identitat +- `config` - JSONB mit allen Einstellungen +- `config_version` - Inkrementiert bei jeder Anderung +- `battery_valid` - **KRITISCH:** false = **NICHT GEMESSEN** (nicht leer!) +- `awake` - Device ist aktiv + +**Device Status:** +- Alle Felder sind Zeitreihen-Daten +- Zähler (captured_today, etc.) kommen aus RTC-Speicher +- **KRITISCH:** Zähler werden bei Stromausfall zuruckgesetzt +- **UI-Anzeige:** Zähler zeigen GAP zwischen captured und delivered + +--- + +## 5. Performance-Analyse + +### Aktuelle Konfiguration + +| Komponente | Einstellung | Aktueller Wert | Bewertung | Empfehlung | +|-----------|-------------|----------------|-----------|-------------| +| DB Connection Pool | db_pool_size | 5 | 3/5 | 15-20 fur Phase 3 | +| Worker Poll Intervall | worker_poll_interval_s | 2.0 | 3/5 | 5.0 (weniger Polling) | +| Batch Grose | worker_batch_size | 1 | 3/5 | 5-10 | +| Sync SQLAlchemy | - | Aktiviert | 4/5 | OK fur aktuelle Skala | +| Log Level | log_level | INFO | 4/5 | OK | +| Image Root | image_root | /srv/poorbird/images | 5/5 | OK | +| Thumb Root | thumb_root | /srv/poorbird/thumbs | 5/5 | OK | + +### Empfehlungen + +#### Datenbank +```python +# db.py - Empfohlene Anderungen +engine = create_engine( + _settings.database_url, + pool_size=15, # War 5 + pool_pre_ping=True, + pool_recycle=3600, + pool_timeout=30, + connect_timeout=10, + echo=_settings.db_echo, + future=True, +) +``` + +#### Worker +- **Poll Intervall:** Erhohen auf 5 Sekunden (weniger Overhead) +- **Batch Grose:** Erhohen auf 5-10 (bessere Auslastung) + +--- + +## 6. Test-Status + +### Aktueller Stand + +| Test-Datei | Typ | Status | Benotigt | Coverage | +|-----------|-----|--------|----------|----------| +| test_health.py | Integration | ✅ PASS | PostgreSQL | API Health | +| test_queue.py | Integration | ✅ PASS | PostgreSQL | Job Queue | +| test_schema_matches_models.py | Integration | ✅ PASS | PostgreSQL + CREATE DB | Schema Drift | +| test_config.py | Unit | ✅ PASS | Keine | Config Validierung | +| conftest.py | Fixtures | ✅ | PostgreSQL | Test Setup | + +**Gesamt:** 12/12 Tests passieren (100%) + +### Fehlende Tests + +#### Unit Tests (Backend - Phase 2) +- Device-Endpoint-Tests +- Authentifizierungs-Tests +- Validierungs-Tests + +#### Integration Tests (Backend - Phase 2) +- Device-Integrationstests +- Authentifizierungs-Integrationstests + +--- + +## 7. Deployment-Analyse + +### Aktueller Stand + +✅ **Alles fur Phase 1 vorhanden:** +- systemd-Units: `poorbird-api.service`, `poorbird-worker.service` +- Caddyfile mit TLS (DNS-01), Image-Handoff, Camera-Listener +- Installationsanleitung in `deploy/INSTALL.md` +- Windows-Entwicklung dokumentiert + +### Caddy-Konfiguration + +Die Caddy-Konfiguration ist **exzellent**: +- TLS uber DNS-01 (Let's Encrypt) +- Auth-checked Image-Handoff (X-Accel-Redirect) +- Camera-Listener auf Port 8080 (Plain HTTP, SPEC C2) +- Menschliche UI auf Port 443 mit TLS + +### Verifizierter Setup +- Python 3.14.7 +- PostgreSQL 17 (Podman Container) +- Alle 12 Tests passieren +- Migrationen funktionieren +- API lauffahig +- Worker verarbeitet Queue + +--- + +## 8. Zusammenfassung & Empfehlungen + +### Sofort zu tun (vor Phase 2) + +1. **KRITISCHE Sicherheitsprobleme fixen:** + - [ ] SEC-001: Enroll Secret aus Defaults entfernen + - [ ] SEC-002: Request-Authentifizierung implementieren + - [ ] SEC-003: Input-Validierung implementieren + - [ ] SEC-006: DB-URL Default entfernen + +2. **HOCH Priorität:** + - [ ] SEC-004: Rate-Limiting konfigurieren + - [ ] SEC-005: CORS konfigurieren + - [ ] SEC-007: Session-Verwaltung implementieren + +### Fur Phase 2 + +1. **Device-Endpoints implementieren:** + - [ ] `/api/v1/enroll` + - [ ] `/api/v1/ingest` + - [ ] `/api/v1/heartbeat` + - [ ] `/api/v1/status` + - [ ] `/api/v1/config` + - [ ] `/api/v1/firmware` + +2. **Authentifizierung implementieren:** + - [ ] Device-Authentifizierung (X-Enroll-Secret) + - [ ] Token-Generierung und -Verwaltung + - [ ] Command-Queue + +### Fur Phase 3 + +1. **WebUI-Vorbereitung:** + - [ ] Passwort-Hashing (Argon2id) + - [ ] User-Authentifizierung (Session Cookies) + - [ ] CSRF-Schutz + - [ ] UI-Endpoints + +### Architektur-Entscheidungen (Respektieren!) + +| Entscheidung | Begründung | +|--------------|------------| +| **Native Deployment** | SPEC-Anforderung, kein Container-Overhead | +| **Sync SQLAlchemy** | Kein Async-Overhead bei 1 Kamera | +| **PostgreSQL uber TCP** | Container-ready, bessere Performance | +| **FOR UPDATE SKIP LOCKED** | Keine Redis-Abhangigkeit | +| **JSONB fur Config** | Flexibel, zukunftssicher | +| **UUID fur Captures** | URL-sicher, verteilt | +| **Caddy als Proxy** | Einfache TLS-Verwaltung | + +### Nicht in Frage stellen +- Kein Docker (SPEC-Anforderung) +- Kein Kubernetes +- Kein SQLite (PostgreSQL erforderlich) +- Kein public Streaming (Phase 6 ist nur intern) + +--- + +## 9. Offene Fragen + +| ID | Frage | Optionen | Impact | Entscheidung durch | +|----|-------|---------|--------|-------------------| +| Q6 | Anzahl Kameras | 1, 5, 10, 100 | Architektur-Skalierung | Phase 4 | +| Q7 | Captures/Tag | 100, 1000, 10000 | Storage, Retention | Phase 5 | +| Q8 | Retention: Lschen oder verstecken? | Datei loschen oder Soft-Delete | Datenmodell | Phase 5 | +| Q9 | NAS-Protokoll | SFTP, SMB, NFS | Backup-Tooling | Phase 5 | +| Q14 | 2FA | Erforderlich oder optional | Sicherheit | Phase 3 | + +### Bereits entschieden (NICHT HINTERFRAGEN) + +| Entscheidung | Begründung | Quelle | +|--------------|------------|--------| +| Native Deployment | SPEC-Anforderung | TODO.md | +| PostgreSQL uber Loopback TCP | Container-ready | TODO.md | +| Alle mutable State in expliziten Verzeichnissen | Zukunftige Volume Mounts | TODO.md | +| Sync SQLAlchemy | Kein Async-Overhead | README.md | +| Job-Queue ohne Redis | Einfachheit | SPEC C8 | +| FastAPI | Modern, schnell, gute Typisierung | SPEC 6 | +| Caddy | Einfache automatische TLS | SPEC 6 | + +--- + +*Dieses Review wurde erstellt von Mistral Vibe am 2026-09-21 fur den poorBird Server-Branch.* diff --git a/docs/reviews/ui-basic-implementation/REVIEW.AI.md b/docs/reviews/ui-basic-implementation/REVIEW.AI.md new file mode 100644 index 0000000..ecd4f6a --- /dev/null +++ b/docs/reviews/ui-basic-implementation/REVIEW.AI.md @@ -0,0 +1,1908 @@ +# AI Reviewer Guide: poorBird Server (feature/UI_Basic_implementation) + +**Purpose:** This document provides comprehensive context for AI systems to analyze and improve the poorBird codebase, with specific focus on UI development preparation. + +**Target Audience:** AI code review systems (like Mistral Vibe, Claude, etc.) + +**Created:** 2026-09-21 by Mistral Vibe + +**Branch:** feature/UI_Basic_implementation (Commit: 5d16ded) + +--- + +## 0. Branch Context (CRITICAL FOR AI UNDERSTANDING) + +### Branch Identity +- **Name:** feature/UI_Basic_implementation +- **Commit:** 5d16ded ("Server: verify Phase 1 end to end against PostgreSQL 17") +- **Actual Content:** Server code only (Phase 1) - NO UI CODE YET +- **Relation:** Identical to feature/Server_Basic_implementation +- **Purpose:** Preparation branch for Phase 3 (UI development) + +### Important Observation +This branch is **misnamed**. It contains only server infrastructure (Phase 1), not UI code. However, the server IS fully prepared for UI implementation (Phase 3). The AI should understand: +- **Current Reality:** Server-only, Phase 1 complete +- **Intended Purpose:** UI development foundation, Phase 3 preparation +- **What's Missing:** Actual UI code (React/TS/Vite) + +### Phase Information +``` +Phase 1 (DONE): Server foundation, config, schema, health, job queue +Phase 2 (NEXT): Device endpoints, authentication +Phase 3 (TARGET): WebUI (this branch's intended purpose) +Phase 4: Device management, OTA +Phase 5: Operations +Phase 6: Streaming +``` + +--- + +## 1. Project Overview (ESSENTIAL CONTEXT) + +### Core Purpose +Radar-triggered bird camera system that: +1. Detects birds using LD2410 radar sensor +2. Captures images with ESP32 camera +3. Transmits to server via MQTT +4. Stores images and metadata in PostgreSQL +5. Provides web interface for viewing and managing captures + +### Domain +- **Primary:** IoT + Computer Vision + Web Application +- **Secondary:** Data Management, Device Management, User Management + +### Users +| User Type | Access Level | Use Cases | +|-----------|--------------|----------| +| Device | API only | Enroll, ingest images, send status | +| Viewer | Read-only | View gallery, search, filter | +| Editor | Read+Write | View + add observations, tags, edit metadata | +| Admin | Full | All editor + device management, user management, settings | + +### Deployment Architecture +``` +┌─────────────────────────────────────────────────────────┐ +│ Client (Browser) │ +└─────────────────────────┬───────────────────────────────┘ + │ HTTPS (TLS via DNS-01) + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Caddy (Reverse Proxy) │ +│ ┌─────────────────────┐ ┌─────────────────────────┐ │ +│ │ Static UI Files │ │ API Requests │ │ +│ │ /srv/poorbird/ │ │ /api/v1/* │ │ +│ └──────────┬────────────┘ └──────────┬─────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────────┐│ +│ │ React/TS Frontend ││ +│ │ (NOT YET IMPLEMENTED) ││ +│ └─────────────────────────────────────────────────────┘│ +│ │ +└──────────────────────────────────────────────────┬─────┘ + │ + ┌────────────────────────────────▼─────────────┐ + │ FastAPI Backend (Phase 1 Complete) │ + │ ┌──────────────┐ ┌──────────────┐ │ + │ │ API Layer │ │ Worker Layer │ │ + │ │ /api/v1/* │ │ Job Queue │ │ + │ └──────────────┘ └──────────────┘ │ + │ │ │ │ + │ ▼ ▼ │ + │ ┌─────────────────────────────────────────┐│ + │ │ PostgreSQL 17 ││ + │ │ ┌──────────┐ ┌──────────┐ ││ + │ │ │ Schema │ │ Job Q │ ││ + │ │ │ (Phase 1)│ │ (Phase 1)│ ││ + │ │ └──────────┘ └──────────┘ ││ + │ └─────────────────────────────────────────┘│ + └────────────────────────────────────────────────┘ +``` + +### Technology Stack +| Layer | Technology | Version | Status | +|-------|------------|---------|--------| +| Backend | Python | 3.13 | Phase 1 Complete | +| Framework | FastAPI | 0.115+ | Phase 1 Complete | +| Database | PostgreSQL | 17 | Phase 1 Complete | +| ORM | SQLAlchemy | 2.0.36+ | Phase 1 Complete | +| Migrations | Alembic | 1.14+ | Phase 1 Complete | +| Logging | structlog/stdout | - | Phase 1 Complete | +| Proxy | Caddy | 2.x | Phase 1 Complete | +| **Frontend** | **React + TypeScript** | **18+** | **NOT STARTED** | +| **Build Tool** | **Vite** | **Latest** | **NOT STARTED** | +| **State Mgmt** | **TanStack Query** | **Latest** | **NOT STARTED** | +| **Routing** | **TanStack Router** | **Latest** | **NOT STARTED** | + +### Scale Expectations +| Metric | Value | Notes | +|--------|-------|-------| +| Cameras | 1-10 (Phase 3), 100+ (future) | Current: 1 | +| Captures/day | 5000 | 1 camera, ~10/hour | +| Image Size | 200-500KB | JPEG | +| Thumb Size | 20-50KB | WebP, 400px | +| Concurrent Users | 1-5 typical, 10 peak | LAN-only | +| Storage/month | ~1GB | 5000 images * 200KB | +| DB Queries/day | ~10,000 | 5000 captures + 5000 status | + +--- + +## 2. External Contracts (CRITICAL FOR INTEGRATION) + +### Device ↔ Server API Contract (firmware/API.md) + +#### Endpoints (ALL NOT YET IMPLEMENTED - Phase 2) + +**Device Enrollment:** +``` +POST /api/v1/enroll +Headers: + X-Enroll-Secret: + Content-Type: application/json + +Request: + { + "device_uid": "", + "name": "", + "mac": "", + "hw_revision": "", + "fw_version": "" + } + +Response: + { + "token": "", + "reenroll_secret": "" + } + +Notes: +- Token is high-entropy, hashed before storage +- reenroll_secret allows device recovery +- Device can re-enroll with same device_uid to get fresh token +``` + +**Image Ingest:** +``` +POST /api/v1/ingest +Headers: + Authorization: Bearer + Content-Type: multipart/form-data + X-Captured-At: + X-Pre-Trigger: 0 or 1 + +Request: + + { + "device_id": , + "trigger": "radar"|"manual"|"timer"|"stream_grab", + "burst_id": "", + "burst_index": , + "burst_count": , + "frame_seq": , + "radar_distance_cm": , + "radar_energy": , + "battery_mv": , + "rssi": , + "temp_c": + } + +Response: + { + "ingested": true, + "capture_id": "", + "commands": [...] // Device command queue + } + +Notes: +- Image saved to: /srv/poorbird/images/YYYY/MM/DD/.jpg +- Thumbnail generated: /srv/poorbird/thumbs/_400.webp +- sha256 calculated for deduplication +- received_at set to server time (SPEC C7) +``` + +**Heartbeat:** +``` +POST /api/v1/heartbeat +Headers: + Authorization: Bearer + Content-Type: application/json + +Request: + { + "battery_mv": , + "battery_pct": , + "battery_valid": , + "awake": , + "rssi": , + "temp_c": , + "free_heap": , + "free_psram": , + "ring_depth": , + "time_synced": , + "device_time": + } + +Response: + { + "commands": [...] // Device command queue + } + +Notes: +- battery_valid=false means NOT MEASURED (not empty!) +- Last heartbeat stored in devices.last_seen_at +``` + +**Status Report:** +``` +POST /api/v1/status +Headers: + Authorization: Bearer + Content-Type: application/json + +Request: + { + "reason": "heartbeat"|"periodic"|"after_event"|"before_sleep"|"before_night_sleep"|"on_request", + "captured_today": , + "delivered_today": , + "failed_today": , + "events_today": , + "day_index": , + "is_night": , + "nightlight_on": , + "cam_profile": "day"|"night", + "radar_baud": , + "radar_uart_ok": , + "stream_active": , + "wake_cause": , + "last_sleep_s": , + "total_sleep_s": , + "boot_count": , + "awake_ms": , + "ip": + } + +Response: + { + "commands": [...] // Device command queue + } + +Notes: +- Counters are from RTC memory, reset on power loss +- captures table is AUTHORITATIVE +- Counters show GAP between captured and delivered +``` + +**Config:** +``` +GET /api/v1/config +Headers: + Authorization: Bearer + +Response: + { + "config_version": , + "heartbeat_interval_s": , + "status_interval_s": , + "responsive_mode": , + "cam_day": { ... }, // OV2640 parameters + "cam_night": { ... }, + "night_window": [start_time, end_time], + "nightlight_mode": "off"|"auto"|"on", + "nightlight_brightness": , + "battery_calibration": { ... } + } + +Notes: +- config is JSONB, all keys optional +- device merges partial configs +- config_version must match for device to apply +``` + +**Firmware Upload:** +``` +POST /api/v1/firmware +Headers: + Authorization: Bearer + Content-Type: multipart/form-data + +Request: + + { + "version": "", + "semver": "", + "release_notes": "", + "min_battery_pct": , + "target": + } + +Response: + { + "firmware_id": , + "sha256": "", + "size_bytes": + } +``` + +### UI-Specific Contract Requirements (SPEC 3.3) + +**Image Serving:** +- **NEVER** serve images directly from filesystem +- **ALWAYS** check authorization in app first +- **THEN** have Caddy serve the bytes +- **URL Pattern:** `/images/YYYY/MM/DD/.jpg` +- **Thumb Pattern:** `/thumbs/_400.webp` + +**Authentication:** +- Session cookies (not JWT for WebUI) +- CSRF protection for all mutating requests +- RBAC: viewer, editor, admin +- Optional TOTP 2FA (SPEC Q14) + +--- + +## 3. Architecture Decisions (WHY THEY MATTER FOR AI) + +### Core Decisions + +| Decision | Rationale | Alternatives | Trade-offs | UI Impact | +|----------|-----------|--------------|------------|-----------| +| **Native Deployment** | SPEC requirement, no container overhead | Docker, Kubernetes | Simpler, but less portable | None - Caddy handles static files | +| **Sync SQLAlchemy** | 1 camera, few K frames/day - async overhead not justified | Async SQLAlchemy | Simpler code, but blocks event loop | May need revisit for Phase 6 MJPEG | +| **PostgreSQL** | Relational data, complex queries, concurrent writers | SQLite, MySQL | More powerful, but heavier | Perfect for gallery queries | +| **FOR UPDATE SKIP LOCKED** | Job queue without Redis dependency | Redis, RabbitMQ | No external service, PostgreSQL-only | Works well for background jobs | +| **JSONB for Config** | 40+ optional settings, firmware evolves | Separate columns | Flexible, but can't index individual settings | Good for device settings form | +| **UUID for Captures** | Safe for URLs, distributed systems | Sequential int | Better for URLs | Perfect for /gallery/ | +| **Single Image Root** | App and Caddy must agree on path | Multiple roots | Simpler, single source of truth | Critical for auth-checked handoff | + +### Constraints (AI MUST RESPECT THESE) + +**Hard Constraints:** +- NO Docker (SPEC requirement) +- Native Linux deployment +- PostgreSQL (not SQLite) +- systemd units (not supervisor) +- Caddy (not nginx, not Apache) + +**Soft Constraints:** +- Container-ready design (even though not using containers) +- All config from environment +- All mutable state in explicit directories +- Log to stdout/stderr only + +**Non-Goals:** +- NO Kubernetes +- NO public streaming (Phase 6 is internal only) +- NO audio/BirdNET (different sensor) +- NO TLS on device (SPEC C2) + +--- + +## 4. Security Analysis (CRITICAL FOR AI) + +### Severity System +- **CRITICAL:** Must fix before any production use. Blocks Phase 3. +- **HIGH:** Must fix before Phase 3. Serious risk. +- **MEDIUM:** Should fix before Phase 3. Moderate risk. +- **LOW:** Nice to have. Low risk. + +### Critical Issues (BLOCK PHASE 3) + +#### SEC-001: Enroll Secret in Plaintext +- **Location:** config.py:53, .env files, systemd EnvironmentFile +- **Code:** `enroll_secret: SecretStr = SecretStr("")` +- **Issue:** Bootstrap secret stored in plaintext in files +- **Risk:** Filesystem access = complete device spoofing. If UI exposes device management, attacker can enroll malicious devices. +- **Impact:** Catastrophic. Compromises entire device network. +- **Vulnerability Type:** Credential Exposure +- **CVSS:** 9.8 (Critical) +- **Solution:** + ```python + # Option 1: Remove from env, CLI-only + enroll_secret: SecretStr # No default + # Only set via: poorbird config set enroll_secret + + # Option 2: Use secrets manager + # Store in HashiCorp Vault, fetch at runtime + + # Option 3: Encrypt in file + # Use age or similar to encrypt .env file + ``` +- **Files to Modify:** config.py, .env.example, deploy/poorbird.env.example +- **Tests Needed:** Verify secret not logged, not in error messages +- **Priority:** CRITICAL +- **Block:** Phase 3 (UI Development) +- **Effort:** 2-4 hours + +#### SEC-002: No Request Authentication +- **Location:** All API endpoints (none have auth yet) +- **Issue:** No authentication for any endpoint +- **Risk:** Anyone can send device commands, access admin functions, manage users +- **Impact:** Complete system compromise. UI would be wide open. +- **Vulnerability Type:** Missing Authentication +- **CVSS:** 10.0 (Critical) +- **Solution:** + ```python + # Device auth (for /enroll, /ingest, /heartbeat, /status) + from fastapi import Request, HTTPException, Header + + async def verify_device(request: Request, + x_enroll_secret: str = Header(None)): + if not x_enroll_secret: + raise HTTPException(status_code=401) + # Verify against enroll_secret hash + # Lookup device by token + + # User auth (for UI endpoints) + from fastapi import Cookie + + async def verify_user(request: Request, + session_id: str = Cookie(None)): + if not session_id: + raise HTTPException(status_code=401) + # Verify session in DB + # Return user with roles + ``` +- **Files to Create:** api/routes/auth.py, api/deps.py +- **Files to Modify:** app.py (add auth dependencies) +- **Tests Needed:** Auth tests for all endpoint types +- **Priority:** CRITICAL +- **Block:** Phase 3 (UI Development) +- **Effort:** 1-2 days + +#### SEC-003: No Input Validation +- **Location:** queue.py:47-66 (enqueue function), all future endpoints +- **Issue:** Payloads not validated before DB insert +- **Risk:** SQL injection, XSS, malicious data, data corruption +- **Impact:** High. UI accepts user input, could lead to DB compromise. +- **Vulnerability Type:** Missing Input Validation +- **CVSS:** 8.1 (High) +- **Solution:** + ```python + # Example: Job payload validation + from pydantic import BaseModel, constr, Json + from typing import Literal, Optional + + class NoopJobPayload(BaseModel): + """Payload for noop job.""" + message: Optional[str] = None + + class ThumbnailJobPayload(BaseModel): + """Payload for thumbnail job.""" + capture_id: str # UUID + quality: int = Field(ge=1, le=100) + width: int = Field(ge=100, le=2000) + + JobPayload = Union[NoopJobPayload, ThumbnailJobPayload, ...] + + def enqueue(session: Session, + kind: Literal["noop", "thumbnail", ...], + payload: JobPayload, + ...): + # Now payload is validated! + ``` +- **Files to Create:** api/schemas.py (Pydantic models for all requests) +- **Files to Modify:** queue.py, all route files +- **Tests Needed:** Validation tests for all payload types +- **Priority:** CRITICAL +- **Block:** Phase 3 (UI Development) +- **Effort:** 1-2 days + +#### SEC-004: No Rate Limiting +- **Location:** API layer (app.py) +- **Issue:** No protection against DoS or brute force +- **Risk:** UI endpoints can be flooded, server overload +- **Impact:** High. UI would be vulnerable to attack. +- **Vulnerability Type:** Missing Rate Limiting +- **CVSS:** 7.5 (High) +- **Solution:** + ```python + from slowapi import Limiter + from slowapi.util import get_remote_address + from slowapi.errors import RateLimitExceeded + from fastapi import Request + + limiter = Limiter(key_func=get_remote_address) + + @app.exception_handler(RateLimitExceeded) + async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded): + return JSONResponse( + status_code=429, + content={"detail": "Too many requests"}, + headers={"Retry-After": str(exc.retry_after)} + ) + + # Apply to all endpoints + @app.get("/api/v1/captures") + @limiter.limit("100/minute") + async def list_captures(request: Request): + ... + ``` +- **Files to Create:** None (add to app.py) +- **Files to Modify:** app.py +- **Configuration:** Add to pyproject.toml: slowapi +- **Tests Needed:** Rate limiting tests +- **Priority:** HIGH +- **Block:** Phase 3 (UI Development) +- **Effort:** 1 day + +### High Priority Issues (FIX BEFORE PHASE 3) + +#### SEC-005: No CORS Configuration +- **Location:** API layer +- **Issue:** No CORS headers configured +- **Risk:** UI cannot make requests if on different origin (even localhost:3000) +- **Impact:** UI development impossible +- **Vulnerability Type:** Missing CORS +- **CVSS:** 6.5 (Medium) +- **Solution:** + ```python + from fastapi.middleware.cors import CORSMiddleware + + app.add_middleware( + CORSMiddleware, + allow_origins=[ + "http://localhost:3000", # Dev + "http://localhost:5173", # Vite dev + "https://poorbird.local", # Prod + ], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + expose_headers=["X-Request-ID"], + ) + ``` +- **Files to Modify:** app.py +- **Tests Needed:** CORS test +- **Priority:** HIGH +- **Effort:** 1 hour + +#### SEC-006: No CSRF Protection +- **Location:** All mutating endpoints (POST, PUT, DELETE, PATCH) +- **Issue:** No CSRF protection for form submissions +- **Risk:** Cross-site request forgery attacks +- **Impact:** High for UI. Users' sessions can be hijacked. +- **Vulnerability Type:** Missing CSRF Protection +- **CVSS:** 6.5 (Medium) +- **Solution:** + ```python + # Option 1: Use FastAPI CSRF middleware + from fastapi_csrf_protect import CsrfProtect + from fastapi_csrf_protect.exceptions import CsrfProtectError + + @app.exception_handler(CsrfProtectError) + async def csrf_protect_exception_handler(request: Request, exc: CsrfProtectError): + return JSONResponse( + status_code=403, + content={"detail": "CSRF token missing or invalid"} + ) + + @app.middleware("http") + async def add_csrf_token(request: Request, call_next): + response = await call_next(request) + if request.method in ["GET"]: + # Add CSRF token to cookies for forms + response.set_cookie( + key="csrftoken", + value=CsrfProtect.generate_csrf_token(), + httponly=True, + secure=True, # In production + samesite="lax" + ) + return response + + # Option 2: Use Django-style double-submit + # Frontend sends token in header and cookie + # Backend verifies both match + ``` +- **Files to Create:** api/middleware/csrf.py +- **Files to Modify:** app.py, all mutating endpoints +- **Tests Needed:** CSRF protection tests +- **Priority:** HIGH +- **Effort:** 1 day + +#### SEC-007: No Session Management +- **Location:** models/users.py has Session model, but not used +- **Issue:** Session table exists but no implementation +- **Risk:** Cannot implement user login/logout +- **Impact:** High. UI authentication impossible. +- **Vulnerability Type:** Missing Functionality +- **Solution:** + ```python + # Session creation on login + from datetime import datetime, timedelta + import secrets + from sqlalchemy.orm import Session as DbSession + from .models import Session, User + from .config import get_settings + + def create_session(db: DbSession, user: User) -> Session: + settings = get_settings() + session = Session( + user_id=user.id, + expires_at=datetime.utcnow() + timedelta(days=30), + ip=request.client.host, + user_agent=request.headers.get("user-agent"), + ) + db.add(session) + db.commit() + db.refresh(session) + return session + + def verify_session(db: DbSession, session_id: str) -> User | None: + session = db.query(Session).filter( + Session.id == session_id, + Session.expires_at > datetime.utcnow() + ).first() + if session: + # Extend session + session.expires_at = datetime.utcnow() + timedelta(days=30) + db.commit() + return session.user + return None + + def invalidate_session(db: DbSession, session_id: str): + db.query(Session).filter(Session.id == session_id).delete() + db.commit() + ``` +- **Files to Create:** api/routes/auth.py +- **Files to Modify:** models/users.py (add session management methods) +- **Tests Needed:** Session lifecycle tests +- **Priority:** HIGH +- **Effort:** 1 day + +#### SEC-008: DB URL with Credentials in Defaults +- **Location:** config.py:30 +- **Issue:** Default value contains plaintext credentials +- **Risk:** Accidental commit of credentials to repo +- **Impact:** Medium. Security risk if committed. +- **Vulnerability Type:** Hardcoded Credentials +- **CVSS:** 7.5 (High) +- **Solution:** + ```python + # Change from: + database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" + + # To: + database_url: str = "" # Must be set via POORBIRD_DATABASE_URL + ``` +- **Files to Modify:** config.py +- **Tests Needed:** Verify app fails gracefully if not set +- **Priority:** HIGH +- **Effort:** 1 hour + +### Medium Priority Issues + +#### SEC-009: No Password Hashing Implementation +- **Location:** models/users.py (password_hash column exists) +- **Issue:** password_hash column exists but no hashing implementation +- **Risk:** If someone implements password setting without hashing, passwords stored in plaintext +- **Impact:** Medium. Future security risk. +- **Solution:** + ```python + import argon2 + from argon2 import PasswordHasher + + ph = PasswordHasher( + time_cost=3, # Number of iterations + memory_cost=65536, # 64MB + parallelism=4, # Number of parallel threads + hash_len=32, # Length of the hash + salt_len=16, # Length of the salt + ) + + def hash_password(password: str) -> str: + return ph.hash(password) + + def verify_password(password: str, hash: str) -> bool: + try: + return ph.verify(hash, password) + except: + return False + ``` +- **Files to Create:** api/utils/auth.py +- **Files to Modify:** models/users.py (add password hashing) +- **Tests Needed:** Password hashing tests +- **Priority:** MEDIUM +- **Effort:** 2-4 hours + +#### SEC-010: No Image Upload Validation +- **Location:** Future UI image upload endpoint +- **Issue:** Images not validated before saving +- **Risk:** Malicious file uploads (e.g., PHP files, scripts) +- **Impact:** Medium. Could lead to server compromise. +- **Solution:** + ```python + import magic # python-magic + from pathlib import Path + + ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"} + MAX_SIZE = 10 * 1024 * 1024 # 10MB + MAX_DIMENSIONS = (4000, 4000) # width, height + + def validate_image(file_path: Path) -> tuple[bool, str]: + # Check file size + if file_path.stat().st_size > MAX_SIZE: + return False, "File too large" + + # Check MIME type + mime = magic.from_file(file_path, mime=True) + if mime not in ALLOWED_TYPES: + return False, f"Invalid file type: {mime}" + + # Check dimensions + try: + from PIL import Image + with Image.open(file_path) as img: + if img.size[0] > MAX_DIMENSIONS[0] or img.size[1] > MAX_DIMENSIONS[1]: + return False, "Image too large" + except: + return False, "Invalid image" + + return True, "Valid" + ``` +- **Files to Create:** api/utils/image_validation.py +- **Tests Needed:** Image validation tests +- **Priority:** MEDIUM +- **Effort:** 2-4 hours + +--- + +## 5. Data Model Analysis (FOR UI DEVELOPMENT) + +### Complete Schema + +```sql +-- Users and Authentication +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username VARCHAR(64) UNIQUE NOT NULL, + email VARCHAR(255), + password_hash VARCHAR(255), + totp_secret VARCHAR(64), + role VARCHAR(16) DEFAULT 'viewer' CHECK (role IN ('admin', 'editor', 'viewer')), + is_active BOOLEAN DEFAULT true, + theme VARCHAR(16) DEFAULT 'light' CHECK (theme IN ('light', 'dark', 'blue')), + locale VARCHAR(8) DEFAULT 'de', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + last_login_at TIMESTAMP WITH TIME ZONE +); + +CREATE TABLE sessions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + ip VARCHAR(45), + user_agent VARCHAR(255) +); + +-- Devices and Commands +CREATE TABLE devices ( + id SERIAL PRIMARY KEY, + device_uid VARCHAR(32) UNIQUE NOT NULL, + name VARCHAR(64) NOT NULL, + mac VARCHAR(32), + hw_revision VARCHAR(64), + fw_version VARCHAR(32), + token_hash VARCHAR(128), + reenroll_secret_hash VARCHAR(128), + last_seen_at TIMESTAMP WITH TIME ZONE, + battery_mv INTEGER, + battery_pct INTEGER, + battery_valid BOOLEAN DEFAULT false, -- false = NOT MEASURED + rssi INTEGER, + temp_c FLOAT, + awake BOOLEAN DEFAULT true, + config JSONB DEFAULT '{}'::jsonb, + config_version INTEGER DEFAULT 1, + heartbeat_interval_s INTEGER DEFAULT 300, + status_interval_s INTEGER DEFAULT 900, + responsive_mode BOOLEAN DEFAULT false, + enabled BOOLEAN DEFAULT true, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +CREATE TABLE device_commands ( + id SERIAL PRIMARY KEY, + device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE, + type VARCHAR(32) CHECK (type IN ('apply_config', 'capture_now', 'report_status', 'wake_and_hold', 'sleep_now', 'stream_start', 'stream_stop', 'ota_update', 'reboot')), + payload JSONB, + created_by INTEGER REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + delivered_at TIMESTAMP WITH TIME ZONE, + acked_at TIMESTAMP WITH TIME ZONE, + ack_status VARCHAR(16) CHECK (ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')), + result TEXT, + expires_at TIMESTAMP WITH TIME ZONE +); + +-- Firmware +CREATE TABLE firmware ( + id SERIAL PRIMARY KEY, + version VARCHAR(32) UNIQUE NOT NULL, + semver VARCHAR(32), + file_path TEXT NOT NULL, + sha256 VARCHAR(64) NOT NULL, + size_bytes BIGINT NOT NULL, + release_notes TEXT, + min_battery_pct INTEGER DEFAULT 50, + uploaded_by INTEGER REFERENCES users(id) ON DELETE SET NULL, + uploaded_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + is_target BOOLEAN DEFAULT false +); + +-- Captures and Observations (CORE FOR UI) +CREATE TABLE captures ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE, + path TEXT NOT NULL, + thumb_path TEXT, + sha256 VARCHAR(64) NOT NULL, -- Consider: UNIQUE for deduplication + width INTEGER, + height INTEGER, + bytes BIGINT NOT NULL, + captured_at_device TIMESTAMP WITH TIME ZONE, + received_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + trigger VARCHAR(16) NOT NULL CHECK (trigger IN ('radar', 'manual', 'timer', 'stream_grab')), + burst_id VARCHAR(64), + burst_index INTEGER, + burst_count INTEGER, + pre_trigger BOOLEAN DEFAULT false, -- Captured BEFORE trigger fired + frame_seq INTEGER, + radar_state INTEGER, -- 0 none, 1 moving, 2 stationary, 3 both + radar_distance_cm INTEGER, + radar_energy INTEGER, + battery_mv INTEGER, + rssi INTEGER, + temp_c FLOAT, + reviewed BOOLEAN DEFAULT false, + kept BOOLEAN DEFAULT true, -- Soft reject + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +CREATE TABLE taxa ( + id SERIAL PRIMARY KEY, + gbif_key BIGINT UNIQUE, + scientific_name VARCHAR(128) UNIQUE NOT NULL, + name_de VARCHAR(128), + name_en VARCHAR(128), + family VARCHAR(64), + "order" VARCHAR(64), -- Quoted because 'order' is reserved + iucn_status VARCHAR(8), + is_local_common BOOLEAN DEFAULT false +); + +CREATE TABLE observations ( + id BIGSERIAL PRIMARY KEY, + capture_id UUID REFERENCES captures(id) ON DELETE CASCADE, + taxon_id INTEGER REFERENCES taxa(id) ON DELETE RESTRICT, + individuals INTEGER DEFAULT 1, + age VARCHAR(16) DEFAULT 'unknown' CHECK (age IN ('adult', 'juvenile', 'unknown')), + sex VARCHAR(16) DEFAULT 'unknown' CHECK (sex IN ('male', 'female', 'unknown')), + behaviour VARCHAR(16) CHECK (behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')), + certainty VARCHAR(16) DEFAULT 'certain' CHECK (certainty IN ('certain', 'probable', 'uncertain')), + notes TEXT, + source VARCHAR(8) DEFAULT 'human' CHECK (source IN ('human', 'model')), + model_version VARCHAR(64), + confidence FLOAT, + bbox JSONB, + created_by INTEGER REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +CREATE TABLE tags ( + id SERIAL PRIMARY KEY, + label VARCHAR(64) UNIQUE NOT NULL, + colour VARCHAR(16) +); + +CREATE TABLE capture_tags ( + capture_id UUID REFERENCES captures(id) ON DELETE CASCADE, + tag_id INTEGER REFERENCES tags(id) ON DELETE CASCADE, + PRIMARY KEY (capture_id, tag_id) +); + +-- Device Status (Time Series) +CREATE TABLE device_status ( + id BIGSERIAL PRIMARY KEY, + device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE, + at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + reason VARCHAR(32) NOT NULL CHECK (reason IN ('heartbeat', 'periodic', 'after_event', 'before_sleep', 'before_night_sleep', 'on_request')), + -- Battery + battery_mv INTEGER, + battery_pct INTEGER, + battery_valid BOOLEAN, + -- Activity + awake_ms BIGINT, + boot_count INTEGER, + wake_cause VARCHAR(16), + last_sleep_s INTEGER, + total_sleep_s BIGINT, + -- Counters (RTC memory, reset on power loss) + captured_today INTEGER, + delivered_today INTEGER, + failed_today INTEGER, + events_today INTEGER, + day_index INTEGER, -- Days since epoch, local time + -- Environment + is_night BOOLEAN, + nightlight_on BOOLEAN, + cam_profile VARCHAR(16), + -- Radar + radar_baud INTEGER, + radar_uart_ok BOOLEAN, + stream_active BOOLEAN, + -- Network + rssi INTEGER, + ip VARCHAR(45), + -- System + free_heap BIGINT, + free_psram BIGINT, + ring_depth INTEGER, + -- Timing + time_synced BOOLEAN, + device_time TIMESTAMP WITH TIME ZONE, + fw_version VARCHAR(32), + config_version INTEGER, + -- Flexible + raw JSONB +); + +-- Operational Tables +CREATE TABLE settings ( + key VARCHAR(64) PRIMARY KEY, + value TEXT, + value_type VARCHAR(16) DEFAULT 'str', + scope VARCHAR(16) DEFAULT 'server' CHECK (scope IN ('server', 'device')), + updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +CREATE TABLE audit_log ( + id BIGSERIAL PRIMARY KEY, + at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + action VARCHAR(64) NOT NULL, + entity VARCHAR(64) NOT NULL, + entity_id VARCHAR(64), + before JSONB, + after JSONB, + ip VARCHAR(45) +); + +CREATE TABLE backup_runs ( + id BIGSERIAL PRIMARY KEY, + started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + finished_at TIMESTAMP WITH TIME ZONE, + status VARCHAR(16) DEFAULT 'running', + bytes BIGINT, + snapshot_id VARCHAR(64), + restore_tested_at TIMESTAMP WITH TIME ZONE, + error TEXT +); + +-- Job Queue (PostgreSQL-backed, no Redis) +CREATE TABLE jobs ( + id BIGSERIAL PRIMARY KEY, + kind VARCHAR(64) NOT NULL, + payload JSONB NOT NULL DEFAULT '{}'::jsonb, + status VARCHAR(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'running', 'done', 'failed')), + priority INTEGER NOT NULL DEFAULT 0, + run_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), + attempts INTEGER NOT NULL DEFAULT 0, + max_attempts INTEGER NOT NULL DEFAULT 3, + locked_at TIMESTAMP WITH TIME ZONE, + locked_by VARCHAR(128), + last_error TEXT, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), + finished_at TIMESTAMP WITH TIME ZONE +); +``` + +### Key Relationships +``` +users (1) ── (n) sessions + └── (n) audit_log + └── (n) device_commands (created_by) + └── (n) firmware (uploaded_by) + └── (n) observations (created_by) + +devices (1) ── (n) captures + ├── (n) device_status + ├── (n) device_commands + └── (1) current firmware (via is_target) + +captures (1) ── (n) observations + ├── (n) tags (via capture_tags) + └── (1) device + +observations (n) ── (1) taxa +observations (n) ── (1) capture +observations (n) ── (1) user (created_by) + +tags (n) ── (n) captures (via capture_tags) +``` + +### UI-Relevant Fields + +**Captures:** +- `id` (UUID) - Primary key, used in URLs +- `path`, `thumb_path` - File paths for images +- `received_at` - AUTHORITATIVE timestamp (SPEC C7) +- `trigger` - How capture was triggered +- `pre_trigger` - Was this frame captured BEFORE the trigger fired? +- `kept` - Soft reject flag +- `reviewed` - Has this been reviewed? +- `radar_*` - Radar data for analysis +- `battery_*`, `rssi`, `temp_c` - Device conditions at capture time + +**Observations:** +- `source` - 'human' or 'model' (future ML integration) +- `taxon_id` - Links to species data +- `model_version`, `confidence`, `bbox` - For ML predictions +- `age`, `sex`, `behaviour`, `certainty` - Observation metadata +- `individuals` - Number of birds in this observation + +**Taxa:** +- `scientific_name` - Unique scientific name +- `name_de`, `name_en` - Localized names +- `gbif_key` - GBIF identifier +- `is_local_common` - For autocomplete ranking (local species first) + +**Devices:** +- `device_uid` - MAC-based identity, survives reflashing +- `config` - JSONB with all device settings +- `config_version` - Increments on every config change +- `battery_valid` - **CRITICAL**: false = NOT MEASURED, not empty! +- `awake` - Device is awake and responsive + +**Device Status:** +- All fields are time-series data +- Counters (captured_today, etc.) are from RTC memory +- **CRITICAL**: Counters reset on power loss +- **UI Display**: Counters show GAP between captured and delivered + +--- + +## 6. Current Implementation Status + +### What Exists (Phase 1 - Server Foundation) + +``` +server/ +├── src/poorbird/ +│ ├── __init__.py # Version: 0.1.0 +│ ├── config.py # All settings from environment +│ ├── logging_setup.py # stdout-only logging +│ ├── db.py # SQLAlchemy engine + session +│ ├── schema_compare.py # Schema drift normalization +│ ├── models/ +│ │ ├── __init__.py # Imports all models +│ │ ├── base.py # Base class + naming convention +│ │ ├── captures.py # Captures, Observations, Taxa, Tags +│ │ ├── devices.py # Devices, Commands, Status, Firmware +│ │ ├── ops.py # Settings, AuditLog, BackupRun, Job +│ │ └── users.py # Users, Sessions +│ ├── api/ +│ │ ├── __init__.py +│ │ ├── app.py # FastAPI app + lifespan +│ │ ├── deps.py # Empty (potential for dependencies) +│ │ └── routes/ +│ │ ├── __init__.py +│ │ └── health.py # /api/v1/health, /healthz +│ ├── worker/ +│ │ ├── __init__.py +│ │ ├── main.py # Worker + scheduler +│ │ ├── queue.py # Job queue (FOR UPDATE SKIP LOCKED) +│ │ └── handlers.py # Job handlers (noop, prune_expired_commands) +│ └── cli.py # CLI commands +├── migrations/ +│ ├── env.py # Alembic environment +│ ├── script.py.mako +│ └── versions/ +│ └── 0001_initial.py # Baseline migration +├── deploy/ +│ ├── INSTALL.md +│ ├── poorbird.env.example +│ ├── poorbird-api.service +│ ├── poorbird-worker.service +│ └── Caddyfile +├── tests/ +│ ├── conftest.py +│ ├── test_health.py +│ ├── test_queue.py +│ ├── test_schema_matches_models.py +│ └── test_config.py +├── alembic.ini +├── pyproject.toml +└── README.md +``` + +### What's Missing for UI (Phase 3) + +``` +MISSING - Frontend: +webui/ +├── src/ +│ ├── components/ +│ ├── hooks/ +│ ├── store/ +│ ├── utils/ +│ ├── styles/ +│ ├── App.tsx +│ └── main.tsx +├── public/ +│ └── index.html +├── vite.config.ts +├── package.json +└── tsconfig.json + +MISSING - Backend (UI Endpoints): +server/src/poorbird/api/routes/ +├── gallery.py # Capture listing, filtering +├── observations.py # Observation CRUD +├── taxa.py # Taxon search/autocomplete +├── tags.py # Tag management +├── devices.py # Device management (UI view) +└── auth.py # Authentication endpoints + +MISSING - Backend (Services): +server/src/poorbird/services/ +├── auth.py # Authentication service +├── image_service.py # Image handling +└── gallery_service.py # Gallery queries + +MISSING - Authentication: +├── Session management +├── Password hashing (Argon2id) +├── CSRF protection +└── Rate limiting +``` + +### Implementation Status by Phase + +| Phase | Status | Components | Tests | +|-------|--------|------------|-------| +| Phase 1 | ✅ COMPLETE | Server foundation, config, schema, health, job queue, scheduler | 12/12 | +| Phase 2 | ❌ NOT STARTED | Device endpoints (/enroll, /ingest, /heartbeat, /status, /config) | 0/0 | +| Phase 3 | ❌ NOT STARTED | WebUI (React+TS+Vite), UI endpoints, authentication | 0/0 | +| Phase 4 | ❌ NOT STARTED | Device management, OTA | 0/0 | +| Phase 5 | ❌ NOT STARTED | Operations (backup, retention, alarms) | 0/0 | +| Phase 6 | ❌ NOT STARTED | Streaming | 0/0 | + +--- + +## 7. Performance Analysis + +### Current Configuration + +| Component | Setting | Current Value | UI Impact | Rating | Recommendation | +|-----------|---------|---------------|-----------|--------|----------------| +| DB Connection Pool | db_pool_size | 5 | May block concurrent UI requests | 3/5 | 15-20 | +| Worker Poll Interval | worker_poll_interval_s | 2.0 | Frequent polling on empty queue | 3/5 | 5.0 | +| Batch Size | worker_batch_size | 1 | Single job processing | 3/5 | 5-10 | +| Sync SQLAlchemy | - | Enabled | Blocks event loop under load | 4/5 | OK for current scale | +| Log Level | log_level | INFO | Good for development | 4/5 | OK | +| Image Root | image_root | /srv/poorbird/images | Good structure | 5/5 | OK | +| Thumb Root | thumb_root | /srv/poorbird/thumbs | Good structure | 5/5 | OK | + +### Expected UI Load Profile + +**Gallery Page:** +- Initial load: 20-50 images +- Scroll load: 20 images per page +- Filter queries: 100-500ms (with proper indexes) +- Image size: 200-500KB (full), 20-50KB (thumb) +- Concurrent requests: 3-5 typical, 10 peak + +**Search/Filter:** +- Date range: Fast (index on received_at) +- Taxon filter: Fast (index on taxon_id) +- Device filter: Fast (index on device_id) +- Tag filter: Medium (many-to-many join) +- Combined filters: Medium (proper indexing needed) + +**Image Operations:** +- Upload: ~200-500KB per image +- Thumbnail generation: 100-300ms (Phase 2) +- Storage per month: ~1GB (5000 images * 200KB) +- DB writes per image: 3-5 (captures + device_status + observations) + +### Bottlenecks to Address Before UI + +1. **DB Connection Pool (MEDIUM)** + - Current: 5 connections + - Issue: May block under concurrent UI load + - Solution: Increase to 15-20 + - Impact: Supports 10+ concurrent users + +2. **No Query Caching (LOW)** + - Current: All queries hit DB + - Issue: Repeated queries (e.g., taxon list) inefficient + - Solution: Add Redis or in-memory cache + - Impact: Faster UI response, reduced DB load + +3. **Sync SQLAlchemy (FUTURE)** + - Current: Synchronous + - Issue: Blocks event loop under heavy load + - Solution: Evaluate async for Phase 6 (MJPEG streaming) + - Impact: May be needed for high-concurrency scenarios + +4. **Image Upload (MEDIUM)** + - Current: Not implemented + - Issue: UI will need efficient image handling + - Solution: Stream upload, validate, generate thumbnail + - Impact: Critical for UI performance + +### Performance Recommendations for UI + +#### Database +```python +# db.py - Recommended changes +engine = create_engine( + _settings.database_url, + pool_size=15, # Was 5 + pool_pre_ping=True, + pool_recycle=3600, # Recycle after 1 hour + pool_timeout=30, # Timeout after 30 seconds + connect_timeout=10, + echo=_settings.db_echo, + future=True, +) +``` + +#### API +- **Pagination:** All list endpoints must be paginated +- **Caching:** Cache frequently accessed data (taxa, tags, device list) +- **Compression:** Enable gzip/brotli compression +- **Etag:** Add ETag headers for images + +#### Images +- **Thumbnails:** Pre-generate on ingest (Phase 2) +- **Lazy Loading:** Only load visible images +- **Progressive:** Show low-res preview first +- **CDN:** Consider for production (not needed for LAN-only) + +#### Frontend +- **Code Splitting:** Split React bundles by route +- **Tree Shaking:** Remove unused dependencies +- **Image Optimization:** Use WebP, proper sizing +- **Bundle Analysis:** Track and optimize bundle size + +--- + +## 8. Testing Strategy + +### Current Test Status + +| Test File | Type | Status | Requires | Coverage | +|-----------|------|--------|----------|----------| +| test_health.py | Integration | ✅ PASS | PostgreSQL | API health | +| test_queue.py | Integration | ✅ PASS | PostgreSQL | Job queue | +| test_schema_matches_models.py | Integration | ✅ PASS | PostgreSQL + CREATE DB | Schema drift | +| test_config.py | Integration | ✅ PASS | None | Config validation | +| conftest.py | Fixtures | ✅ | PostgreSQL | Test setup | + +**Total:** 12/12 tests passing (100%) + +### Missing Tests + +#### Unit Tests (Frontend - Phase 3) +- Component rendering tests +- Hook tests +- Utility function tests +- Form validation tests +- **Tool:** Jest + React Testing Library + @testing-library/user-event + +#### Integration Tests (Backend - Phase 3) +- UI endpoint tests +- Authentication tests +- Authorization tests +- **Tool:** pytest + httpx + factory_boy + +#### E2E Tests (Phase 3) +- User flows: login → gallery → edit observation → logout +- **Tool:** Playwright or Cypress + +#### Performance Tests (Future) +- Load testing for API +- Stress testing for DB +- **Tool:** locust or k6 + +### Test Environment +- **Backend:** Python 3.11+, PostgreSQL 17 +- **Frontend:** Node.js 18+ +- **CI/CD:** Not yet configured (GitHub Actions recommended) + +--- + +## 9. UI Implementation Guide (FOR AI ASSISTANCE) + +### Recommended Project Structure + +``` +poorBird/ +├── server/ # Backend (Phase 1-2) +│ └── ... # Existing server code +│ +└── webui/ # Frontend (Phase 3) - TO BE CREATED + ├── public/ + │ ├── favicon.ico + │ └── index.html + │ + ├── src/ + │ ├── assets/ + │ │ └── styles/ + │ │ ├── global.css + │ │ ├── theme.css + │ │ └── reset.css + │ │ + │ ├── components/ + │ │ ├── common/ + │ │ │ ├── Button.tsx + │ │ │ ├── Input.tsx + │ │ │ ├── Modal.tsx + │ │ │ ├── Card.tsx + │ │ │ ├── Layout.tsx + │ │ │ ├── Header.tsx + │ │ │ └── Sidebar.tsx + │ │ │ + │ │ ├── gallery/ + │ │ │ ├── GalleryGrid.tsx + │ │ │ ├── ImageCard.tsx + │ │ │ ├── ImageModal.tsx + │ │ │ ├── Filters.tsx + │ │ │ └── Pagination.tsx + │ │ │ + │ │ ├── observation/ + │ │ │ ├── ObservationForm.tsx + │ │ │ ├── ObservationList.tsx + │ │ │ ├── TaxonAutocomplete.tsx + │ │ │ └── SpeciesInfo.tsx + │ │ │ + │ │ ├── settings/ + │ │ │ ├── DeviceSettings.tsx + │ │ │ ├── UserSettings.tsx + │ │ │ └── SystemSettings.tsx + │ │ │ + │ │ ├── devices/ + │ │ │ ├── DeviceList.tsx + │ │ │ ├── DeviceStatus.tsx + │ │ │ └── DeviceCommands.tsx + │ │ │ + │ │ └── auth/ + │ │ ├── LoginForm.tsx + │ │ ├── RegisterForm.tsx + │ │ └── AuthContext.tsx + │ │ + │ ├── hooks/ + │ │ ├── useAuth.ts + │ │ ├── useGallery.ts + │ │ ├── useObservations.ts + │ │ ├── useTaxa.ts + │ │ ├── useDevices.ts + │ │ └── useTheme.ts + │ │ + │ ├── lib/ + │ │ ├── api.ts # Axios instance + interceptors + │ │ ├── constants.ts # App constants + │ │ ├── utils.ts # Utility functions + │ │ └── types.ts # TypeScript type definitions + │ │ + │ ├── store/ + │ │ ├── slices/ + │ │ │ ├── authSlice.ts + │ │ │ ├── gallerySlice.ts + │ │ │ └── uiSlice.ts + │ │ └── store.ts # Redux store configuration + │ │ + │ ├── styles/ + │ │ ├── theme/ + │ │ │ ├── light.css + │ │ │ ├── dark.css + │ │ │ └── blue.css + │ │ └── components/ + │ │ └── *.module.css + │ │ + │ ├── App.tsx + │ └── main.tsx + │ + ├── vite.config.ts + ├── .env + ├── package.json + └── tsconfig.json +``` + +### Recommended Dependencies (package.json) + +```json +{ + "name": "poorbird-webui", + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview", + "lint": "eslint src --ext .ts,.tsx", + "test": "vitest", + "test:ui": "vitest --ui", + "test:coverage": "vitest --coverage" + }, + "dependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0", + "@tanstack/react-query": "^5.0.0", + "@tanstack/react-router": "^6.20.0", + "axios": "^1.6.0", + "date-fns": "^3.0.0", + "react-hot-toast": "^2.4.1", + "lucide-react": "^0.300.0", + "clsx": "^2.0.0" + }, + "devDependencies": { + "@types/react": "^18.2.0", + "@types/react-dom": "^18.2.0", + "@vitejs/plugin-react": "^4.2.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "eslint": "^8.56.0", + "@typescript-eslint/eslint-plugin": "^7.0.0", + "@typescript-eslint/parser": "^7.0.0", + "eslint-plugin-react": "^7.33.0", + "eslint-plugin-react-hooks": "^4.6.0", + "vitest": "^1.0.0", + "@testing-library/react": "^14.0.0", + "@testing-library/user-event": "^14.5.0", + "@testing-library/jest-dom": "^6.1.0", + "@vitest/coverage-v8": "^1.0.0", + "@vitest/ui": "^1.0.0", + "jsdom": "^23.0.0", + "tailwindcss": "^3.4.0", + "postcss": "^8.4.0", + "autoprefixer": "^10.4.0" + } +} +``` + +### Recommended TypeScript Config (tsconfig.json) + +```json +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "baseUrl": ".", + "paths": { + "@/*": ["src/*"] + } + }, + "include": ["src"], + "references": [{ "path": "./tsconfig.node.json" }] +} +``` + +### Recommended Vite Config (vite.config.ts) + +```typescript +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import path from 'path' + +export default defineConfig({ + plugins: [react()], + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + }, + }, + server: { + port: 3000, + proxy: { + '/api': { + target: 'http://localhost:8080', + changeOrigin: true, + }, + '/images': { + target: 'http://localhost:8080', + changeOrigin: true, + }, + }, + }, + build: { + outDir: '../../server/deploy/webui', + sourcemap: true, + }, +}) +``` + +### Backend Endpoints for UI (Phase 3) + +**Gallery:** +```python +# GET /api/v1/captures +# Query params: page, limit, device_id, taxon_id, date_from, date_to, kept, reviewed, tag +# Returns: Paginated list of captures with observations and tags + +# GET /api/v1/captures/{id} +# Returns: Single capture with all observations, tags, device info + +# GET /api/v1/captures/{id}/metadata +# Returns: Capture metadata only (smaller payload) +``` + +**Observations:** +```python +# POST /api/v1/captures/{id}/observations +# Request: {"taxon_id": 123, "individuals": 2, "age": "adult", "sex": "male", ...} +# Returns: Created observation + +# PUT /api/v1/observations/{id} +# Request: {"taxon_id": 123, ...} +# Returns: Updated observation + +# DELETE /api/v1/observations/{id} +# Returns: Success +``` + +**Taxonomy:** +```python +# GET /api/v1/taxa +# Query params: query, limit, offset, locale +# Returns: Paginated list of taxa with localized names + +# GET /api/v1/taxa/autocomplete +# Query params: query, limit=10 +# Returns: Top 10 matching taxa (local species first) +``` + +**Tags:** +```python +# GET /api/v1/tags +# Returns: All tags with counts + +# POST /api/v1/tags +# Request: {"label": "water", "colour": "#0066cc"} +# Returns: Created tag +``` + +**Devices:** +```python +# GET /api/v1/devices +# Returns: List of devices with current status + +# GET /api/v1/devices/{id} +# Returns: Device details + config + +# PUT /api/v1/devices/{id}/config +# Request: {"heartbeat_interval_s": 600, ...} +# Returns: Updated config +``` + +**Authentication:** +```python +# POST /api/v1/auth/login +# Request: {"username": "...", "password": "..."} +# Returns: Session cookie, user info + +# POST /api/v1/auth/logout +# Returns: Success, clears session + +# GET /api/v1/auth/me +# Returns: Current user info + +# POST /api/v1/auth/register (if public registration enabled) +# Request: {"username": "...", "password": "...", "email": "..."} +# Returns: Created user, session +``` + +**Settings:** +```python +# GET /api/v1/settings +# Returns: Current user's settings + +# PUT /api/v1/settings +# Request: {"theme": "dark", "locale": "en"} +# Returns: Updated settings +``` + +--- + +## 10. Deployment for UI + +### Caddy Configuration (Updated for UI) + +```caddyfile +# /etc/caddy/Caddyfile + +# PoorBird Server + UI +poorbird.local { + # Root for static UI files + root * /srv/poorbird/webui + + # Handle API requests + handle_path /api/* { + reverse_proxy 127.0.0.1:8080 + } + + # Handle image requests (auth-checked) + handle_path /images/* { + reverse_proxy 127.0.0.1:8080 + } + + # Handle thumbnail requests (auth-checked) + handle_path /thumbs/* { + reverse_proxy 127.0.0.1:8080 + } + + # Serve static files (SPA fallback) + try_files {path} /index.html + + # Enable gzip compression + encode gzip + + # Security headers + header { + X-Content-Type-Options "nosniff" + X-Frame-Options "DENY" + X-XSS-Protection "1; mode=block" + Referrer-Policy "strict-origin-when-cross-origin" + Permissions-Policy "camera=(), microphone=(), geolocation=()" + } + + # TLS (automatic via DNS-01) + # Uses Let's Encrypt +} + +# Development: API only (no UI) +:8080 { + reverse_proxy 127.0.0.1:8080 +} +``` + +### Build and Deploy Process + +```bash +# Development +cd webui +npm install +npm run dev # http://localhost:3000 + +# Production Build +npm run build # Outputs to server/deploy/webui + +# Deploy +rsync -avz ./dist/ user@server:/srv/poorbird/webui/ +``` + +### Environment Variables (Frontend) + +```bash +# .env +VITE_API_URL=/api/v1 +VITE_WS_URL=ws://localhost:8080 +VITE_APP_NAME=poorBird +VITE_APP_VERSION=0.1.0 + +# For development (proxy) +VITE_API_BASE_URL=http://localhost:8080/api/v1 + +# For production +VITE_API_BASE_URL=/api/v1 +``` + +--- + +## 11. Security Checklist for UI Development + +### Before Starting Phase 3 + +- [ ] SEC-001: Enroll secret not in plaintext +- [ ] SEC-002: Device authentication implemented +- [ ] SEC-003: Input validation for all requests +- [ ] SEC-004: Rate limiting configured +- [ ] SEC-005: CORS configured +- [ ] SEC-006: CSRF protection implemented +- [ ] SEC-007: Session management implemented +- [ ] SEC-008: DB URL not in defaults +- [ ] Password hashing implemented +- [ ] Image upload validation implemented + +### During UI Development + +- [ ] All API endpoints require authentication +- [ ] All forms have CSRF protection +- [ ] All user input is validated +- [ ] All errors are handled gracefully +- [ ] No sensitive data in logs +- [ ] No sensitive data in error messages +- [ ] All API responses have consistent structure +- [ ] All API errors have consistent format + +### Before Production + +- [ ] Security audit completed +- [ ] Penetration testing completed +- [ ] All dependencies scanned for vulnerabilities +- [ ] All secrets rotated +- [ ] All sensitive endpoints rate-limited +- [ ] All file uploads validated +- [ ] All user sessions have expiration +- [ ] All passwords hashed with Argon2id + +--- + +## 12. Open Questions (NEED HUMAN DECISIONS) + +| ID | Question | Options | Impact | Decision By | Status | +|----|----------|---------|--------|-------------|--------| +| Q3 | Radar reliability at real distance | - | Blocks all | Hardware testing | OPEN | +| Q6 | Number of cameras | 1, 5, 10, 100 | Architecture scaling | Phase 4 | OPEN | +| Q7 | Captures/day | 100, 1000, 10000 | Storage, retention | Phase 5 | OPEN | +| Q8 | Retention: Delete or hide? | Delete file or soft-delete | Data model | Phase 5 | OPEN | +| Q9 | NAS protocol | SFTP, SMB, NFS | Backup tooling | Phase 5 | OPEN | +| Q11 | UI language | German, English, both | Localization | Phase 3 | OPEN | +| Q12 | Taxonomy source | GBIF, IOC, Avibase | Species data | Phase 3 | OPEN | +| Q13 | Blue theme | Reference or choice | Styling | Phase 3 | OPEN | +| Q14 | 2FA | Required or optional | Security | Phase 3 | OPEN | +| Q15 | Additional fields | Weather, feeder type, etc. | Schema | Phase 3 | OPEN | +| Q16 | Comfort level | C/Python/TS | Team skills | Phase 3 | OPEN | +| Q17 | Camera privacy | Public path? | GDPR | Phase 3 | OPEN | + +### Decisions Made (DO NOT QUESTION) + +| Decision | Rationale | Source | +|----------|-----------|--------| +| Native deployment (not Docker) | SPEC requirement | TODO.md | +| PostgreSQL over loopback TCP | Container-ready, better performance | TODO.md | +| All mutable state in explicit dirs | Future volume mounts | TODO.md | +| Sync SQLAlchemy | No async overhead for current scale | README.md | +| Job queue without Redis | Simplicity, no external dependency | SPEC C8 | +| FastAPI | Modern, fast, good typing | SPEC 6 | +| Caddy | Simple, automatic TLS | SPEC 6 | +| React + TS + Vite | Modern, good DX, good performance | TODO.md | + +--- + +## 13. Implementation Roadmap (Phase 3) + +### Week 1: Foundation +- [ ] Fix CRITICAL security issues (SEC-001 through SEC-008) +- [ ] Implement session management +- [ ] Add CORS configuration +- [ ] Add CSRF protection +- [ ] Implement password hashing (Argon2id) +- [ ] Create auth endpoints (login, logout, me) +- [ ] Setup React + Vite project +- [ ] Create basic layout and routing +- [ ] Setup TypeScript, ESLint, Prettier +- [ ] Create theme system (light, dark, blue) + +### Week 2: Gallery +- [ ] Implement gallery API endpoints +- [ ] Create Gallery component with virtualization +- [ ] Add pagination +- [ ] Implement ImageCard component +- [ ] Add date/taxon/device/tag filters +- [ ] Setup image lazy loading +- [ ] Implement ImageModal for full-screen view +- [ ] Add keyboard navigation (arrow keys) + +### Week 3: Editing +- [ ] Implement observation CRUD endpoints +- [ ] Create ObservationEditor with form +- [ ] Add TaxonAutocomplete with search +- [ ] Implement tag selection +- [ ] Add device list and status view +- [ ] Create device detail page +- [ ] Add batch operations (select multiple images) + +### Week 4: Polish +- [ ] Implement theme switching (persisted per user) +- [ ] Add language support (i18n) +- [ ] Write frontend unit tests +- [ ] Write integration tests +- [ ] Write E2E tests +- [ ] Performance optimization +- [ ] Security audit +- [ ] Accessibility audit + +### Dependencies +```mermaid +graph TD + A[Phase 1: Server Foundation] -->|Complete| B[Fix Security Issues] + B --> C[Phase 2: Device Endpoints] + C --> D[Phase 3: WebUI] + D --> E[Phase 4: Device Management] + E --> F[Phase 5: Operations] + F --> G[Phase 6: Streaming] +``` + +--- + +## 14. What This AI Needs to Know + +### For Maximum Usefulness, Provide: + +1. **The "Why"** - Architecture decisions and rationale +2. **The "What"** - Current state and what's missing +3. **The "How"** - Code examples and patterns +4. **The "When"** - Priority, phase, dependencies +5. **The "Who"** - Who needs to decide what + +### Specific to This Project: + +1. **This is a multi-phase project** - Phase 1 is done, Phase 2 is next, Phase 3 (UI) is the target +2. **The branch name is misleading** - It's server-only, but UI-ready +3. **Security is blocking** - Cannot start UI without fixing CRITICAL issues +4. **The data model is excellent** - Perfectly designed for the UI +5. **The deployment is UI-ready** - Caddy can serve static files + +### What the AI Should NOT Do: + +1. **Don't suggest Docker** - Native deployment is a hard requirement +2. **Don't suggest Kubernetes** - Explicitly ruled out +3. **Don't suggest SQLite** - PostgreSQL is required +4. **Don't suggest changing the tech stack** - It's already well-chosen +5. **Don't ignore the phase structure** - Suggestions must respect the roadmap + +### What the AI SHOULD Do: + +1. **Focus on Phase 3** - UI implementation +2. **Respect the architecture** - Work within existing patterns +3. **Prioritize security** - CRITICAL issues must be fixed first +4. **Provide code examples** - Show, don't just tell +5. **Reference the SPEC** - All decisions should align with SPEC.md + +--- + +## 15. Summary: Action Items for AI + +### If Asked to Help with UI Development: + +1. **First, verify security issues are fixed** + - Check if SEC-001 through SEC-008 are resolved + - If not, prioritize those fixes + +2. **Understand the phase structure** + - Phase 1: ✅ Done + - Phase 2: ⏳ Should be done before Phase 3 + - Phase 3: ❌ Target (UI) + +3. **Use the existing patterns** + - Follow the code structure in server/ + - Use the same typing conventions + - Use the same error handling patterns + - Use the same logging patterns + +4. **Respect the contracts** + - Device API is defined in firmware/API.md + - UI API should follow similar patterns + - All endpoints should be under /api/v1/ + +5. **Focus on the gaps** + - UI code doesn't exist yet + - UI endpoints don't exist yet + - Authentication doesn't exist yet + - Authorization doesn't exist yet + +--- + +*This AI reviewer guide was created by Mistral Vibe on 2026-09-21 for the poorBird project.* diff --git a/docs/reviews/ui-basic-implementation/REVIEW.md b/docs/reviews/ui-basic-implementation/REVIEW.md new file mode 100644 index 0000000..750c560 --- /dev/null +++ b/docs/reviews/ui-basic-implementation/REVIEW.md @@ -0,0 +1,732 @@ +# Code Review: poorBird Server (feature/UI_Basic_implementation) + +**Reviewer:** Mistral Vibe +**Date:** 2026-09-21 +**Branch:** feature/UI_Basic_implementation +**Commit:** 5d16ded (Server: verify Phase 1 end to end against PostgreSQL 17) +**Version:** 0.1.0 + +--- + +## Executive Summary + +**Important Note:** This branch (`feature/UI_Basic_implementation`) currently contains **ONLY server code** (Phase 1) - **no UI implementation exists yet**. The branch name indicates it's **prepared for UI development** (Phase 3), but the UI itself is not implemented. + +The server infrastructure is **architecturally excellent** and **UI-ready**. All foundational work for Phase 3 (WebUI) is in place. The code quality is very high, documentation is outstanding, but **critical security issues must be fixed before UI development begins**. + +| Category | Rating | Priority | Notes | +|----------|--------|----------|-------| +| **Architecture** | 5/5 | Low | UI-ready foundation | +| **Security** | 2/5 | **High** | **Must fix before Phase 3** | +| **Performance** | 4/5 | Medium | Good for current scale | +| **Code Quality** | 5/5 | Low | Excellent | +| **UI Readiness** | 4/5 | Medium | Infrastructure ready, UI missing | +| **Test Coverage** | 5/5 | Low | 12/12 tests passing | + +--- + +## Branch Status + +### Current State +- **Branch Name:** feature/UI_Basic_implementation +- **Actual Content:** Server code only (identical to feature/Server_Basic_implementation) +- **Commit:** 5d16ded +- **Phase:** 1 (Server Foundation) - **UI Phase (3) not started** + +### Interpretation +This branch appears to be a **preparation branch** for UI development. It contains: +- ✅ Complete server foundation (Phase 1) +- ✅ All infrastructure needed for UI (Phase 3) +- ❌ No actual UI code (React/TS/Vite) +- ⏳ UI endpoints not implemented (Phase 3 task) + +**Recommendation:** Either rename the branch to reflect its actual content, or start UI implementation. + +--- + +## 1. Architecture Analysis - UI Perspective + +### What's Already UI-Ready + +#### ✅ **API Infrastructure for UI** +- FastAPI app with proper lifespan management +- API versioning (`/api/v1/` prefix) +- Health endpoints for UI monitoring +- CORS-ready (needs configuration) + +#### ✅ **Data Models for UI** +- `captures` table with all UI-needed fields +- `observations` table for species data +- `taxa` table for taxonomy autocomplete +- `tags` table for categorization +- `devices` table with status for device list +- `device_status` for time-series data + +#### ✅ **Storage for UI** +- `image_root` and `thumb_root` configured +- Image path structure: `/srv/poorbird/images/YYYY/MM/DD/.jpg` +- Thumbnails: `_400.webp` suffix +- Auth-checked image serving planned (app authorizes, Caddy serves) + +#### ✅ **Authentication Infrastructure** +- `users` table with roles (admin, editor, viewer) +- `sessions` table for session management +- Argon2id password hashing planned +- RBAC ready (SPEC 3.1) + +#### ✅ **Deployment for UI** +- Caddy reverse proxy with TLS (DNS-01) +- Static file serving via Caddy +- systemd units for API and worker + +### What's Missing for UI + +#### ❌ **No UI Code** +- No React/TypeScript code +- No Vite configuration +- No frontend build process +- No UI dependency management + +#### ❌ **No UI Endpoints** +- No gallery API endpoints +- No observation management endpoints +- No settings endpoints +- No user management endpoints + +#### ❌ **No Authentication Implementation** +- No session cookie handling +- No login/logout endpoints +- No password hashing implementation +- No CSRF protection + +#### ❌ **No UI-Specific Configuration** +- No frontend build directory +- No static asset configuration +- No theme settings implementation + +--- + +## 2. Security Analysis - Critical for UI + +### 🔴 CRITICAL Issues (Must Fix Before Phase 3 / UI Development) + +#### 1. **Enroll Secret in Plaintext (CRITICAL)** +- **Location:** config.py:53, .env files, systemd EnvironmentFile +- **Issue:** Shared bootstrap secret stored in plaintext +- **Risk:** Filesystem access = complete device spoofing +- **UI Impact:** If UI exposes device management, this is catastrophic +- **Solution:** + - Use HashiCorp Vault or AWS Secrets Manager + - Or: Only accept via CLI, never store in files + - Set file permissions to 600 +- **Priority:** **CRITICAL - Block Phase 3** + +#### 2. **No Request Authentication (CRITICAL)** +- **Location:** All API endpoints +- **Issue:** No authentication for any endpoint +- **Risk:** Anyone can send device commands, access admin functions +- **UI Impact:** UI would be completely insecure +- **Solution:** + - Device auth: X-Enroll-Secret header validation + - User auth: Session cookies with CSRF protection + - Admin auth: API keys or JWT +- **Priority:** **CRITICAL - Block Phase 3** + +#### 3. **No Input Validation (CRITICAL for UI)** +- **Location:** queue.py, future UI endpoints +- **Issue:** No validation of user input +- **Risk:** SQL injection, XSS, malicious data +- **UI Impact:** High - UI accepts user input +- **Solution:** Pydantic models for ALL requests +- **Priority:** **CRITICAL - Block Phase 3** + +#### 4. **No Rate Limiting (HIGH for UI)** +- **Location:** API layer +- **Issue:** No protection against DoS/brute force +- **Risk:** UI endpoints can be flooded +- **Solution:** slowapi middleware, 100 req/min/IP +- **Priority:** **HIGH - Fix Before Phase 3** + +### 🟡 HIGH Priority Issues (Fix Before Phase 3) + +#### 5. **No CORS Configuration** +- **Issue:** No CORS headers +- **Risk:** UI cannot make requests if on different origin +- **Solution:** Add CORS middleware with specific origins +- **Priority:** HIGH + +#### 6. **No CSRF Protection** +- **Issue:** Required for WebUI forms +- **Risk:** Cross-site request forgery attacks +- **Solution:** CSRF tokens for all mutating requests +- **Priority:** HIGH + +#### 7. **No Session Management** +- **Issue:** sessions table exists but not used +- **Risk:** Cannot implement user authentication +- **Solution:** Implement session cookie handling +- **Priority:** HIGH + +#### 8. **Database URL with Credentials in Defaults** +- **Location:** config.py:30 +- **Issue:** Plaintext credentials in default value +- **Risk:** Accidental commit of credentials +- **Solution:** Set default to empty string +- **Priority:** HIGH + +### 🟡 MEDIUM Priority Issues + +#### 9. **No Password Hashing Implementation** +- **Issue:** password_hash column exists but no hashing code +- **Solution:** Implement Argon2id hashing (planned per SPEC) +- **Priority:** MEDIUM + +#### 10. **No Image Upload Validation** +- **Issue:** Images not validated before saving +- **Risk:** Malicious file uploads +- **Solution:** Validate file type, size, dimensions +- **Priority:** MEDIUM + +--- + +## 3. UI-Specific Analysis + +### 3.1 What's Prepared for UI + +#### ✅ **Data Model** +``` +Captures (1:n) Observations + - UUID primary key (good for URLs) + - path, thumb_path + - sha256 (for deduplication) + - trigger, burst_id, burst_index + - pre_trigger flag + - radar data (distance, energy) + - battery, rssi, temp + - kept, reviewed flags + - received_at (authoritative timestamp) + +Observations + - capture_id (FK) + - taxon_id (FK to Taxa) + - source (human/model) + - model_version, confidence, bbox (for ML) + - age, sex, behaviour, certainty + - notes + +Taxa + - scientific_name, name_de, name_en + - gbif_key, family, order + - is_local_common (for autocomplete ranking) + +Tags + - label, colour + - Many-to-many with captures + +Devices + - device_uid (MAC-based identity) + - config (JSONB - all device settings) + - status fields (battery, rssi, etc.) + - commands queue + - reenroll_secret_hash +``` + +**Rating:** 5/5 - Excellent data model for UI + +#### ✅ **Storage Structure** +- `/srv/poorbird/images/YYYY/MM/DD/.jpg` +- `/srv/poorbird/thumbs/_400.webp` +- Single source of truth: `image_root` in config + +**Rating:** 5/5 - Well-designed for UI consumption + +#### ✅ **Authentication Model** +- Users: admin, editor, viewer roles +- Sessions: for persistent login +- TOTP 2FA: optional (SPEC Q14) +- Argon2id: for password hashing + +**Rating:** 4/5 - Good foundation, needs implementation + +### 3.2 What Needs to Be Built for UI + +#### 📋 **Phase 3 Tasks (from TODO.md)** + +**Frontend:** +- [ ] React + TS + Vite + TanStack Query/Router +- [ ] Virtualised gallery grid with filters +- [ ] Observation editor +- [ ] Taxon autocomplete +- [ ] Tags, favourite/reject, review flag +- [ ] Three themes (light, dark, blue) +- [ ] Auth: session cookies, CSRF, RBAC + +**Backend (UI Endpoints):** +- [ ] Gallery API (list, filter, paginate) +- [ ] Observation CRUD +- [ ] Taxa search/autocomplete +- [ ] Tag management +- [ ] User management +- [ ] Settings management +- [ ] Auth endpoints (login, logout, register) + +**Security:** +- [ ] Session cookie implementation +- [ ] CSRF protection +- [ ] Password hashing (Argon2id) +- [ ] Audit logging +- [ ] Image upload validation + +### 3.3 UI Technology Stack (Planned) + +| Component | Technology | Status | +|-----------|------------|--------| +| Frontend Framework | React + TypeScript | Not started | +| Build Tool | Vite | Not started | +| State Management | TanStack Query | Not started | +| Routing | TanStack Router | Not started | +| Styling | CSS Custom Properties | Not started | +| Theming | Design tokens → CSS vars | Not started | +| Backend | FastAPI | Phase 1 complete | +| Auth | Session cookies + CSRF | Not started | +| 2FA | TOTP (optional) | Not started | + +--- + +## 4. Performance Analysis - UI Considerations + +### Current Configuration +| Component | Setting | UI Impact | Rating | +|-----------|---------|-----------|--------| +| DB Connection Pool | 5 | May limit concurrent UI requests | 3/5 | +| Worker Poll Interval | 2s | Affected by background jobs only | 4/5 | +| Sync SQLAlchemy | Enabled | Blocks event loop under load | 4/5 | +| Image Storage | Date-based directories | Good for organization | 5/5 | + +### Expected UI Load +- **Gallery View:** 20-50 images per page, paginated +- **Search/Filter:** 100-500ms per query (with indexes) +- **Image Upload:** ~200-500KB per image +- **Thumbnail Generation:** 100-300ms per image (Phase 2) +- **Concurrent Users:** 1-5 typical, 10 peak + +### Performance Recommendations for UI + +#### 1. **Database Optimization** +```python +# Current: 5 connections +# Recommended for UI: 15-20 connections +db_pool_size: int = 15 + +# Add timeouts +pool_recycle=3600 # Recycle after 1 hour +pool_timeout=30 # Timeout after 30 seconds +connect_timeout=10 +``` + +#### 2. **API Performance** +- **Pagination:** All list endpoints should be paginated +- **Caching:** Cache gallery queries, taxon lists +- **Lazy Loading:** Images should load as user scrolls +- **Compression:** Enable gzip for API responses + +#### 3. **Image Handling** +- **Thumbnails:** Pre-generate on ingest (Phase 2) +- **Lazy Load:** Only load visible images +- **Progressive Loading:** Show low-res first, then high-res +- **CDN:** Consider for production (not needed for LAN-only) + +#### 4. **Frontend Performance** +- **Code Splitting:** Split React bundles +- **Tree Shaking:** Remove unused code +- **Image Optimization:** WebP format for thumbnails +- **Bundle Analysis:** Track bundle size + +--- + +## 5. Data Model Analysis - UI Perspective + +### ✅ Excellent Decisions + +#### 1. **Captures with UUID Primary Key** +- **Benefit:** Safe for URLs, distributed systems +- **UI Usage:** `/gallery/{capture_id}` URLs +- **Rating:** 5/5 + +#### 2. **Observations 1:n to Captures** +- **Benefit:** One photo can have multiple species +- **UI Usage:** Multiple birds in one photo +- **Rating:** 5/5 + +#### 3. **Human vs Model Observations** +- **Benefit:** Same table, different source +- **UI Usage:** Human labels + future ML predictions +- **Rating:** 5/5 + +#### 4. **JSONB for Device Config** +- **Benefit:** Flexible, future-proof +- **UI Usage:** Device settings form +- **Rating:** 5/5 + +#### 5. **battery_valid Flag** +- **Important:** false = **not measured**, not empty +- **UI Requirement:** Display as "N/A", never as low battery alarm +- **Rating:** 5/5 + +### ⚠️ Potential Issues + +#### 1. **No Index on sha256** +- **Issue:** Deduplication queries may be slow +- **Solution:** Add unique index on sha256 +- **Priority:** MEDIUM + +#### 2. **No Index on burst_id** +- **Issue:** Burst grouping queries may be slow +- **Check:** Already has index (ix_captures_burst) +- **Status:** ✅ Already indexed + +#### 3. **Daily Counters in RTC Memory** +- **Important:** Counters reset on power loss +- **UI Display:** Show as "gap" between captured and delivered +- **Rating:** 4/5 - Good design, UI must understand + +--- + +## 6. UI Implementation Recommendations + +### 6.1 Frontend Structure + +``` +webui/ +├── src/ +│ ├── components/ +│ │ ├── Gallery/ +│ │ │ ├── GalleryGrid.tsx +│ │ │ ├── ImageCard.tsx +│ │ │ └── Filters.tsx +│ │ ├── Observation/ +│ │ │ ├── ObservationEditor.tsx +│ │ │ └── TaxonAutocomplete.tsx +│ │ ├── Settings/ +│ │ │ └── DeviceSettings.tsx +│ │ └── Common/ +│ │ ├── ThemeToggle.tsx +│ │ ├── LanguageToggle.tsx +│ │ └── Layout.tsx +│ ├── hooks/ +│ │ ├── useGallery.ts +│ │ ├── useObservations.ts +│ │ └── useAuth.ts +│ ├── store/ +│ │ ├── gallerySlice.ts +│ │ └── authSlice.ts +│ ├── utils/ +│ │ └── api.ts (axios/fetch wrapper) +│ ├── styles/ +│ │ ├── theme.css +│ │ └── global.css +│ ├── App.tsx +│ └── main.tsx +├── public/ +│ └── index.html +├── vite.config.ts +├── package.json +└── tsconfig.json +``` + +### 6.2 Backend Endpoints Needed for UI + +#### Gallery +- `GET /api/v1/captures` - Paginated list with filters +- `GET /api/v1/captures/{id}` - Single capture with observations +- `GET /api/v1/captures/{id}/image` - Full image (auth-checked) +- `GET /api/v1/captures/{id}/thumb` - Thumbnail (auth-checked) + +#### Observations +- `POST /api/v1/captures/{id}/observations` - Add observation +- `PUT /api/v1/observations/{id}` - Update observation +- `DELETE /api/v1/observations/{id}` - Delete observation + +#### Taxonomy +- `GET /api/v1/taxa` - Search with pagination +- `GET /api/v1/taxa/autocomplete` - Autocomplete endpoint + +#### Tags +- `GET /api/v1/tags` - List all tags +- `POST /api/v1/tags` - Create tag (admin only) + +#### Devices +- `GET /api/v1/devices` - List devices with status +- `GET /api/v1/devices/{id}` - Device details +- `PUT /api/v1/devices/{id}/settings` - Update settings + +#### Users +- `POST /api/v1/auth/login` - Login +- `POST /api/v1/auth/logout` - Logout +- `GET /api/v1/users/me` - Current user + +### 6.3 UI-Specific Security + +#### Authentication Flow +``` +1. POST /api/v1/auth/login (username, password) + → Returns session cookie + +2. All authenticated requests include session cookie + +3. CSRF token in forms (for POST/PUT/DELETE) + +4. Role-based access control (RBAC): + - viewer: Read-only + - editor: Read + Write (observations, tags) + - admin: Full access (devices, users, settings) +``` + +#### Image Security +- **Never** serve images directly from filesystem +- **Always** check authorization in app first +- **Then** have Caddy serve the bytes +- **URLs** should be unguessable (UUID-based) + +--- + +## 7. Deployment Analysis - UI Impact + +### ✅ Current Deployment (UI-Ready) +- **Reverse Proxy:** Caddy with TLS (DNS-01) +- **Static Files:** Caddy can serve built React app +- **API:** FastAPI behind Caddy +- **Images:** Auth-checked handoff to Caddy + +### 📋 UI Deployment Tasks + +#### Caddy Configuration +```caddyfile +# Current (API only) +:8080 { + reverse_proxy /api/* 127.0.0.1:8090 +} + +# Needed for UI +:80 { + # Serve static UI files + root * /srv/poorbird/webui + try_files {path} /index.html + + # API reverse proxy + handle_path /api/* { + reverse_proxy 127.0.0.1:8090 + } + + # Image serving (auth-checked) + handle_path /images/* { + reverse_proxy 127.0.0.1:8090 + } +} +``` + +#### systemd Unit for UI +- **Not needed:** Static files served by Caddy +- **Build process:** Should be part of deployment +- **Location:** `/srv/poorbird/webui` + +--- + +## 8. Test Analysis - UI Considerations + +### Current Tests +- **12/12 tests passing** (server only) +- All tests require PostgreSQL 17 +- Integration tests for queue, schema, config, health + +### Missing UI Tests + +#### Unit Tests (Frontend) +- Component rendering tests +- Hook tests +- Utility function tests +- **Tool:** Jest + React Testing Library + +#### Integration Tests (API) +- UI endpoint tests +- Authentication tests +- Authorization tests +- **Tool:** pytest + httpx + +#### E2E Tests +- User flows: login → gallery → edit → logout +- **Tool:** Playwright or Cypress + +### Test Environment for UI +- **Frontend:** Node.js 18+ +- **Testing:** Jest, React Testing Library, Playwright +- **CI/CD:** GitHub Actions or similar + +--- + +## 9. Recommended Implementation Order + +### Phase 3: WebUI (Estimated: 3-4 weeks) + +#### Week 1: Authentication & Foundation +1. [ ] Implement session management +2. [ ] Add CORS configuration +3. [ ] Add CSRF protection +4. [ ] Implement password hashing (Argon2id) +5. [ ] Create auth endpoints (login, logout, me) +6. [ ] Setup React + Vite project +7. [ ] Create basic layout and routing + +#### Week 2: Gallery & Viewing +1. [ ] Implement gallery API endpoints +2. [ ] Create Gallery component +3. [ ] Add pagination +4. [ ] Implement ImageCard component +5. [ ] Add date/taxon/device filters +6. [ ] Setup image lazy loading + +#### Week 3: Editing & Management +1. [ ] Implement observation CRUD endpoints +2. [ ] Create ObservationEditor +3. [ ] Add TaxonAutocomplete +4. [ ] Implement tag management +5. [ ] Add device list and status view +6. [ ] Create settings pages + +#### Week 4: Polish & Testing +1. [ ] Implement theme switching +2. [ ] Add language support +3. [ ] Write frontend tests +4. [ ] Write E2E tests +5. [ ] Performance optimization +6. [ ] Security audit + +### Dependencies +- **Phase 2 must be complete** (device endpoints) +- **Security issues must be fixed** (CRITICAL items) +- **Authentication must work** before UI can be used + +--- + +## 10. Architecture Rating + +| Criterion | Rating | Notes | +|-----------|--------|-------| +| **Scalability** | 4/5 | Good for 10 cameras, may need optimization for 100+ | +| **Maintainability** | 5/5 | Very clean code, excellent docs | +| **Security** | 2/5 | **Critical issues block Phase 3** | +| **Performance** | 4/5 | Good for current scale | +| **UI Readiness** | 4/5 | Infrastructure ready, UI missing | +| **Code Quality** | 5/5 | Excellent | +| **Test Coverage** | 5/5 | Server: 12/12 passing | +| **Documentation** | 5/5 | Outstanding | + +### SPEC Compliance +| Requirement | Status | Rating | +|-------------|--------|--------| +| Native Deployment | ✅ | 5/5 | +| Container-Ready | ✅ | 5/5 | +| PostgreSQL | ✅ | 5/5 | +| Job Queue without Redis | ✅ | 5/5 | +| FastAPI | ✅ | 5/5 | +| PostgreSQL 17 Support | ✅ | 5/5 | +| **UI Infrastructure** | ⚠️ | **4/5 (Ready, not implemented)** | +| Device Contract | ❌ | Not implemented (Phase 2) | +| Auth System | ❌ | Not implemented (Phase 2) | + +--- + +## 11. Conclusion & Recommendations + +### What's Excellent +1. ✅ **Architecture** - UI-ready foundation +2. ✅ **Data Model** - Perfect for gallery and observations +3. ✅ **Storage** - Well-designed for images and thumbnails +4. ✅ **Deployment** - Caddy + systemd ready for UI +5. ✅ **Tests** - Complete server test coverage + +### What's Missing (But Prepared For) +1. ❌ **UI Code** - React/TS/Vite project not started +2. ❌ **UI Endpoints** - Gallery, observation, auth endpoints missing +3. ❌ **Authentication** - Session management not implemented +4. ❌ **Authorization** - RBAC not enforced + +### Critical Blockers for Phase 3 +1. 🔴 **Enroll Secret in Plaintext** - Must fix +2. 🔴 **No Request Authentication** - Must fix +3. 🔴 **No Input Validation** - Must fix +4. 🔴 **No Rate Limiting** - Must fix +5. 🟡 **No CORS Configuration** - Must fix +6. 🟡 **No CSRF Protection** - Must fix + +### Summary + +The `feature/UI_Basic_implementation` branch is **misnamed** - it contains only server code (Phase 1), not UI code. However, the server is **perfectly prepared** for UI development (Phase 3). + +**The server infrastructure is production-ready for UI development, but critical security issues must be fixed first.** + +### Overall Rating +- **Code Quality:** 5/5 - Excellent +- **Architecture:** 5/5 - Excellent (UI-ready) +- **Security:** 2/5 - **Critical (blocking)** +- **Performance:** 4/5 - Good +- **UI Readiness:** 4/5 - Infrastructure ready +- **Test Coverage:** 5/5 - Excellent (server) + +--- + +## 12. Quick Start: UI Implementation + +### Prerequisites +1. Fix CRITICAL security issues (enroll secret, authentication) +2. Complete Phase 2 (device endpoints) +3. Setup Node.js 18+ and npm + +### Setup +```bash +# Create webui directory +mkdir -p webui +cd webui + +# Initialize Vite + React + TypeScript +npm create vite@latest . -- --template react-ts + +# Install dependencies +npm install @tanstack/react-query @tanstack/react-router axios +npm install --save-dev @types/react @types/node + +# Install Vite plugins +npm install vite-plugin-svgr @svgr/core + +# Setup project structure (see Section 6.1) +``` + +### First Endpoints to Implement +```python +# server/src/poorbird/api/routes/gallery.py +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from typing import Optional +from datetime import date + +router = APIRouter(prefix="/api/v1/captures", tags=["gallery"]) + +@router.get("/") +async def list_captures( + page: int = 1, + limit: int = 20, + device_id: Optional[int] = None, + taxon_id: Optional[int] = None, + date_from: Optional[date] = None, + date_to: Optional[date] = None, + kept: Optional[bool] = None, + reviewed: Optional[bool] = None, +): + """List captures with pagination and filters.""" + # Implementation here + pass +``` + +--- + +*Review created by Mistral Vibe on 2026-09-21. Based on commit 5d16ded.* diff --git a/firmware/.gitignore b/firmware/.gitignore new file mode 100644 index 0000000..6e32b61 --- /dev/null +++ b/firmware/.gitignore @@ -0,0 +1,4 @@ +.pio/ +.vscode/ +secrets.ini +*.bin diff --git a/firmware/API.md b/firmware/API.md new file mode 100644 index 0000000..892d606 --- /dev/null +++ b/firmware/API.md @@ -0,0 +1,588 @@ +# Device ↔ Endpoint contract + +Written for: whoever implements the server side — framework-neutral, and +host-neutral. The firmware only needs *an HTTP endpoint at an IP and port*, so +a Raspberry Pi, a thin client, a NUC or a VM are all the same to it. This +document says "the endpoint" throughout for that reason. + +This is what the firmware in `firmware/` actually sends and expects. It refines +`SPEC.md` §4.1 in two places, both noted below. Base URL is +`http://:/api/v1`, plain HTTP on the LAN, TLS terminating on +the endpoint (SPEC C2/C3). + +--- + +## Authentication + +Two steps. The long-lived token never exists in firmware source or in a build +flag. + +### 1. Enrollment (once per device) + +``` +POST /api/v1/enroll +X-Enroll-Secret: +Content-Type: application/json + +{ "device_uid": "a0b7651f2c3d", "device_name": "poorbird-cam-1", + "hw_revision": "xiao-esp32s3-sense-ld2410", "fw_version": "0.1.0", + "mac": "A0:B7:65:1F:2C:3D" } +``` + +`device_uid` is the eFuse MAC in hex. It survives reflashing, which is what +makes it usable as an identity. + +``` +201 { "token": "<64 hex chars>", "device_id": 1, + "reenroll_secret": "<64 hex chars, per device>", + "server_time": 1758376267000, "config_version": 7 } +``` + +The endpoint stores only `token_hash` (SPEC §3 `devices.token_hash`; the token +is high-entropy, so a fast hash is defensible here). + +### `reenroll_secret` — why the device keeps a credential + +**The camera cannot be reached over USB once it is mounted.** That single fact +decides this design. If enrollment wiped the device's secret, rotating a token +in the admin UI would permanently lock the device out, and recovering it would +mean taking it down and reflashing. So: + +1. The device enrolls with the **shared bootstrap secret** from `secrets.ini`. +2. The endpoint returns a **per-device** `reenroll_secret`, which the device + stores in NVS *in place of* the shared one. +3. On any `401`, the device clears its token, re-enrolls with that per-device + secret, and retries — mid-burst, without rebooting. + +Rotating a token is therefore a normal operation with no physical access. The +credential left on the device is scoped to that device and cannot enroll any +other identity, which is the part that makes keeping it acceptable. + +`reenroll_secret` is optional. Omit it and the device keeps using the shared +bootstrap secret instead — still self-healing, just a coarser credential. + +There is one last-resort path: the shared bootstrap secret is compiled into +the firmware image, and the device falls back to it if the stored per-device +secret is ever rejected. The consequence worth knowing: **do not rotate the +shared bootstrap secret server-side without also shipping new firmware**, or +you remove the escape hatch. + +Re-enrollment of a known `device_uid` must return the existing device row with +a fresh token, not create a duplicate. Expect to see this on every token +rotation and after any endpoint database restore. + +### 2. Everything else + +``` +Authorization: Bearer +``` + +Scoped to `/ingest`, `/heartbeat`, `/status`, `/config`, `/commands/*/ack`, +`/firmware/*`, `/stream/*`. **Never** the gallery (SPEC §3.1: devices are not +users). + +Rotating a token in the admin UI needs no device-side action: the next request +gets a `401` and the device re-enrolls itself, as described above. + +--- + +## Common request headers + +Present on every authenticated request: + +| Header | Meaning | +|---|---| +| `X-Device-Uid` | eFuse MAC hex | +| `X-Fw-Version` | running firmware version | +| `X-Hw-Revision` | build-time hardware tag | +| `X-Config-Version` | config version the device is running | +| `X-Rssi` | current WiFi RSSI in dBm | + +`X-Config-Version` is what lets the Pi push settings without the device +polling: if it differs from the server's, put the new version in the response +envelope and the device pulls `/config`. + +--- + +## Response envelope + +`/ingest` and `/heartbeat` return the **same** JSON shape. This is deliberate — +SPEC §4.1 — so a capture that was going to happen anyway also delivers the +command queue at no extra cost. + +```json +{ + "capture_id": 4711, + "server_time": 1758376267000, + "config_version": 7, + "firmware": { + "version": "0.2.0", + "url": "/firmware/0.2.0.bin", + "sha256": "3f786850e387550fdab836ed7e6dc881de23001b…", + "size": 1148320 + }, + "commands": [ + { "id": 12, "type": "stream_start", + "payload": { "session_id": "s-88f1", "duration_s": 45, "mode": 0 }, + "expires_at": 1758376400000 } + ] +} +``` + +- `server_time` — epoch ms, UTC. **Authoritative** (SPEC C7). The device adopts + it whenever it is unsynced or more than 2 s out, so the Pi works as the clock + even if SNTP is unavailable. +- `firmware` — omit the key entirely when the device is on target. Present and + different ⇒ the device flashes it on its own; no command needed. Use an + explicit `ota_update` command only for staged rollouts. +- `commands` — omit or send `[]` when empty. + +--- + +## `POST /api/v1/ingest` + +**Deviation from SPEC §4.1.** The spec says `multipart/form-data` with image + +JSON meta. The firmware sends the **raw JPEG as the body** with metadata in +headers. + +Why: multipart makes the device assemble a second buffer purely to add a +wrapper the server strips immediately. Raw body hands the framebuffer pointer +straight to the HTTP client — no copy, less heap, fewer failure modes. The +metadata is a dozen flat scalars, which is exactly what headers are good at. +It is still plainly REST: + +``` +curl -X POST http://pi:8080/api/v1/ingest \ + -H 'Authorization: Bearer …' -H 'Content-Type: image/jpeg' \ + -H 'X-Trigger: radar' -H 'X-Burst-Id: a0b765-3-91204' \ + --data-binary @frame.jpg +``` + +| Header | Type | Notes | +|---|---|---| +| `Content-Type` | `image/jpeg` | body is the JPEG, nothing else | +| `X-Trigger` | enum | `radar` · `manual` · `timer` · `stream_grab` | +| `X-Burst-Id` | string | groups the frames of one event → `captures.burst_id` | +| `X-Burst-Index` | int | 0-based → `captures.burst_index` | +| `X-Burst-Count` | int | frames in this burst | +| `X-Pre-Trigger` | 0/1 | **1 = this frame predates the trigger** (see below) | +| `X-Captured-At` | int64 | epoch ms UTC, **0 when the device clock is unsynced** | +| `X-Frame-Seq` | int | monotonic per boot | +| `X-Radar-State` | 0–3 | none / moving / stationary / both | +| `X-Radar-Distance-Cm` | int | | +| `X-Radar-Energy` | 0–100 | | + +Response: `201` + the envelope above. + +### `X-Pre-Trigger` — worth a column in the database + +With mains power the camera runs continuously into a PSRAM ring, so a burst +contains frames from **before** the radar fired. Those are usually the good +ones: the bird is still arriving rather than already leaving. + +Add a `pre_trigger BOOL` column to `captures` and surface it in the gallery as +a sort key within a burst. `X-Captured-At` already orders them correctly, but +the flag tells you *why* a frame predates its own trigger, which is otherwise a +confusing thing to see in the data. + +**`X-Captured-At: 0` means unsynced, not 1970.** Store `NULL`, not an epoch +date. `received_at` stays authoritative either way (SPEC C7). + +--- + +## Device conditions — `POST /heartbeat` and `POST /status` + +**One body, two endpoints.** Both send exactly the same JSON; they differ only +in what comes back: + +| | `POST /api/v1/heartbeat` | `POST /api/v1/status` | +|---|---|---| +| Response | `200` + the envelope (commands, config, firmware) | `204`, no body | +| Cadence | `heartbeat_interval_s` (default 300 s) | `status_interval_s` (default 900 s), plus on events | +| Also sent | — | after an upload burst, before sleep, before night sleep, on `report_status` | + +The split exists for one reason: **the device posts status immediately before +deep sleep**, and pulling down a command queue at that moment would mark +commands delivered that the device is about to become unable to execute. So +`/status` deliberately returns nothing actionable. If you only want to +implement one endpoint, implement `/heartbeat` and return `204` from +`/status` — everything still works, you just get coarser telemetry. + +```json +{ + "reason": "periodic", + "fw_version": "0.1.0", "hw_revision": "xiao-esp32s3-sense-ld2410", + "config_version": 8, + + "power": { + "uptime_ms": 91204, + "awake_ms": 91204, // ticks since the last wake + "boot_count": 37, + "wake_cause": "radar", // power-on | radar | timer | other + "last_sleep_s": 300, + "total_sleep_s": 10800, + "sleep_enabled": false, + "sleep_allowed": false, + "inhibits": "stream,upload" + }, + + "battery": { + "valid": true, // false = no divider wired + "mv": 3912, "pct": 74, "raw_mv": 1956, + "chemistry": 1, "low": false + }, + + "counters": { + "captured_today": 412, "delivered_today": 407, + "failed_today": 5, "events_today": 41, + "day_index": 20716, + "captured_boot": 88, "delivered_boot": 88 + }, + + "camera": { "frame_size": 8, "jpeg_quality": 12, "profile": "day", "ready": true }, + "night": { "is_night": false, "nightlight_on": false, + "behaviour": 2, "capture_allowed": true }, + "stream": { "enabled": false, "active": false, "frames_sent": 0, "seconds_left": 0 }, + "radar": { "baud": 256000, "uart_ok": true, "out_pin": false, "state": 0, + "moving_cm": 0, "moving_energy": 0, + "stationary_cm": 0, "stationary_energy": 0 }, + "system": { "rssi": -61, "ip": "192.168.1.88", + "free_heap": 184320, "free_psram": 6815744, + "ring_depth": 24, "ring_bytes": 1179648 }, + + "time_synced": true, + "device_time": "2026-09-20T14:31:07Z" +} +``` + +`reason` is one of `heartbeat` · `periodic` · `after_event` · `before_sleep` · +`before_night_sleep` · `on_request`. Useful for spotting *why* a device went +quiet: the last row before a gap tells you whether it slept deliberately. + +### Reading the fields that are easy to misread + +**`battery.valid: false` means not measured, not empty.** No divider is wired +by default — the XIAO does not bring its battery rail out to a readable pin. +Render this as "—", never as 0 V, and do not raise a low-battery alarm on it. +`chemistry: 0` likewise means `pct` is meaningless; show the voltage only. + +**The counters are the device's opinion, not the truth.** They live in RTC +memory: they survive deep sleep and reset on power loss, and they are +approximate by design. Your `captures` table is authoritative. What the +counters are genuinely good for is the *gap*: `captured_today` well above +`delivered_today` means frames are being taken and not arriving, which is a +WiFi or disk problem you would otherwise only notice as "quiet camera". + +**`day_index` is days since epoch in local time**, and it is the rollover key. +It stays `0` until the clock syncs, so counters accumulated before the first +sync land in a phantom day and then roll over once. Do not chart that bucket. + +**`power.awake_ms` is the "ticks since last sleep"** — it resets on every wake, +unlike `uptime_ms`, which also resets but only on reboot. In awake mode they +are identical; in sleep mode `awake_ms` is the useful one. + +A heartbeat the endpoint **accepts** is also what confirms an OTA trial boot. +Returning `5xx` to a device on a trial image will roll it back — correct +behaviour, but worth knowing before you restart the Pi mid-rollout. + +--- + +## `GET /api/v1/config` + +Returns the full device config. Every key optional; the device merges and +clamps. See `AppConfig` in `include/app_config.h` for the authoritative list. + +```json +{ + "config_version": 8, + + "frame_size": "SVGA", "jpeg_quality": 12, "vflip": false, "hmirror": false, + "cam_day": { "...": "see below" }, + "cam_night": { "...": "see below" }, + + "ring_frames": 24, "pre_roll": 4, "post_roll": 6, + "post_roll_gap_ms": 250, "cooldown_s": 5, "idle_period_ms": 400, + + "radar_mode": 2, "accept_stationary": true, + "min_distance_cm": 20, "max_distance_cm": 300, "min_energy": 20, + "radar_baud": 0, + + "stream_enabled": false, "stream_frame_size": "VGA", "stream_jpeg_quality": 15, + "stream_duration_s": 60, "stream_fps": 10, "stream_mode": 0, + "stream_blocks_sleep": true, + + "night_start_min": 1260, "night_end_min": 360, + "night_behaviour": 2, "nightlight_mode": 0, "nightlight_brightness": 128, + + "battery_chemistry": 0, "battery_divider_x100": 200, + "battery_offset_mv": 0, "battery_min_pct_ota": 50, "battery_warn_pct": 20, + + "heartbeat_interval_s": 300, "status_interval_s": 900, "ota_enabled": true, + + "deep_sleep_enabled": false, "deep_sleep_s": 300, + "sleep_wake_on_radar": true, "sleep_idle_timeout_s": 20, + "sleep_max_awake_s": 300, + + "tz": "CET-1CEST,M3.5.0,M10.5.0/3" +} +``` + +Bump `config_version` on every change — that is the only thing the device +compares. Every key is optional and the device clamps out-of-range values, so +partial pushes are fine. + +### Enums + +| Key | Values | +|---|---| +| `frame_size`, `stream_frame_size` | **a name**: `QVGA` `CIF` `VGA` `SVGA` `XGA` `HD` `SXGA` `UXGA` `QXGA` `QSXGA` `5MP` — see below | +| `stream_mode` | 0=watch 1=record 2=both | +| `radar_mode` | 0=OUT pin only 1=UART only 2=both | +| `night_behaviour` | 0=capture 1=idle 2=sleep | +| `nightlight_mode` | 0=off 1=on during burst 2=always on at night | +| `battery_chemistry` | 0=none 1=Li-ion/LiPo 2=LiFePO4 | +| `radar_baud` | 0=autodetect (recommended), or an explicit rate to pin | + +`radar.baud` in the status payload reports what the device actually settled +on, and `0` there means no valid frame was decoded at any rate — wiring or a +dead module, worth an alert. + +### Send frame sizes by name, not by number + +`framesize_t` is an enum in the camera driver, and **entries have been +inserted into the middle of it between driver releases** — `FRAMESIZE_128X128` +and `FRAMESIZE_320X320` both landed after the original ordering. A stored +numeric index therefore means a *different resolution* after a firmware +update built against a newer driver. + +This bit this very firmware: an early draft defaulted to `frame_size: 8` +believing it was SVGA 800×600. In the driver actually installed, index 8 is +CIF 400×296. + +So the device accepts a name and resolves it against the enum symbols: + +| Name | Pixels | Note | +|---|---|---| +| `QVGA` | 320×240 | | +| `CIF` | 400×296 | | +| `VGA` | 640×480 | stream default | +| `SVGA` | 800×600 | stills default | +| `XGA` | 1024×768 | | +| `HD` | 1280×720 | | +| `SXGA` | 1280×1024 | | +| `UXGA` | 1600×1200 | OV2640 maximum | +| `QXGA` | 2048×1536 | OV3660 / OV5640 only | +| `QSXGA` / `5MP` | 2560×1920 / 2592×1944 | OV5640 only | + +A raw index is still accepted for compatibility, but store names. + +The status payload reports both, plus the dimensions and the sensor's PID, so +the UI never has to guess: + +```json +"camera": { "frame_size": "SVGA", "frame_size_id": 11, + "width": 800, "height": 600, + "sensor_pid": 9646, "profile": "day", "ready": true } +``` + +`sensor_pid` is `0x2640` OV2640, `0x3660` OV3660, `0x5640` OV5640. Worth +surfacing: **newer XIAO Sense units have shipped with OV3660 rather than +OV2640**, so do not assume from the product listing. A frame size the fitted +sensor cannot reach is refused by the driver and logged, and the previous size +stays in effect. + +### Camera tuning — `cam_day` and `cam_night` + +Two complete OV2640 profiles. The device switches between them at the night +boundary on its own, so dusk costs no round trip. + +```json +"cam_day": { + "brightness": 0, "contrast": 1, "saturation": 0, "sharpness": 0, + "ae_level": 1, "special_effect": 0, "wb_mode": 0, + "gainceiling": 1, "agc_gain": 0, "aec_value": 300, + "whitebal": true, "awb_gain": true, + "exposure_ctrl": true, "aec2": true, "gain_ctrl": true, + "bpc": true, "wpc": true, "raw_gma": true, "lenc": true, + "dcw": true, "colorbar": false +} +``` + +| Key | Range | What it does here | +|---|---|---| +| `brightness`, `contrast`, `saturation`, `sharpness` | −2…2 | Cosmetic. `sharpness` support on the OV2640 is patchy. | +| `ae_level` | −2…2 | Exposure bias. **Raise it.** Birds are usually backlit against bright sky, which fools metering into underexposing the bird. | +| `gainceiling` | 0…6 (2×…128×) | **The setting that matters most.** High gain lets the sensor pick a shorter shutter (freezes the bird, noisier); low gain forces a longer one (clean, smeared). Day default 4×, night 32×. | +| `exposure_ctrl` | bool | `false` = manual, use `aec_value`. Set this if motion blur turns out to be your limiting factor — it is the direct lever. | +| `aec_value` | 0…1200 | Manual shutter. Only read when `exposure_ctrl` is false. | +| `gain_ctrl` / `agc_gain` | bool / 0…30 | Same pattern for gain. | +| `aec2` | bool | DSP-assisted metering. On. | +| `wb_mode` | 0…4 | auto / sunny / cloudy / office / home. Auto is fine outdoors. | +| `whitebal`, `awb_gain` | bool | Leave on. | +| `bpc`, `wpc`, `raw_gma`, `lenc` | bool | Dead-pixel, gamma and lens-shading correction. Leave on. | +| `dcw` | bool | Downsize/crop. On. | +| `special_effect` | 0…6 | none/negative/grayscale/red/green/blue/sepia. Grayscale (2) is arguably right for a night profile with IR illumination. | +| `colorbar` | bool | Test pattern. **Set true to prove the whole pipeline works before you have optics or light** — very useful during bring-up. | + +### Night window and nightlight + +`night_start_min` / `night_end_min` are **minutes from local midnight** +(1260 = 21:00, 360 = 06:00). The fixed defaults are a fallback: the Pi knows +the site's latitude, so the intended design is for it to compute real +sunset/sunrise and push them daily via `apply_config`. That is a much better +boundary than a fixed clock time, which is two hours wrong by December. + +`night_behaviour` decides what happens inside that window: + +| | Behaviour | Reachable at night? | +|---|---|---| +| 0 `capture` | Keep working, using `cam_night` and the illuminator | yes | +| 1 `idle` | Stay awake and reachable, capture nothing | yes | +| 2 `sleep` | **Deep sleep until morning, even when `deep_sleep_enabled` is false** | **no** | + +Mode 2 is the one that answers "nightlight off could make the ESP sleep by +night". It is deliberately independent of the deep-sleep switch: a camera with +no illuminator has nothing to do at 03:00 whether it is mains-powered or not. +The cost is that the device is unreachable until `night_end_min`, so a config +change made at 23:00 lands at dawn. It wakes a minute early to let +auto-exposure settle. + +Night sleep never wakes on the radar — the point is to ignore the night, not +to photograph every cat that walks past. + +**Before you buy an illuminator, read the warning at the top of +`include/nightlight.h`.** Short version: the obvious choice is 850 nm IR, +because birds barely perceive it — but the OV2640 on the XIAO Sense has an IR +cut filter bonded over the sensor, so an IR LED produces a black frame. +Your options are to accept no night capture (mode 2, and most garden birds are +diurnal anyway), use dim continuous white light, or remove the IR filter. + +### Streaming vs sleeping + +`stream_blocks_sleep` (default `true`) is the coupling between the two. A +sleeping device cannot be told to start a stream (SPEC C1), so with this set, +merely **enabling** streaming keeps the device awake and reachable — not just +while a session runs. Clear it to let the device sleep anyway and accept that +`stream_start` waits for the next wake. + +The status payload reports this: `power.sleep_allowed: false` with +`inhibits` naming the reason, so the WebUI can explain why a device that is +configured to sleep is not sleeping. + +### Battery sensing + +Nothing is wired by default and readings report `valid: false`. To enable it, +add an external divider from BAT+ to `PIN_BATTERY_ADC` (default D3/GPIO4) — +the wiring diagram is at the top of `include/battery.h` — then set +`battery_divider_x100` to your measured ratio and trim `battery_offset_mv` +against a multimeter. + +`battery_min_pct_ota` is SPEC C6's flash gate. Note the deliberate choice in +`batteryAboveOtaThreshold()`: with no sensing hardware the gate **allows** the +flash rather than blocking it, because refusing every OTA on a mains-powered +device because an optional sensor is absent would be worse than the risk. +Wire the divider if you want the gate to bite. + +--- + +## Commands + +`POST /api/v1/commands/{id}/ack` → `{ "status": "done|failed|rejected", "detail": "…" }` + +| `type` | payload | when it runs | +|---|---|---| +| `apply_config` | inline config object, or omit to make the device `GET /config` | immediately | +| `capture_now` | — | next capture-task tick | +| `report_status` | — | main loop; posts `/status` with `reason: on_request` | +| `wake_and_hold` | `{"seconds": 60}` (capped at 900) | immediately | +| `sleep_now` | `{"seconds": 0}` (0 = `deep_sleep_s`) | after the ack is sent | +| `stream_start` | `{"session_id","duration_s","mode","frame_size"}` | main loop | +| `stream_stop` | — | immediately | +| `ota_update` | `{"url","sha256","size"}`, or empty to use the envelope target | main loop | +| `reboot` | — | immediately, acked first | + +`sleep_now` on a device with sleep switched off acks `rejected`. + +--- + +## Firmware / OTA + +`GET /api/v1/firmware/{version}.bin` — bearer auth, **must send +`Content-Length`** (the device refuses chunked: it wants to size-check against +the manifest before erasing a partition). + +The device verifies SHA-256 over the whole image before activating the slot, +then boots it in `PENDING_VERIFY`. It calls `esp_ota_mark_app_valid` **only +after a heartbeat the endpoint accepted** — that proves WiFi, HTTP, auth and +JSON parsing all work on the new image. Anything weaker would confirm a +firmware that boots but cannot talk. If the trial image never checks in, the +next reset rolls back automatically. + +So: a bad firmware costs a reboot cycle, not a ladder. + +--- + +## Streaming + +``` +POST /api/v1/stream/{session_id} +Authorization: Bearer … +Content-Type: multipart/x-mixed-replace; boundary=poorbirdframe +X-Stream-Mode: watch | record | both +X-Duration-S: 60 +Transfer-Encoding: chunked +``` + +The device pushes; the endpoint relays and/or records (SPEC C3 — the ESP32 +never serves a stream and is never reachable from outside the LAN). + +**Getting it outside is then entirely the endpoint's problem**, which is the +point of the design: the hard parts (TLS, certificate renewal, auth, rate +limiting, abuse handling) live on the machine with a package manager and logs, +not on the camera. In rough order of effort: + +- **LAN only** — the endpoint re-serves the same `multipart/x-mixed-replace` + stream to a browser. An `` tag renders it with no + JavaScript. Maybe thirty lines of server code. +- **Public, low effort** — the same MJPEG endpoint behind a Cloudflare Tunnel: + public hostname and TLS, no port forwarding, nothing exposed inbound. + MJPEG is bandwidth-hungry but perfectly watchable for one or two viewers. +- **Public, done properly** — feed the frames into MediaMTX and serve WebRTC + or HLS. Lower latency, many viewers, and the transcode happens on the + endpoint where there is CPU to spare. + +None of these change anything on the device. It pushes JPEGs to one URL in +every case. + +Each part: + +``` +--poorbirdframe +Content-Type: image/jpeg +Content-Length: 18422 +X-Timestamp: 1758376267123 + + +``` + +Terminated by `--poorbirdframe--`. The device stops itself at `X-Duration-S` +(hard-capped at 600 s in firmware, SPEC C9). **Closing the connection +server-side is a supported way to stop a stream** — the device treats five +consecutive failed writes as a normal end, so a viewer navigating away does not +need a `stream_stop` command. + +`mode` is advisory to the Pi; the device sends identical bytes in all three. + +--- + +## Behaviour the Pi should expect + +- **Bounded retries, always.** Three WiFi attempts with exponential backoff, + then give up until the next cycle (SPEC §4.3). The device never hammers. +- **Heartbeat backoff.** After four consecutive failures the interval doubles + per failure up to one hour. A Pi that is down for maintenance does not + generate a wall of failed requests. +- **Burst uploads are sequential, not concurrent.** One connection at a time. +- **401 anywhere** clears the stored token and triggers re-enrollment. +- **Events are dropped while a stream is running.** You will see a gap in + captures for the duration of a session. diff --git a/firmware/README.md b/firmware/README.md new file mode 100644 index 0000000..5f980da --- /dev/null +++ b/firmware/README.md @@ -0,0 +1,314 @@ +# poorBird firmware — XIAO ESP32S3 Sense + HLK-LD2410 + +ESP-side skeleton. + +**Verified:** builds clean from scratch against pioarduino 53.03.13 +(Arduino-ESP32 3.1.x / IDF 5.3), no warnings in project sources. +1132 KB flash (34 % of a 3.2 MB OTA slot), 60 KB static RAM. + +**Not verified:** none of it has run on hardware. The LD2410 frame offsets are +transcribed from the datasheet, the XIAO status-LED pin has moved between board +revisions, and no radio, camera or radar code path has executed. Treat the +first bring-up as a debugging session, not a smoke test. + +## Layout + +``` +platformio.ini build config; the knobs live in [common] +secrets.ini.example copy to secrets.ini (gitignored) before flashing +partitions/ 8 MB, dual OTA slots + rollback (SPEC C6) +scripts/load_secrets.py turns secrets.ini into -D flags + +include/board_pins.h ALL wiring in one place, every free pin overridable +include/app_config.h the full runtime config struct + +src/app_config.cpp NVS load/save, JSON merge from the endpoint, clamps +src/power_mgr.cpp the deep-sleep on/off switch and its inhibit locks +src/camera_mgr.cpp OV2640 lifecycle + day/night tuning profiles +src/frame_ring.cpp PSRAM pre-trigger ring ← the interesting one +src/ld2410.cpp radar UART protocol + presence pin +src/net_mgr.cpp WiFi with bounded retries, clock from the endpoint +src/api_client.cpp REST client: enroll, ingest, heartbeat, status, config, stream +src/battery.cpp supply voltage, percentage curves, the OTA gate +src/device_stats.cpp daily counters in RTC memory, local-midnight rollover +src/nightlight.cpp night window, illuminator, what to do after dark +src/ota_mgr.cpp SHA-256 verify, trial boot, automatic rollback +src/stream_session.cpp time-boxed MJPEG push +src/commands.cpp the WebUI → device command queue +src/main.cpp both operating modes +``` + +`API.md` is the contract for the Pi side. + +## Wiring + +| LD2410 | XIAO | GPIO | Note | +|---|---|---|---| +| VCC | 5V | — | plain LD2410, no Bluetooth | +| GND | GND | — | | +| TX | D1 | 2 | ESP receives — **measure this, see below** | +| RX | D0 | 1 | ESP transmits; 3.3 V clears the module's input threshold | +| OUT | D2 | 3 | active high; RTC-capable, so it doubles as the deep-sleep wake pin — **measure this too** | + +**Measure OUT and TX with a multimeter before connecting them.** The LD2410's +logic is supposed to be 3.3 V even on a 5 V supply, but this varies between +batches and clones, and the ESP32-S3 is not 5 V tolerant. Wave a hand at the +module so OUT asserts, then measure. If either reads ~5 V, drop it with a +divider: 10k from the module into the GPIO, 20k from the GPIO to ground. Two +minutes now beats discovering a dead pin on a camera you cannot reach. + +**Baud rate needs no decision.** `radarBegin()` probes 256000, 115200, 57600, +38400 and 9600 and keeps whichever produces valid frames, so a factory-default +module and a reconfigured one both just work — and a factory reset (which +returns the module to 256000) does not silently take the trigger offline. Pin +it with the `radar_baud` setting if you would rather it not probe. + +Optional, nothing wired by default: + +| Function | Default pin | Note | +|---|---|---| +| Battery sense | `D3` / GPIO4 | needs an external divider — see the diagram in `include/battery.h` | +| Divider enable | — (`-1`) | MOSFET on the divider's low side, so it only draws during a read | +| Nightlight | — (`-1`) | PWM; drive a MOSFET, never the LED directly | +| Radar power gate | — (`-1`) | only useful for timer-only deep sleep | + +Still free: `D4`/GPIO5 + `D5`/GPIO6 (I²C for a future BME280 or DS3231), +`D6`/GPIO43 + `D7`/GPIO44 (UART0 — deliberately left for hardware debug). +`D8`–`D10` are the Sense board's microSD; leave them if you want local +buffering later. + +Change any of it with a `-D` flag, no source edit: + +```ini +build_flags = ${common.build_flags} -DPIN_RADAR_OUT=4 -DRADAR_BAUD=115200 +``` + +## First flash + +```bash +cp secrets.ini.example secrets.ini # then edit it +pio run -e xiao_s3_sense -t upload +pio device monitor +``` + +The first build downloads ~1 GB of toolchain and takes about 12 minutes; +afterwards a clean rebuild is under a minute. + +`platformio.ini` pins pioarduino `53.03.13` because PlatformIO Core 6.1.x +cannot load the current `stable` release (it needs Core >= 6.2.0). If you run +`pio upgrade` to 6.2.0, you can switch the `platform =` line to the `stable` +alias and get Arduino 3.3 / IDF 5.5. + +On the Pi, generate the enrollment secret with `openssl rand -hex 32` and put +the same value in both places. On first boot the device trades it for a +per-device token, stores that in NVS, and wipes the secret. + +Expected first-boot log: + +``` +poorBird 0.1.0 (xiao-esp32s3-sense-ld2410) +power: boot #1, wake cause power-on, 0s slept so far +--- poorBird config --- +radar: UART1 @256000 baud (detected) rx=2 tx=1 out=3 +radar self-test: 1284 bytes, 7 decoded frames, OUT=0 +wifi: 192.168.1.88 rssi -58 dBm +enrolled via stored secret: token + per-device re-enrollment secret stored +time: synced, 2026-09-20T14:31:07Z +camera ready: sensor PID 0x2640, SVGA (800x600) quality=12 psram_free=6784KB +ring: 24 slots x 48KB = 1152KB PSRAM (free 6784KB) +awake mode: pre-trigger ring active (24 frames, ~9.6 s of history) +``` + +`radar: no UART frames at any baud` ⇒ TX and RX are not crossed, the module +is not powered, or it is dead. The baud rate is no longer a candidate +explanation, since all the plausible rates were tried. The OUT pin path still +works in the meantime: set `radar_mode: 0` to trigger on it alone. + +## The two power modes + +One flag, `deep_sleep_enabled`, switchable from the WebUI at runtime. + +| | **awake** (default) | **sleep** | +|---|---|---| +| Camera | always initialised | off between events | +| Pre-trigger frames | **yes**, ~10 s of history | no | +| Trigger→first frame | effectively negative | 1–3 s (SPEC C4) | +| Command latency | one loop tick | up to `deep_sleep_s` | +| Streaming | on demand | only from the next wake | +| ESP current | ~80–120 mA | tens of µA asleep | + +Switching it on does not slam the door: the device finishes the current wake +(so the ack reaches the Pi) and only then sleeps, giving you +`sleep_idle_timeout_s` to change your mind. Switching it off takes effect at +the next wake — unavoidable, that is SPEC C1. + +Sleep is blocked outright by refcounted inhibits: an upload in flight, a live +stream, an OTA flash, a `wake_and_hold`. `sleep_max_awake_s` is a deadlock +escape that overrides all of them **except OTA** — sleeping mid-flash bricks +the device. + +### The honest caveat + +The LD2410 draws roughly 80 mA continuously and must stay powered to act as a +wake source. So with `sleep_wake_on_radar = true`, the ESP sleeping at 20 µA +saves you almost nothing — the radar dominates. Deep sleep is a real power win +only if you either: + +- set `sleep_wake_on_radar = false`, wake on the timer alone, and power-gate + the radar through a MOSFET on `PIN_RADAR_EN`; or +- fit an AM312 PIR on `PIN_AUX_ADC` as the wake source and use the radar only + to confirm once awake. + +That is a wiring decision. The switch works either way. + +## Why the ring buffer is the point + +SPEC C4 says the first usable frame lands 1–3 s after the bird arrives, by +which time a small bird is gone. That is only true if capture *starts* at the +trigger. + +Running on mains, the camera captures continuously into a PSRAM ring. On a +trigger the device ships `pre_roll` frames from **before** it plus `post_roll` +frames from after. Effective latency goes negative and C4 stops being a +problem. Cost: `ring_frames × ~48 KB` of the 8 MB PSRAM — about 1.1 MB at the +defaults, for roughly 10 s of history. + +This is the single largest quality difference between the battery design in +`SPEC.md` and this one, and it is why the mains decision is worth more than it +first looks. + +## Cameras + +The XIAO ESP32S3 **Sense** ships with an OV2640 on its expansion board, and +that is what this firmware drives. The ESP32-S3 handles it better than the +original ESP32-CAM does, because the S3 has a dedicated LCD_CAM peripheral +rather than repurposing I²S. + +Three things worth knowing before you buy or swap anything: + +**The bare XIAO ESP32S3 cannot take a camera.** The DVP pins (GPIO 10–18, 38, +39, 40, 47, 48) are not on the 14 castellated pads — they only come out +through the board-to-board connector that the Sense expansion board mates +with. "XIAO ESP32S3 + a camera module" is not a working combination; you need +the Sense. + +**You may receive an OV3660 rather than an OV2640.** Seeed's wiki still says +OV2640, but newer units have reportedly shipped with OV3660. The driver +detects the sensor over SCCB at init, so the firmware does not care — it logs +the PID (`0x2640` / `0x3660` / `0x5640`) and reports it in the status payload. +An OV3660 gives you QXGA 2048×1536 instead of the OV2640's UXGA ceiling. + +**The OV5640 is an official drop-in upgrade** (Seeed sells it for this board, +with a heat sink). 2592×1944 versus the OV2640's 1600×1200, better low light, +and autofocus. Whether it is worth it here: + +- *For* — pixels on target is the real limit when the bird is small in frame. +- *Against* — bigger JPEGs mean fewer ring slots and longer uploads, it is + slower at full resolution (so a lower ring frame rate and less pre-trigger + history), and it runs hot enough to ship with a heat sink. Autofocus is + arguably a downside on a fixed-distance feeder, where fixed focus is more + predictable and never hunts at the wrong moment. +- If you switch, **drop `ring_frames`**. Twenty-four slots at ~400 KB is + 9.6 MB, more than the 8 MB of PSRAM; the ring degrades gracefully and logs, + but you want about 12. + +The frame size is set by name (`"SVGA"`, `"UXGA"`), never by number — see +`API.md` for why that matters. + +## Night, and why the default is to sleep through it + +`night_behaviour` decides what happens between `night_start_min` and +`night_end_min` (minutes from local midnight; the Pi should push real +sunset/sunrise, the 21:00–06:00 defaults are a fallback): + +- **0 `capture`** — keep working, using the `cam_night` tuning profile and the + illuminator if one is fitted. +- **1 `idle`** — stay awake and reachable, capture nothing. +- **2 `sleep`** (default) — deep sleep until morning, **even when + `deep_sleep_enabled` is false**. A camera with no illuminator has nothing to + do at 03:00 whether it is mains-powered or not. The cost: unreachable until + dawn, so a config change made at 23:00 lands in the morning. + +Night sleep never wakes on the radar. The point is to ignore the night, not to +photograph every cat that walks past. + +### Read this before buying an illuminator + +The obvious choice is 850 nm or 940 nm IR, because birds barely perceive it and +white light at a feeder at night is disruptive. But **the OV2640 module on the +XIAO Sense has an IR cut filter bonded over the sensor**, which blocks exactly +those wavelengths. An IR LED on an unmodified Sense gives you a black frame. + +In the order I would try them: + +1. Accept no night capture (`night_behaviour: 2`). Most garden birds are + diurnal; you lose very little and the whole problem goes away. +2. Dim, warm, continuous white light (`nightlight_mode: 2`). Continuous beats a + flash per burst — animals habituate to steady light and startle at sudden + light — and auto-exposure is already settled when a bird arrives. Still + disturbs wildlife. +3. Remove the IR filter and use 850 nm. Best images, irreversible, and it + wrecks daytime colour unless you fit a switchable filter. + +The firmware supports all three; option 3 needs no code change. + +## Battery sensing + +Off by default: the XIAO does not bring its battery rail out to a pin you can +simply read, so this needs an external divider from BAT+ to `PIN_BATTERY_ADC`. +The wiring is documented at the top of `include/battery.h`. Until it is wired, +readings report `valid: false` — which the endpoint must render as "not +measured", never as 0 V. + +Once wired, set `battery_divider_x100` from your *measured* resistor values +(not their printed ones) and trim `battery_offset_mv` against a multimeter. +Percentage comes from a piecewise curve per chemistry. For LiFePO4 be warned +that the curve is nearly flat between 20 % and 90 % — the percentage there is +close to meaningless, which is a property of the chemistry, not of the code. + +This also arms SPEC C6's OTA battery gate. One deliberate choice worth +knowing: with **no** sensing hardware the gate allows the flash rather than +blocking it, on the grounds that refusing every OTA on a mains-powered device +because an optional sensor is absent is worse than the risk it guards against. + +## Tuning the radar for birds + +The LD2410 is designed to detect *humans*. A blue tit has a far smaller radar +cross-section, and swaying branches and heavy rain both register. Expect to +spend an evening on this. Everything below is a config push, not a reflash: + +- `max_distance_cm` — window it tightly to the feeder. The single most + effective false-positive filter. +- `min_energy` — raise until branches stop triggering, lower until birds start. +- `accept_stationary` — a bird sitting on a perch is a stationary target. On + for a feeder, off if you only care about arrivals. +- `radar_mode` — `0` ignores the UART entirely and trusts the OUT pin. Useful + to isolate whether a problem is the protocol decode or the sensor itself. + +If it cannot be made to work, `PIN_AUX_ADC` is free for an AM312 and the +trigger logic is one function (`radarIsTrigger`). + +## What is deliberately not here + +- **Local SD buffering.** Uploads that fail are lost rather than queued to the + microSD. Worth adding if the WiFi link turns out to be marginal; the pins are + free. +- **On-device frame differencing** (SPEC Option C). The ring buffer makes this + much easier to add later — you already have consecutive frames in PSRAM. +- **TLS.** Deliberate, SPEC C2. + +## Open items in the code + +- `ld2410.cpp` frame offsets are from the datasheet, not verified. +- Battery percentage curves are generic open-circuit approximations at room + temperature. Good enough for a low banner and the OTA gate, not for a + runtime estimate. +- `nightlight.cpp` allocates an LEDC channel after the camera has taken + channel 0 for XCLK. That should route around it, but it is untested. +- Daily counters live in RTC memory and reset on power loss, by design. The + endpoint's own count is authoritative. +- `radarSetGateSensitivity` sends the command but only checks that *something* + came back, not that the ACK matches. +- `PIN_STATUS_LED` (GPIO21) has moved between XIAO board revisions — verify. +- The LD2410's logic level on a 5 V supply is unverified on this hardware. + Measure before connecting; see Wiring. diff --git a/firmware/include/api_client.h b/firmware/include/api_client.h new file mode 100644 index 0000000..3cbd756 --- /dev/null +++ b/firmware/include/api_client.h @@ -0,0 +1,103 @@ +// api_client.h — everything the device says to the Pi. +// +// TRANSPORT DECISION (answers "standard REST API, I guess?") +// Yes, REST over plain HTTP with a bearer token (SPEC C2 — TLS stays on the +// Pi). One deviation from SPEC §4.1, and it is worth making: +// +// SPEC says: POST /ingest multipart/form-data: image + JSON meta +// we do: POST /ingest Content-Type: image/jpeg, raw body, meta in headers +// +// Why: multipart means the device assembles a body with boundaries, so the +// JPEG gets copied into a second buffer purely to add a wrapper the server +// immediately strips. Raw body + headers hands esp_http_client the framebuffer +// pointer directly — no copy, no assembly, less heap, and one fewer thing to +// get wrong at 3 a.m. It is still an ordinary REST call; `curl --data-binary +// @frame.jpg -H 'X-Trigger: radar'` reproduces it exactly. +// +// The metadata is small and flat (a dozen scalars), which is precisely the +// case headers handle well. If it ever grows nested structure, switch that one +// endpoint to multipart and keep the rest. +// +// AUTH DECISION (answers "the token comes from the endpoint, I guess?") +// Yes. Two-step, and the long-lived token is never in source or in a build +// flag: +// 1. A *shared enrollment secret* is compiled in (or typed once). The device +// POSTs /enroll with its eFuse-derived UID. +// 2. The Pi creates the device row, returns a per-device token, and the +// device stores it in NVS and wipes the enrollment secret. +// From then on every request carries `Authorization: Bearer `. Rotating +// a token in the admin UI just means the next request 401s and the device +// re-enrolls. The Pi stores only the hash (SPEC §3 `devices.token_hash`). +#pragma once + +#include +#include + +#include "frame_ring.h" + +// What the endpoint sends back on ingest/heartbeat. SPEC §4.1: the upload +// response carries the command queue, so a capture that was going to happen +// anyway also delivers pending commands at no extra cost. +struct ServerEnvelope { + bool ok; + int http_status; + int64_t server_time_ms; // authoritative clock (SPEC C7) + uint32_t config_version; // if it differs from ours, pull config + bool has_firmware; + char fw_version[24]; + char fw_url[160]; + char fw_sha256[65]; + uint32_t fw_size; + // Commands are handled inside the parse callback rather than copied out, + // so this struct stays a fixed-size value type. + uint8_t command_count; +}; + +struct CaptureMeta { + const char* trigger; // radar | timer | manual | prebuffer | stream_grab + const char* burst_id; // groups the frames of one event + uint8_t burst_index; + uint8_t burst_count; + int8_t pre_trigger; // 1 if this frame predates the trigger + uint16_t radar_distance_cm; + uint8_t radar_energy; + uint8_t radar_state; +}; + +// Called once per command in a response envelope. +typedef void (*CommandHandler)(JsonObjectConst cmd); + +void apiBegin(); + +// Exchange the enrollment secret for a device token. No-op if already enrolled. +// Returns true when g_cfg.device_token is populated and persisted. +bool apiEnroll(); + +// POST one JPEG. `meta` rides in headers. +ServerEnvelope apiIngest(const FrameCopy& frame, const CaptureMeta& meta, CommandHandler on_cmd); + +// POST device conditions; the response carries the same envelope as ingest. +// This is the call that drains the command queue, so it is also the one that +// must not be made from somewhere the device cannot then act on a command. +ServerEnvelope apiHeartbeat(CommandHandler on_cmd); + +// POST the same conditions body to /status, which returns 204 and no command +// queue. For pushes where picking up commands would be wrong or wasteful: +// immediately before deep sleep (the device is about to become unable to act), +// after an upload burst, or on an explicit report_status command. +// Returns true on a 2xx. +bool apiPostStatus(const char* reason); + +// GET the full device config and merge it into g_cfg. Returns true if changed. +bool apiFetchConfig(); + +// Report a command's outcome so the WebUI can stop showing it as pending. +bool apiAckCommand(uint32_t command_id, const char* status, const char* detail); + +// Open a chunked MJPEG push for a streaming session. See stream_session.cpp. +bool apiStreamOpen(const char* session_id, uint8_t mode, uint16_t duration_s); +bool apiStreamSendFrame(const uint8_t* jpeg, size_t len, int64_t epoch_ms); +void apiStreamClose(); + +// True when the last request returned 401 — the caller should re-enroll. +bool apiTokenRejected(); diff --git a/firmware/include/app_config.h b/firmware/include/app_config.h new file mode 100644 index 0000000..ec30484 --- /dev/null +++ b/firmware/include/app_config.h @@ -0,0 +1,193 @@ +// app_config.h — the device's entire runtime configuration. +// +// Three layers, later ones win: +// 1. compile-time defaults (platformio.ini -D flags) +// 2. NVS, written on first boot and on every accepted config push +// 3. `apply_config` command from the endpoint, carrying a config_version +// +// The endpoint is the source of truth. The device reports the config_version it +// is running in every request; the endpoint pushes a new config whenever those +// disagree. That keeps SPEC §3.4 ("Device settings pushed via apply_config") +// working without a separate settings-fetch round trip. +#pragma once + +#include +#include + +enum StreamMode : uint8_t { + STREAM_WATCH = 0, // relay to viewers, do not persist + STREAM_RECORD = 1, // persist on the Pi, no live viewers + STREAM_BOTH = 2, +}; + +enum RadarMode : uint8_t { + RADAR_OUT_PIN_ONLY = 0, // trust the module's presence pin, ignore UART + RADAR_UART_ONLY = 1, // decode reports, apply distance/energy windows + RADAR_BOTH = 2, // OUT pin arms, UART report confirms (default) +}; + +enum NightBehaviour : uint8_t { + NIGHT_CAPTURE = 0, // keep working, using the night camera profile + NIGHT_IDLE = 1, // stay awake and reachable, but capture nothing + NIGHT_SLEEP = 2, // deep sleep until morning, even if deep sleep is off +}; + +enum NightlightMode : uint8_t { + NIGHTLIGHT_OFF = 0, + NIGHTLIGHT_ON_BURST = 1, // illuminate only while a burst is being captured + NIGHTLIGHT_ALWAYS = 2, // on for the whole night; kinder to wildlife +}; + +enum BatteryChemistry : uint8_t { + BATT_NONE = 0, // no cell wired; report voltage only, no percentage + BATT_LIION = 1, // Li-ion / LiPo, 4.20 V full + BATT_LIFEPO4 = 2, // LiFePO4, 3.65 V full — flat curve, see battery.cpp +}; + +// OV2640 tuning. Held twice (day and night) so the device can switch profiles +// at dusk without a round trip to the endpoint. Ranges are the sensor's own; +// see camera_mgr.cpp for what each one is worth on a bird camera. +struct CamTuning { + int8_t brightness; // -2..2 + int8_t contrast; // -2..2 + int8_t saturation; // -2..2 + int8_t sharpness; // -2..2 (OV2640 support is patchy) + int8_t ae_level; // -2..2 exposure bias + uint8_t special_effect; // 0 none 1 negative 2 grayscale 3 red 4 green 5 blue 6 sepia + uint8_t wb_mode; // 0 auto 1 sunny 2 cloudy 3 office 4 home + uint8_t gainceiling; // 0=2x 1=4x 2=8x 3=16x 4=32x 5=64x 6=128x + uint8_t agc_gain; // 0..30, only used when gain_ctrl = 0 + uint16_t aec_value; // 0..1200, only used when exposure_ctrl = 0 + bool whitebal; + bool awb_gain; + bool exposure_ctrl; // false = manual, use aec_value + bool aec2; // DSP-assisted auto exposure + bool gain_ctrl; // false = manual, use agc_gain + bool bpc; // black pixel correction + bool wpc; // white pixel correction + bool raw_gma; + bool lenc; // lens shading correction + bool dcw; // downsize/crop enable + bool colorbar; // test pattern — bring-up only +}; + +struct AppConfig { + // --- identity & endpoint --------------------------------------------- + char device_name[32]; + char wifi_ssid[33]; + char wifi_pass[64]; + char api_host[64]; // Pi's IP. Use a DHCP reservation, not mDNS. + uint16_t api_port; + char api_base[24]; // "/api/v1" + char device_token[65]; // issued by the endpoint at enrollment + // The secret used to (re-)enroll. Starts as the shared bootstrap secret + // from secrets.ini and is replaced, at first enrollment, by a per-device + // one issued by the endpoint. Deliberately NOT wiped: the device must be + // able to recover from a token rotation on its own, because reaching it + // over USB is not an option once it is mounted. See api_client.h. + char enroll_secret[65]; + + // --- time (SPEC C7: the endpoint is the time server) ------------------- + char ntp_host[64]; // empty => use api_host + char tz[48]; // POSIX TZ string + + // --- camera ------------------------------------------------------------ + uint8_t frame_size; // framesize_t + uint8_t jpeg_quality; // 4..40, lower is better + bool vflip; + bool hmirror; + CamTuning cam_day; + CamTuning cam_night; // applied automatically between dusk and dawn + + // --- capture / trigger --------------------------------------------------- + uint8_t ring_frames; // PSRAM history depth + uint8_t pre_roll; // frames sent from before the trigger + uint8_t post_roll; // frames sent after + uint16_t post_roll_gap_ms; // spacing between post-roll frames + uint16_t cooldown_s; // minimum gap between two trigger events + uint16_t idle_period_ms; // ring refresh period when nothing is happening + + // --- radar --------------------------------------------------------------- + uint8_t radar_mode; // RadarMode + bool accept_stationary; // a motionless bird still counts + uint16_t min_distance_cm; + uint16_t max_distance_cm; + uint8_t min_energy; // 0..100, per-report energy floor + uint32_t radar_baud; // 0 = autodetect (recommended) + + // --- live stream (SPEC C9 — plumbing built, off by default) -------------- + bool stream_enabled; + uint8_t stream_frame_size; // usually lower than stills + uint8_t stream_jpeg_quality; + uint16_t stream_duration_s; // hard cap; the device stops itself + uint8_t stream_fps; + uint8_t stream_mode; // StreamMode + + // Streaming and sleeping are mutually exclusive: a sleeping device cannot + // be told to start a stream (SPEC C1). With this set, enabling streaming + // keeps the device awake and reachable so `stream_start` arrives promptly. + // Clear it to let the device sleep anyway and accept the wake latency. + bool stream_blocks_sleep; + + // --- night --------------------------------------------------------------- + // The window is minutes from local midnight. The endpoint knows the site's + // latitude, so the intended use is for the Pi to push real sunset/sunrise + // daily; the fixed defaults are only a fallback. + uint16_t night_start_min; // default 21:00 + uint16_t night_end_min; // default 06:00 + uint8_t night_behaviour; // NightBehaviour + uint8_t nightlight_mode; // NightlightMode + uint8_t nightlight_brightness; // 0..255 PWM duty + + // --- battery / supply ----------------------------------------------------- + uint8_t battery_chemistry; // BatteryChemistry + uint16_t battery_divider_x100; // divider ratio x100, e.g. 200 = 2.00:1 + int16_t battery_offset_mv; // calibration trim, added after scaling + uint8_t battery_min_pct_ota; // SPEC C6: refuse to flash below this + uint8_t battery_warn_pct; // surfaced to the WebUI as a low alarm + + // --- ops ----------------------------------------------------------------- + uint16_t heartbeat_interval_s; + uint16_t status_interval_s; // POST /status cadence; 0 = only on events + bool ota_enabled; + + // --- power (see power_mgr.h for what each mode gives up) ------------------ + bool deep_sleep_enabled; // the master on/off switch + uint16_t deep_sleep_s; // timer wake interval while asleep + bool sleep_wake_on_radar; // also wake on the LD2410 OUT pin + uint16_t sleep_idle_timeout_s; // stay awake this long after the last event + uint16_t sleep_max_awake_s; // hard cap: sleep even if something is stuck + + uint32_t config_version; +}; + +extern AppConfig g_cfg; + +// Load from NVS, filling anything missing from the compile-time defaults. +void configLoad(); + +// Persist the current g_cfg to NVS. Returns false if the write failed. +bool configSave(); + +// Merge a config document pushed by the endpoint into g_cfg. Only keys present +// in `doc` are touched, so the endpoint can send partial updates. Returns true +// if anything actually changed (caller decides whether a reboot is needed). +bool configApplyJson(JsonObjectConst doc); + +// True when a change needs the camera re-initialised rather than just applied. +bool configNeedsCameraRestart(const AppConfig& before, const AppConfig& after); + +// Stable per-device identifier derived from the eFuse MAC. Survives reflashing, +// which is what makes it usable as the enrollment key. +const char* deviceUid(); + +// The shared bootstrap secret compiled in from secrets.ini. Kept reachable as +// a last-resort fallback: if the per-device re-enrollment secret in NVS is +// ever rejected, the device can still get back in with this one rather than +// needing a USB cable. +const char* configBootstrapSecret(); + +// Base URL without trailing slash, e.g. "http://192.168.1.50:8080/api/v1". +String apiBaseUrl(); + +void configDump(); diff --git a/firmware/include/battery.h b/firmware/include/battery.h new file mode 100644 index 0000000..7ee3121 --- /dev/null +++ b/firmware/include/battery.h @@ -0,0 +1,47 @@ +// battery.h — supply / battery voltage sensing. +// +// WIRING (nothing is wired by default; reads report invalid until it is) +// The XIAO ESP32S3 does not bring the battery rail out to an ADC pin you can +// simply read — the documented approaches involve soldering, and the divider +// differs between board revisions. So this driver assumes an *external* +// divider you add yourself: +// +// BAT+ ──[ R1 ]──┬──[ R2 ]── GND +// └── PIN_BATTERY_ADC (default D3 / GPIO4) +// +// Two 1 MΩ resistors give a 2.00:1 ratio and ~2 µA of continuous drain, which +// is negligible on mains and tolerable on battery. If you care about the last +// microamp, gate the low side with a MOSFET on PIN_BATTERY_EN — SPEC §9 is +// right that an always-connected divider is a permanent load. +// +// Set `battery_divider_x100` to your actual ratio: measure the real resistors +// rather than trusting their printed value, then trim with +// `battery_offset_mv` against a multimeter. The ESP32 ADC is not linear and +// `analogReadMilliVolts()` only corrects for the part of that Espressif +// characterised at the factory. +#pragma once + +#include + +struct BatteryReading { + bool valid; // false when no divider is configured or the read failed + uint16_t mv; // battery terminal voltage in millivolts + uint8_t pct; // 0..100, 0 when chemistry is BATT_NONE + uint16_t raw_mv; // at the pin, before the divider ratio is applied +}; + +void batteryBegin(); + +// Averaged, calibrated read. Powers the divider for the measurement if +// PIN_BATTERY_EN is wired, then turns it off again. +BatteryReading batteryRead(); + +// Last reading without touching the ADC. Cheap; use this in status payloads +// that are built more often than the voltage can meaningfully change. +BatteryReading batteryLast(); + +// Refresh the cached reading. Called on a timer from the main loop. +void batteryPoll(); + +// SPEC C6 gate, registered with otaSetBatteryCheck(). +bool batteryAboveOtaThreshold(uint8_t min_pct); diff --git a/firmware/include/board_pins.h b/firmware/include/board_pins.h new file mode 100644 index 0000000..e9be1b4 --- /dev/null +++ b/firmware/include/board_pins.h @@ -0,0 +1,131 @@ +// board_pins.h — single place where physical wiring is declared. +// +// Hardware is not in hand yet, so every free-pin assignment here is a default +// that can be overridden with a -D build flag without touching source. The +// camera pins are fixed by the XIAO ESP32S3 Sense expansion board and are not +// overridable; they are listed so the wiring is documented in one place. +#pragma once + +// --------------------------------------------------------------------------- +// XIAO ESP32S3 Sense — OV2640 on the expansion board. Fixed by the PCB. +// --------------------------------------------------------------------------- +#define CAM_PIN_PWDN -1 +#define CAM_PIN_RESET -1 +#define CAM_PIN_XCLK 10 +#define CAM_PIN_SIOD 40 // SCCB SDA +#define CAM_PIN_SIOC 39 // SCCB SCL +#define CAM_PIN_D7 48 +#define CAM_PIN_D6 11 +#define CAM_PIN_D5 12 +#define CAM_PIN_D4 14 +#define CAM_PIN_D3 16 +#define CAM_PIN_D2 18 +#define CAM_PIN_D1 17 +#define CAM_PIN_D0 15 +#define CAM_PIN_VSYNC 38 +#define CAM_PIN_HREF 47 +#define CAM_PIN_PCLK 13 + +// --------------------------------------------------------------------------- +// HLK-LD2410 24 GHz radar +// +// Wiring (module -> XIAO): +// VCC -> 5V (plain LD2410, no Bluetooth) +// GND -> GND +// TX -> D1 / GPIO2 (ESP RX) +// RX -> D0 / GPIO1 (ESP TX) +// OUT -> D2 / GPIO3 (presence, active HIGH; RTC-capable so it can also +// serve as a deep-sleep wake source later) +// +// MEASURE THE LOGIC LEVELS BEFORE CONNECTING. The LD2410's logic is supposed +// to be 3.3 V even when VCC is 5 V (it regulates internally), but this varies +// between batches and clones, and the ESP32-S3 is not 5 V tolerant. A 5 V OUT +// into GPIO3 damages the pin, and on a camera you cannot physically reach +// that is an expensive way to find out. +// +// Two minutes with a multimeter on OUT and TX (wave a hand in front of the +// module so OUT asserts) settles it. If either reads ~5 V, drop it with a +// divider -- 10k from the module into the GPIO, 20k from the GPIO to GND +// gives 3.3 V from 5 V. The ESP's TX into the module's RX needs nothing: +// 3.3 V comfortably clears the module's input threshold. +// +// Baud rate is autodetected (see radarBegin), so a module at the factory +// 256000 and one reconfigured to 115200 both just work, and a factory reset +// does not take the trigger offline. +// +// Deliberately NOT on D6/D7 (GPIO43/44): those are UART0, which the ROM +// bootloader spews boot logs onto at every reset. Harmless for the radar, but +// it costs you the one easy hardware debug port. Keep 43/44 free. +// --------------------------------------------------------------------------- +#ifndef PIN_RADAR_TX +#define PIN_RADAR_TX 1 // D0 — ESP transmits, goes to LD2410 RX +#endif +#ifndef PIN_RADAR_RX +#define PIN_RADAR_RX 2 // D1 — ESP receives, comes from LD2410 TX +#endif +#ifndef PIN_RADAR_OUT +#define PIN_RADAR_OUT 3 // D2 — presence output +#endif +#ifndef RADAR_UART_NUM +#define RADAR_UART_NUM 1 // UART1 via the GPIO matrix +#endif +#ifndef RADAR_BAUD +#define RADAR_BAUD 256000 // LD2410 factory default +#endif + +// Optional high-side MOSFET gating the radar's supply. -1 = permanently powered. +// Only worth wiring if you run deep sleep with sleep_wake_on_radar = false: +// the LD2410 draws ~80 mA continuously, which dwarfs anything the ESP saves by +// sleeping. See the note at the top of power_mgr.h. +#ifndef PIN_RADAR_EN +#define PIN_RADAR_EN -1 +#endif + +// --------------------------------------------------------------------------- +// Spare I/O — reserved, nothing wired yet. +// --------------------------------------------------------------------------- +#ifndef PIN_AUX_ADC +#define PIN_AUX_ADC 4 // D3 / A3 — spare ADC, or a PIR fallback +#endif +#ifndef PIN_I2C_SDA +#define PIN_I2C_SDA 5 // D4 — future BME280 / DS3231 +#endif +#ifndef PIN_I2C_SCL +#define PIN_I2C_SCL 6 // D5 +#endif + +// Battery / supply sensing. Defaults to the spare ADC pin above. The XIAO +// does not expose its battery rail on a readable pin, so this needs an +// external divider — see the wiring diagram at the top of battery.h. +// Set to -1 to disable; voltage then reports as invalid rather than as zero. +#ifndef PIN_BATTERY_ADC +#define PIN_BATTERY_ADC PIN_AUX_ADC +#endif + +// Optional MOSFET on the divider's low side, so it only draws current during +// a measurement (SPEC §9). -1 = divider permanently connected. +#ifndef PIN_BATTERY_EN +#define PIN_BATTERY_EN -1 +#endif + +// Nightlight / illuminator, PWM driven. -1 = not fitted. +// Drive a MOSFET or a constant-current module, never the LED directly: an +// ESP32 pin is good for ~20 mA short-term and an illuminator worth having +// draws far more. Read the warning at the top of nightlight.h before choosing +// between IR and white. +#ifndef PIN_NIGHTLIGHT +#define PIN_NIGHTLIGHT -1 +#endif + +// D8/D9/D10 (GPIO7/8/9) are the Sense board's microSD (SD_MMC 1-bit: +// CLK=7, D0=8, CMD=9). Leave them alone if you ever want local buffering. + +// Onboard user LED. Active LOW on the XIAO ESP32S3. +// NOTE: verify against your board revision before trusting it — Seeed has +// moved this pin between revisions. +#ifndef PIN_STATUS_LED +#define PIN_STATUS_LED 21 +#endif +#ifndef STATUS_LED_ACTIVE_LOW +#define STATUS_LED_ACTIVE_LOW 1 +#endif diff --git a/firmware/include/camera_mgr.h b/firmware/include/camera_mgr.h new file mode 100644 index 0000000..8c5d4ff --- /dev/null +++ b/firmware/include/camera_mgr.h @@ -0,0 +1,53 @@ +// camera_mgr.h — OV2640 lifecycle. +// +// Unlike the battery design in SPEC §4.3, the camera stays initialised for the +// life of the boot. That removes the 300-600 ms sensor init and auto-exposure +// settle from the trigger path entirely (SPEC C4) and is what makes the +// pre-trigger ring possible. +#pragma once + +#include +#include + +bool cameraBegin(); +void cameraEnd(); +bool cameraRestart(); // after a frame_size change + +// Push the current g_cfg (quality, flip, mirror) plus the active tuning +// profile onto a running sensor. Frame size is deliberately excluded — see +// configNeedsCameraRestart(). +void cameraApplyConfig(); + +// Apply the day or night tuning profile. Called on dusk/dawn transitions and +// whenever the endpoint pushes new tuning. +void cameraApplyTuning(bool night); + +// Which profile is currently loaded. +bool cameraNightProfileActive(); + +// --- frame sizes ------------------------------------------------------------ +// Resolutions are configured BY NAME ("SVGA", "UXGA"), not by the numeric +// framesize_t index, and these two functions are the only place the mapping +// lives. The reason is not cosmetic: esp32-camera has inserted entries into +// framesize_t between releases — FRAMESIZE_128X128 and FRAMESIZE_320X320 were +// added mid-enum — so a hardcoded index silently means a different resolution +// after a driver update. The tables below are built from the enum symbols, so +// they stay correct by construction. +// +// Numeric values are still accepted from the endpoint for compatibility, but +// names are what the settings UI should send. +uint8_t framesizeFromName(const char* name, uint8_t fallback); +const char* framesizeName(uint8_t fs); +void framesizeDims(uint8_t fs, uint16_t* w, uint16_t* h); + +// Temporarily switch resolution for a streaming session, then put it back. +bool cameraSetFrameSize(uint8_t framesize); + +// Grab one JPEG. Returns nullptr on failure. Caller must esp_camera_fb_return(). +camera_fb_t* cameraGrab(); + +// Throw away the first frames after init so auto-exposure has settled before +// anything is uploaded (SPEC C4). +void cameraDiscardFrames(uint8_t n); + +bool cameraReady(); diff --git a/firmware/include/commands.h b/firmware/include/commands.h new file mode 100644 index 0000000..21baf73 --- /dev/null +++ b/firmware/include/commands.h @@ -0,0 +1,22 @@ +// commands.h — the WebUI -> device channel (SPEC C1). +// +// The device is never contacted directly. The WebUI writes a row into +// `device_commands`; the endpoint attaches pending rows to the next +// ingest/heartbeat response; this module executes them and acks. +// +// Deferred execution: some commands must not run inside the HTTP response +// callback (OTA reboots, streaming blocks for a minute). Those are queued and +// run from the main loop, which is also where sleep decisions are made. +#pragma once + +#include +#include + +// Pass this to apiIngest/apiHeartbeat. Parses and either executes immediately +// or defers. Cheap commands ack from here; deferred ones ack on completion. +void commandOnReceived(JsonObjectConst cmd); + +// Run anything that was deferred. Call once per main-loop tick. +void commandRunDeferred(); + +bool commandHasPending(); diff --git a/firmware/include/device_stats.h b/firmware/include/device_stats.h new file mode 100644 index 0000000..df10c18 --- /dev/null +++ b/firmware/include/device_stats.h @@ -0,0 +1,42 @@ +// device_stats.h — the counters reported in the conditions payload. +// +// Kept in RTC slow memory, so they survive deep sleep. They do NOT survive a +// power cycle, which is deliberate: the endpoint already has the authoritative +// count of what arrived, and a device-side counter that claimed to be durable +// would just be a second source of truth to disagree with the first. Treat +// these as "what this device believes it did today" and reconcile against the +// database, not the other way round. +// +// "Today" is local-midnight to local-midnight, using the TZ pushed from the +// endpoint. Rollover needs a synced clock; before the first sync the counters +// accumulate under day 0 and roll over once when time arrives. +#pragma once + +#include + +struct DeviceStats { + uint16_t captured_today; // frames handed to the uploader + uint16_t delivered_today; // frames the endpoint accepted (2xx) + uint16_t failed_today; // upload attempts that did not get a 2xx + uint16_t events_today; // trigger events, not frames + uint32_t day_index; // days since epoch, local — the rollover key + + uint16_t captured_boot; // since this boot, for spotting a reset + uint16_t delivered_boot; +}; + +void statsBegin(); + +// Roll the daily counters over if the local date has changed. Cheap; call +// from the main loop and before building any status payload. +void statsRollover(); + +void statsCountEvent(); +void statsCountCaptured(uint16_t frames); +void statsCountDelivered(uint16_t frames); +void statsCountFailed(uint16_t frames); + +DeviceStats statsGet(); + +// Ticks since the device last woke, in ms — "ticks since last sleep". +uint32_t statsAwakeMs(); diff --git a/firmware/include/frame_ring.h b/firmware/include/frame_ring.h new file mode 100644 index 0000000..56d6559 --- /dev/null +++ b/firmware/include/frame_ring.h @@ -0,0 +1,52 @@ +// frame_ring.h — pre-trigger history in PSRAM. +// +// THE POINT OF THIS FILE +// SPEC C4 says the first usable frame lands 1-3 s after the bird arrives, by +// which time a small bird is gone. That is only true if capture *starts* at the +// trigger. With mains power we can instead capture continuously into a ring and, +// on a trigger, ship the frames from *before* it. Effective latency goes +// negative and C4 stops being a problem. +// +// Cost: ring_frames * ~45 KB of the 8 MB PSRAM. At depth 24 that is ~1 MB for +// roughly 10 s of history at the default 400 ms cadence. +// +// Ownership: the ring owns its buffers and recycles them in place. Anything +// handed to the uploader is a *copy*, so a slow network cannot stall capture +// and there is no refcounting to get wrong. +#pragma once + +#include + +struct RingFrame { + uint8_t* data; // PSRAM, owned by the ring + size_t len; + size_t cap; // allocated size, >= len + uint32_t seq; // monotonic, 0 = never filled + uint32_t at_ms; // millis() at capture + int64_t at_epoch; // wall-clock ms, 0 if time not yet synced +}; + +// A frame copied out for upload. Caller owns `data` and must free() it. +struct FrameCopy { + uint8_t* data; + size_t len; + uint32_t seq; + uint32_t at_ms; + int64_t at_epoch; +}; + +bool ringBegin(uint8_t depth); +void ringEnd(); + +// Store a frame. Copies into the ring's own PSRAM buffer, growing it if the +// JPEG is larger than the slot currently holds. +bool ringPush(const uint8_t* data, size_t len, int64_t epoch_ms); + +// Copy out the newest `n` frames, oldest first. Returns how many were written +// into `out` (may be fewer than n if the ring has not filled yet). +// Every returned FrameCopy.data must be free()d by the caller. +size_t ringTakeNewest(size_t n, FrameCopy* out, size_t out_cap); + +uint32_t ringSeq(); // sequence of the most recent frame +size_t ringCount(); // frames currently held +size_t ringBytesUsed(); diff --git a/firmware/include/ld2410.h b/firmware/include/ld2410.h new file mode 100644 index 0000000..bdcfab4 --- /dev/null +++ b/firmware/include/ld2410.h @@ -0,0 +1,84 @@ +// ld2410.h — HLK-LD2410 24 GHz presence radar. +// +// The module streams a report frame a few times a second on UART (256000 8N1 by +// factory default) and simultaneously drives an active-high OUT pin. We use +// both: the pin is a zero-latency "something is there", the UART report carries +// the distance and energy needed to reject swaying branches and passing people. +// +// Frame formats (HLK datasheet): +// report F4 F3 F2 F1 | len(2,LE) | payload | F8 F7 F6 F5 +// command FD FC FB FA | len(2,LE) | payload | 04 03 02 01 +// +// Basic report payload (type 0x02): +// [0] 0x02 type [1] 0xAA head +// [2] target state: 0=none 1=moving 2=stationary 3=both +// [3..4] moving distance cm (LE) [5] moving energy 0..100 +// [6..7] stationary distance cm (LE) [8] stationary energy 0..100 +// [9..10] detection distance cm (LE) +// [11] 0x55 tail [12] 0x00 check +// +// These offsets are transcribed from the datasheet, not verified against real +// hardware. Run `radarSelfTest()` once the module is wired and check the log +// before trusting the parsed values. +#pragma once + +#include + +enum RadarTarget : uint8_t { + TARGET_NONE = 0, + TARGET_MOVING = 1, + TARGET_STATIONARY = 2, + TARGET_BOTH = 3, +}; + +struct RadarReading { + bool valid; // a well-formed frame was decoded + uint8_t target; // RadarTarget + uint16_t moving_cm; + uint8_t moving_energy; // 0..100 + uint16_t stationary_cm; + uint8_t stationary_energy; // 0..100 + uint16_t detect_cm; + bool out_pin; // raw presence pin, independent of UART + uint32_t at_ms; // millis() when decoded +}; + +// Bring up UART1 on the configured pins and set the OUT pin as an input. +// +// Probes for the module's baud rate rather than assuming one: the LD2410 +// ships at 256000 and can be reconfigured to 115200 and others, and a factory +// reset puts it back. Autodetecting means neither event takes the trigger +// offline on a device you cannot physically reach. Pin it with +// `g_cfg.radar_baud` to skip the probe. +// +// Returns false if no baud produced a valid frame. That is not fatal — the +// OUT pin path (radar_mode = RADAR_OUT_PIN_ONLY) needs no UART at all. +bool radarBegin(); + +// The baud actually in use, or 0 if nothing was decoded. +uint32_t radarBaud(); + +// Pump the UART. Call often (the radar task does, every few ms). Returns true +// when a new report frame was decoded since the last call. +bool radarPoll(); + +// Most recent decoded report, plus a live read of the OUT pin. +RadarReading radarLast(); + +// Apply the configured distance window, energy floor and stationary policy. +// This is the single place that decides "is this worth waking the camera for", +// so tuning it in the field is one config push, not a firmware change. +bool radarIsTrigger(const RadarReading& r); + +// Log raw bytes for a few seconds so you can confirm baud rate and framing +// when the hardware arrives. Blocking; bring-up only. +void radarSelfTest(uint32_t duration_ms = 5000); + +// Enter/leave the module's configuration mode. Needed before any parameter +// write; the module stops reporting while in config mode. +bool radarEnterConfig(); +bool radarExitConfig(); + +// Per-gate sensitivity. gate 0..8 (~0.75 m each), values 0..100. +// Only call between radarEnterConfig()/radarExitConfig(). +bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary); diff --git a/firmware/include/net_mgr.h b/firmware/include/net_mgr.h new file mode 100644 index 0000000..eaf75e6 --- /dev/null +++ b/firmware/include/net_mgr.h @@ -0,0 +1,40 @@ +// net_mgr.h — WiFi association and clock. +// +// TIME (SPEC C7, and "timeserver is on endpoint") +// Two sources, in order of preference: +// 1. SNTP against the Pi. Cheap, standard, works before any HTTP call. +// 2. The `server_time` field every ingest/heartbeat response carries. This +// is the fallback that matters: if SNTP is blocked or the Pi is not +// running an NTP daemon after all, the device still converges on the +// endpoint's clock without extra configuration. +// Either way `received_at` on the Pi stays authoritative for ordering. The +// device timestamp is a hint, and it is explicitly 0 when unsynced rather than +// silently 1970. +#pragma once + +#include + +bool netBegin(); + +// Associate, with bounded retries and backoff. SPEC §4.3: never loop forever +// on a WiFi outage. Returns false after `max_attempts` failures; the caller +// decides whether that means sleep or retry later. +bool netConnect(uint8_t max_attempts = 3); + +bool netIsConnected(); +void netDisconnect(); + +// Start SNTP against ntp_host (or api_host if unset) and wait up to +// `timeout_ms` for the first sync. +bool netSyncTime(uint32_t timeout_ms = 5000); + +// Accept the endpoint's clock from a response envelope. Only steps the RTC if +// we are unsynced or off by more than 2 s, so normal jitter does not cause a +// timestamp discontinuity mid-burst. +void netAdoptServerTime(int64_t server_ms); + +bool netTimeValid(); +int64_t netEpochMs(); // 0 when not yet synced — never a fake 1970 value + +// "2026-09-20T14:31:07Z" into `out`. Empty string when unsynced. +void netIsoTime(char* out, size_t cap); diff --git a/firmware/include/nightlight.h b/firmware/include/nightlight.h new file mode 100644 index 0000000..5eaf245 --- /dev/null +++ b/firmware/include/nightlight.h @@ -0,0 +1,54 @@ +// nightlight.h — illuminator control and what the device does after dark. +// +// A HARDWARE WARNING WORTH READING BEFORE YOU BUY ANYTHING +// The obvious choice for a wildlife camera is an infrared illuminator (850 nm +// or 940 nm), because birds barely perceive it and white light at a feeder at +// night is disruptive. But the OV2640 module on the XIAO Sense ships with an +// **IR cut filter bonded over the sensor**, which blocks exactly those +// wavelengths. An IR LED on an unmodified Sense produces a black frame. +// +// So, three options, in the order I would try them: +// 1. Accept no night capture. Set night_behaviour = NIGHT_SLEEP. Most garden +// birds are diurnal; you lose very little and save the whole problem. +// 2. Warm, dim, continuous white light (NIGHTLIGHT_ALWAYS at low duty). +// Continuous is markedly better than a flash per burst: animals habituate +// to steady light and startle at sudden light. Still disturbs wildlife. +// 3. Remove the IR filter and use 850 nm. Best images, irreversible, and it +// wrecks daytime colour rendition unless you fit a switchable filter. +// +// The firmware supports all three. Option 2 is what NIGHTLIGHT_ON_BURST and +// NIGHTLIGHT_ALWAYS drive; option 3 needs no code change at all. +// +// NIGHT WINDOW +// `night_start_min` / `night_end_min` are minutes from local midnight. The Pi +// knows the site latitude, so the intended use is for it to push real +// sunset/sunrise daily via apply_config. The defaults (21:00-06:00) are a +// fallback for before that exists. +#pragma once + +#include + +void nightBegin(); + +// Is the current local time inside the configured night window? +// Always false while the clock is unsynced — better to capture pointless dark +// frames than to sleep through a day because the device thinks it is 03:00. +bool nightIsNight(); + +// Call every loop tick. Handles dusk/dawn transitions: swaps the camera +// profile, and drives the illuminator for NIGHTLIGHT_ALWAYS. +void nightTick(); + +// Bracket a capture burst. No-ops unless mode is NIGHTLIGHT_ON_BURST and it +// is actually night; includes the settle delay the sensor needs to adapt. +void nightIlluminateBurstBegin(); +void nightIlluminateBurstEnd(); + +bool nightlightIsOn(); + +// Seconds until night_end_min, for NIGHT_SLEEP. 0 if it is not night. +uint32_t nightSecondsUntilMorning(); + +// Should the capture pipeline be running right now? False at night under +// NIGHT_IDLE and NIGHT_SLEEP. +bool nightCaptureAllowed(); diff --git a/firmware/include/ota_mgr.h b/firmware/include/ota_mgr.h new file mode 100644 index 0000000..3d45cce --- /dev/null +++ b/firmware/include/ota_mgr.h @@ -0,0 +1,53 @@ +// ota_mgr.h — OTA with SHA-256 verification and trial-boot rollback (SPEC C6). +// +// The rules from the spec, implemented here: +// - dual OTA slots exist from the first flash (partitions CSV) +// - verify SHA-256 of the downloaded image before activating the slot +// - boot the new image ONCE in a trial state +// - if the trial image cannot check in with the endpoint, roll back +// automatically on the next reset +// - never sleep mid-flash (INHIBIT_OTA) +// +// The battery gate from SPEC C6 is kept as a hook (`otaBatteryOkFn`) but has +// no default sensor: this build is mains-powered and the XIAO's battery-sense +// divider is not wired. Register a callback if that changes. +#pragma once + +#include + +struct OtaTarget { + char version[24]; + char url[160]; // absolute, or a path relative to the API base + char sha256[65]; // lowercase hex + uint32_t size; +}; + +void otaBegin(); + +// True when this boot is the first run of a freshly flashed image and has not +// yet been confirmed. Until otaMarkValid() is called, a reset rolls back. +bool otaPendingVerify(); + +// Call once the device has proven the new image works — we use "a heartbeat +// was accepted by the endpoint", which exercises WiFi, HTTP, auth and config +// in one go. Anything less and a firmware that boots but cannot talk would be +// marked good. +void otaMarkValid(); + +// Give up on the trial image and reboot into the previous slot. +void otaRollback(const char* reason); + +// Is `target.version` different from what we are running? +bool otaIsNewer(const OtaTarget& target); + +// Download, verify, activate, reboot. Blocks for the duration. Returns only on +// failure — on success the device restarts into the new slot. +// Holds INHIBIT_OTA for the whole operation. +bool otaApply(const OtaTarget& target); + +// Optional battery gate (SPEC C6: refuse to flash below a threshold). +typedef bool (*OtaBatteryOkFn)(uint8_t min_pct); +void otaSetBatteryCheck(OtaBatteryOkFn fn, uint8_t min_pct); + +const char* otaRunningVersion(); +const char* otaRunningPartition(); diff --git a/firmware/include/power_mgr.h b/firmware/include/power_mgr.h new file mode 100644 index 0000000..35b8121 --- /dev/null +++ b/firmware/include/power_mgr.h @@ -0,0 +1,125 @@ +// power_mgr.h — the deep-sleep on/off switch and everything it interferes with. +// +// TWO MODES, ONE FLAG (`g_cfg.deep_sleep_enabled`, pushable from the WebUI) +// +// AWAKE (default, mains powered) +// Camera stays initialised, the PSRAM ring holds ~10 s of pre-trigger +// history, commands execute within a loop tick, streaming works on demand. +// This is the mode that makes good bird photos. +// +// SLEEP (battery / solar) +// Wake on the LD2410 OUT pin (EXT1) or the timer, capture a post-trigger +// burst, upload, drain the command queue, sleep again. +// You give up, unavoidably: +// - the pre-trigger ring: the camera is off, so there is no history. +// Back to SPEC C4's 1-3 s latency; expect to miss fast arrivals. +// - on-demand streaming: a stream_start command is only seen at the next +// wake. The device then holds itself awake for the session and sleeps +// after (see powerInhibit below). +// - command latency: worst case equals deep_sleep_s (SPEC C1). +// +// HONEST NOTE ON WHAT DEEP SLEEP ACTUALLY SAVES HERE +// The XIAO ESP32S3 sleeps at tens of µA, but the LD2410 draws roughly 80 mA +// continuously and must stay powered to act as a wake source. So with +// sleep_wake_on_radar = true, system current is dominated by the radar and the +// ESP sleeping buys you very little. Deep sleep is only a real power win if you +// either (a) set sleep_wake_on_radar = false and wake on the timer alone, with +// the radar power-gated via PIN_RADAR_EN, or (b) fit a low-quiescent PIR such +// as the AM312 on PIN_AUX_ADC as the wake source and use the radar only for +// confirmation once awake. The switch is implemented either way; this is a +// wiring decision, not a firmware one. +#pragma once + +#include + +enum WakeCause : uint8_t { + WAKE_POWER_ON = 0, // cold boot, or reset + WAKE_RADAR = 1, // EXT1 on the LD2410 OUT pin + WAKE_TIMER = 2, + WAKE_OTHER = 3, +}; + +// Reasons the device must not sleep right now. Refcounted, so nested holders +// (a stream inside a wake_and_hold, say) cannot cut each other short. +enum SleepInhibit : uint8_t { + INHIBIT_BOOT = 0, // released once the first heartbeat succeeds + INHIBIT_UPLOAD = 1, + INHIBIT_STREAM = 2, // the "stream interferes with sleep" case + INHIBIT_OTA = 3, // sleeping mid-flash bricks the device (SPEC C6) + INHIBIT_HOLD = 4, // wake_and_hold command + INHIBIT_COUNT +}; + +// Reads the wake cause and restores the counters kept in RTC memory. +// Call first in setup(), before anything else looks at boot state. +void powerBegin(); + +WakeCause powerWakeCause(); +const char* powerWakeCauseName(); +uint32_t powerBootCount(); // survives deep sleep, resets on power loss +uint32_t powerLastSleepSeconds(); // how long the most recent sleep lasted +uint32_t powerTotalSleepSeconds(); // cumulative since power-on + +// Is sleeping permitted at all right now, ignoring the idle timer? +// +// This is where streaming and sleeping are reconciled. A sleeping device +// cannot be told to start a stream (SPEC C1), so with `stream_blocks_sleep` +// set — the default — merely *enabling* streaming keeps the device awake and +// reachable, whether or not a session is running. Clear that flag to let it +// sleep anyway and accept that `stream_start` waits for the next wake. +// +// Returns false, with a reason, when: deep sleep is switched off, streaming +// is enabled and blocks sleep, or an inhibit is held. +bool powerSleepAllowed(); +const char* powerSleepBlockedReason(); + +// Sleep inhibits. Always pair them; prefer the RAII guard below. +void powerInhibit(SleepInhibit reason); +void powerRelease(SleepInhibit reason); +bool powerIsInhibited(); +const char* powerInhibitSummary(); // for logs and heartbeats + +struct SleepGuard { + SleepInhibit r; + explicit SleepGuard(SleepInhibit reason) : r(reason) { powerInhibit(r); } + ~SleepGuard() { powerRelease(r); } +}; + +// Mark that something worth staying awake for just happened. Resets the idle +// timer, so a busy feeder keeps the device up instead of thrashing sleep/wake. +void powerNoteActivity(); + +// Hold awake for at least `seconds` (the wake_and_hold command). +void powerHoldAwake(uint32_t seconds); + +// Would the next powerMaybeSleep() actually sleep? Lets the caller do the +// things that must happen before the radio goes off — a final status push, +// say — without doing them on every loop tick. +bool powerWouldSleepNow(); + +// Called every loop tick. Sleeps if, and only if: +// deep_sleep_enabled && no inhibit && idle longer than sleep_idle_timeout_s +// Returns false if it decided to stay awake; does not return if it slept. +bool powerMaybeSleep(); + +// Sleep now regardless of the idle timer, but still never while inhibited. +// `seconds` == 0 uses g_cfg.deep_sleep_s. Used by the `sleep_now` command and +// by the "every failure path ends in sleep" rule of SPEC §4.3. +void powerSleepNow(uint32_t seconds = 0); + +// Sleep through the night (NIGHT_SLEEP). Unlike powerSleepNow() this works +// even when deep_sleep_enabled is false, because "sleep at night" is a +// separate decision from "sleep between events" — a mains-powered camera +// still has no reason to be awake at 03:00 with no illuminator fitted. +// Never wakes on the radar: the point is to ignore the night, not to +// photograph every cat that walks past. No-op if it is not night. +void powerSleepUntilMorning(); + +// True while the device is running in SLEEP mode. Other subsystems consult +// this to decide whether the ring buffer is worth maintaining. +bool powerSleepModeActive(); + +// Applies a change to deep_sleep_enabled that arrived from the endpoint. +// Turning sleep ON never takes effect instantly: the device first finishes the +// current wake so the ack for the config command still reaches the Pi. +void powerOnConfigChanged(bool was_enabled); diff --git a/firmware/include/stream_session.h b/firmware/include/stream_session.h new file mode 100644 index 0000000..4040aba --- /dev/null +++ b/firmware/include/stream_session.h @@ -0,0 +1,40 @@ +// stream_session.h — time-boxed MJPEG push (SPEC C9). +// +// WHAT IS BUILT +// The full path: a `stream_start` command opens a chunked POST to the Pi, the +// device pushes JPEGs at the configured rate and resolution, and the session +// ends itself at the duration cap. Mode (watch / record / both) rides in a +// header; what the Pi does with the bytes is the Pi's decision, so the device +// never needs to change when you add recording or a public relay. +// +// WHAT IS NOT BUILT +// Anything outward-facing. Per SPEC C3 the ESP32 never serves a stream and is +// never reachable from outside the LAN; relaying to a browser or to a public +// domain is the Pi's job (MediaMTX, or plain MJPEG passthrough). +// +// INTERACTION WITH DEEP SLEEP +// A session holds INHIBIT_STREAM, so the device cannot sleep underneath it. +// In SLEEP mode a stream_start command is only seen at the next wake; the +// device then serves the session and sleeps once it ends. That latency is +// inherent (SPEC C1), not a gap in the implementation. +#pragma once + +#include + +bool streamActive(); + +// Start a session. `session_id` comes from the endpoint so both sides agree on +// a name for it. Overrides are optional: 0 means "use the configured value". +bool streamStart(const char* session_id, + uint8_t mode_override = 0xFF, + uint8_t framesize_override = 0, + uint16_t duration_override = 0); + +// Pump one frame if it is time. Call from the main loop; cheap when idle. +// Ends the session automatically at the duration cap. +void streamTick(); + +void streamStop(const char* reason); + +uint32_t streamFramesSent(); +uint32_t streamSecondsLeft(); diff --git a/firmware/partitions/poorbird_8mb_ota.csv b/firmware/partitions/poorbird_8mb_ota.csv new file mode 100644 index 0000000..d32550d --- /dev/null +++ b/firmware/partitions/poorbird_8mb_ota.csv @@ -0,0 +1,13 @@ +# poorBird partition table — 8 MB flash, dual OTA slots + rollback (SPEC C6) +# +# Two app slots of 3.1 MB each. This MUST be right on the very first flash: +# retrofitting OTA onto a device that is already mounted outdoors means taking +# it down and reflashing over USB. +# +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xE000, 0x2000, +app0, app, ota_0, 0x10000, 0x330000, +app1, app, ota_1, 0x340000, 0x330000, +spiffs, data, spiffs, 0x670000, 0x180000, +coredump, data, coredump, 0x7F0000, 0x10000, diff --git a/firmware/platformio.ini b/firmware/platformio.ini new file mode 100644 index 0000000..7f75dcc --- /dev/null +++ b/firmware/platformio.ini @@ -0,0 +1,78 @@ +; poorBird - ESP32-S3 camera node +; Board: Seeed Studio XIAO ESP32S3 Sense (ESP32-S3R8, 8 MB flash, 8 MB PSRAM, OV2640) +; +; PLATFORM NOTE +; The official `espressif32` platform in the PlatformIO registry lags well behind +; Arduino-ESP32 3.x / ESP-IDF 5.x and has poor ESP32-S3 support. The community fork +; `pioarduino` is what current S3 work uses. +; +; The pin below (53.03.13 = Arduino core 3.1.x / IDF 5.3) is chosen to match +; PlatformIO Core 6.1.x. The `stable` release alias now requires Core >= 6.2.0; +; if you upgrade Core, you can switch to: +; https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip + +[platformio] +default_envs = xiao_s3_sense + +; --------------------------------------------------------------------------- +; Everything you are likely to edit lives in [common]. Secrets belong in +; secrets.ini (gitignored) - see secrets.ini.example. +; --------------------------------------------------------------------------- +[common] +fw_version = 0.1.0 + +build_flags = + -DFW_VERSION=\"${common.fw_version}\" + -DHW_REVISION=\"xiao-esp32s3-sense-ld2410\" + -DCORE_DEBUG_LEVEL=3 + -DARDUINO_USB_CDC_ON_BOOT=1 + -DARDUINO_USB_MODE=1 + -DBOARD_HAS_PSRAM + ; --- camera defaults (runtime-overridable from the endpoint) ---------- + ; Use the enum SYMBOLS, never the numbers: esp32-camera has inserted + ; entries into framesize_t between releases, so a literal index silently + ; changes resolution after a driver update. + -DCFG_FRAME_SIZE=FRAMESIZE_SVGA ; 800x600 stills + -DCFG_STREAM_FRAME_SIZE=FRAMESIZE_VGA ; 640x480 while streaming + -DCFG_JPEG_QUALITY=12 ; 4..40, lower = better = bigger + ; --- pre-trigger ring buffer (the reason mains power is worth it) ----- + -DCFG_RING_FRAMES=24 ; PSRAM history depth + -DCFG_PRE_ROLL=4 ; frames sent from *before* the trigger + -DCFG_POST_ROLL=6 ; frames sent after the trigger + ; --- ops -------------------------------------------------------------- + -DCFG_HEARTBEAT_S=300 + -DCFG_COOLDOWN_S=5 + +; --------------------------------------------------------------------------- +[env:xiao_s3_sense] +platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.13/platform-espressif32.zip +board = seeed_xiao_esp32s3 +framework = arduino + +board_build.partitions = partitions/poorbird_8mb_ota.csv +board_build.flash_mode = qio +board_upload.flash_size = 8MB + +; PSRAM is mandatory: the frame ring and the camera framebuffers both live there. +board_build.arduino.memory_type = qio_opi + +monitor_speed = 115200 +monitor_filters = esp32_exception_decoder, time + +lib_deps = + bblanchon/ArduinoJson @ ^7.2.0 + +build_flags = + ${common.build_flags} + +extra_scripts = pre:scripts/load_secrets.py + +; --------------------------------------------------------------------------- +; Same firmware, verbose logging - for bring-up on the bench. +[env:xiao_s3_sense_debug] +extends = env:xiao_s3_sense +build_type = debug +build_flags = + ${common.build_flags} + -DCORE_DEBUG_LEVEL=5 + -DPB_VERBOSE_RADAR=1 diff --git a/firmware/scripts/load_secrets.py b/firmware/scripts/load_secrets.py new file mode 100644 index 0000000..75880ae --- /dev/null +++ b/firmware/scripts/load_secrets.py @@ -0,0 +1,51 @@ +"""Inject secrets.ini into the build as -D flags. + +Keeps WiFi credentials and the enrollment secret out of git and out of +platformio.ini. Copy secrets.ini.example to secrets.ini and fill it in; the +build works without the file, it just produces an unconfigured device that +cannot associate. +""" + +import configparser +import os + +Import("env") # noqa: F821 (provided by SCons/PlatformIO) + +SECRETS = os.path.join(env.subst("$PROJECT_DIR"), "secrets.ini") # noqa: F821 + +# key in secrets.ini -> build flag. Strings are quoted, numbers are not. +STRING_KEYS = { + "wifi_ssid": "CFG_WIFI_SSID", + "wifi_pass": "CFG_WIFI_PASS", + "api_host": "CFG_API_HOST", + "enroll_secret": "CFG_ENROLL_SECRET", + "tz": "CFG_TZ", +} +NUMERIC_KEYS = { + "api_port": "CFG_API_PORT", + "deep_sleep": "CFG_DEEP_SLEEP", +} + +if not os.path.isfile(SECRETS): + print("load_secrets: no secrets.ini found — building with defaults.") + print(" copy secrets.ini.example to secrets.ini before flashing.") +else: + parser = configparser.ConfigParser() + parser.read(SECRETS) + if not parser.has_section("secrets"): + raise SystemExit("load_secrets: secrets.ini has no [secrets] section") + + flags = [] + for key, macro in STRING_KEYS.items(): + if parser.has_option("secrets", key): + value = parser.get("secrets", key) + flags.append(f'-D{macro}=\\"{value}\\"') + for key, macro in NUMERIC_KEYS.items(): + if parser.has_option("secrets", key): + flags.append(f"-D{macro}={parser.get('secrets', key)}") + + env.Append(CPPDEFINES=[]) # noqa: F821 + env.Append(BUILD_FLAGS=flags) # noqa: F821 + + # Do not print the values themselves. + print(f"load_secrets: applied {len(flags)} flag(s) from secrets.ini") diff --git a/firmware/secrets.ini.example b/firmware/secrets.ini.example new file mode 100644 index 0000000..3c27f26 --- /dev/null +++ b/firmware/secrets.ini.example @@ -0,0 +1,32 @@ +; Copy to secrets.ini (which is gitignored) and fill in. +; +; Only three of these really matter for a first flash: the WiFi credentials, +; the Pi's address, and the enrollment secret. Everything else the device +; learns from the endpoint after it enrolls. + +[secrets] +wifi_ssid = YourNetwork +wifi_pass = YourPassword + +; The endpoint — a Pi, a thin client, a NUC, a VM; the firmware does not care. +; Use a DHCP reservation and hardcode the address: mDNS on an ESP32 is one +; more thing that can fail silently at 4 a.m. (SPEC §9). +api_host = 192.168.1.50 +api_port = 8080 + +; Bootstrap provisioning secret, shared with the endpoint. The device trades +; it for a bearer token plus a per-device re-enrollment secret on first boot, +; and keeps the latter so a token rotation heals itself without a USB cable. +; Generate with: openssl rand -hex 32 +; +; It stays compiled into the image as a last-resort recovery path, so do not +; rotate it server-side without also shipping new firmware. +enroll_secret = replace-me + +; POSIX TZ. Central Europe with DST. +tz = CET-1CEST,M3.5.0,M10.5.0/3 + +; 0 = stay awake (mains, pre-trigger ring, streaming works) +; 1 = deep sleep between events (battery; see power_mgr.h for the trade-offs) +; This is only the *initial* value — the endpoint can flip it at runtime. +deep_sleep = 0 diff --git a/firmware/src/api_client.cpp b/firmware/src/api_client.cpp new file mode 100644 index 0000000..1dd31a5 --- /dev/null +++ b/firmware/src/api_client.cpp @@ -0,0 +1,583 @@ +#include "api_client.h" + +#include +#include + +#include "app_config.h" +#include "battery.h" +#include "camera_mgr.h" +#include "device_stats.h" +#include "ld2410.h" +#include "net_mgr.h" +#include "nightlight.h" +#include "power_mgr.h" +#include "stream_session.h" + +static bool s_token_rejected = false; +static esp_http_client_handle_t s_stream = nullptr; + +// One response buffer, reused. 4 KB comfortably holds an envelope with a +// handful of queued commands; anything larger is a server-side bug. +static const size_t kRespCap = 4096; +static char s_resp[kRespCap]; + +void apiBegin() { s_token_rejected = false; } +bool apiTokenRejected() { return s_token_rejected; } + +static String url(const char* path) { return apiBaseUrl() + path; } + +static void setAuth(esp_http_client_handle_t c) { + char bearer[80]; + snprintf(bearer, sizeof(bearer), "Bearer %s", g_cfg.device_token); + esp_http_client_set_header(c, "Authorization", bearer); +} + +// Headers present on every device request, so the Pi can spot a device that +// is behind on config or firmware without the device having to ask. +static void setCommonHeaders(esp_http_client_handle_t c) { + char buf[24]; + esp_http_client_set_header(c, "X-Device-Uid", deviceUid()); + esp_http_client_set_header(c, "X-Fw-Version", FW_VERSION); + esp_http_client_set_header(c, "X-Hw-Revision", HW_REVISION); + snprintf(buf, sizeof(buf), "%u", (unsigned)g_cfg.config_version); + esp_http_client_set_header(c, "X-Config-Version", buf); + snprintf(buf, sizeof(buf), "%d", WiFi.RSSI()); + esp_http_client_set_header(c, "X-Rssi", buf); +} + +// Read the body into s_resp. Returns bytes read, or -1. +static int readBody(esp_http_client_handle_t c) { + int len = esp_http_client_read_response(c, s_resp, kRespCap - 1); + if (len < 0) return -1; + s_resp[len] = '\0'; + return len; +} + +// Shared response handling: pull the envelope fields out and fan the command +// array out to the handler. Used identically by ingest and heartbeat, which is +// the whole reason the two endpoints return the same shape (SPEC §4.1). +static void parseEnvelope(ServerEnvelope& env, int body_len, CommandHandler on_cmd) { + if (body_len <= 0) return; + + JsonDocument doc; + DeserializationError err = deserializeJson(doc, s_resp, body_len); + if (err) { + log_w("response is not JSON: %s", err.c_str()); + return; + } + + env.server_time_ms = doc["server_time"] | (int64_t)0; + env.config_version = doc["config_version"] | (uint32_t)0; + + JsonObjectConst fw = doc["firmware"]; + if (!fw.isNull() && fw["version"].is()) { + env.has_firmware = true; + strncpy(env.fw_version, fw["version"] | "", sizeof(env.fw_version) - 1); + strncpy(env.fw_url, fw["url"] | "", sizeof(env.fw_url) - 1); + strncpy(env.fw_sha256, fw["sha256"] | "", sizeof(env.fw_sha256) - 1); + env.fw_size = fw["size"] | (uint32_t)0; + } + + JsonArrayConst cmds = doc["commands"]; + if (!cmds.isNull()) { + for (JsonObjectConst cmd : cmds) { + env.command_count++; + if (on_cmd) on_cmd(cmd); + } + } +} + +// --------------------------------------------------------------------------- +// Enrollment +// --------------------------------------------------------------------------- +// One enrollment attempt with a specific secret. +static bool enrollWith(const char* secret, const char* which) { + if (!secret || !secret[0]) return false; + + JsonDocument body; + body["device_uid"] = deviceUid(); + body["device_name"] = g_cfg.device_name; + body["hw_revision"] = HW_REVISION; + body["fw_version"] = FW_VERSION; + body["mac"] = WiFi.macAddress(); + + String payload; + serializeJson(body, payload); + + esp_http_client_config_t cfg = {}; + String u = url("/enroll"); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_POST; + cfg.timeout_ms = 8000; + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + esp_http_client_set_header(c, "Content-Type", "application/json"); + esp_http_client_set_header(c, "X-Enroll-Secret", secret); + setCommonHeaders(c); + + bool ok = false; + if (esp_http_client_open(c, payload.length()) == ESP_OK) { + esp_http_client_write(c, payload.c_str(), payload.length()); + esp_http_client_fetch_headers(c); + int status = esp_http_client_get_status_code(c); + int len = readBody(c); + + if (status == 200 || status == 201) { + JsonDocument doc; + if (!deserializeJson(doc, s_resp, len > 0 ? len : 0)) { + const char* tok = doc["token"] | ""; + if (strlen(tok) > 0) { + strncpy(g_cfg.device_token, tok, sizeof(g_cfg.device_token) - 1); + g_cfg.device_token[sizeof(g_cfg.device_token) - 1] = '\0'; + + // Upgrade the shared bootstrap secret to a per-device one + // if the endpoint offers it. That keeps re-enrollment + // self-service without leaving a credential on the device + // that could enroll *other* identities. + const char* re = doc["reenroll_secret"] | ""; + if (strlen(re) > 0) { + strncpy(g_cfg.enroll_secret, re, sizeof(g_cfg.enroll_secret) - 1); + g_cfg.enroll_secret[sizeof(g_cfg.enroll_secret) - 1] = '\0'; + log_i("enrolled via %s: token + per-device re-enrollment secret stored", which); + } else { + // Endpoint does not implement it. Keep the secret we + // used rather than wiping it — a device that cannot + // re-enroll after a token rotation is a device that + // needs a ladder. + strncpy(g_cfg.enroll_secret, secret, sizeof(g_cfg.enroll_secret) - 1); + g_cfg.enroll_secret[sizeof(g_cfg.enroll_secret) - 1] = '\0'; + log_i("enrolled via %s: token stored (endpoint sent no re-enrollment secret)", which); + } + + configSave(); + s_token_rejected = false; + ok = true; + } + } + } else { + log_w("enroll via %s rejected: HTTP %d", which, status); + } + } else { + log_e("enroll: cannot reach %s", u.c_str()); + } + + esp_http_client_close(c); + esp_http_client_cleanup(c); + return ok; +} + +bool apiEnroll() { + if (g_cfg.device_token[0]) return true; + + // Stored secret first: after the first enrollment this is the per-device + // one, so a token rotation in the admin UI heals itself on the next + // request with no physical access. + if (enrollWith(g_cfg.enroll_secret, "stored secret")) return true; + + // Last resort: the shared bootstrap secret compiled into the image. This + // is the escape hatch for a device whose stored secret has been + // invalidated — rotating the shared secret server-side without also + // reflashing is what would strand it, so don't do that. + const char* boot = configBootstrapSecret(); + if (boot[0] && strcmp(boot, g_cfg.enroll_secret) != 0) { + log_w("enroll: stored secret failed, trying the compiled-in bootstrap secret"); + if (enrollWith(boot, "bootstrap secret")) return true; + } + + if (!g_cfg.enroll_secret[0] && !boot[0]) { + log_e("not enrolled and no secret available — set enroll_secret in secrets.ini"); + } + return false; +} + +// --------------------------------------------------------------------------- +// Ingest — raw JPEG body, metadata in headers +// --------------------------------------------------------------------------- +ServerEnvelope apiIngest(const FrameCopy& frame, const CaptureMeta& meta, CommandHandler on_cmd) { + ServerEnvelope env = {}; + if (!frame.data || frame.len == 0) return env; + + esp_http_client_config_t cfg = {}; + String u = url("/ingest"); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_POST; + cfg.timeout_ms = 15000; // a 60 KB JPEG over marginal WiFi is not instant + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + esp_http_client_set_header(c, "Content-Type", "image/jpeg"); + setAuth(c); + setCommonHeaders(c); + + char b[32]; + esp_http_client_set_header(c, "X-Trigger", meta.trigger); + esp_http_client_set_header(c, "X-Burst-Id", meta.burst_id); + snprintf(b, sizeof(b), "%u", meta.burst_index); esp_http_client_set_header(c, "X-Burst-Index", b); + snprintf(b, sizeof(b), "%u", meta.burst_count); esp_http_client_set_header(c, "X-Burst-Count", b); + snprintf(b, sizeof(b), "%d", meta.pre_trigger); esp_http_client_set_header(c, "X-Pre-Trigger", b); + snprintf(b, sizeof(b), "%lld", (long long)frame.at_epoch); + esp_http_client_set_header(c, "X-Captured-At", b); // ms since epoch, UTC, 0 if unsynced + snprintf(b, sizeof(b), "%u", (unsigned)frame.seq); esp_http_client_set_header(c, "X-Frame-Seq", b); + snprintf(b, sizeof(b), "%u", meta.radar_distance_cm); esp_http_client_set_header(c, "X-Radar-Distance-Cm", b); + snprintf(b, sizeof(b), "%u", meta.radar_energy); esp_http_client_set_header(c, "X-Radar-Energy", b); + snprintf(b, sizeof(b), "%u", meta.radar_state); esp_http_client_set_header(c, "X-Radar-State", b); + + if (esp_http_client_open(c, frame.len) == ESP_OK) { + int written = esp_http_client_write(c, (const char*)frame.data, frame.len); + if (written == (int)frame.len) { + esp_http_client_fetch_headers(c); + env.http_status = esp_http_client_get_status_code(c); + int len = readBody(c); + + if (env.http_status == 401) { + s_token_rejected = true; + log_w("ingest: 401, token rotated or revoked"); + } else if (env.http_status >= 200 && env.http_status < 300) { + env.ok = true; + parseEnvelope(env, len, on_cmd); + } else { + log_w("ingest: HTTP %d", env.http_status); + } + } else { + log_w("ingest: short write %d of %u", written, (unsigned)frame.len); + } + } else { + log_w("ingest: connect failed"); + } + + esp_http_client_close(c); + esp_http_client_cleanup(c); + return env; +} + +// --------------------------------------------------------------------------- +// Device conditions +// +// One body, two endpoints: /heartbeat (returns the command envelope) and +// /status (returns 204, no commands). Built in one place so the two can never +// drift apart and the endpoint only has to parse one shape. +// --------------------------------------------------------------------------- +static void buildConditions(JsonDocument& body, const char* reason) { + statsRollover(); + const DeviceStats st = statsGet(); + const BatteryReading bt = batteryLast(); + const RadarReading rd = radarLast(); + + body["reason"] = reason; + body["fw_version"] = FW_VERSION; + body["hw_revision"] = HW_REVISION; + body["config_version"] = g_cfg.config_version; + + // --- uptime and sleep --------------------------------------------------- + JsonObject p = body["power"].to(); + p["uptime_ms"] = (uint32_t)millis(); + p["awake_ms"] = statsAwakeMs(); // ticks since the last sleep + p["boot_count"] = powerBootCount(); + p["wake_cause"] = powerWakeCauseName(); + p["last_sleep_s"] = powerLastSleepSeconds(); + p["total_sleep_s"] = powerTotalSleepSeconds(); + p["sleep_enabled"] = g_cfg.deep_sleep_enabled; + p["sleep_allowed"] = powerSleepAllowed(); + p["inhibits"] = powerInhibitSummary(); + + // --- battery ------------------------------------------------------------ + // `valid: false` means no divider is wired. The endpoint should render + // that as "not measured", never as 0 V — a low-battery alarm that fires + // because a sensor is absent is worse than no alarm. + JsonObject b = body["battery"].to(); + b["valid"] = bt.valid; + b["mv"] = bt.mv; + b["pct"] = bt.pct; + b["raw_mv"] = bt.raw_mv; + b["chemistry"] = g_cfg.battery_chemistry; + b["low"] = bt.valid && g_cfg.battery_chemistry != BATT_NONE && + bt.pct < g_cfg.battery_warn_pct; + + // --- counters ----------------------------------------------------------- + // Reset on power cycle, not on reboot-from-sleep. The endpoint's own count + // is authoritative; these are the device's view, useful mainly as a + // delivery-gap detector (captured_today >> delivered_today = upload trouble). + JsonObject c = body["counters"].to(); + c["captured_today"] = st.captured_today; + c["delivered_today"] = st.delivered_today; + c["failed_today"] = st.failed_today; + c["events_today"] = st.events_today; + c["day_index"] = st.day_index; + c["captured_boot"] = st.captured_boot; + c["delivered_boot"] = st.delivered_boot; + + // --- camera / night ----------------------------------------------------- + uint16_t cw = 0, ch = 0; + framesizeDims(g_cfg.frame_size, &cw, &ch); + JsonObject cam = body["camera"].to(); + cam["frame_size"] = framesizeName(g_cfg.frame_size); // name, not index + cam["frame_size_id"] = g_cfg.frame_size; + cam["width"] = cw; + cam["height"] = ch; + cam["jpeg_quality"] = g_cfg.jpeg_quality; + cam["profile"] = cameraNightProfileActive() ? "night" : "day"; + cam["ready"] = cameraReady(); + // Sensor PID identifies what is actually fitted: 0x2640 OV2640, + // 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have shipped with + // OV3660 rather than OV2640, so do not assume. + sensor_t* sens = esp_camera_sensor_get(); + cam["sensor_pid"] = sens ? sens->id.PID : 0; + + JsonObject n = body["night"].to(); + n["is_night"] = nightIsNight(); + n["nightlight_on"] = nightlightIsOn(); + n["behaviour"] = g_cfg.night_behaviour; + n["capture_allowed"] = nightCaptureAllowed(); + + // --- stream ------------------------------------------------------------- + JsonObject s = body["stream"].to(); + s["enabled"] = g_cfg.stream_enabled; + s["active"] = streamActive(); + s["frames_sent"] = streamFramesSent(); + s["seconds_left"] = streamSecondsLeft(); + + // --- radar -------------------------------------------------------------- + JsonObject r = body["radar"].to(); + r["baud"] = radarBaud(); // 0 = no frames decoded at any baud + r["uart_ok"] = rd.valid; + r["out_pin"] = rd.out_pin; + r["state"] = rd.target; + r["moving_cm"] = rd.moving_cm; + r["moving_energy"] = rd.moving_energy; + r["stationary_cm"] = rd.stationary_cm; + r["stationary_energy"] = rd.stationary_energy; + + // --- network / memory --------------------------------------------------- + JsonObject sys = body["system"].to(); + sys["rssi"] = WiFi.RSSI(); + sys["ip"] = WiFi.localIP().toString(); + sys["free_heap"] = (uint32_t)ESP.getFreeHeap(); + sys["free_psram"] = (uint32_t)ESP.getFreePsram(); + sys["ring_depth"] = (uint32_t)ringCount(); + sys["ring_bytes"] = (uint32_t)ringBytesUsed(); + + char iso[32]; + netIsoTime(iso, sizeof(iso)); + body["time_synced"] = netTimeValid(); + body["device_time"] = iso; // empty string when unsynced +} + +bool apiPostStatus(const char* reason) { + JsonDocument body; + buildConditions(body, reason); + + String payload; + serializeJson(body, payload); + + esp_http_client_config_t cfg = {}; + String u = url("/status"); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_POST; + cfg.timeout_ms = 6000; + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + esp_http_client_set_header(c, "Content-Type", "application/json"); + setAuth(c); + setCommonHeaders(c); + + bool ok = false; + if (esp_http_client_open(c, payload.length()) == ESP_OK) { + esp_http_client_write(c, payload.c_str(), payload.length()); + esp_http_client_fetch_headers(c); + int st = esp_http_client_get_status_code(c); + readBody(c); + if (st == 401) s_token_rejected = true; + ok = (st >= 200 && st < 300); + if (!ok) log_w("status: HTTP %d", st); + } else { + log_w("status: connect failed"); + } + + esp_http_client_close(c); + esp_http_client_cleanup(c); + return ok; +} + +ServerEnvelope apiHeartbeat(CommandHandler on_cmd) { + ServerEnvelope env = {}; + + JsonDocument body; + buildConditions(body, "heartbeat"); + + String payload; + serializeJson(body, payload); + + esp_http_client_config_t cfg = {}; + String u = url("/heartbeat"); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_POST; + cfg.timeout_ms = 8000; + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + esp_http_client_set_header(c, "Content-Type", "application/json"); + setAuth(c); + setCommonHeaders(c); + + if (esp_http_client_open(c, payload.length()) == ESP_OK) { + esp_http_client_write(c, payload.c_str(), payload.length()); + esp_http_client_fetch_headers(c); + env.http_status = esp_http_client_get_status_code(c); + int len = readBody(c); + + if (env.http_status == 401) { + s_token_rejected = true; + } else if (env.http_status >= 200 && env.http_status < 300) { + env.ok = true; + parseEnvelope(env, len, on_cmd); + } + } + + esp_http_client_close(c); + esp_http_client_cleanup(c); + return env; +} + +// --------------------------------------------------------------------------- +bool apiFetchConfig() { + esp_http_client_config_t cfg = {}; + String u = url("/config"); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_GET; + cfg.timeout_ms = 8000; + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + setAuth(c); + setCommonHeaders(c); + + bool changed = false; + if (esp_http_client_open(c, 0) == ESP_OK) { + esp_http_client_fetch_headers(c); + int status = esp_http_client_get_status_code(c); + int len = readBody(c); + if (status == 401) s_token_rejected = true; + if (status >= 200 && status < 300 && len > 0) { + JsonDocument doc; + if (!deserializeJson(doc, s_resp, len)) { + changed = configApplyJson(doc.as()); + if (changed) { + configSave(); + log_i("config updated to version %u", g_cfg.config_version); + } + } + } + } + + esp_http_client_close(c); + esp_http_client_cleanup(c); + return changed; +} + +bool apiAckCommand(uint32_t command_id, const char* status, const char* detail) { + JsonDocument body; + body["status"] = status; + body["detail"] = detail ? detail : ""; + + String payload; + serializeJson(body, payload); + + char path[64]; + snprintf(path, sizeof(path), "/commands/%u/ack", (unsigned)command_id); + + esp_http_client_config_t cfg = {}; + String u = url(path); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_POST; + cfg.timeout_ms = 6000; + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + esp_http_client_set_header(c, "Content-Type", "application/json"); + setAuth(c); + setCommonHeaders(c); + + bool ok = false; + if (esp_http_client_open(c, payload.length()) == ESP_OK) { + esp_http_client_write(c, payload.c_str(), payload.length()); + esp_http_client_fetch_headers(c); + int st = esp_http_client_get_status_code(c); + readBody(c); + ok = (st >= 200 && st < 300); + } + + esp_http_client_close(c); + esp_http_client_cleanup(c); + return ok; +} + +// --------------------------------------------------------------------------- +// Stream push — chunked multipart/x-mixed-replace, device -> Pi. +// +// The device pushes and the Pi relays (SPEC C3: the ESP32 is never reachable +// from outside the LAN, and here not even from outside the Pi). The Pi decides +// per X-Stream-Mode whether to relay to viewers, write to disk, or both. +// --------------------------------------------------------------------------- +static const char* kBoundary = "poorbirdframe"; + +bool apiStreamOpen(const char* session_id, uint8_t mode, uint16_t duration_s) { + if (s_stream) apiStreamClose(); + + char path[96]; + snprintf(path, sizeof(path), "/stream/%s", session_id); + + esp_http_client_config_t cfg = {}; + String u = url(path); + cfg.url = u.c_str(); + cfg.method = HTTP_METHOD_POST; + cfg.timeout_ms = 10000; + + s_stream = esp_http_client_init(&cfg); + esp_http_client_set_header(s_stream, "Content-Type", + "multipart/x-mixed-replace; boundary=" "poorbirdframe"); + setAuth(s_stream); + setCommonHeaders(s_stream); + + const char* mode_s = (mode == 1) ? "record" : (mode == 2) ? "both" : "watch"; + esp_http_client_set_header(s_stream, "X-Stream-Mode", mode_s); + + char b[16]; + snprintf(b, sizeof(b), "%u", duration_s); + esp_http_client_set_header(s_stream, "X-Duration-S", b); + + // -1 == chunked transfer encoding: we do not know the total length. + if (esp_http_client_open(s_stream, -1) != ESP_OK) { + log_e("stream: cannot open %s", u.c_str()); + esp_http_client_cleanup(s_stream); + s_stream = nullptr; + return false; + } + + log_i("stream %s open, mode=%s, cap %us", session_id, mode_s, duration_s); + return true; +} + +bool apiStreamSendFrame(const uint8_t* jpeg, size_t len, int64_t epoch_ms) { + if (!s_stream || !jpeg || len == 0) return false; + + char head[192]; + int hl = snprintf(head, sizeof(head), + "\r\n--%s\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: %u\r\n" + "X-Timestamp: %lld\r\n\r\n", + kBoundary, (unsigned)len, (long long)epoch_ms); + + if (esp_http_client_write(s_stream, head, hl) != hl) return false; + return esp_http_client_write(s_stream, (const char*)jpeg, len) == (int)len; +} + +void apiStreamClose() { + if (!s_stream) return; + char tail[64]; + int tl = snprintf(tail, sizeof(tail), "\r\n--%s--\r\n", kBoundary); + esp_http_client_write(s_stream, tail, tl); + + esp_http_client_fetch_headers(s_stream); + int st = esp_http_client_get_status_code(s_stream); + esp_http_client_close(s_stream); + esp_http_client_cleanup(s_stream); + s_stream = nullptr; + log_i("stream closed, HTTP %d", st); +} diff --git a/firmware/src/app_config.cpp b/firmware/src/app_config.cpp new file mode 100644 index 0000000..a7edbf6 --- /dev/null +++ b/firmware/src/app_config.cpp @@ -0,0 +1,475 @@ +#include "app_config.h" + +#include +#include +#include + +#include "board_pins.h" +#include "camera_mgr.h" + +AppConfig g_cfg; + +static Preferences s_nvs; +static const char* kNamespace = "poorbird"; +static char s_uid[13] = {0}; + +// Compile-time fallbacks. Anything secret comes in via secrets.ini, never here. +#ifndef CFG_WIFI_SSID +#define CFG_WIFI_SSID "" +#endif +#ifndef CFG_WIFI_PASS +#define CFG_WIFI_PASS "" +#endif +#ifndef CFG_API_HOST +#define CFG_API_HOST "192.168.1.50" +#endif +#ifndef CFG_API_PORT +#define CFG_API_PORT 8080 +#endif +#ifndef CFG_ENROLL_SECRET +#define CFG_ENROLL_SECRET "" +#endif +#ifndef CFG_TZ +#define CFG_TZ "CET-1CEST,M3.5.0,M10.5.0/3" +#endif +#ifndef CFG_DEEP_SLEEP +#define CFG_DEEP_SLEEP 0 +#endif + +static void setStr(char* dst, size_t cap, const char* src) { + strncpy(dst, src ? src : "", cap - 1); + dst[cap - 1] = '\0'; +} + +static void loadDefaults(AppConfig& c) { + memset(&c, 0, sizeof(c)); + + setStr(c.device_name, sizeof(c.device_name), "poorbird-cam-1"); + setStr(c.wifi_ssid, sizeof(c.wifi_ssid), CFG_WIFI_SSID); + setStr(c.wifi_pass, sizeof(c.wifi_pass), CFG_WIFI_PASS); + setStr(c.api_host, sizeof(c.api_host), CFG_API_HOST); + c.api_port = CFG_API_PORT; + setStr(c.api_base, sizeof(c.api_base), "/api/v1"); + setStr(c.device_token, sizeof(c.device_token), ""); + setStr(c.enroll_secret, sizeof(c.enroll_secret), CFG_ENROLL_SECRET); + + setStr(c.ntp_host, sizeof(c.ntp_host), ""); // empty => api_host + setStr(c.tz, sizeof(c.tz), CFG_TZ); + + c.frame_size = CFG_FRAME_SIZE; + c.jpeg_quality = CFG_JPEG_QUALITY; + c.vflip = false; + c.hmirror = false; + + // Day: everything automatic, exposure biased up for birds backlit against + // sky, gain capped at 4x so the sensor prefers a short shutter over a + // noisy one. Motion blur is the enemy, not noise. + c.cam_day.brightness = 0; + c.cam_day.contrast = 1; + c.cam_day.saturation = 0; + c.cam_day.sharpness = 0; + c.cam_day.ae_level = 1; + c.cam_day.special_effect = 0; + c.cam_day.wb_mode = 0; // auto + c.cam_day.gainceiling = 1; // 4x + c.cam_day.agc_gain = 0; + c.cam_day.aec_value = 300; + c.cam_day.whitebal = true; + c.cam_day.awb_gain = true; + c.cam_day.exposure_ctrl = true; + c.cam_day.aec2 = true; + c.cam_day.gain_ctrl = true; + c.cam_day.bpc = true; + c.cam_day.wpc = true; + c.cam_day.raw_gma = true; + c.cam_day.lenc = true; + c.cam_day.dcw = true; + c.cam_day.colorbar = false; + + // Night: the trade reverses. A noisy identifiable bird beats a clean black + // rectangle, so the gain ceiling goes up and saturation comes down + // (colour under artificial light is wrong anyway). + c.cam_night = c.cam_day; + c.cam_night.brightness = 1; + c.cam_night.contrast = 0; + c.cam_night.saturation = -1; + c.cam_night.ae_level = 2; + c.cam_night.gainceiling = 4; // 32x + + c.ring_frames = CFG_RING_FRAMES; + c.pre_roll = CFG_PRE_ROLL; + c.post_roll = CFG_POST_ROLL; + c.post_roll_gap_ms = 250; + c.cooldown_s = CFG_COOLDOWN_S; + c.idle_period_ms = 400; // ~2.5 fps into the ring; ~10 s of history at depth 24 + + c.radar_mode = RADAR_BOTH; + c.accept_stationary = true; + c.min_distance_cm = 20; + c.max_distance_cm = 300; // a feeder at 1-3 m; widen after field testing + c.min_energy = 20; + c.radar_baud = 0; // autodetect + + c.stream_enabled = false; + c.stream_frame_size = CFG_STREAM_FRAME_SIZE; + c.stream_jpeg_quality = 15; + c.stream_duration_s = 60; // SPEC C9: always time-boxed + c.stream_fps = 10; + c.stream_mode = STREAM_WATCH; + c.stream_blocks_sleep = true; + + c.night_start_min = 21 * 60; // 21:00, overridden by pushed sunset + c.night_end_min = 6 * 60; // 06:00 + c.night_behaviour = NIGHT_SLEEP; // most garden birds are diurnal + c.nightlight_mode = NIGHTLIGHT_OFF; + c.nightlight_brightness = 128; + + c.battery_chemistry = BATT_NONE; // mains by default; no cell wired + c.battery_divider_x100 = 200; // two equal resistors + c.battery_offset_mv = 0; + c.battery_min_pct_ota = 50; // SPEC C6 + c.battery_warn_pct = 20; + + c.heartbeat_interval_s = CFG_HEARTBEAT_S; + c.status_interval_s = 900; + c.ota_enabled = true; + + c.deep_sleep_enabled = CFG_DEEP_SLEEP; // 0 = mains powered, stay awake + c.deep_sleep_s = 300; + c.sleep_wake_on_radar = true; + c.sleep_idle_timeout_s = 20; + c.sleep_max_awake_s = 300; + + c.config_version = 0; +} + +void configLoad() { + loadDefaults(g_cfg); + + if (!s_nvs.begin(kNamespace, /*readOnly=*/true)) { + log_w("no NVS namespace yet, running on compile-time defaults"); + return; + } + + // Stored as one blob. The size check means a struct change during + // development degrades to "fall back to defaults" instead of reading + // garbage into half the fields. + size_t stored = s_nvs.getBytesLength("cfg"); + if (stored == sizeof(AppConfig)) { + AppConfig tmp; + s_nvs.getBytes("cfg", &tmp, sizeof(tmp)); + g_cfg = tmp; + log_i("config loaded from NVS (version %u)", g_cfg.config_version); + } else if (stored > 0) { + log_w("NVS config is %u bytes, expected %u — layout changed, using defaults", + (unsigned)stored, (unsigned)sizeof(AppConfig)); + } + s_nvs.end(); + + // Credentials are stored outside the blob so that a struct layout change + // during development never costs you the enrollment — which, on a device + // you cannot reach over USB, would mean a ladder. + if (s_nvs.begin(kNamespace, true)) { + String tok = s_nvs.getString("token", ""); + if (tok.length()) setStr(g_cfg.device_token, sizeof(g_cfg.device_token), tok.c_str()); + + String sec = s_nvs.getString("enroll", ""); + if (sec.length()) setStr(g_cfg.enroll_secret, sizeof(g_cfg.enroll_secret), sec.c_str()); + s_nvs.end(); + } +} + +bool configSave() { + if (!s_nvs.begin(kNamespace, /*readOnly=*/false)) { + log_e("NVS open for write failed"); + return false; + } + bool ok = s_nvs.putBytes("cfg", &g_cfg, sizeof(g_cfg)) == sizeof(g_cfg); + ok &= s_nvs.putString("token", g_cfg.device_token) >= 0; + ok &= s_nvs.putString("enroll", g_cfg.enroll_secret) >= 0; + s_nvs.end(); + if (!ok) log_e("NVS write failed"); + return ok; +} + +// --- JSON merge ------------------------------------------------------------- +// Helpers keep configApplyJson readable and make "only touch keys that are +// present" the default behaviour rather than something each field repeats. + +#define MERGE_NUM(field, key) \ + if (!doc[key].isNull()) { \ + auto v = doc[key].as();\ + if (v != g_cfg.field) { g_cfg.field = v; changed = true; } \ + } + +#define MERGE_BOOL(field, key) \ + if (!doc[key].isNull()) { \ + bool v = doc[key].as(); \ + if (v != g_cfg.field) { g_cfg.field = v; changed = true; } \ + } + +#define MERGE_STR(field, key) \ + if (!doc[key].isNull()) { \ + const char* v = doc[key].as(); \ + if (v && strcmp(v, g_cfg.field) != 0) { \ + setStr(g_cfg.field, sizeof(g_cfg.field), v); \ + changed = true; \ + } \ + } + +// A frame size may arrive as a name ("SVGA") or as a raw framesize_t index. +// Names are the supported form; the numeric path exists so an older endpoint +// keeps working, and because a number is unambiguous once you know the +// driver version. +static bool mergeFrameSize(uint8_t& field, JsonVariantConst v) { + if (v.isNull()) return false; + + uint8_t next = field; + if (v.is()) { + next = framesizeFromName(v.as(), field); + } else if (v.is() || v.is()) { + int n = v.as(); + if (n < 0 || n >= FRAMESIZE_INVALID) { + log_w("config: frame size index %d out of range, ignoring", n); + return false; + } + next = (uint8_t)n; + } else { + return false; + } + + if (next == field) return false; + field = next; + return true; +} + +// Camera tuning arrives as a nested object ("cam_day" / "cam_night") so the +// two profiles stay visually distinct in the endpoint's settings UI. +static bool mergeTuning(CamTuning& t, JsonObjectConst d) { + if (d.isNull()) return false; + bool changed = false; + +#define T_NUM(field, key) \ + if (!d[key].isNull()) { \ + auto v = d[key].as(); \ + if (v != t.field) { t.field = v; changed = true; } \ + } +#define T_BOOL(field, key) \ + if (!d[key].isNull()) { \ + bool v = d[key].as(); \ + if (v != t.field) { t.field = v; changed = true; } \ + } + + T_NUM(brightness, "brightness"); + T_NUM(contrast, "contrast"); + T_NUM(saturation, "saturation"); + T_NUM(sharpness, "sharpness"); + T_NUM(ae_level, "ae_level"); + T_NUM(special_effect, "special_effect"); + T_NUM(wb_mode, "wb_mode"); + T_NUM(gainceiling, "gainceiling"); + T_NUM(agc_gain, "agc_gain"); + T_NUM(aec_value, "aec_value"); + T_BOOL(whitebal, "whitebal"); + T_BOOL(awb_gain, "awb_gain"); + T_BOOL(exposure_ctrl, "exposure_ctrl"); + T_BOOL(aec2, "aec2"); + T_BOOL(gain_ctrl, "gain_ctrl"); + T_BOOL(bpc, "bpc"); + T_BOOL(wpc, "wpc"); + T_BOOL(raw_gma, "raw_gma"); + T_BOOL(lenc, "lenc"); + T_BOOL(dcw, "dcw"); + T_BOOL(colorbar, "colorbar"); + +#undef T_NUM +#undef T_BOOL + + // Sensor ranges. Out-of-range values are rejected silently by the driver, + // which makes a typo in the settings UI look like the device ignored it. + if (t.brightness < -2) t.brightness = -2; if (t.brightness > 2) t.brightness = 2; + if (t.contrast < -2) t.contrast = -2; if (t.contrast > 2) t.contrast = 2; + if (t.saturation < -2) t.saturation = -2; if (t.saturation > 2) t.saturation = 2; + if (t.sharpness < -2) t.sharpness = -2; if (t.sharpness > 2) t.sharpness = 2; + if (t.ae_level < -2) t.ae_level = -2; if (t.ae_level > 2) t.ae_level = 2; + if (t.special_effect > 6) t.special_effect = 0; + if (t.wb_mode > 4) t.wb_mode = 0; + if (t.gainceiling > 6) t.gainceiling = 6; + if (t.agc_gain > 30) t.agc_gain = 30; + if (t.aec_value > 1200) t.aec_value = 1200; + + return changed; +} + +bool configApplyJson(JsonObjectConst doc) { + bool changed = false; + + MERGE_STR(device_name, "device_name"); + MERGE_STR(api_host, "api_host"); + MERGE_NUM(api_port, "api_port"); + MERGE_STR(ntp_host, "ntp_host"); + MERGE_STR(tz, "tz"); + + // Frame sizes accept "SVGA" or a raw index. Names are preferred and are + // what the settings UI should send — see framesizeFromName(). + changed |= mergeFrameSize(g_cfg.frame_size, doc["frame_size"]); + changed |= mergeFrameSize(g_cfg.stream_frame_size, doc["stream_frame_size"]); + + MERGE_NUM(jpeg_quality, "jpeg_quality"); + MERGE_BOOL(vflip, "vflip"); + MERGE_BOOL(hmirror, "hmirror"); + + changed |= mergeTuning(g_cfg.cam_day, doc["cam_day"]); + changed |= mergeTuning(g_cfg.cam_night, doc["cam_night"]); + + MERGE_NUM(ring_frames, "ring_frames"); + MERGE_NUM(pre_roll, "pre_roll"); + MERGE_NUM(post_roll, "post_roll"); + MERGE_NUM(post_roll_gap_ms, "post_roll_gap_ms"); + MERGE_NUM(cooldown_s, "cooldown_s"); + MERGE_NUM(idle_period_ms, "idle_period_ms"); + + MERGE_NUM(radar_mode, "radar_mode"); + MERGE_BOOL(accept_stationary,"accept_stationary"); + MERGE_NUM(min_distance_cm, "min_distance_cm"); + MERGE_NUM(max_distance_cm, "max_distance_cm"); + MERGE_NUM(min_energy, "min_energy"); + MERGE_NUM(radar_baud, "radar_baud"); + + MERGE_BOOL(stream_enabled, "stream_enabled"); + MERGE_NUM(stream_frame_size, "stream_frame_size"); + MERGE_NUM(stream_jpeg_quality, "stream_jpeg_quality"); + MERGE_NUM(stream_duration_s, "stream_duration_s"); + MERGE_NUM(stream_fps, "stream_fps"); + MERGE_NUM(stream_mode, "stream_mode"); + MERGE_BOOL(stream_blocks_sleep,"stream_blocks_sleep"); + + MERGE_NUM(night_start_min, "night_start_min"); + MERGE_NUM(night_end_min, "night_end_min"); + MERGE_NUM(night_behaviour, "night_behaviour"); + MERGE_NUM(nightlight_mode, "nightlight_mode"); + MERGE_NUM(nightlight_brightness, "nightlight_brightness"); + + MERGE_NUM(battery_chemistry, "battery_chemistry"); + MERGE_NUM(battery_divider_x100, "battery_divider_x100"); + MERGE_NUM(battery_offset_mv, "battery_offset_mv"); + MERGE_NUM(battery_min_pct_ota, "battery_min_pct_ota"); + MERGE_NUM(battery_warn_pct, "battery_warn_pct"); + + MERGE_NUM(heartbeat_interval_s, "heartbeat_interval_s"); + MERGE_NUM(status_interval_s, "status_interval_s"); + MERGE_BOOL(ota_enabled, "ota_enabled"); + + MERGE_BOOL(deep_sleep_enabled, "deep_sleep_enabled"); + MERGE_NUM(deep_sleep_s, "deep_sleep_s"); + MERGE_BOOL(sleep_wake_on_radar, "sleep_wake_on_radar"); + MERGE_NUM(sleep_idle_timeout_s, "sleep_idle_timeout_s"); + MERGE_NUM(sleep_max_awake_s, "sleep_max_awake_s"); + + // Clamp the things that brick the device or the battery if the endpoint + // sends nonsense. The device is the last line of defence here, because a + // bad config push reaches a box that is mounted outdoors. + if (g_cfg.jpeg_quality < 4) g_cfg.jpeg_quality = 4; + if (g_cfg.jpeg_quality > 40) g_cfg.jpeg_quality = 40; + if (g_cfg.ring_frames < 2) g_cfg.ring_frames = 2; + if (g_cfg.ring_frames > 60) g_cfg.ring_frames = 60; + if (g_cfg.pre_roll >= g_cfg.ring_frames) g_cfg.pre_roll = g_cfg.ring_frames - 1; + if (g_cfg.stream_duration_s > 600) g_cfg.stream_duration_s = 600; // C9 hard cap + if (g_cfg.stream_fps < 1) g_cfg.stream_fps = 1; + if (g_cfg.stream_fps > 25) g_cfg.stream_fps = 25; + if (g_cfg.heartbeat_interval_s < 30) g_cfg.heartbeat_interval_s = 30; + if (g_cfg.idle_period_ms < 100) g_cfg.idle_period_ms = 100; + + // Sleep floors. A device that sleeps too eagerly can become unreachable + // before it has drained the command queue that would turn sleep back off. + if (g_cfg.deep_sleep_s < 30) g_cfg.deep_sleep_s = 30; + if (g_cfg.deep_sleep_s > 3600) g_cfg.deep_sleep_s = 3600; + if (g_cfg.sleep_idle_timeout_s < 10) g_cfg.sleep_idle_timeout_s = 10; + if (g_cfg.sleep_max_awake_s < g_cfg.sleep_idle_timeout_s) + g_cfg.sleep_max_awake_s = g_cfg.sleep_idle_timeout_s; + + if (g_cfg.night_start_min > 1439) g_cfg.night_start_min = 1439; + if (g_cfg.night_end_min > 1439) g_cfg.night_end_min = 1439; + if (g_cfg.night_behaviour > NIGHT_SLEEP) g_cfg.night_behaviour = NIGHT_CAPTURE; + if (g_cfg.nightlight_mode > NIGHTLIGHT_ALWAYS) g_cfg.nightlight_mode = NIGHTLIGHT_OFF; + + if (g_cfg.battery_chemistry > BATT_LIFEPO4) g_cfg.battery_chemistry = BATT_NONE; + // A zero divider would report the pin voltage as the battery voltage and + // silently trip the OTA gate at the worst possible moment. + if (g_cfg.battery_divider_x100 < 100) g_cfg.battery_divider_x100 = 100; + if (g_cfg.battery_divider_x100 > 2000) g_cfg.battery_divider_x100 = 2000; + if (g_cfg.battery_min_pct_ota > 95) g_cfg.battery_min_pct_ota = 95; + + // config_version last, so it only advances if the payload was processed. + if (!doc["config_version"].isNull()) { + uint32_t v = doc["config_version"].as(); + if (v != g_cfg.config_version) { g_cfg.config_version = v; changed = true; } + } + + return changed; +} + +#undef MERGE_NUM +#undef MERGE_BOOL +#undef MERGE_STR + +bool configNeedsCameraRestart(const AppConfig& a, const AppConfig& b) { + // Frame size changes the framebuffer allocation, so it cannot be applied + // to a running sensor without tearing the driver down. + return a.frame_size != b.frame_size; +} + +const char* configBootstrapSecret() { return CFG_ENROLL_SECRET; } + +const char* deviceUid() { + if (s_uid[0]) return s_uid; + uint8_t mac[6] = {0}; + esp_read_mac(mac, ESP_MAC_WIFI_STA); + snprintf(s_uid, sizeof(s_uid), "%02x%02x%02x%02x%02x%02x", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return s_uid; +} + +String apiBaseUrl() { + String u = "http://"; + u += g_cfg.api_host; + u += ":"; + u += String(g_cfg.api_port); + u += g_cfg.api_base; + return u; +} + +void configDump() { + log_i("--- poorBird config ------------------------------"); + log_i(" uid %s name %s", deviceUid(), g_cfg.device_name); + log_i(" fw %s cfg_version %u", FW_VERSION, g_cfg.config_version); + log_i(" endpoint %s", apiBaseUrl().c_str()); + log_i(" enrolled %s", g_cfg.device_token[0] ? "yes" : "NO"); + uint16_t cw = 0, ch = 0, sw = 0, sh = 0; + framesizeDims(g_cfg.frame_size, &cw, &ch); + framesizeDims(g_cfg.stream_frame_size, &sw, &sh); + log_i(" camera %s (%ux%u) quality=%u | stream %s (%ux%u)", + framesizeName(g_cfg.frame_size), cw, ch, g_cfg.jpeg_quality, + framesizeName(g_cfg.stream_frame_size), sw, sh); + log_i(" ring depth=%u pre=%u post=%u period=%ums", + g_cfg.ring_frames, g_cfg.pre_roll, g_cfg.post_roll, g_cfg.idle_period_ms); + log_i(" radar mode=%u window=%u..%ucm energy>=%u stationary=%d", + g_cfg.radar_mode, g_cfg.min_distance_cm, g_cfg.max_distance_cm, + g_cfg.min_energy, g_cfg.accept_stationary); + log_i(" stream enabled=%d mode=%u %us @%ufps size=%u", + g_cfg.stream_enabled, g_cfg.stream_mode, g_cfg.stream_duration_s, + g_cfg.stream_fps, g_cfg.stream_frame_size); + log_i(" night %02u:%02u-%02u:%02u behaviour=%u light=%u/%u", + g_cfg.night_start_min / 60, g_cfg.night_start_min % 60, + g_cfg.night_end_min / 60, g_cfg.night_end_min % 60, + g_cfg.night_behaviour, g_cfg.nightlight_mode, g_cfg.nightlight_brightness); + log_i(" battery chem=%u divider=%.2f:1 trim=%dmV ota_min=%u%%", + g_cfg.battery_chemistry, g_cfg.battery_divider_x100 / 100.0f, + g_cfg.battery_offset_mv, g_cfg.battery_min_pct_ota); + log_i(" heartbeat %us status %us ota=%d", + g_cfg.heartbeat_interval_s, g_cfg.status_interval_s, g_cfg.ota_enabled); + log_i(" power deep_sleep=%s wake_on_radar=%d every=%us idle=%us max_awake=%us", + g_cfg.deep_sleep_enabled ? "ON" : "off", g_cfg.sleep_wake_on_radar, + g_cfg.deep_sleep_s, g_cfg.sleep_idle_timeout_s, g_cfg.sleep_max_awake_s); + log_i("--------------------------------------------------"); +} diff --git a/firmware/src/battery.cpp b/firmware/src/battery.cpp new file mode 100644 index 0000000..2f5d3e3 --- /dev/null +++ b/firmware/src/battery.cpp @@ -0,0 +1,115 @@ +#include "battery.h" + +#include "app_config.h" +#include "board_pins.h" + +static BatteryReading s_last = {}; + +// Discharge curves, millivolts at 100/90/…/0 %. Both are open-circuit +// approximations at moderate load and room temperature; they are good enough +// to drive a "low battery" banner and the OTA gate, and not good enough to +// promise a runtime estimate. +static const uint16_t kLiIon[11] = { + 4200, 4060, 3980, 3920, 3870, 3820, 3790, 3700, 3620, 3500, 3300 +}; +// LiFePO4 sits on a plateau near 3.2 V for most of its discharge. Percentage +// from voltage is genuinely unreliable here — treat anything between 20 % and +// 90 % as "somewhere in the middle" (SPEC §9 suggests this chemistry). +static const uint16_t kLiFePO4[11] = { + 3650, 3350, 3320, 3300, 3280, 3260, 3240, 3220, 3200, 3100, 2800 +}; + +static uint8_t pctFromCurve(const uint16_t* curve, uint16_t mv) { + if (mv >= curve[0]) return 100; + if (mv <= curve[10]) return 0; + for (int i = 0; i < 10; i++) { + if (mv <= curve[i] && mv > curve[i + 1]) { + const uint16_t hi = curve[i], lo = curve[i + 1]; + const int top = 100 - i * 10; + return (uint8_t)(top - (10 * (hi - mv)) / (hi - lo)); + } + } + return 0; +} + +void batteryBegin() { +#if PIN_BATTERY_ADC >= 0 + analogSetPinAttenuation(PIN_BATTERY_ADC, ADC_11db); // full ~0-3.1 V range +#if PIN_BATTERY_EN >= 0 + pinMode(PIN_BATTERY_EN, OUTPUT); + digitalWrite(PIN_BATTERY_EN, LOW); // divider off by default +#endif + log_i("battery: sensing on GPIO%d, divider %.2f:1", + PIN_BATTERY_ADC, g_cfg.battery_divider_x100 / 100.0f); + batteryPoll(); +#else + log_i("battery: no sense pin configured, voltage will report as invalid"); +#endif +} + +BatteryReading batteryRead() { + BatteryReading r = {}; + +#if PIN_BATTERY_ADC < 0 + return r; // not wired; valid stays false +#else + if (g_cfg.battery_divider_x100 == 0) return r; + +#if PIN_BATTERY_EN >= 0 + digitalWrite(PIN_BATTERY_EN, HIGH); + delayMicroseconds(200); // let the divider settle +#endif + + // Average several samples: a single ESP32 ADC read is noisy enough to move + // the reported percentage by a point or two between calls. + uint32_t acc = 0; + const uint8_t samples = 16; + for (uint8_t i = 0; i < samples; i++) acc += analogReadMilliVolts(PIN_BATTERY_ADC); + +#if PIN_BATTERY_EN >= 0 + digitalWrite(PIN_BATTERY_EN, LOW); +#endif + + r.raw_mv = (uint16_t)(acc / samples); + + int32_t mv = (int32_t)r.raw_mv * g_cfg.battery_divider_x100 / 100; + mv += g_cfg.battery_offset_mv; + if (mv < 0) mv = 0; + r.mv = (uint16_t)mv; + r.valid = true; + + switch (g_cfg.battery_chemistry) { + case BATT_LIION: r.pct = pctFromCurve(kLiIon, r.mv); break; + case BATT_LIFEPO4: r.pct = pctFromCurve(kLiFePO4, r.mv); break; + default: r.pct = 0; break; // BATT_NONE: voltage only + } + return r; +#endif +} + +void batteryPoll() { + BatteryReading r = batteryRead(); + if (r.valid) s_last = r; +} + +BatteryReading batteryLast() { return s_last; } + +bool batteryAboveOtaThreshold(uint8_t min_pct) { + BatteryReading r = batteryRead(); + + // No sensing hardware, or no chemistry configured, means we cannot judge. + // Allow the flash: this build is mains-powered by default, and refusing + // every OTA because an optional sensor is absent would be worse than the + // risk it guards against. Wire the divider if you want the gate to bite. + if (!r.valid || g_cfg.battery_chemistry == BATT_NONE) { + log_w("battery: no reading, OTA battery gate not enforced"); + return true; + } + + if (r.pct < min_pct) { + log_w("battery: %u%% (%umV) is below the %u%% OTA threshold", + r.pct, r.mv, min_pct); + return false; + } + return true; +} diff --git a/firmware/src/camera_mgr.cpp b/firmware/src/camera_mgr.cpp new file mode 100644 index 0000000..7860ebb --- /dev/null +++ b/firmware/src/camera_mgr.cpp @@ -0,0 +1,231 @@ +#include "camera_mgr.h" + +#include // strcasecmp + +#include "app_config.h" +#include "board_pins.h" + +static bool s_ready = false; + +// Built from the enum symbols rather than literal indices, so this table +// cannot drift when esp32-camera renumbers framesize_t. +struct FsName { framesize_t fs; const char* name; }; +static const FsName kFsNames[] = { + {FRAMESIZE_96X96, "96X96"}, {FRAMESIZE_QQVGA, "QQVGA"}, + {FRAMESIZE_128X128, "128X128"}, {FRAMESIZE_QCIF, "QCIF"}, + {FRAMESIZE_HQVGA, "HQVGA"}, {FRAMESIZE_240X240, "240X240"}, + {FRAMESIZE_QVGA, "QVGA"}, {FRAMESIZE_320X320, "320X320"}, + {FRAMESIZE_CIF, "CIF"}, {FRAMESIZE_HVGA, "HVGA"}, + {FRAMESIZE_VGA, "VGA"}, {FRAMESIZE_SVGA, "SVGA"}, + {FRAMESIZE_XGA, "XGA"}, {FRAMESIZE_HD, "HD"}, + {FRAMESIZE_SXGA, "SXGA"}, {FRAMESIZE_UXGA, "UXGA"}, + {FRAMESIZE_FHD, "FHD"}, {FRAMESIZE_QXGA, "QXGA"}, + {FRAMESIZE_QHD, "QHD"}, {FRAMESIZE_WQXGA, "WQXGA"}, + {FRAMESIZE_QSXGA, "QSXGA"}, {FRAMESIZE_5MP, "5MP"}, +}; + +uint8_t framesizeFromName(const char* name, uint8_t fallback) { + if (!name || !name[0]) return fallback; + for (const FsName& e : kFsNames) { + if (strcasecmp(name, e.name) == 0) return (uint8_t)e.fs; + } + log_w("camera: unknown frame size '%s', keeping %s", name, framesizeName(fallback)); + return fallback; +} + +const char* framesizeName(uint8_t fs) { + for (const FsName& e : kFsNames) { + if ((uint8_t)e.fs == fs) return e.name; + } + return "?"; +} + +void framesizeDims(uint8_t fs, uint16_t* w, uint16_t* h) { + if (w) *w = 0; + if (h) *h = 0; + if (fs >= FRAMESIZE_INVALID) return; + // resolution[] is the driver's own table, so these always match reality. + if (w) *w = resolution[fs].width; + if (h) *h = resolution[fs].height; +} + +static camera_config_t buildConfig() { + camera_config_t c = {}; + c.ledc_channel = LEDC_CHANNEL_0; + c.ledc_timer = LEDC_TIMER_0; + c.pin_d0 = CAM_PIN_D0; + c.pin_d1 = CAM_PIN_D1; + c.pin_d2 = CAM_PIN_D2; + c.pin_d3 = CAM_PIN_D3; + c.pin_d4 = CAM_PIN_D4; + c.pin_d5 = CAM_PIN_D5; + c.pin_d6 = CAM_PIN_D6; + c.pin_d7 = CAM_PIN_D7; + c.pin_xclk = CAM_PIN_XCLK; + c.pin_pclk = CAM_PIN_PCLK; + c.pin_vsync = CAM_PIN_VSYNC; + c.pin_href = CAM_PIN_HREF; + c.pin_sccb_sda = CAM_PIN_SIOD; + c.pin_sccb_scl = CAM_PIN_SIOC; + c.pin_pwdn = CAM_PIN_PWDN; + c.pin_reset = CAM_PIN_RESET; + c.xclk_freq_hz = 20000000; + c.pixel_format = PIXFORMAT_JPEG; + c.frame_size = (framesize_t)g_cfg.frame_size; + c.jpeg_quality = g_cfg.jpeg_quality; + + // Two framebuffers in PSRAM with CAM_GRAB_LATEST: the driver keeps + // capturing while we are busy copying the previous frame into the ring, + // and a grab always returns the newest frame rather than a queued stale + // one. On a trigger, "newest" is what you want. + c.fb_location = CAMERA_FB_IN_PSRAM; + c.fb_count = 2; + c.grab_mode = CAMERA_GRAB_LATEST; + return c; +} + +bool cameraBegin() { + if (s_ready) return true; + + if (!psramFound()) { + // Without PSRAM there is no ring buffer and no SVGA framebuffer. + // Fail loudly rather than silently running a crippled node. + log_e("PSRAM not found — check board_build.arduino.memory_type=qio_opi"); + return false; + } + + camera_config_t c = buildConfig(); + esp_err_t err = esp_camera_init(&c); + if (err != ESP_OK) { + log_e("esp_camera_init failed: 0x%x", err); + return false; + } + + s_ready = true; + cameraApplyConfig(); + cameraDiscardFrames(3); + + uint16_t w = 0, h = 0; + framesizeDims(g_cfg.frame_size, &w, &h); + sensor_t* s = esp_camera_sensor_get(); + log_i("camera ready: sensor PID 0x%04x, %s (%ux%u) quality=%u psram_free=%uKB", + s ? s->id.PID : 0, framesizeName(g_cfg.frame_size), w, h, + g_cfg.jpeg_quality, + (unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024)); + return true; +} + +void cameraEnd() { + if (!s_ready) return; + esp_camera_deinit(); + s_ready = false; +} + +bool cameraRestart() { + cameraEnd(); + delay(50); + return cameraBegin(); +} + +static bool s_night_profile = false; + +bool cameraNightProfileActive() { return s_night_profile; } + +// Everything the OV2640 exposes that is worth touching on a bird camera. +// Notes on the ones that actually matter here: +// +// gainceiling The single most important setting for small fast birds. +// High gain lets the sensor pick a shorter exposure in poor +// light, but amplifies noise; low gain forces a longer +// exposure and smears a moving bird into a streak. 4x by day +// is a good compromise; the night profile raises it because a +// noisy photo beats a black one. +// exposure_ctrl Leave auto by day. Set false + aec_value to force a fixed +// short shutter if you find motion blur is the limiting +// factor at your feeder — that is the tuning lever. +// ae_level Exposure bias. Birds are usually backlit against bright sky, +// which fools metering into underexposing the bird; +1 helps. +// lenc Lens shading correction. On, unless you are stitching. +// colorbar Test pattern. Set true to prove the data path works before +// you have optics or light. +void cameraApplyTuning(bool night) { + sensor_t* s = esp_camera_sensor_get(); + if (!s) return; + + const CamTuning& t = night ? g_cfg.cam_night : g_cfg.cam_day; + s_night_profile = night; + + s->set_brightness(s, t.brightness); + s->set_contrast(s, t.contrast); + s->set_saturation(s, t.saturation); + s->set_sharpness(s, t.sharpness); + s->set_special_effect(s, t.special_effect); + + s->set_whitebal(s, t.whitebal ? 1 : 0); + s->set_awb_gain(s, t.awb_gain ? 1 : 0); + s->set_wb_mode(s, t.wb_mode); + + s->set_exposure_ctrl(s, t.exposure_ctrl ? 1 : 0); + s->set_aec2(s, t.aec2 ? 1 : 0); + s->set_ae_level(s, t.ae_level); + if (!t.exposure_ctrl) s->set_aec_value(s, t.aec_value); + + s->set_gain_ctrl(s, t.gain_ctrl ? 1 : 0); + if (!t.gain_ctrl) s->set_agc_gain(s, t.agc_gain); + s->set_gainceiling(s, (gainceiling_t)t.gainceiling); + + s->set_bpc(s, t.bpc ? 1 : 0); + s->set_wpc(s, t.wpc ? 1 : 0); + s->set_raw_gma(s, t.raw_gma ? 1 : 0); + s->set_lenc(s, t.lenc ? 1 : 0); + s->set_dcw(s, t.dcw ? 1 : 0); + s->set_colorbar(s, t.colorbar ? 1 : 0); + + // The sensor needs a couple of frames to act on an exposure change. + cameraDiscardFrames(2); + + log_i("camera: %s profile applied (gainceiling=%u ae_level=%d aec=%s)", + night ? "night" : "day", t.gainceiling, t.ae_level, + t.exposure_ctrl ? "auto" : "manual"); +} + +void cameraApplyConfig() { + sensor_t* s = esp_camera_sensor_get(); + if (!s) return; + s->set_quality(s, g_cfg.jpeg_quality); + s->set_vflip(s, g_cfg.vflip ? 1 : 0); + s->set_hmirror(s, g_cfg.hmirror ? 1 : 0); + cameraApplyTuning(s_night_profile); +} + +bool cameraSetFrameSize(uint8_t framesize) { + sensor_t* s = esp_camera_sensor_get(); + if (!s) return false; + + // set_framesize refuses anything above the sensor's own maximum, which is + // how an OV2640 (max UXGA) tells you it cannot do the QXGA an OV5640 + // would manage. Report it rather than silently keeping the old size. + if (s->set_framesize(s, (framesize_t)framesize) != 0) { + log_w("camera: sensor rejected frame size %s — above its maximum?", + framesizeName(framesize)); + return false; + } + cameraDiscardFrames(2); + return true; +} + +camera_fb_t* cameraGrab() { + if (!s_ready) return nullptr; + camera_fb_t* fb = esp_camera_fb_get(); + if (!fb) log_w("camera grab failed"); + return fb; +} + +void cameraDiscardFrames(uint8_t n) { + for (uint8_t i = 0; i < n; i++) { + camera_fb_t* fb = esp_camera_fb_get(); + if (fb) esp_camera_fb_return(fb); + } +} + +bool cameraReady() { return s_ready; } diff --git a/firmware/src/commands.cpp b/firmware/src/commands.cpp new file mode 100644 index 0000000..8e5c159 --- /dev/null +++ b/firmware/src/commands.cpp @@ -0,0 +1,200 @@ +#include "commands.h" + +#include "api_client.h" +#include "app_config.h" +#include "camera_mgr.h" +#include "ota_mgr.h" +#include "power_mgr.h" +#include "stream_session.h" + +// main.cpp owns the capture pipeline; this is how a command reaches it. +extern void requestManualCapture(); + +// A deferred command, kept as a fixed-size record so the queue needs no heap. +struct Deferred { + bool used; + uint32_t id; + char type[20]; + char s_arg[64]; // session id, or firmware url + char s_arg2[65]; // sha256 + uint32_t n_arg; // seconds, size + uint8_t u_arg[3]; // mode, framesize, spare +}; + +static const size_t kQueueDepth = 4; +static Deferred s_queue[kQueueDepth] = {}; + +static bool enqueue(const Deferred& d) { + for (size_t i = 0; i < kQueueDepth; i++) { + if (!s_queue[i].used) { s_queue[i] = d; s_queue[i].used = true; return true; } + } + return false; +} + +void commandOnReceived(JsonObjectConst cmd) { + const uint32_t id = cmd["id"] | (uint32_t)0; + const char* type = cmd["type"] | ""; + JsonObjectConst p = cmd["payload"]; + + log_i("cmd #%u: %s", (unsigned)id, type); + powerNoteActivity(); + + // --- immediate, cheap --------------------------------------------------- + + if (strcmp(type, "apply_config") == 0) { + const bool was_sleeping = g_cfg.deep_sleep_enabled; + const AppConfig before = g_cfg; + + bool changed = false; + if (!p.isNull()) { + changed = configApplyJson(p); + } else { + // No inline payload: the endpoint wants us to pull the full doc. + changed = apiFetchConfig(); + } + + if (changed) { + configSave(); + cameraApplyConfig(); + powerOnConfigChanged(was_sleeping); + if (configNeedsCameraRestart(before, g_cfg)) { + log_i("cmd: frame size changed, restarting camera"); + cameraRestart(); + } + } + apiAckCommand(id, "done", changed ? "config applied" : "no change"); + return; + } + + if (strcmp(type, "capture_now") == 0) { + requestManualCapture(); + apiAckCommand(id, "done", "capture queued"); + return; + } + + if (strcmp(type, "report_status") == 0) { + // Deferred: we are currently inside the heartbeat's response handler, + // and opening a second connection from here would nest HTTP clients. + Deferred d = {}; + d.id = id; + strncpy(d.type, "report_status", sizeof(d.type) - 1); + if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full"); + return; + } + + if (strcmp(type, "wake_and_hold") == 0) { + uint32_t secs = p["seconds"] | (uint32_t)60; + if (secs > 900) secs = 900; // bounded, per SPEC §4.3 + powerHoldAwake(secs); + apiAckCommand(id, "done", "holding awake"); + return; + } + + if (strcmp(type, "sleep_now") == 0) { + // Deferred: we want the ack to reach the Pi before the radio goes off. + Deferred d = {}; + d.id = id; + d.n_arg = p["seconds"] | (uint32_t)0; + strncpy(d.type, "sleep_now", sizeof(d.type) - 1); + if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full"); + return; + } + + if (strcmp(type, "stream_stop") == 0) { + streamStop("stopped by command"); + apiAckCommand(id, "done", "stream stopped"); + return; + } + + if (strcmp(type, "reboot") == 0) { + apiAckCommand(id, "done", "rebooting"); + delay(200); + ESP.restart(); + return; + } + + // --- deferred: these block, so they run from the main loop --------------- + + if (strcmp(type, "stream_start") == 0) { + Deferred d = {}; + d.id = id; + strncpy(d.type, "stream_start", sizeof(d.type) - 1); + strncpy(d.s_arg, p["session_id"] | "", sizeof(d.s_arg) - 1); + d.n_arg = p["duration_s"] | (uint32_t)0; + d.u_arg[0] = p["mode"] | (uint8_t)0xFF; + d.u_arg[1] = p["frame_size"] | (uint8_t)0; + if (!d.s_arg[0]) { apiAckCommand(id, "rejected", "no session_id"); return; } + if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full"); + return; + } + + if (strcmp(type, "ota_update") == 0) { + Deferred d = {}; + d.id = id; + strncpy(d.type, "ota_update", sizeof(d.type) - 1); + strncpy(d.s_arg, p["url"] | "", sizeof(d.s_arg) - 1); + strncpy(d.s_arg2, p["sha256"] | "", sizeof(d.s_arg2) - 1); + d.n_arg = p["size"] | (uint32_t)0; + // The version lands in s_arg's tail via the firmware envelope instead; + // an ota_update command without a url means "use the target from the + // envelope", which main.cpp already tracks. + if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full"); + return; + } + + log_w("cmd #%u: unknown type '%s'", (unsigned)id, type); + apiAckCommand(id, "rejected", "unknown command type"); +} + +// The firmware target from the most recent response envelope, so an +// `ota_update` command with no explicit url still knows what to fetch. +extern OtaTarget g_fw_target; + +void commandRunDeferred() { + for (size_t i = 0; i < kQueueDepth; i++) { + if (!s_queue[i].used) continue; + + Deferred d = s_queue[i]; + s_queue[i].used = false; // clear first: a reboot must not replay it + + if (strcmp(d.type, "stream_start") == 0) { + bool ok = streamStart(d.s_arg, d.u_arg[0], d.u_arg[1], (uint16_t)d.n_arg); + apiAckCommand(d.id, ok ? "done" : "failed", + ok ? "streaming" : "could not start stream"); + + } else if (strcmp(d.type, "ota_update") == 0) { + OtaTarget t = g_fw_target; + if (d.s_arg[0]) strncpy(t.url, d.s_arg, sizeof(t.url) - 1); + if (d.s_arg2[0]) strncpy(t.sha256, d.s_arg2, sizeof(t.sha256) - 1); + if (d.n_arg) t.size = d.n_arg; + + if (!t.url[0]) { + apiAckCommand(d.id, "rejected", "no firmware url"); + continue; + } + // Ack before flashing: otaApply() reboots on success and would + // never get the chance to report it. + apiAckCommand(d.id, "done", "flashing"); + if (!otaApply(t)) { + apiAckCommand(d.id, "failed", "ota failed, still on old image"); + } + + } else if (strcmp(d.type, "report_status") == 0) { + bool ok = apiPostStatus("on_request"); + apiAckCommand(d.id, ok ? "done" : "failed", ok ? "status posted" : "status post failed"); + + } else if (strcmp(d.type, "sleep_now") == 0) { + apiAckCommand(d.id, "done", "sleeping"); + powerSleepNow(d.n_arg); + // Returns only if sleep is switched off or OTA is in flight. + apiAckCommand(d.id, "rejected", "deep sleep is off"); + } + } +} + +bool commandHasPending() { + for (size_t i = 0; i < kQueueDepth; i++) { + if (s_queue[i].used) return true; + } + return false; +} diff --git a/firmware/src/device_stats.cpp b/firmware/src/device_stats.cpp new file mode 100644 index 0000000..56689d6 --- /dev/null +++ b/firmware/src/device_stats.cpp @@ -0,0 +1,94 @@ +#include "device_stats.h" + +#include + +#include "net_mgr.h" + +// RTC slow memory: survives deep sleep, lost on power cycle. +RTC_DATA_ATTR static uint16_t s_captured_today = 0; +RTC_DATA_ATTR static uint16_t s_delivered_today = 0; +RTC_DATA_ATTR static uint16_t s_failed_today = 0; +RTC_DATA_ATTR static uint16_t s_events_today = 0; +RTC_DATA_ATTR static uint32_t s_day_index = 0; + +static uint16_t s_captured_boot = 0; +static uint16_t s_delivered_boot = 0; +static uint32_t s_wake_ms = 0; + +// Days since epoch in *local* time. localtime_r honours the TZ set by +// net_mgr, so this rolls over at local midnight rather than at UTC midnight — +// which matters in CEST, where UTC midnight is 02:00 the next morning. +static uint32_t localDayIndex() { + const int64_t ms = netEpochMs(); + if (ms == 0) return 0; // unsynced: everything is "day 0" + + time_t t = (time_t)(ms / 1000); + struct tm lt; + localtime_r(&t, <); + + // mktime of local midnight, divided into days. Simpler than date maths and + // correct across DST, because mktime resolves the offset for that date. + struct tm midnight = lt; + midnight.tm_hour = 0; + midnight.tm_min = 0; + midnight.tm_sec = 0; + time_t m = mktime(&midnight); + return (uint32_t)(m / 86400); +} + +void statsBegin() { + s_wake_ms = millis(); + s_captured_boot = 0; + s_delivered_boot = 0; + statsRollover(); +} + +void statsRollover() { + const uint32_t today = localDayIndex(); + if (today == 0) return; // clock not yet trustworthy + + if (today != s_day_index) { + if (s_day_index != 0) { + log_i("stats: new day, resetting counters (was %u captured, %u delivered)", + s_captured_today, s_delivered_today); + } + s_day_index = today; + s_captured_today = 0; + s_delivered_today = 0; + s_failed_today = 0; + s_events_today = 0; + } +} + +void statsCountEvent() { statsRollover(); s_events_today++; } + +void statsCountCaptured(uint16_t frames) { + statsRollover(); + s_captured_today += frames; + s_captured_boot += frames; +} + +void statsCountDelivered(uint16_t frames) { + statsRollover(); + s_delivered_today += frames; + s_delivered_boot += frames; +} + +void statsCountFailed(uint16_t frames) { + statsRollover(); + s_failed_today += frames; +} + +DeviceStats statsGet() { + DeviceStats s = {}; + s.captured_today = s_captured_today; + s.delivered_today = s_delivered_today; + s.failed_today = s_failed_today; + s.events_today = s_events_today; + s.day_index = s_day_index; + s.captured_boot = s_captured_boot; + s.delivered_boot = s_delivered_boot; + return s; +} + +uint32_t statsAwakeMs() { return millis() - s_wake_ms; } diff --git a/firmware/src/frame_ring.cpp b/firmware/src/frame_ring.cpp new file mode 100644 index 0000000..875a896 --- /dev/null +++ b/firmware/src/frame_ring.cpp @@ -0,0 +1,140 @@ +#include "frame_ring.h" + +#include + +static RingFrame* s_ring = nullptr; +static size_t s_depth = 0; +static size_t s_head = 0; // next slot to write +static size_t s_count = 0; +static uint32_t s_seq = 0; +static SemaphoreHandle_t s_mtx = nullptr; + +// Slots start at a plausible SVGA JPEG size and grow if a frame does not fit. +// Growing costs one realloc; shrinking is never worth the churn. +static const size_t kInitialSlotBytes = 48 * 1024; + +bool ringBegin(uint8_t depth) { + ringEnd(); + if (depth == 0) return false; + + s_mtx = xSemaphoreCreateMutex(); + if (!s_mtx) return false; + + s_ring = (RingFrame*)heap_caps_calloc(depth, sizeof(RingFrame), MALLOC_CAP_SPIRAM); + if (!s_ring) { + log_e("ring: cannot allocate slot table in PSRAM"); + vSemaphoreDelete(s_mtx); + s_mtx = nullptr; + return false; + } + + for (size_t i = 0; i < depth; i++) { + s_ring[i].data = (uint8_t*)heap_caps_malloc(kInitialSlotBytes, MALLOC_CAP_SPIRAM); + if (!s_ring[i].data) { + log_e("ring: PSRAM exhausted at slot %u of %u", (unsigned)i, depth); + // Run with the slots we got rather than failing outright — a + // shallower ring is still far better than none. + depth = i; + break; + } + s_ring[i].cap = kInitialSlotBytes; + } + if (depth == 0) { ringEnd(); return false; } + + s_depth = depth; + s_head = s_count = 0; + s_seq = 0; + log_i("ring: %u slots x %uKB = %uKB PSRAM (free %uKB)", + (unsigned)s_depth, (unsigned)(kInitialSlotBytes / 1024), + (unsigned)(s_depth * kInitialSlotBytes / 1024), + (unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024)); + return true; +} + +void ringEnd() { + if (s_mtx) xSemaphoreTake(s_mtx, portMAX_DELAY); + if (s_ring) { + for (size_t i = 0; i < s_depth; i++) free(s_ring[i].data); + free(s_ring); + s_ring = nullptr; + } + s_depth = s_head = s_count = 0; + s_seq = 0; + if (s_mtx) { + xSemaphoreGive(s_mtx); + vSemaphoreDelete(s_mtx); + s_mtx = nullptr; + } +} + +bool ringPush(const uint8_t* data, size_t len, int64_t epoch_ms) { + if (!s_ring || !data || len == 0) return false; + if (xSemaphoreTake(s_mtx, pdMS_TO_TICKS(100)) != pdTRUE) return false; + + RingFrame& f = s_ring[s_head]; + + if (len > f.cap) { + uint8_t* bigger = (uint8_t*)heap_caps_realloc(f.data, len, MALLOC_CAP_SPIRAM); + if (!bigger) { + xSemaphoreGive(s_mtx); + log_w("ring: cannot grow slot to %u bytes, dropping frame", (unsigned)len); + return false; + } + f.data = bigger; + f.cap = len; + } + + memcpy(f.data, data, len); + f.len = len; + f.at_ms = millis(); + f.at_epoch = epoch_ms; + f.seq = ++s_seq; + + s_head = (s_head + 1) % s_depth; + if (s_count < s_depth) s_count++; + + xSemaphoreGive(s_mtx); + return true; +} + +size_t ringTakeNewest(size_t n, FrameCopy* out, size_t out_cap) { + if (!s_ring || !out || out_cap == 0) return 0; + if (xSemaphoreTake(s_mtx, pdMS_TO_TICKS(500)) != pdTRUE) return 0; + + if (n > s_count) n = s_count; + if (n > out_cap) n = out_cap; + + size_t written = 0; + for (size_t i = 0; i < n; i++) { + // Walk oldest-of-the-newest-n forward to newest. + size_t back = n - i; // 1 == newest + size_t idx = (s_head + s_depth - back) % s_depth; + RingFrame& f = s_ring[idx]; + if (f.seq == 0 || f.len == 0) continue; + + // Copies live in PSRAM. A ten-frame event is ~450 KB, which would + // exhaust internal RAM and starve the WiFi stack exactly when it is + // about to do the most work. + uint8_t* buf = (uint8_t*)heap_caps_malloc(f.len, MALLOC_CAP_SPIRAM); + if (!buf) { + log_w("ring: out of memory copying frame for upload"); + break; + } + memcpy(buf, f.data, f.len); + + out[written++] = FrameCopy{buf, f.len, f.seq, f.at_ms, f.at_epoch}; + } + + xSemaphoreGive(s_mtx); + return written; +} + +uint32_t ringSeq() { return s_seq; } +size_t ringCount() { return s_count; } + +size_t ringBytesUsed() { + if (!s_ring) return 0; + size_t total = 0; + for (size_t i = 0; i < s_depth; i++) total += s_ring[i].cap; + return total; +} diff --git a/firmware/src/ld2410.cpp b/firmware/src/ld2410.cpp new file mode 100644 index 0000000..a0d9a27 --- /dev/null +++ b/firmware/src/ld2410.cpp @@ -0,0 +1,296 @@ +#include "ld2410.h" + +#include + +#include "app_config.h" +#include "board_pins.h" + +static HardwareSerial s_uart(RADAR_UART_NUM); +static RadarReading s_last = {}; + +// Incremental frame assembler. The radar streams continuously and we share the +// core with the camera, so parsing has to tolerate being called late and +// finding several frames queued in the driver buffer. +static uint8_t s_buf[64]; +static size_t s_len = 0; +static bool s_sync = false; + +static const uint8_t kReportHead[4] = {0xF4, 0xF3, 0xF2, 0xF1}; +static const uint8_t kReportTail[4] = {0xF8, 0xF7, 0xF6, 0xF5}; +static const uint8_t kCmdHead[4] = {0xFD, 0xFC, 0xFB, 0xFA}; +static const uint8_t kCmdTail[4] = {0x04, 0x03, 0x02, 0x01}; + +static inline uint16_t rd16(const uint8_t* p) { + return (uint16_t)p[0] | ((uint16_t)p[1] << 8); +} + +// Baud rates to probe, most likely first. The LD2410 leaves the factory at +// 256000; 115200 is the usual choice when someone has reconfigured it. +static const uint32_t kBaudCandidates[] = {256000, 115200, 57600, 38400, 9600}; +static uint32_t s_baud = 0; + +uint32_t radarBaud() { return s_baud; } + +// Open at `baud` and listen for a well-formed report frame. +static bool tryBaud(uint32_t baud, uint32_t listen_ms) { + s_uart.end(); + delay(20); + s_uart.setRxBufferSize(512); // must precede begin() + s_uart.begin(baud, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX); + + s_len = 0; + s_sync = false; + memset(&s_last, 0, sizeof(s_last)); + + const uint32_t end = millis() + listen_ms; + while ((int32_t)(end - millis()) > 0) { + if (radarPoll()) return true; // decoded a real frame: right baud + delay(5); + } + return false; +} + +bool radarBegin() { + pinMode(PIN_RADAR_OUT, INPUT); + + // Autodetect rather than hardcode. The module reports a few times a + // second, so a wrong baud is obvious within a second — and detecting it + // means a factory reset (which returns the module to 256000) does not + // silently take the camera's trigger offline on a device you cannot + // easily reach. Pin it with `radar_baud` if you would rather it not probe. + if (g_cfg.radar_baud != 0) { + if (tryBaud(g_cfg.radar_baud, 1500)) { + s_baud = g_cfg.radar_baud; + log_i("radar: UART%d @%u baud (pinned) rx=%d tx=%d out=%d", + RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT); + return true; + } + log_w("radar: no frames at the pinned %u baud, falling back to autodetect", + (unsigned)g_cfg.radar_baud); + } + + for (uint32_t cand : kBaudCandidates) { + if (tryBaud(cand, 900)) { + s_baud = cand; + log_i("radar: UART%d @%u baud (detected) rx=%d tx=%d out=%d", + RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT); + return true; + } + } + + // Nothing decoded. Leave the port open at the default so radarSelfTest() + // can still dump raw bytes, and so the OUT pin path keeps working — + // RADAR_OUT_PIN_ONLY mode does not need the UART at all. + s_baud = 0; + s_uart.end(); + delay(20); + s_uart.setRxBufferSize(512); + s_uart.begin(RADAR_BAUD, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX); + log_w("radar: no UART frames at any baud — check TX/RX are crossed. " + "The OUT pin still works; radar_mode=0 uses it alone."); + return false; +} + +// Decode a complete report payload (header and tail already stripped). +static bool decodeReport(const uint8_t* p, size_t n) { + // Basic report: 13 payload bytes. Engineering mode reports are longer and + // start the same way, so we accept anything >= 13 and read the common head. + if (n < 13) return false; + if (p[0] != 0x02 || p[1] != 0xAA) return false; + + RadarReading r = {}; + r.valid = true; + r.target = p[2]; + r.moving_cm = rd16(&p[3]); + r.moving_energy = p[5]; + r.stationary_cm = rd16(&p[6]); + r.stationary_energy = p[8]; + r.detect_cm = rd16(&p[9]); + r.at_ms = millis(); + r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH; + s_last = r; + +#ifdef PB_VERBOSE_RADAR + log_d("radar: state=%u mov=%ucm/%u stat=%ucm/%u det=%ucm out=%d", + r.target, r.moving_cm, r.moving_energy, + r.stationary_cm, r.stationary_energy, r.detect_cm, r.out_pin); +#endif + return true; +} + +bool radarPoll() { + bool got = false; + + while (s_uart.available()) { + uint8_t b = (uint8_t)s_uart.read(); + + if (!s_sync) { + // Slide a 4-byte window until it matches either header. + if (s_len < 4) { + s_buf[s_len++] = b; + } else { + memmove(s_buf, s_buf + 1, 3); + s_buf[3] = b; + } + if (s_len == 4 && + (memcmp(s_buf, kReportHead, 4) == 0 || memcmp(s_buf, kCmdHead, 4) == 0)) { + s_sync = true; + } + continue; + } + + if (s_len >= sizeof(s_buf)) { // runaway frame: resynchronise + s_len = 0; + s_sync = false; + continue; + } + s_buf[s_len++] = b; + + // Need header(4) + length(2) before we know how much to expect. + if (s_len < 6) continue; + + const uint16_t payload_len = rd16(&s_buf[4]); + const size_t total = 4 + 2 + payload_len + 4; + if (payload_len > sizeof(s_buf) - 10) { // implausible length + s_len = 0; + s_sync = false; + continue; + } + if (s_len < total) continue; + + const uint8_t* tail = &s_buf[6 + payload_len]; + const bool is_rpt = memcmp(s_buf, kReportHead, 4) == 0; + const uint8_t* expect = is_rpt ? kReportTail : kCmdTail; + + if (memcmp(tail, expect, 4) == 0 && is_rpt) { + got |= decodeReport(&s_buf[6], payload_len); + } + // Command ACKs are consumed silently; the write helpers below poll for + // them separately rather than routing them through this path. + + s_len = 0; + s_sync = false; + } + + // Keep the pin fresh even when the UART is silent (or absent). + s_last.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH; + return got; +} + +RadarReading radarLast() { + RadarReading r = s_last; + r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH; + return r; +} + +bool radarIsTrigger(const RadarReading& r) { + switch (g_cfg.radar_mode) { + case RADAR_OUT_PIN_ONLY: + return r.out_pin; + + case RADAR_UART_ONLY: + break; // fall through to the windowed check + + case RADAR_BOTH: + default: + // The pin arms; the report has to agree. If the UART has gone + // quiet (bad wiring, wrong baud) we would otherwise never trigger, + // so a stale report degrades to pin-only rather than to silence. + if (!r.out_pin) return false; + if (!r.valid || (millis() - r.at_ms) > 3000) return true; + break; + } + + if (!r.valid) return false; + if (r.target == TARGET_NONE) return false; + + const bool moving = (r.target == TARGET_MOVING || r.target == TARGET_BOTH); + const bool stationary = (r.target == TARGET_STATIONARY || r.target == TARGET_BOTH); + + if (moving && + r.moving_energy >= g_cfg.min_energy && + r.moving_cm >= g_cfg.min_distance_cm && + r.moving_cm <= g_cfg.max_distance_cm) { + return true; + } + + if (stationary && g_cfg.accept_stationary && + r.stationary_energy >= g_cfg.min_energy && + r.stationary_cm >= g_cfg.min_distance_cm && + r.stationary_cm <= g_cfg.max_distance_cm) { + return true; + } + + return false; +} + +void radarSelfTest(uint32_t duration_ms) { + log_i("radar self-test: dumping raw UART for %u ms", duration_ms); + const uint32_t end = millis() + duration_ms; + size_t bytes = 0; + uint32_t frames = 0; + while ((int32_t)(end - millis()) > 0) { + while (s_uart.available()) { s_uart.read(); bytes++; } + if (radarPoll()) frames++; + delay(5); + } + log_i("radar self-test: %u bytes, %u decoded frames, OUT=%d", + (unsigned)bytes, (unsigned)frames, digitalRead(PIN_RADAR_OUT)); + if (bytes == 0) { + log_w(" no UART data. Check TX/RX are crossed and the baud rate " + "(factory 256000, some units ship at 115200)."); + } +} + +// --- command path ----------------------------------------------------------- +// Minimal: enough to raise sensitivity if the default rejects small targets. + +static bool sendCommand(const uint8_t* payload, uint16_t len, uint32_t timeout_ms = 300) { + uint8_t frame[32]; + if (len + 10 > sizeof(frame)) return false; + + memcpy(frame, kCmdHead, 4); + frame[4] = len & 0xFF; + frame[5] = (len >> 8) & 0xFF; + memcpy(frame + 6, payload, len); + memcpy(frame + 6 + len, kCmdTail, 4); + + while (s_uart.available()) s_uart.read(); // drop queued reports + s_uart.write(frame, len + 10); + s_uart.flush(); + + // The ACK mirrors the command word with bit 8 set. We only check that + // *something* well-formed came back; the module is not chatty enough for + // a mismatched ACK to be ambiguous in practice. + const uint32_t end = millis() + timeout_ms; + while ((int32_t)(end - millis()) > 0) { + if (s_uart.available() >= 10) return true; + delay(5); + } + log_w("radar: no ACK for command 0x%02X%02X", payload[1], payload[0]); + return false; +} + +bool radarEnterConfig() { + const uint8_t p[] = {0xFF, 0x00, 0x01, 0x00}; + return sendCommand(p, sizeof(p)); +} + +bool radarExitConfig() { + const uint8_t p[] = {0xFE, 0x00}; + bool ok = sendCommand(p, sizeof(p)); + s_len = 0; s_sync = false; // report stream resumes; drop partial state + return ok; +} + +bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary) { + if (gate > 8) return false; + // Command 0x0064: three (param-id, uint32 value) pairs. + const uint8_t p[] = { + 0x64, 0x00, + 0x00, 0x00, gate, 0x00, 0x00, 0x00, + 0x01, 0x00, moving, 0x00, 0x00, 0x00, + 0x02, 0x00, stationary, 0x00, 0x00, 0x00, + }; + return sendCommand(p, sizeof(p)); +} diff --git a/firmware/src/main.cpp b/firmware/src/main.cpp new file mode 100644 index 0000000..3302c12 --- /dev/null +++ b/firmware/src/main.cpp @@ -0,0 +1,562 @@ +// poorBird — ESP32-S3 camera node +// +// Two operating modes, selected by g_cfg.deep_sleep_enabled and switchable +// from the WebUI. See power_mgr.h for what each one costs you. +// +// AWAKE MODE (default, mains powered) +// capture task (core 1) camera + PSRAM ring + stream frames +// loop() (core 0) uploads, heartbeat, commands, OTA, sleep check +// +// Splitting it this way means a 3-second upload over marginal WiFi never +// stops the ring from filling, so the pre-trigger history stays continuous +// even while the previous event is still being sent. Exactly one task ever +// touches the camera, which is the only threading rule esp32-camera cares +// about. +// +// SLEEP MODE (battery) +// One linear pass in setup(): wake -> capture burst -> upload -> drain +// commands -> sleep. No tasks, no ring, no pre-trigger frames. +// +// Every failure path ends in sleep when sleep is on, and in a retry with +// backoff when it is not (SPEC §4.3). + +#include + +#include "api_client.h" +#include "app_config.h" +#include "battery.h" +#include "board_pins.h" +#include "camera_mgr.h" +#include "commands.h" +#include "device_stats.h" +#include "frame_ring.h" +#include "ld2410.h" +#include "net_mgr.h" +#include "nightlight.h" +#include "ota_mgr.h" +#include "power_mgr.h" +#include "stream_session.h" + +// Firmware target from the most recent response envelope. commands.cpp reads it. +OtaTarget g_fw_target = {}; + +// --- capture event handoff -------------------------------------------------- +struct CaptureEvent { + uint32_t at_ms; + const char* trigger; + RadarReading radar; +}; + +static QueueHandle_t s_events = nullptr; +static TaskHandle_t s_capture_task = nullptr; +static volatile bool s_manual_req = false; +static uint32_t s_last_trigger_ms = 0; +static uint32_t s_next_heartbeat_ms = 0; +static uint32_t s_next_status_ms = 0; +static uint32_t s_next_battery_ms = 0; +static uint32_t s_burst_light_until_ms = 0; +static uint8_t s_upload_failures = 0; + +void requestManualCapture() { s_manual_req = true; } + +static void statusLed(bool on) { +#if STATUS_LED_ACTIVE_LOW + digitalWrite(PIN_STATUS_LED, on ? LOW : HIGH); +#else + digitalWrite(PIN_STATUS_LED, on ? HIGH : LOW); +#endif +} + +// A burst id the Pi can group frames by. Device uid + boot + millis is unique +// without needing a random source or a synced clock. +static void makeBurstId(char* out, size_t cap) { + snprintf(out, cap, "%s-%u-%u", deviceUid(), (unsigned)powerBootCount(), (unsigned)millis()); +} + +// --------------------------------------------------------------------------- +// Response handling shared by every API call +// --------------------------------------------------------------------------- +static void handleEnvelope(const ServerEnvelope& env) { + if (!env.ok) return; + + netAdoptServerTime(env.server_time_ms); + + if (env.config_version != g_cfg.config_version) { + log_i("config: endpoint is at v%u, we are at v%u — pulling", + (unsigned)env.config_version, (unsigned)g_cfg.config_version); + const bool was_sleeping = g_cfg.deep_sleep_enabled; + const AppConfig before = g_cfg; + if (apiFetchConfig()) { + cameraApplyConfig(); + powerOnConfigChanged(was_sleeping); + if (configNeedsCameraRestart(before, g_cfg)) cameraRestart(); + } + } + + if (env.has_firmware) { + strncpy(g_fw_target.version, env.fw_version, sizeof(g_fw_target.version) - 1); + strncpy(g_fw_target.url, env.fw_url, sizeof(g_fw_target.url) - 1); + strncpy(g_fw_target.sha256, env.fw_sha256, sizeof(g_fw_target.sha256) - 1); + g_fw_target.size = env.fw_size; + + // The endpoint naming a different target is itself the instruction; + // an explicit ota_update command is only needed for staged rollouts. + if (otaIsNewer(g_fw_target) && g_cfg.ota_enabled) { + log_i("ota: endpoint targets %s, we run %s", g_fw_target.version, FW_VERSION); + otaApply(g_fw_target); // reboots on success + } + } +} + +// Recover from a rotated or revoked token without physical access: clear it, +// re-enroll with the stored per-device secret, and carry on. This is why +// enrollment does not wipe its secret — see apiEnroll(). +static bool reenrollAfterRejection() { + log_w("auth: token rejected, re-enrolling"); + g_cfg.device_token[0] = '\0'; + configSave(); + + if (apiEnroll()) { + log_i("auth: recovered, new token in use"); + return true; + } + log_e("auth: re-enrollment failed, will retry at the next check-in"); + return false; +} + +static bool sendHeartbeat() { + // A token cleared by a failed upload earlier in the loop gets replaced + // here rather than waiting for a reboot. + if (!g_cfg.device_token[0]) apiEnroll(); + + ServerEnvelope env = apiHeartbeat(commandOnReceived); + + if (!env.ok && apiTokenRejected() && reenrollAfterRejection()) { + env = apiHeartbeat(commandOnReceived); // one retry with the new token + } + + if (env.ok) { + handleEnvelope(env); + // A heartbeat the endpoint accepted proves WiFi, HTTP, auth and JSON + // all work on this image. That is the bar for confirming a trial boot. + otaMarkValid(); + powerRelease(INHIBIT_BOOT); // no-op after the first time + s_upload_failures = 0; + return true; + } + return false; +} + +// --------------------------------------------------------------------------- +// Upload one event's worth of frames +// --------------------------------------------------------------------------- +static void uploadEvent(const CaptureEvent& ev, FrameCopy* frames, size_t n) { + if (n == 0) return; + + SleepGuard guard(INHIBIT_UPLOAD); + statusLed(true); + + char burst[48]; + makeBurstId(burst, sizeof(burst)); + + // pre_roll is how many of these frames predate the trigger, capped at what + // the ring actually had. + const size_t pre = (g_cfg.pre_roll < n) ? g_cfg.pre_roll : 0; + + statsCountCaptured((uint16_t)n); + + size_t sent = 0; + for (size_t i = 0; i < n; i++) { + CaptureMeta meta = {}; + meta.trigger = ev.trigger; + meta.burst_id = burst; + meta.burst_index = (uint8_t)i; + meta.burst_count = (uint8_t)n; + meta.pre_trigger = (i < pre) ? 1 : 0; + meta.radar_distance_cm = ev.radar.moving_cm ? ev.radar.moving_cm : ev.radar.stationary_cm; + meta.radar_energy = ev.radar.moving_energy ? ev.radar.moving_energy + : ev.radar.stationary_energy; + meta.radar_state = ev.radar.target; + + ServerEnvelope env = apiIngest(frames[i], meta, commandOnReceived); + if (env.ok) { + sent++; + // Only the first response needs acting on; the rest of the burst + // would just repeat the same commands. + if (i == 0) handleEnvelope(env); + } else if (apiTokenRejected()) { + // Recover in place and finish the burst rather than losing the + // whole event to a token that was rotated a second ago. + if (reenrollAfterRejection()) { + ServerEnvelope retry = apiIngest(frames[i], meta, commandOnReceived); + if (retry.ok) { sent++; continue; } + } + log_w("auth: cannot recover mid-burst, abandoning the remaining frames"); + break; + } + } + + for (size_t i = 0; i < n; i++) free(frames[i].data); + + statsCountDelivered((uint16_t)sent); + statsCountFailed((uint16_t)(n - sent)); + + statusLed(false); + log_i("event: %s, %u/%u frames uploaded (%u pre-trigger)", + ev.trigger, (unsigned)sent, (unsigned)n, (unsigned)pre); + + if (sent == 0) s_upload_failures++; + else s_upload_failures = 0; + + // Push conditions after a burst so the WebUI's delivered-today counter + // tracks reality without waiting for the next heartbeat. /status carries + // no command queue, so this costs one small POST and nothing else. + if (g_cfg.status_interval_s) { + apiPostStatus("after_event"); + s_next_status_ms = millis() + g_cfg.status_interval_s * 1000UL; + } +} + +// Pull pre+post roll out of the ring and ship it. In AWAKE mode the ring is +// still being filled by the capture task while we wait, so the post-roll +// frames are real frames from after the trigger, not re-sent history. +static void serviceEvent(const CaptureEvent& ev) { + const size_t pre = g_cfg.pre_roll; + const size_t post = g_cfg.post_roll; + + // Let the capture task collect the post-roll before we take the slice. + const uint32_t settle_ms = post * g_cfg.idle_period_ms; + if (settle_ms) vTaskDelay(pdMS_TO_TICKS(settle_ms)); + + const size_t want = pre + post; + FrameCopy frames[64]; + size_t n = ringTakeNewest(want, frames, sizeof(frames) / sizeof(frames[0])); + if (n == 0) { + log_w("event: ring was empty, nothing to upload"); + return; + } + uploadEvent(ev, frames, n); +} + +// --------------------------------------------------------------------------- +// AWAKE MODE — capture task +// --------------------------------------------------------------------------- +static void captureTask(void*) { + log_i("capture task running on core %d", xPortGetCoreID()); + + for (;;) { + // Streaming takes over the camera entirely; the ring pauses for the + // session. You are watching live, so history is not the point. + if (streamActive()) { + streamTick(); + radarPoll(); + vTaskDelay(pdMS_TO_TICKS(5)); + continue; + } + + radarPoll(); + RadarReading r = radarLast(); + + nightTick(); + + // NIGHT_IDLE / NIGHT_SLEEP: stop feeding the ring after dark. A manual + // capture_now still works — an operator asking for a frame should get + // one, dark or not. + if (!nightCaptureAllowed() && !s_manual_req) { + vTaskDelay(pdMS_TO_TICKS(1000)); + continue; + } + + camera_fb_t* fb = cameraGrab(); + if (fb) { + ringPush(fb->buf, fb->len, netEpochMs()); + esp_camera_fb_return(fb); + } + + const bool manual = s_manual_req; + const bool trigger = manual || radarIsTrigger(r); + const bool cooled = (millis() - s_last_trigger_ms) > (g_cfg.cooldown_s * 1000UL); + + if (trigger && (cooled || manual)) { + s_last_trigger_ms = millis(); + s_manual_req = false; + + // NIGHTLIGHT_ON_BURST: light up and let exposure settle before the + // post-roll frames are grabbed. Costs ~120 ms of trigger latency, + // which is why NIGHTLIGHT_ALWAYS is the better option if you are + // willing to run the light all night. + nightIlluminateBurstBegin(); + + CaptureEvent ev = {millis(), manual ? "manual" : "radar", r}; + statsCountEvent(); + if (xQueueSend(s_events, &ev, 0) != pdTRUE) { + log_w("event queue full, dropping trigger"); + } else { + log_i("TRIGGER (%s) dist=%ucm energy=%u state=%u ring=%u", + ev.trigger, r.moving_cm, r.moving_energy, r.target, + (unsigned)ringCount()); + } + // Keep the light on until the post-roll frames have been grabbed; + // serviceEvent() takes its slice of the ring at about that point. + s_burst_light_until_ms = + millis() + g_cfg.post_roll * g_cfg.idle_period_ms + 300; + + powerNoteActivity(); + } + + if (s_burst_light_until_ms && + (int32_t)(s_burst_light_until_ms - millis()) <= 0) { + s_burst_light_until_ms = 0; + nightIlluminateBurstEnd(); + } + + vTaskDelay(pdMS_TO_TICKS(g_cfg.idle_period_ms)); + } +} + +// --------------------------------------------------------------------------- +// SLEEP MODE — one linear pass, then sleep +// --------------------------------------------------------------------------- +static void runSleepCycle() { + log_i("=== sleep-mode wake (%s) ===", powerWakeCauseName()); + + const bool radar_wake = (powerWakeCause() == WAKE_RADAR); + + if (radar_wake && !nightCaptureAllowed()) { + log_i("woken by radar during the night window, not capturing"); + sendHeartbeat(); + commandRunDeferred(); + if (g_cfg.night_behaviour == NIGHT_SLEEP && !powerIsInhibited()) { + apiPostStatus("before_night_sleep"); + powerSleepUntilMorning(); + } + return; + } + + if (radar_wake) { + // No ring in this mode: the camera was off. This is SPEC C4's + // 1-3 second latency, unavoidable without continuous capture. + if (!cameraBegin()) { + log_e("camera init failed, sleeping"); + powerSleepNow(); + return; + } + nightBegin(); // selects the day/night tuning profile for this wake + + // A shallow ring just to reuse the same upload path. Depth = the burst + // size; frames are grabbed back to back rather than at idle_period_ms. + const uint8_t burst = g_cfg.post_roll ? g_cfg.post_roll : 5; + ringBegin(burst); + + radarPoll(); + RadarReading r = radarLast(); + statsCountEvent(); + + nightIlluminateBurstBegin(); + for (uint8_t i = 0; i < burst; i++) { + camera_fb_t* fb = cameraGrab(); + if (fb) { + ringPush(fb->buf, fb->len, netEpochMs()); + esp_camera_fb_return(fb); + } + if (g_cfg.post_roll_gap_ms) delay(g_cfg.post_roll_gap_ms); + } + nightIlluminateBurstEnd(); + + FrameCopy frames[64]; + size_t n = ringTakeNewest(burst, frames, sizeof(frames) / sizeof(frames[0])); + if (n) { + CaptureEvent ev = {millis(), "radar", r}; + // Nothing here predates the trigger, so pre_roll must not claim + // otherwise in the metadata. + const uint8_t saved_pre = g_cfg.pre_roll; + g_cfg.pre_roll = 0; + uploadEvent(ev, frames, n); + g_cfg.pre_roll = saved_pre; + } + } + + // Always check in, whatever woke us: this is how commands, config and + // firmware targets reach a sleeping device (SPEC C1). + sendHeartbeat(); + commandRunDeferred(); + + // A stream_start or wake_and_hold command may have just arrived. Stay up + // and let loop() handle it; powerMaybeSleep() will put us back down. + if (powerIsInhibited() || streamActive() || commandHasPending()) { + log_i("sleep deferred: %s", powerInhibitSummary()); + return; + } + + // The endpoint may have switched sleep off in the heartbeat we just did. + if (!g_cfg.deep_sleep_enabled) { + log_i("deep sleep switched off by the endpoint, continuing in awake mode"); + return; + } + + if (g_cfg.night_behaviour == NIGHT_SLEEP && nightIsNight()) { + apiPostStatus("before_night_sleep"); + powerSleepUntilMorning(); + } + + apiPostStatus("before_sleep"); + powerSleepNow(); +} + +// --------------------------------------------------------------------------- +static void startAwakeMode() { + if (s_capture_task) return; + + if (!cameraBegin()) { + log_e("camera init failed — retrying in 5 s"); + delay(5000); + ESP.restart(); + } + + if (!ringBegin(g_cfg.ring_frames)) { + log_w("ring buffer unavailable, running without pre-trigger history"); + } + + nightBegin(); // after cameraBegin(): LEDC channel 0 is the camera's XCLK + + s_events = xQueueCreate(4, sizeof(CaptureEvent)); + xTaskCreatePinnedToCore(captureTask, "capture", 6144, nullptr, 5, &s_capture_task, 1); + log_i("awake mode: pre-trigger ring active (%u frames, ~%.1f s of history)", + (unsigned)ringCount(), g_cfg.ring_frames * g_cfg.idle_period_ms / 1000.0f); +} + +void setup() { + Serial.begin(115200); + delay(300); // let USB CDC enumerate so the boot banner is not lost + + pinMode(PIN_STATUS_LED, OUTPUT); + statusLed(true); + + log_i(""); + log_i("poorBird %s (%s)", FW_VERSION, HW_REVISION); + + powerBegin(); // first: reads the wake cause before anything resets it + configLoad(); + otaBegin(); + statsBegin(); + configDump(); + + batteryBegin(); + otaSetBatteryCheck(batteryAboveOtaThreshold, g_cfg.battery_min_pct_ota); + + radarBegin(); + if (powerWakeCause() == WAKE_POWER_ON) { + // Only on a cold boot: it is noisy and pointless on every timer wake. + radarSelfTest(2000); + } + + netBegin(); + apiBegin(); + + if (!netConnect()) { + log_e("no network on boot"); + if (g_cfg.deep_sleep_enabled) powerSleepNow(); + else { delay(10000); ESP.restart(); } + } + + if (!apiEnroll()) { + log_e("not enrolled — cannot talk to the endpoint"); + if (g_cfg.deep_sleep_enabled) powerSleepNow(); + else { delay(30000); ESP.restart(); } + } + + netSyncTime(); + + statusLed(false); + + if (g_cfg.deep_sleep_enabled) { + runSleepCycle(); + // Only reached if sleep was deferred or switched off. + } + + if (!g_cfg.deep_sleep_enabled) startAwakeMode(); + + s_next_heartbeat_ms = millis(); + s_next_status_ms = millis() + 5000; + s_next_battery_ms = millis(); +} + +void loop() { + // In sleep mode with a deferred sleep, the capture task does not exist and + // loop() is just servicing whatever held us awake. + if (s_events) { + CaptureEvent ev; + while (xQueueReceive(s_events, &ev, 0) == pdTRUE) { + if (streamActive()) { + log_i("event dropped: a stream is running"); + continue; + } + serviceEvent(ev); + } + } + + commandRunDeferred(); + + if ((int32_t)(s_next_heartbeat_ms - millis()) <= 0) { + if (!netIsConnected()) netConnect(); + if (netIsConnected()) sendHeartbeat(); + + // Back off when the endpoint is unreachable so a Pi that is down for + // an hour does not mean an hour of failed requests every 5 minutes. + uint32_t interval = g_cfg.heartbeat_interval_s; + if (s_upload_failures > 3) { + uint8_t shift = s_upload_failures - 3; + if (shift > 4) shift = 4; + interval <<= shift; + if (interval > 3600) interval = 3600; + log_w("endpoint unreachable, next check-in in %us", (unsigned)interval); + } + s_next_heartbeat_ms = millis() + interval * 1000UL; + } + + // Battery is read on its own slower timer: the ADC read powers the divider + // and averages 16 samples, so there is no point doing it per loop tick. + if ((int32_t)(s_next_battery_ms - millis()) <= 0) { + batteryPoll(); + s_next_battery_ms = millis() + 60000; + } + + // Conditions push. Distinct from the heartbeat because it carries no + // command queue — see apiPostStatus(). + if (g_cfg.status_interval_s && (int32_t)(s_next_status_ms - millis()) <= 0) { + if (netIsConnected()) apiPostStatus("periodic"); + s_next_status_ms = millis() + g_cfg.status_interval_s * 1000UL; + } + + statsRollover(); + + // Night policy. NIGHT_SLEEP overrides the deep-sleep switch: a camera with + // no illuminator has nothing to do at 03:00 whether it is on mains or not. + if (g_cfg.night_behaviour == NIGHT_SLEEP && nightIsNight() && !streamActive()) { + if (netIsConnected()) apiPostStatus("before_night_sleep"); + powerSleepUntilMorning(); // does not return if it sleeps + } + + if (g_cfg.deep_sleep_enabled) { + // Turning sleep on at runtime: tear the awake-mode machinery down + // cleanly, then let powerMaybeSleep() take us under. + if (s_capture_task) { + log_i("deep sleep switched on, stopping capture task"); + vTaskDelete(s_capture_task); + s_capture_task = nullptr; + ringEnd(); + } + // Tell the endpoint where we stand before the radio goes off. /status + // carries no command queue, which is exactly right here: picking up a + // command we are about to become unable to execute would just make it + // look delivered. + if (powerWouldSleepNow() && netIsConnected()) apiPostStatus("before_sleep"); + + powerMaybeSleep(); // does not return if it sleeps + } else if (!s_capture_task) { + // Sleep was switched off while we were running a sleep cycle. + startAwakeMode(); + } + + delay(20); +} diff --git a/firmware/src/net_mgr.cpp b/firmware/src/net_mgr.cpp new file mode 100644 index 0000000..da89d08 --- /dev/null +++ b/firmware/src/net_mgr.cpp @@ -0,0 +1,137 @@ +#include "net_mgr.h" + +#include +#include +#include +#include + +#include "app_config.h" + +static bool s_time_valid = false; + +// Anything before this is obviously not a real clock reading. +static const int64_t kSaneEpochMs = 1735689600000LL; // 2025-01-01 + +bool netBegin() { + WiFi.persistent(false); + WiFi.mode(WIFI_STA); + WiFi.setSleep(true); // DTIM-based modem sleep; harmless on mains + WiFi.setAutoReconnect(true); + WiFi.setHostname(g_cfg.device_name); + + setenv("TZ", g_cfg.tz, 1); // SPEC C7: set TZ explicitly, everywhere + tzset(); + return true; +} + +bool netConnect(uint8_t max_attempts) { + if (WiFi.status() == WL_CONNECTED) return true; + + if (!g_cfg.wifi_ssid[0]) { + log_e("no WiFi SSID configured — set CFG_WIFI_SSID in secrets.ini"); + return false; + } + + for (uint8_t attempt = 1; attempt <= max_attempts; attempt++) { + log_i("wifi: connecting to '%s' (attempt %u/%u)", + g_cfg.wifi_ssid, attempt, max_attempts); + + WiFi.begin(g_cfg.wifi_ssid, g_cfg.wifi_pass); + + const uint32_t deadline = millis() + 10000; + while (WiFi.status() != WL_CONNECTED && (int32_t)(deadline - millis()) > 0) { + delay(100); + } + + if (WiFi.status() == WL_CONNECTED) { + log_i("wifi: %s rssi %d dBm", WiFi.localIP().toString().c_str(), WiFi.RSSI()); + if (WiFi.RSSI() < -75) { + // Worth surfacing: weak signal lengthens every transmit, which + // on battery is a direct runtime cost (SPEC C5). + log_w("wifi: RSSI %d dBm is marginal at this mounting point", WiFi.RSSI()); + } + return true; + } + + WiFi.disconnect(true, false); + // Exponential backoff, bounded. Never a tight retry loop (SPEC §4.3). + if (attempt < max_attempts) delay(1000UL << attempt); + } + + log_w("wifi: giving up after %u attempts", max_attempts); + return false; +} + +bool netIsConnected() { return WiFi.status() == WL_CONNECTED; } + +void netDisconnect() { + WiFi.disconnect(true, false); + WiFi.mode(WIFI_OFF); +} + +bool netSyncTime(uint32_t timeout_ms) { + const char* host = g_cfg.ntp_host[0] ? g_cfg.ntp_host : g_cfg.api_host; + log_i("time: SNTP against %s", host); + + esp_sntp_stop(); + esp_sntp_setoperatingmode(SNTP_OPMODE_POLL); + esp_sntp_setservername(0, host); + esp_sntp_init(); + + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(deadline - millis()) > 0) { + if (esp_sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED || netEpochMs() > kSaneEpochMs) { + s_time_valid = true; + char iso[32]; + netIsoTime(iso, sizeof(iso)); + log_i("time: synced, %s", iso); + return true; + } + delay(100); + } + + // Not fatal. The next ingest/heartbeat response will carry server_time and + // netAdoptServerTime() picks it up from there. + log_w("time: SNTP did not complete, falling back to the API response clock"); + return false; +} + +void netAdoptServerTime(int64_t server_ms) { + if (server_ms < kSaneEpochMs) return; + + const int64_t now = netEpochMs(); + const int64_t drift = (now > server_ms) ? (now - server_ms) : (server_ms - now); + + if (s_time_valid && drift < 2000) return; // within tolerance, leave it + + struct timeval tv = { + .tv_sec = (time_t)(server_ms / 1000), + .tv_usec = (suseconds_t)((server_ms % 1000) * 1000), + }; + settimeofday(&tv, nullptr); + s_time_valid = true; + + char iso[32]; + netIsoTime(iso, sizeof(iso)); + log_i("time: adopted endpoint clock (%s, drift was %lld ms)", iso, (long long)drift); +} + +int64_t netEpochMs() { + struct timeval tv; + if (gettimeofday(&tv, nullptr) != 0) return 0; + int64_t ms = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; + return (ms > kSaneEpochMs) ? ms : 0; +} + +bool netTimeValid() { return s_time_valid && netEpochMs() > 0; } + +void netIsoTime(char* out, size_t cap) { + if (!cap) return; + out[0] = '\0'; + int64_t ms = netEpochMs(); + if (ms == 0) return; + time_t t = (time_t)(ms / 1000); + struct tm gm; + gmtime_r(&t, &gm); + strftime(out, cap, "%Y-%m-%dT%H:%M:%SZ", &gm); +} diff --git a/firmware/src/nightlight.cpp b/firmware/src/nightlight.cpp new file mode 100644 index 0000000..f481191 --- /dev/null +++ b/firmware/src/nightlight.cpp @@ -0,0 +1,129 @@ +#include "nightlight.h" + +#include + +#include "app_config.h" +#include "board_pins.h" +#include "camera_mgr.h" +#include "net_mgr.h" + +static bool s_led_on = false; +static bool s_was_night = false; +static bool s_pwm_ready = false; + +static const uint32_t kPwmFreq = 5000; +static const uint8_t kPwmBits = 8; + +static void ledSet(bool on, uint8_t duty) { +#if PIN_NIGHTLIGHT >= 0 + if (!s_pwm_ready) return; + ledcWrite(PIN_NIGHTLIGHT, on ? duty : 0); + s_led_on = on; +#else + (void)on; (void)duty; +#endif +} + +void nightBegin() { +#if PIN_NIGHTLIGHT >= 0 + // ledcAttach picks a free LEDC channel. The camera driver has already + // taken channel 0 / timer 0 for XCLK by this point, so call nightBegin() + // after cameraBegin() and let the allocator route around it. + s_pwm_ready = ledcAttach(PIN_NIGHTLIGHT, kPwmFreq, kPwmBits); + if (!s_pwm_ready) { + log_e("nightlight: LEDC attach failed on GPIO%d (channel exhausted?)", PIN_NIGHTLIGHT); + } else { + ledcWrite(PIN_NIGHTLIGHT, 0); + log_i("nightlight: PWM on GPIO%d", PIN_NIGHTLIGHT); + } +#else + log_i("nightlight: no LED pin configured"); +#endif + s_was_night = nightIsNight(); + cameraApplyTuning(s_was_night); +} + +bool nightIsNight() { + if (!netTimeValid()) return false; + + const int64_t ms = netEpochMs(); + if (ms == 0) return false; + + time_t t = (time_t)(ms / 1000); + struct tm lt; + localtime_r(&t, <); + const uint16_t now_min = lt.tm_hour * 60 + lt.tm_min; + + const uint16_t start = g_cfg.night_start_min; + const uint16_t end = g_cfg.night_end_min; + if (start == end) return false; // window disabled + + // The normal case wraps midnight (21:00 -> 06:00); the non-wrapping case + // is only reachable from a deliberately odd config, but costs one branch. + return (start > end) ? (now_min >= start || now_min < end) + : (now_min >= start && now_min < end); +} + +uint32_t nightSecondsUntilMorning() { + if (!nightIsNight()) return 0; + + const int64_t ms = netEpochMs(); + time_t t = (time_t)(ms / 1000); + struct tm lt; + localtime_r(&t, <); + const int32_t now_s = lt.tm_hour * 3600 + lt.tm_min * 60 + lt.tm_sec; + const int32_t end_s = (int32_t)g_cfg.night_end_min * 60; + + int32_t delta = end_s - now_s; + if (delta <= 0) delta += 86400; // morning is tomorrow + + // Wake a minute early: the first frames after a long sleep are throwaway + // while auto-exposure settles, and being late for dawn is worse than + // being early for it. + if (delta > 60) delta -= 60; + return (uint32_t)delta; +} + +bool nightCaptureAllowed() { + if (!nightIsNight()) return true; + return g_cfg.night_behaviour == NIGHT_CAPTURE; +} + +bool nightlightIsOn() { return s_led_on; } + +void nightTick() { + const bool is_night = nightIsNight(); + + if (is_night != s_was_night) { + log_i("night: %s", is_night ? "dusk — switching to the night profile" + : "dawn — back to the day profile"); + s_was_night = is_night; + cameraApplyTuning(is_night); + } + + // NIGHTLIGHT_ALWAYS keeps the illuminator on for the whole night. Steady + // light is easier on wildlife than a burst per trigger, and it also means + // auto-exposure is already settled when a bird arrives. + const bool want_on = is_night && + g_cfg.nightlight_mode == NIGHTLIGHT_ALWAYS && + g_cfg.night_behaviour == NIGHT_CAPTURE; + + if (want_on != s_led_on) ledSet(want_on, g_cfg.nightlight_brightness); +} + +void nightIlluminateBurstBegin() { + if (!nightIsNight()) return; + if (g_cfg.nightlight_mode != NIGHTLIGHT_ON_BURST) return; + if (g_cfg.night_behaviour != NIGHT_CAPTURE) return; + + ledSet(true, g_cfg.nightlight_brightness); + // Auto-exposure needs a moment to react to the light appearing. Without + // this the first frames of the burst are the blown-out ones. + delay(120); + cameraDiscardFrames(2); +} + +void nightIlluminateBurstEnd() { + if (g_cfg.nightlight_mode != NIGHTLIGHT_ON_BURST) return; + ledSet(false, 0); +} diff --git a/firmware/src/ota_mgr.cpp b/firmware/src/ota_mgr.cpp new file mode 100644 index 0000000..d95d699 --- /dev/null +++ b/firmware/src/ota_mgr.cpp @@ -0,0 +1,191 @@ +#include "ota_mgr.h" + +#include +#include +#include +#include +#include // strcasecmp + +#include "app_config.h" +#include "power_mgr.h" + +static bool s_pending_verify = false; +static OtaBatteryOkFn s_battery_fn = nullptr; +static uint8_t s_battery_min = 50; + +void otaBegin() { + const esp_partition_t* running = esp_ota_get_running_partition(); + esp_ota_img_states_t state; + + if (esp_ota_get_state_partition(running, &state) == ESP_OK) { + s_pending_verify = (state == ESP_OTA_IMG_PENDING_VERIFY); + } + + log_i("ota: running %s from %s%s", FW_VERSION, running->label, + s_pending_verify ? " [TRIAL BOOT - unconfirmed]" : ""); +} + +bool otaPendingVerify() { return s_pending_verify; } + +void otaMarkValid() { + if (!s_pending_verify) return; + if (esp_ota_mark_app_valid_cancel_rollback() == ESP_OK) { + s_pending_verify = false; + log_i("ota: trial image confirmed good, rollback cancelled"); + } else { + log_e("ota: failed to confirm trial image"); + } +} + +void otaRollback(const char* reason) { + log_e("ota: rolling back — %s", reason); + delay(200); + esp_ota_mark_app_invalid_rollback_and_reboot(); +} + +bool otaIsNewer(const OtaTarget& t) { + // Deliberately a string inequality, not a semver comparison: the endpoint + // decides which version a device should run (SPEC §3 `firmware.is_target`), + // so "different from target" is the correct trigger. That also makes + // deliberate downgrades work, which semver ordering would block. + return t.version[0] && strcmp(t.version, FW_VERSION) != 0; +} + +void otaSetBatteryCheck(OtaBatteryOkFn fn, uint8_t min_pct) { + s_battery_fn = fn; + s_battery_min = min_pct; +} + +static bool hexEq(const uint8_t* digest, const char* expect_hex) { + char hex[65]; + for (int i = 0; i < 32; i++) snprintf(hex + i * 2, 3, "%02x", digest[i]); + hex[64] = '\0'; + return strcasecmp(hex, expect_hex) == 0; +} + +bool otaApply(const OtaTarget& t) { + if (!g_cfg.ota_enabled) { + log_w("ota: disabled in config, ignoring target %s", t.version); + return false; + } + + // SPEC C6: a brownout mid-write bricks the device. + if (s_battery_fn && !s_battery_fn(s_battery_min)) { + log_w("ota: refused, battery below %u%%", s_battery_min); + return false; + } + + if (strlen(t.sha256) != 64) { + log_e("ota: refused, target has no usable SHA-256"); + return false; + } + + // Never sleep while flashing. + SleepGuard guard(INHIBIT_OTA); + + String url = (strncmp(t.url, "http", 4) == 0) ? String(t.url) : (apiBaseUrl() + t.url); + log_i("ota: %s -> %s (%u bytes) from %s", FW_VERSION, t.version, (unsigned)t.size, url.c_str()); + + esp_http_client_config_t cfg = {}; + cfg.url = url.c_str(); + cfg.method = HTTP_METHOD_GET; + cfg.timeout_ms = 30000; + + esp_http_client_handle_t c = esp_http_client_init(&cfg); + char bearer[80]; + snprintf(bearer, sizeof(bearer), "Bearer %s", g_cfg.device_token); + esp_http_client_set_header(c, "Authorization", bearer); + + bool ok = false; + esp_ota_handle_t ota = 0; + const esp_partition_t* target_part = nullptr; + mbedtls_sha256_context sha; + mbedtls_sha256_init(&sha); + + do { + if (esp_http_client_open(c, 0) != ESP_OK) { log_e("ota: connect failed"); break; } + + int content_len = esp_http_client_fetch_headers(c); + int status = esp_http_client_get_status_code(c); + if (status != 200) { log_e("ota: HTTP %d", status); break; } + if (content_len <= 0) { + // Chunked responses are legal but we want the length to sanity + // check against the manifest before erasing a partition. + log_e("ota: server did not send Content-Length"); + break; + } + if (t.size && (uint32_t)content_len != t.size) { + log_e("ota: size mismatch, manifest %u vs body %d", (unsigned)t.size, content_len); + break; + } + + target_part = esp_ota_get_next_update_partition(nullptr); + if (!target_part) { log_e("ota: no free OTA slot"); break; } + if ((uint32_t)content_len > target_part->size) { + log_e("ota: image %d does not fit in %s (%u)", content_len, + target_part->label, (unsigned)target_part->size); + break; + } + + log_i("ota: erasing %s", target_part->label); + if (esp_ota_begin(target_part, content_len, &ota) != ESP_OK) { + log_e("ota: esp_ota_begin failed"); + ota = 0; + break; + } + + mbedtls_sha256_starts(&sha, 0); + + static uint8_t buf[4096]; + int written = 0, last_pct = -10; + bool io_error = false; + + while (written < content_len) { + int n = esp_http_client_read(c, (char*)buf, sizeof(buf)); + if (n <= 0) { log_e("ota: download truncated at %d/%d", written, content_len); io_error = true; break; } + + if (esp_ota_write(ota, buf, n) != ESP_OK) { log_e("ota: flash write failed"); io_error = true; break; } + mbedtls_sha256_update(&sha, buf, n); + written += n; + + int pct = (int)((int64_t)written * 100 / content_len); + if (pct >= last_pct + 10) { log_i("ota: %d%%", pct); last_pct = pct; } + } + if (io_error) break; + + uint8_t digest[32]; + mbedtls_sha256_finish(&sha, digest); + if (!hexEq(digest, t.sha256)) { + log_e("ota: SHA-256 mismatch, discarding image"); + break; + } + log_i("ota: SHA-256 verified"); + + if (esp_ota_end(ota) != ESP_OK) { log_e("ota: esp_ota_end failed"); ota = 0; break; } + ota = 0; + + if (esp_ota_set_boot_partition(target_part) != ESP_OK) { + log_e("ota: set_boot_partition failed"); + break; + } + ok = true; + } while (false); + + if (ota) esp_ota_abort(ota); + mbedtls_sha256_free(&sha); + esp_http_client_close(c); + esp_http_client_cleanup(c); + + if (ok) { + // The new image boots in PENDING_VERIFY. If it cannot reach the + // endpoint it never calls otaMarkValid(), and the next reset returns + // to this slot automatically. + log_i("ota: activated %s, restarting into trial boot", target_part->label); + delay(300); + esp_restart(); + } + return ok; +} + +const char* otaRunningVersion() { return FW_VERSION; } +const char* otaRunningPartition() { return esp_ota_get_running_partition()->label; } diff --git a/firmware/src/power_mgr.cpp b/firmware/src/power_mgr.cpp new file mode 100644 index 0000000..5c7a331 --- /dev/null +++ b/firmware/src/power_mgr.cpp @@ -0,0 +1,247 @@ +#include "power_mgr.h" + +#include +#include + +#include "app_config.h" +#include "board_pins.h" +#include "camera_mgr.h" +#include "nightlight.h" +#include "stream_session.h" + +// RTC slow memory survives deep sleep but not a power cycle — exactly the +// semantics SPEC C7 assumes for the boot counter. +RTC_DATA_ATTR static uint32_t s_boot_count = 0; +RTC_DATA_ATTR static uint32_t s_sleep_epoch = 0; // seconds slept, cumulative +RTC_DATA_ATTR static uint32_t s_last_sleep_s = 0; // duration of the last sleep + +static WakeCause s_cause = WAKE_POWER_ON; +static uint8_t s_inhibit[INHIBIT_COUNT] = {0}; +static uint32_t s_last_activity_ms = 0; +static uint32_t s_awake_since_ms = 0; +static uint32_t s_hold_until_ms = 0; + +static const char* kInhibitNames[INHIBIT_COUNT] = { + "boot", "upload", "stream", "ota", "hold" +}; + +void powerBegin() { + s_boot_count++; + s_awake_since_ms = millis(); + s_last_activity_ms = millis(); + + switch (esp_sleep_get_wakeup_cause()) { + case ESP_SLEEP_WAKEUP_EXT1: s_cause = WAKE_RADAR; break; + case ESP_SLEEP_WAKEUP_TIMER: s_cause = WAKE_TIMER; break; + case ESP_SLEEP_WAKEUP_UNDEFINED: s_cause = WAKE_POWER_ON; break; + default: s_cause = WAKE_OTHER; break; + } + + // Hold the device awake until the first successful check-in. Without this + // a device configured with a bad endpoint would sleep before it could ever + // be told otherwise, and the only fix would be USB. + memset(s_inhibit, 0, sizeof(s_inhibit)); + powerInhibit(INHIBIT_BOOT); + + log_i("power: boot #%u, wake cause %s, %us slept so far", + (unsigned)s_boot_count, powerWakeCauseName(), (unsigned)s_sleep_epoch); +} + +WakeCause powerWakeCause() { return s_cause; } +uint32_t powerBootCount() { return s_boot_count; } +uint32_t powerLastSleepSeconds() { return s_last_sleep_s; } +uint32_t powerTotalSleepSeconds() { return s_sleep_epoch; } + +const char* powerWakeCauseName() { + switch (s_cause) { + case WAKE_RADAR: return "radar"; + case WAKE_TIMER: return "timer"; + case WAKE_POWER_ON: return "power-on"; + default: return "other"; + } +} + +void powerInhibit(SleepInhibit r) { + if (r < INHIBIT_COUNT && s_inhibit[r] < 255) s_inhibit[r]++; +} + +void powerRelease(SleepInhibit r) { + if (r < INHIBIT_COUNT && s_inhibit[r] > 0) s_inhibit[r]--; +} + +bool powerIsInhibited() { + for (uint8_t i = 0; i < INHIBIT_COUNT; i++) { + if (s_inhibit[i]) return true; + } + return (int32_t)(s_hold_until_ms - millis()) > 0; +} + +const char* powerInhibitSummary() { + static char buf[64]; + buf[0] = '\0'; + for (uint8_t i = 0; i < INHIBIT_COUNT; i++) { + if (!s_inhibit[i]) continue; + if (buf[0]) strncat(buf, ",", sizeof(buf) - strlen(buf) - 1); + strncat(buf, kInhibitNames[i], sizeof(buf) - strlen(buf) - 1); + } + if (!buf[0]) strncpy(buf, "none", sizeof(buf)); + return buf; +} + +void powerNoteActivity() { s_last_activity_ms = millis(); } + +void powerHoldAwake(uint32_t seconds) { + uint32_t until = millis() + seconds * 1000UL; + if ((int32_t)(until - s_hold_until_ms) > 0) s_hold_until_ms = until; + powerNoteActivity(); + log_i("power: holding awake for %us", (unsigned)seconds); +} + +bool powerSleepModeActive() { return g_cfg.deep_sleep_enabled; } + +const char* powerSleepBlockedReason() { + if (!g_cfg.deep_sleep_enabled) return "deep sleep switched off"; + if (g_cfg.stream_enabled && g_cfg.stream_blocks_sleep) + return "streaming enabled (stream_blocks_sleep)"; + if (powerIsInhibited()) return powerInhibitSummary(); + return ""; +} + +bool powerSleepAllowed() { return powerSleepBlockedReason()[0] == '\0'; } + +// Configure wake sources and go. Does not return. +// `wake_on_radar` is separate from the config flag so the night sleep can +// force it off without mutating config. +static void enterDeepSleep(uint32_t seconds, bool wake_on_radar) { + if (seconds == 0) seconds = g_cfg.deep_sleep_s; + + log_i("power: sleeping %us (wake: timer%s)", (unsigned)seconds, + wake_on_radar ? " + radar" : ""); + + // Flush the camera and radio explicitly. Letting deep sleep cut power out + // from under an initialised camera has been a reliable source of failures + // to re-init on the next boot. + cameraEnd(); + WiFi.disconnect(true, /*eraseap=*/false); + WiFi.mode(WIFI_OFF); + delay(20); + + esp_sleep_enable_timer_wakeup((uint64_t)seconds * 1000000ULL); + + if (wake_on_radar) { + // ESP32-S3 has no EXT0; EXT1 with ANY_HIGH is the supported way to + // wake on an active-high presence pin. PIN_RADAR_OUT must be an RTC + // GPIO (0-21 on the S3) — GPIO3 is. + esp_sleep_enable_ext1_wakeup(1ULL << PIN_RADAR_OUT, ESP_EXT1_WAKEUP_ANY_HIGH); + + // If the radar is *already* asserting when we try to sleep we would + // wake instantly and spin. Wait briefly for it to clear; if it does + // not, drop to a timer-only sleep for this cycle. + uint32_t wait_until = millis() + 3000; + while (digitalRead(PIN_RADAR_OUT) == HIGH && (int32_t)(wait_until - millis()) > 0) { + delay(50); + } + if (digitalRead(PIN_RADAR_OUT) == HIGH) { + log_w("power: radar still asserted, sleeping on timer only this cycle"); + esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_EXT1); + } + } + + s_sleep_epoch += seconds; + s_last_sleep_s = seconds; + Serial.flush(); + esp_deep_sleep_start(); + // unreachable +} + +void powerSleepUntilMorning() { + const uint32_t secs = nightSecondsUntilMorning(); + if (secs == 0) return; // not night, or clock unsynced + + // Night sleep overrides the deep_sleep_enabled switch, but never an OTA. + if (s_inhibit[INHIBIT_OTA]) { + log_w("power: night sleep deferred, OTA in progress"); + return; + } + if (streamActive()) { + log_i("power: night sleep deferred, a stream is running"); + return; + } + + log_i("power: night — sleeping %u min until morning", (unsigned)(secs / 60)); + enterDeepSleep(secs, /*wake_on_radar=*/false); +} + +bool powerWouldSleepNow() { + if (!powerSleepAllowed()) return false; + return (millis() - s_last_activity_ms) >= g_cfg.sleep_idle_timeout_s * 1000UL; +} + +bool powerMaybeSleep() { + if (!g_cfg.deep_sleep_enabled) return false; + + const uint32_t now = millis(); + const uint32_t idle_ms = now - s_last_activity_ms; + const uint32_t awake_ms = now - s_awake_since_ms; + + // The hard cap is a deadlock escape, not a normal path: if something holds + // an inhibit forever (a stream whose socket never closes, an OTA that + // stalled) the device would otherwise stay awake until the battery is flat. + // OTA is the one inhibit we never override — sleeping mid-flash bricks it. + if (awake_ms > g_cfg.sleep_max_awake_s * 1000UL) { + if (s_inhibit[INHIBIT_OTA]) { + log_w("power: past max_awake but OTA in progress, staying up"); + return false; + } + log_w("power: max_awake %us exceeded (inhibits: %s), sleeping anyway", + g_cfg.sleep_max_awake_s, powerInhibitSummary()); + enterDeepSleep(0, g_cfg.sleep_wake_on_radar); + } + + // Streaming enabled means "keep me reachable", not just "a session is + // running" — a sleeping device cannot be told to start one (SPEC C1). + if (!powerSleepAllowed()) return false; + if (idle_ms < g_cfg.sleep_idle_timeout_s * 1000UL) return false; + + enterDeepSleep(0, g_cfg.sleep_wake_on_radar); + return true; // unreachable +} + +void powerSleepNow(uint32_t seconds) { + // Deliberately laxer than powerSleepAllowed(): an explicit sleep request + // overrides "streaming is enabled" and the boot hold, because something + // asked for it on purpose. It does NOT override an OTA (bricks the device) + // or a live stream (cutting a viewer off mid-frame is never what was meant + // — send stream_stop first). + if (!g_cfg.deep_sleep_enabled) { + log_w("power: sleep_now ignored, deep sleep is switched off"); + return; + } + if (s_inhibit[INHIBIT_OTA]) { + log_w("power: sleep_now refused, OTA in progress"); + return; + } + if (streamActive()) { + log_w("power: sleep_now refused, a stream is running"); + return; + } + enterDeepSleep(seconds, g_cfg.sleep_wake_on_radar); +} + +void powerOnConfigChanged(bool was_enabled) { + if (was_enabled == g_cfg.deep_sleep_enabled) return; + + if (g_cfg.deep_sleep_enabled) { + // Do not slam the door on the way out: finish this wake so the ack for + // the config command reaches the Pi, and so an operator who flipped the + // switch by mistake still has sleep_idle_timeout_s to flip it back. + log_i("power: deep sleep switched ON, will sleep after %us idle", + g_cfg.sleep_idle_timeout_s); + powerNoteActivity(); + } else { + log_i("power: deep sleep switched OFF, staying awake"); + s_hold_until_ms = 0; + // The ring and camera are brought back up by the caller in main.cpp, + // which owns their lifecycle. + } +} diff --git a/firmware/src/stream_session.cpp b/firmware/src/stream_session.cpp new file mode 100644 index 0000000..dd7698c --- /dev/null +++ b/firmware/src/stream_session.cpp @@ -0,0 +1,118 @@ +#include "stream_session.h" + +#include "api_client.h" +#include "app_config.h" +#include "camera_mgr.h" +#include "net_mgr.h" +#include "power_mgr.h" + +static bool s_active = false; +static char s_id[40] = {0}; +static uint32_t s_end_ms = 0; +static uint32_t s_next_ms = 0; +static uint32_t s_period_ms = 100; +static uint32_t s_frames = 0; +static uint8_t s_prev_size = 0; +static uint8_t s_fail_streak = 0; + +bool streamActive() { return s_active; } + +bool streamStart(const char* session_id, uint8_t mode_override, + uint8_t framesize_override, uint16_t duration_override) { + if (s_active) { + log_w("stream: already running as %s", s_id); + return false; + } + if (!g_cfg.stream_enabled) { + log_w("stream: refused, streaming is disabled in config"); + return false; + } + if (!netIsConnected() || !cameraReady()) { + log_w("stream: refused, network or camera not ready"); + return false; + } + + const uint8_t mode = (mode_override == 0xFF) ? g_cfg.stream_mode : mode_override; + const uint8_t fsize = framesize_override ? framesize_override : g_cfg.stream_frame_size; + uint16_t duration = duration_override ? duration_override : g_cfg.stream_duration_s; + if (duration > 600) duration = 600; // SPEC C9: always time-boxed + + strncpy(s_id, session_id, sizeof(s_id) - 1); + s_id[sizeof(s_id) - 1] = '\0'; + + if (!apiStreamOpen(s_id, mode, duration)) return false; + + // Drop to the stream resolution for the session and restore it after, so + // a stream never silently changes the resolution of stills. + s_prev_size = g_cfg.frame_size; + if (fsize != s_prev_size) cameraSetFrameSize(fsize); + + s_period_ms = 1000UL / (g_cfg.stream_fps ? g_cfg.stream_fps : 10); + s_end_ms = millis() + duration * 1000UL; + s_next_ms = millis(); + s_frames = 0; + s_fail_streak = 0; + s_active = true; + + powerInhibit(INHIBIT_STREAM); // released in streamStop() + powerNoteActivity(); + + log_i("stream: %s started, %us @ %ufps, size %u", s_id, duration, g_cfg.stream_fps, fsize); + return true; +} + +void streamTick() { + if (!s_active) return; + + if ((int32_t)(s_end_ms - millis()) <= 0) { streamStop("duration reached"); return; } + if (!netIsConnected()) { streamStop("wifi lost"); return; } + if ((int32_t)(s_next_ms - millis()) > 0) return; + + s_next_ms += s_period_ms; + // If we fell behind (a slow upload, a burst of uploads competing for the + // radio) do not try to catch up by bursting — just resync to now. + if ((int32_t)(s_next_ms - millis()) < 0) s_next_ms = millis() + s_period_ms; + + camera_fb_t* fb = cameraGrab(); + if (!fb) { + if (++s_fail_streak > 10) streamStop("camera keeps failing"); + return; + } + + bool sent = apiStreamSendFrame(fb->buf, fb->len, netEpochMs()); + esp_camera_fb_return(fb); + + if (sent) { + s_frames++; + s_fail_streak = 0; + powerNoteActivity(); + } else if (++s_fail_streak > 5) { + // The Pi closed the connection — a viewer navigated away, or the + // session was cancelled server-side. Treat that as a normal end. + streamStop("endpoint stopped accepting frames"); + } +} + +void streamStop(const char* reason) { + if (!s_active) return; + s_active = false; + + apiStreamClose(); + if (s_prev_size && s_prev_size != g_cfg.stream_frame_size) { + cameraSetFrameSize(s_prev_size); + } + + powerRelease(INHIBIT_STREAM); + powerNoteActivity(); // give the idle timer a fresh start before sleeping + + log_i("stream: %s ended after %u frames — %s", s_id, (unsigned)s_frames, reason); + s_id[0] = '\0'; +} + +uint32_t streamFramesSent() { return s_frames; } + +uint32_t streamSecondsLeft() { + if (!s_active) return 0; + int32_t left = (int32_t)(s_end_ms - millis()); + return left > 0 ? (uint32_t)(left / 1000) : 0; +} diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..fb710db --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,10 @@ +.venv/ +venv/ +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ +.pytest_cache/ +.ruff_cache/ +.env diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..10b06ab --- /dev/null +++ b/server/README.md @@ -0,0 +1,202 @@ +# poorBird server + +Phases 1 and 2 plus the Phase 3 server half: configuration, schema, health, job +queue, scheduler, every endpoint the camera calls, and user auth with the +gallery's API behind it. + +**Device endpoints** — bearer token, no cookies: + +``` +POST /api/v1/enroll X-Enroll-Secret, returns a bearer token +POST /api/v1/ingest raw JPEG body, metadata in headers +POST /api/v1/heartbeat conditions in, envelope + commands out +POST /api/v1/status conditions in, 204 out +GET /api/v1/config ~40 optional keys the device merges +POST /api/v1/commands/{id}/ack 204 +GET /api/v1/firmware/{version}.bin OTA image, exact Content-Length +GET /api/v1/health +``` + +**Operator endpoints** — session cookie + CSRF, never a bearer token: + +``` +POST /api/v1/auth/login password + TOTP, sets the session cookie +POST /api/v1/auth/logout 204, and the session row is deleted +GET /api/v1/auth/session who am I, or 401 +GET /api/v1/captures cursor-paged, filterable +GET /api/v1/captures/{id} detail incl. observations and tags +GET /api/v1/captures/{id}/image authorized, then handed to Caddy +GET /api/v1/captures/{id}/thumb 404 when the thumbnail job has not run +``` + +[`../firmware/API.md`](../firmware/API.md) is the contract for the device half, +and it wins over anything here: it is what the firmware already does, and the +camera is the side that cannot be patched from a laptop once it is mounted +outdoors. Of the operator half, auth and the gallery exist; firmware *upload* +and device management are Phase 4. + +Stack per SPEC §6, deployed natively per [`../TODO.md`](../TODO.md) Phase 1.2: +FastAPI + PostgreSQL 17 + SQLAlchemy 2.0 + Alembic, run as systemd units +behind Caddy. No containers — but nothing here blocks them either. + +--- + +## Developing on Windows (uv + Podman) + +This is the verified setup on the dev machine. Python is managed by `uv`, so +nothing touches the system PATH or the registry, and PostgreSQL runs in a +throwaway Podman container. Neither changes how the project deploys — the app +still talks loopback TCP exactly as it will on the server. + +```powershell +winget install astral-sh.uv +uv python install 3.14.7 + +podman machine start +podman run -d --name poorbird-db -p 127.0.0.1:5432:5432 ` + -e POSTGRES_USER=poorbird -e POSTGRES_PASSWORD=poorbird -e POSTGRES_DB=poorbird ` + docker.io/library/postgres:17 + +cd server +uv venv --python 3.14.7 +uv pip install -e ".[dev]" +# write .env (see the Linux section below; use Windows paths for the roots) + +.venv\Scripts\poorbird check +.venv\Scripts\poorbird migrate +.venv\Scripts\python -m pytest +``` + +Later sessions only need `podman machine start` and `podman start poorbird-db`. + +## Try it on any Linux machine + +Needs Python ≥ 3.11 and a PostgreSQL you can reach. Production targets 3.13; +the floor is lower so this runs on a stock Debian 12 or Ubuntu 24.04 box. + +```bash +sudo apt install -y python3-venv postgresql + +sudo -u postgres psql <<'SQL' +CREATE ROLE poorbird LOGIN PASSWORD 'poorbird'; +CREATE DATABASE poorbird OWNER poorbird; +SQL + +cd server +python3 -m venv .venv && . .venv/bin/activate +pip install -e '.[dev]' + +cat > .env <<'ENV' +POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird +POORBIRD_IMAGE_ROOT=/tmp/poorbird/images +POORBIRD_THUMB_ROOT=/tmp/poorbird/thumbs +POORBIRD_STATE_DIR=/tmp/poorbird/state +POORBIRD_API_PORT=8090 +ENV +mkdir -p /tmp/poorbird/{images,thumbs,state} + +poorbird check # config, paths, database — before starting anything +poorbird migrate # alembic upgrade head +poorbird serve # http://127.0.0.1:8090/api/v1/health +``` + +In a second shell: + +```bash +cd server && . .venv/bin/activate +poorbird worker & +poorbird enqueue noop '{"hello": "world"}' # the worker logs it within ~2s +``` + +`poorbird check` is the fast answer to "is this machine set up correctly" — it +validates config, storage paths and database connectivity and prints what it +found, without starting a service. + +### Tests + +```bash +pytest # everything reachable +pytest -m 'not db' # no PostgreSQL needed +``` + +Queue and schema tests need a real PostgreSQL — `FOR UPDATE SKIP LOCKED` has +no equivalent elsewhere, and mocking it would test nothing. They skip +automatically when the database is unreachable, so a green run with no +Postgres proves less than it looks. **Check for `skipped` in the summary**; +a complete run is 308 passed, 0 skipped. + +`test_schema_matches_models.py` creates and drops a `poorbird_schema_check` +database on the same server. It needs a role that may `CREATE DATABASE`. + +--- + +## Layout + +``` +src/poorbird/ + config.py every value from the environment, nothing baked in + logging_setup.py stdout only; journald or a log driver catches it + db.py engine + session factory (sync, deliberately) + models/ SPEC §3 schema + the SPEC §0 additions + images.py JPEG sniffing, atomic writes, thumbnails + passwords.py Argon2id — slow on purpose, unlike the device tokens + totp.py 2FA secrets, provisioning URIs, code verification + seed.py synthetic captures, so the gallery has volume to face + api/ FastAPI app, device + operator routes, auth, rate limiting + worker/ queue (SKIP LOCKED), handlers, scheduler + cli.py serve | worker | migrate | check | enqueue | user | seed +migrations/ Alembic +deploy/ systemd units, Caddyfile, env template, INSTALL.md +tests/ +``` + +--- + +## Decisions worth knowing before you read the code + +**Sync SQLAlchemy, not async.** At one camera and a few thousand frames a day +the async machinery buys nothing and costs clarity, and the worker's claim +loop is far easier to reason about synchronously. FastAPI runs `def` handlers +in a threadpool, so this does not block the event loop. The one thing that may +argue otherwise later is the MJPEG relay in Phase 6. + +**Device config is one JSONB column, not forty.** `GET /config` returns ~40 +optional keys and the firmware merges and clamps partial documents, so a +column per key would mean a migration every time the firmware gains a tunable. +Validation belongs in a Pydantic model, not in the DDL. The trade: you cannot +index or constrain an individual setting in SQL. If one ever needs querying +across devices, promote just that key to a column. + +**Server defaults are compared through a normaliser.** Postgres reflects a +varchar default as `'viewer'::character varying` while the model renders +`'viewer'`. Compared literally, every string default in the schema reads as +drift forever — which trains you to ignore the one time it isn't. See +`schema_compare.py`; autogenerate and the drift test share it, so the tool and +the test can never disagree about what counts as a difference. + +**Migration 0001 builds from `Base.metadata`.** A bounded exception, and +`tests/test_schema_matches_models.py` migrates a scratch database and asserts +an empty autogenerate diff, so the models and the migration cannot silently +diverge. Every later revision is a normal autogenerated one. If you prefer +explicit DDL in the baseline, autogenerate it against an empty database and +replace the file — the drift test passes either way. + +**The scheduler only enqueues, never executes.** Every unit of work goes +through the queue, where it is visible, retried and auditable, rather than +running inside a timer callback where a failure disappears. + +--- + +## Two things the code already guards, and the UI must too + +- `battery_valid = false` means **not measured** — no divider is wired by + default. Render it as "—", never as a low-battery alarm. +- The daily counters live in the device's RTC memory and reset on power loss. + `captures` is authoritative. The counters' value is the *gap* between + captured and delivered, which is an upload-health signal. + +--- + +## Deploying for real + +See [`deploy/INSTALL.md`](deploy/INSTALL.md). diff --git a/server/alembic.ini b/server/alembic.ini new file mode 100644 index 0000000..21c715d --- /dev/null +++ b/server/alembic.ini @@ -0,0 +1,39 @@ +[alembic] +script_location = migrations +prepend_sys_path = src +# The URL is NOT set here. migrations/env.py takes it from POORBIRD_DATABASE_URL +# so that config comes from exactly one place (TODO.md Phase 1.2). + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stdout,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/server/deploy/Caddyfile b/server/deploy/Caddyfile new file mode 100644 index 0000000..f35916a --- /dev/null +++ b/server/deploy/Caddyfile @@ -0,0 +1,80 @@ +# poorBird reverse proxy. Install to /etc/caddy/Caddyfile. +# +# Ports, so nothing collides: +# 127.0.0.1:8090 uvicorn (POORBIRD_API_PORT) -- never exposed +# :8080 plain HTTP for the camera (SPEC C2, firmware/API.md) +# :443 TLS for humans +# +# TLS: Caddy gets a real Let's Encrypt certificate for a LAN-only hostname via +# DNS-01, so there is no port forwarding and no browser warning. That needs a +# Caddy build with your DNS provider's plugin: +# +# caddy add-package github.com/caddy-dns/cloudflare +# +# For a first test on any Linux box you can skip the whole human-facing block +# and just use the :8080 one. + +(protected_files) { + # Auth-checked image serving (SPEC 3.3). + # + # An unguessable URL is not access control. The app authorizes the + # request, then replies with an empty body and + # X-Accel-Redirect: /images/2026/09/08/.jpg + # and Caddy serves the bytes from disk. The browser never receives a + # directly fetchable URL. + # + # The root below is the PARENT of POORBIRD_IMAGE_ROOT and + # POORBIRD_THUMB_ROOT in /etc/poorbird/poorbird.env. One value, two + # readers -- keep them in step. + @accel header X-Accel-Redirect * + handle_response @accel { + rewrite * {rp.header.X-Accel-Redirect} + file_server { + root /srv/poorbird + } + } +} + +# --- humans ----------------------------------------------------------------- +poorbird.example.internal { + tls { + dns cloudflare {env.CLOUDFLARE_API_TOKEN} + } + + encode zstd gzip + + reverse_proxy 127.0.0.1:8090 { + header_up X-Real-IP {remote_host} + import protected_files + } +} + +# --- the camera -------------------------------------------------------------- +# Plain HTTP on the LAN, deliberately (SPEC C2): TLS on the ESP32 means a CA +# baked into firmware, and a mounted camera that silently stops uploading when +# the chain rotates. +:8080 { + handle /api/v1/* { + request_body { + # A burst frame at UXGA can be a few hundred KB; an OTA image is + # ~1-2 MB. The default limit is too small for both. + max_size 12MB + } + reverse_proxy 127.0.0.1:8090 { + # Required, not cosmetic. Rate limiting keys enrollment on the + # caller's address, and without this every camera arrives as + # 127.0.0.1 and they all share one bucket - one noisy device + # would lock the rest out. The app trusts this header only + # because uvicorn binds loopback and nothing else can reach it. + header_up X-Real-IP {remote_host} + } + } + + handle /healthz { + reverse_proxy 127.0.0.1:8090 + } + + handle { + respond 404 + } +} diff --git a/server/deploy/INSTALL.md b/server/deploy/INSTALL.md new file mode 100644 index 0000000..148ed08 --- /dev/null +++ b/server/deploy/INSTALL.md @@ -0,0 +1,144 @@ +# Installing poorBird on the thin client + +Written for: whoever sets up the server host — assumes comfort with systemd +and `psql`, but not with this project. + +Target is an x86 Linux box on the same LAN as the camera (SPEC §0). Native +packages and systemd units, no containers. Commands below assume Debian or +Ubuntu; adjust the package manager otherwise. + +--- + +## 1. Packages and user + +```bash +sudo apt update +sudo apt install -y postgresql python3-venv python3-pip git caddy + +sudo useradd --system --home-dir /opt/poorbird --shell /usr/sbin/nologin poorbird +sudo mkdir -p /opt/poorbird /etc/poorbird /srv/poorbird/{images,thumbs} /var/lib/poorbird +sudo chown -R poorbird:poorbird /srv/poorbird /var/lib/poorbird /opt/poorbird +``` + +## 2. Database + +Loopback TCP with `scram-sha-256`, deliberately not a Unix socket — see +`TODO.md` Phase 1.2. + +```bash +sudo -u postgres psql <<'SQL' +CREATE ROLE poorbird LOGIN PASSWORD 'PUT_A_REAL_PASSWORD_HERE'; +CREATE DATABASE poorbird OWNER poorbird; +SQL +``` + +Confirm `pg_hba.conf` has a `host all all 127.0.0.1/32 scram-sha-256` +line before any `trust` line, then `sudo systemctl reload postgresql`. + +Verify the path the app will actually use, not the socket: + +```bash +psql "postgresql://poorbird:PUT_A_REAL_PASSWORD_HERE@127.0.0.1:5432/poorbird" -c 'SELECT 1' +``` + +## 3. Application + +```bash +sudo -u poorbird git clone /opt/poorbird/src +sudo ln -sfn /opt/poorbird/src/server /opt/poorbird/app +sudo -u poorbird python3 -m venv /opt/poorbird/venv +sudo -u poorbird /opt/poorbird/venv/bin/pip install -e /opt/poorbird/app +``` + +## 4. Configuration + +```bash +sudo cp /opt/poorbird/app/deploy/poorbird.env.example /etc/poorbird/poorbird.env +sudo chown root:poorbird /etc/poorbird/poorbird.env +sudo chmod 0640 /etc/poorbird/poorbird.env +sudo -e /etc/poorbird/poorbird.env # set the DB password and the enroll secret +``` + +Generate the enroll secret with `openssl rand -hex 32`. + +> **Before you ever rotate `POORBIRD_ENROLL_SECRET`:** it is compiled into the +> firmware image as the last-resort recovery path for a camera that cannot be +> reached over USB once mounted. Rotating it here without also shipping new +> firmware removes that escape hatch (`firmware/API.md`). + +Check the machine before starting anything: + +```bash +sudo -u poorbird env $(sudo cat /etc/poorbird/poorbird.env | grep -v '^#' | xargs) \ + /opt/poorbird/venv/bin/poorbird check +``` + +## 5. Services + +```bash +sudo cp /opt/poorbird/app/deploy/poorbird-*.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now poorbird-api poorbird-worker +systemctl status poorbird-api poorbird-worker +journalctl -u poorbird-api -f +``` + +The API unit runs `poorbird migrate` in `ExecStartPre`. The worker unit +deliberately does not, so two units never race to apply the same revision. + +Smoke test: + +```bash +curl -s localhost:8090/api/v1/health | python3 -m json.tool +``` + +## 6. Reverse proxy + +```bash +sudo cp /opt/poorbird/app/deploy/Caddyfile /etc/caddy/Caddyfile +sudo -e /etc/caddy/Caddyfile # set your hostname and DNS provider +sudo systemctl reload caddy +``` + +Ports, so nothing collides: + +| Port | Who | +|---|---| +| `127.0.0.1:8090` | uvicorn — never exposed | +| `:8080` | plain HTTP for the camera (SPEC C2) | +| `:443` | TLS for humans | + +DNS-01 needs a Caddy build with your provider's plugin: +`caddy add-package github.com/caddy-dns/cloudflare`. For a first test, replace +the human-facing site block with `http://:8081` and drop the `tls` block. + +## 7. Network + +Give the server a **DHCP reservation or a static IP, then hardcode that +address in the firmware** — simpler and more reliable than mDNS (SPEC §9). +The camera has no way to be told a new address once it is mounted and cannot +reach the endpoint. + +--- + +## Upgrading + +```bash +sudo -u poorbird git -C /opt/poorbird/src pull +sudo -u poorbird /opt/poorbird/venv/bin/pip install -e /opt/poorbird/app +sudo systemctl restart poorbird-api poorbird-worker +``` + +`ExecStartPre` applies migrations on restart. + +> Restarting mid-OTA-rollout matters: a device on a trial image marks that +> image valid **only after a heartbeat the endpoint accepted**. Returning 5xx +> to a trial device rolls it back — correct behaviour, but know it before you +> restart the API during a rollout (`firmware/API.md`). + +## Backups + +Not built yet — TODO Phase 5, and blocked on open question 9 (whether the NAS +offers SFTP, or only SMB/NFS), which decides between restic and a mounted +path. Until then **this machine is not backed up.** Do not let real captures +accumulate here before that is done. diff --git a/server/deploy/poorbird-api.service b/server/deploy/poorbird-api.service new file mode 100644 index 0000000..f3d90b5 --- /dev/null +++ b/server/deploy/poorbird-api.service @@ -0,0 +1,44 @@ +[Unit] +Description=poorBird API +After=network-online.target postgresql.service +Wants=network-online.target +Requires=postgresql.service + +[Service] +Type=exec +User=poorbird +Group=poorbird +WorkingDirectory=/opt/poorbird/app +EnvironmentFile=/etc/poorbird/poorbird.env + +# Migrations run as a separate idempotent command, never at app import time. +# Same command a container entrypoint or init job would call. +ExecStartPre=/opt/poorbird/venv/bin/poorbird migrate +ExecStart=/opt/poorbird/venv/bin/poorbird serve + +Restart=on-failure +RestartSec=5 +TimeoutStopSec=20 + +# Logs go to stdout and journald picks them up. No app-managed log files. +StandardOutput=journal +StandardError=journal +SyslogIdentifier=poorbird-api + +# --- hardening +NoNewPrivileges=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=no +ReadWritePaths=/srv/poorbird /var/lib/poorbird + +[Install] +WantedBy=multi-user.target diff --git a/server/deploy/poorbird-worker.service b/server/deploy/poorbird-worker.service new file mode 100644 index 0000000..4043631 --- /dev/null +++ b/server/deploy/poorbird-worker.service @@ -0,0 +1,42 @@ +[Unit] +Description=poorBird worker (job queue + scheduler) +After=network-online.target postgresql.service poorbird-api.service +Wants=network-online.target +Requires=postgresql.service + +[Service] +Type=exec +User=poorbird +Group=poorbird +WorkingDirectory=/opt/poorbird/app +EnvironmentFile=/etc/poorbird/poorbird.env + +# No ExecStartPre=migrate here: the API unit owns migrations, so two units +# never race to apply the same revision. +ExecStart=/opt/poorbird/venv/bin/poorbird worker + +Restart=on-failure +RestartSec=5 +# The worker finishes its current job on SIGTERM. +KillSignal=SIGTERM +TimeoutStopSec=60 + +StandardOutput=journal +StandardError=journal +SyslogIdentifier=poorbird-worker + +# --- hardening +NoNewPrivileges=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +LockPersonality=yes +ReadWritePaths=/srv/poorbird /var/lib/poorbird + +[Install] +WantedBy=multi-user.target diff --git a/server/deploy/poorbird.env.example b/server/deploy/poorbird.env.example new file mode 100644 index 0000000..5d2ffbe --- /dev/null +++ b/server/deploy/poorbird.env.example @@ -0,0 +1,96 @@ +# poorBird configuration. +# +# Install to /etc/poorbird/poorbird.env, owned by root:poorbird, mode 0640. +# systemd loads it via EnvironmentFile. This same file becomes a compose .env +# unchanged if containers ever happen (TODO.md Phase 1.2). +# +# Note: systemd's EnvironmentFile does NOT do shell quoting or expansion. +# Write VALUES literally, with no surrounding quotes. + +# --- database --------------------------------------------------------------- +# Loopback TCP with scram-sha-256, deliberately not a Unix socket. +# Required: the app has no built-in default and refuses to start without it. +# The literal CHANGE_ME below is rejected at startup, so you cannot copy this +# file and forget to edit it. +POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird +# +# Connection pool. The API and the worker are separate processes and each gets +# its own pool, so the most either can open is POOL_SIZE + MAX_OVERFLOW and the +# most both together can open is twice that -- keep it under PostgreSQL's +# max_connections (100 by default). The worker opens connections lazily and +# needs about three, so the size below is really sizing the API. +POORBIRD_DB_POOL_SIZE=15 +POORBIRD_DB_MAX_OVERFLOW=10 + +# --- http ------------------------------------------------------------------- +# Bind to loopback only; Caddy is the only thing that talks to it. +# Caddy itself takes :8080 for the camera and :443 for humans, so uvicorn sits +# behind on 8090. See deploy/Caddyfile. +POORBIRD_API_HOST=127.0.0.1 +POORBIRD_API_PORT=8090 + +# --- storage ---------------------------------------------------------------- +# Read by the app AND referenced by the Caddyfile: the auth-checked image +# handoff needs both to agree on this path (SPEC 3.3). +POORBIRD_IMAGE_ROOT=/srv/poorbird/images +POORBIRD_THUMB_ROOT=/srv/poorbird/thumbs +POORBIRD_STATE_DIR=/var/lib/poorbird + +# Who copies the image bytes (SPEC 3.3). +# +# Leave this FALSE in production. The app authorises the request and answers +# with X-Accel-Redirect, and Caddy reads the file, so a 3 MB JPEG never +# occupies a Python worker thread. +# +# Set it true ONLY for local development, where there is no Caddy to honour +# that header and every image in the gallery would otherwise arrive as an +# empty 200. It does NOT relax the authorisation -- the same check runs either +# way; it only changes how an already-authorised response is finished. +# +# NOTE: with this false, IMAGE_ROOT and THUMB_ROOT must be siblings named +# images/ and thumbs/ under the directory the Caddyfile's file_server serves +# (deploy/Caddyfile, the protected_files snippet). `poorbird check` verifies +# that, because getting it wrong produces 404s from Caddy and nothing in the +# app's log. +POORBIRD_SERVE_IMAGES_DIRECTLY=false + +# --- devices ---------------------------------------------------------------- +# Shared bootstrap secret the firmware presents in X-Enroll-Secret. +# Generate with: openssl rand -hex 32 +# +# WARNING (firmware/API.md): this value is compiled into the firmware image as +# the last-resort recovery path for a camera that cannot be reached over USB. +# Rotating it here WITHOUT shipping new firmware removes that escape hatch. +POORBIRD_ENROLL_SECRET= + +# --- user sessions ---------------------------------------------------------- +# How long a signed-in browser stays signed in. SPEC 3.4 makes this a +# UI-editable server setting eventually; for now it is here. +POORBIRD_SESSION_LIFETIME_H=336 + +# Leave this TRUE in production. Caddy always terminates HTTPS, so the cookie +# can and must be Secure. +# +# Set it false ONLY for local development against the Vite dev server, which is +# plain http on localhost. A Secure cookie is silently discarded by the browser +# over http, and the symptom is "login returns 200 but I am never signed in", +# with nothing in any log to explain it. That is the only reason this is a +# setting rather than a constant. +POORBIRD_SESSION_COOKIE_SECURE=true + +# --- rate limiting ------------------------------------------------------------ +# In-process token buckets. Sized for ONE uvicorn process: if you ever run the +# API with workers, each gets its own buckets and the effective limit +# multiplies. Set false only for local development. +POORBIRD_RATE_LIMIT_ENABLED=true + +# --- worker ----------------------------------------------------------------- +# How long to wait after finding the queue empty. Does not delay a queue that +# already has work: the worker drains that without pausing. +POORBIRD_WORKER_POLL_INTERVAL_S=5 +POORBIRD_JOB_MAX_ATTEMPTS=3 + +# --- logging ---------------------------------------------------------------- +POORBIRD_LOG_LEVEL=INFO +# text for journalctl by eye, json once you are shipping logs somewhere. +POORBIRD_LOG_FORMAT=text diff --git a/server/migrations/env.py b/server/migrations/env.py new file mode 100644 index 0000000..cc804ac --- /dev/null +++ b/server/migrations/env.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +from poorbird.config import get_settings +from poorbird.models import Base +from poorbird.schema_compare import COMPARE_OPTS + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# One source of truth for the URL: the environment, via Settings. An explicit +# override still wins, so tests can point a run at a scratch database. +if not config.get_main_option("sqlalchemy.url", None): + config.set_main_option("sqlalchemy.url", get_settings().database_url) + +target_metadata = Base.metadata + +OPTS = COMPARE_OPTS + + +def run_migrations_offline() -> None: + context.configure( + url=config.get_main_option("sqlalchemy.url"), + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + **OPTS, + ) + with context.begin_transaction(): + context.run_migrations() + + +def _run(connection) -> None: + context.configure(connection=connection, target_metadata=target_metadata, **OPTS) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + # A caller may hand us a live connection (the schema-drift test does). + injected = config.attributes.get("connection", None) + if injected is not None: + _run(injected) + return + + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + with connectable.connect() as connection: + _run(connection) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/server/migrations/script.py.mako b/server/migrations/script.py.mako new file mode 100644 index 0000000..063ed2a --- /dev/null +++ b/server/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" +from __future__ import annotations + +from collections.abc import Sequence + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +revision: str = ${repr(up_revision)} +down_revision: str | None = ${repr(down_revision)} +branch_labels: str | Sequence[str] | None = ${repr(branch_labels)} +depends_on: str | Sequence[str] | None = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/server/migrations/versions/0001_initial.py b/server/migrations/versions/0001_initial.py new file mode 100644 index 0000000..dc89352 --- /dev/null +++ b/server/migrations/versions/0001_initial.py @@ -0,0 +1,529 @@ +"""Baseline schema: SPEC 3 plus the SPEC 0 additions. + +Explicit DDL, and frozen. + +This revision used to call ``Base.metadata.create_all()``. That could not drift +from the models, which was the point, but it also meant a fresh database got +the *current* models here and then had every later migration applied on top of +what it had already created -- so the first revision added after it failed with +"column token_hash of relation sessions already exists". +``tests/test_schema_matches_models.py`` caught that the moment one was added, +which is the only reason it did not reach a deployment. + +So the baseline is now what Alembic expects a baseline to be: the schema as it +stood at the end of Phase 1, and nothing after it. Later revisions change it. + +**Do not edit this file to reflect a model change -- add a revision.** Editing +it would reintroduce exactly the failure above, for anyone whose database is +already past this point. + +Revision ID: 0001 +Revises: +Create Date: 2026-09-20 +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision: str = "0001" +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.create_table( + "backup_runs", + sa.Column("id", sa.BigInteger(), nullable=False), + sa.Column( + "started_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("status", sa.String(length=16), nullable=False), + sa.Column("bytes", sa.BigInteger(), nullable=True), + sa.Column("snapshot_id", sa.String(length=64), nullable=True), + sa.Column("restore_tested_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("error", sa.Text(), nullable=True), + sa.PrimaryKeyConstraint("id", name=op.f("pk_backup_runs")), + ) + op.create_table( + "devices", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("device_uid", sa.String(length=32), nullable=False), + sa.Column("name", sa.String(length=64), nullable=False), + sa.Column("mac", sa.String(length=32), nullable=True), + sa.Column("hw_revision", sa.String(length=64), nullable=True), + sa.Column("fw_version", sa.String(length=32), nullable=True), + sa.Column("token_hash", sa.String(length=128), nullable=True), + sa.Column("reenroll_secret_hash", sa.String(length=128), nullable=True), + sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("battery_mv", sa.Integer(), nullable=True), + sa.Column("battery_pct", sa.Integer(), nullable=True), + sa.Column("battery_valid", sa.Boolean(), nullable=False), + sa.Column("rssi", sa.Integer(), nullable=True), + sa.Column("temp_c", sa.Float(), nullable=True), + sa.Column("awake", sa.Boolean(), nullable=False), + sa.Column( + "config", postgresql.JSONB(astext_type=sa.Text()), server_default="{}", nullable=False + ), + sa.Column("config_version", sa.Integer(), server_default="1", nullable=False), + sa.Column("heartbeat_interval_s", sa.Integer(), server_default="300", nullable=False), + sa.Column("status_interval_s", sa.Integer(), server_default="900", nullable=False), + sa.Column("responsive_mode", sa.Boolean(), server_default="false", nullable=False), + sa.Column("enabled", sa.Boolean(), server_default="true", nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_devices")), + ) + op.create_index(op.f("ix_devices_device_uid"), "devices", ["device_uid"], unique=True) + op.create_index(op.f("ix_devices_token_hash"), "devices", ["token_hash"], unique=True) + op.create_table( + "jobs", + sa.Column("id", sa.BigInteger(), nullable=False), + sa.Column("kind", sa.String(length=64), nullable=False), + sa.Column( + "payload", postgresql.JSONB(astext_type=sa.Text()), server_default="{}", nullable=False + ), + sa.Column("status", sa.String(length=16), server_default="queued", nullable=False), + sa.Column("priority", sa.Integer(), server_default="0", nullable=False), + sa.Column( + "run_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False + ), + sa.Column("attempts", sa.Integer(), server_default="0", nullable=False), + sa.Column("max_attempts", sa.Integer(), server_default="3", nullable=False), + sa.Column("locked_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("locked_by", sa.String(length=128), nullable=True), + sa.Column("last_error", sa.Text(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint( + "status IN ('queued', 'running', 'done', 'failed')", name=op.f("ck_jobs_status_valid") + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_jobs")), + ) + op.create_index("ix_jobs_claimable", "jobs", ["status", "run_at", "priority"], unique=False) + op.create_table( + "tags", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("label", sa.String(length=64), nullable=False), + sa.Column("colour", sa.String(length=16), nullable=True), + sa.PrimaryKeyConstraint("id", name=op.f("pk_tags")), + sa.UniqueConstraint("label", name=op.f("uq_tags_label")), + ) + op.create_table( + "taxa", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("gbif_key", sa.BigInteger(), nullable=True), + sa.Column("scientific_name", sa.String(length=128), nullable=False), + sa.Column("name_de", sa.String(length=128), nullable=True), + sa.Column("name_en", sa.String(length=128), nullable=True), + sa.Column("family", sa.String(length=64), nullable=True), + sa.Column("order", sa.String(length=64), nullable=True), + sa.Column("iucn_status", sa.String(length=8), nullable=True), + sa.Column("is_local_common", sa.Boolean(), server_default="false", nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_taxa")), + sa.UniqueConstraint("gbif_key", name=op.f("uq_taxa_gbif_key")), + sa.UniqueConstraint("scientific_name", name=op.f("uq_taxa_scientific_name")), + ) + op.create_index(op.f("ix_taxa_name_de"), "taxa", ["name_de"], unique=False) + op.create_index(op.f("ix_taxa_name_en"), "taxa", ["name_en"], unique=False) + op.create_table( + "users", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("username", sa.String(length=64), nullable=False), + sa.Column("email", sa.String(length=255), nullable=True), + sa.Column("password_hash", sa.String(length=255), nullable=True), + sa.Column("role", sa.String(length=16), server_default="viewer", nullable=False), + sa.Column("totp_secret", sa.String(length=64), nullable=True), + sa.Column("is_active", sa.Boolean(), server_default="true", nullable=False), + sa.Column("theme", sa.String(length=16), server_default="light", nullable=False), + sa.Column("locale", sa.String(length=8), server_default="de", nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("last_login_at", sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint( + "role IN ('admin', 'editor', 'viewer')", name=op.f("ck_users_role_valid") + ), + sa.CheckConstraint("theme IN ('light', 'dark', 'blue')", name=op.f("ck_users_theme_valid")), + sa.PrimaryKeyConstraint("id", name=op.f("pk_users")), + sa.UniqueConstraint("username", name=op.f("uq_users_username")), + ) + op.create_table( + "audit_log", + sa.Column("id", sa.BigInteger(), nullable=False), + sa.Column( + "at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False + ), + sa.Column("user_id", sa.Integer(), nullable=True), + sa.Column("action", sa.String(length=64), nullable=False), + sa.Column("entity", sa.String(length=64), nullable=False), + sa.Column("entity_id", sa.String(length=64), nullable=True), + sa.Column("before", postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column("after", postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column("ip", sa.String(length=45), nullable=True), + sa.ForeignKeyConstraint( + ["user_id"], ["users.id"], name=op.f("fk_audit_log_user_id_users"), ondelete="SET NULL" + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_audit_log")), + ) + op.create_index("ix_audit_log_entity", "audit_log", ["entity", "entity_id", "at"], unique=False) + op.create_table( + "captures", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("device_id", sa.Integer(), nullable=False), + sa.Column("path", sa.Text(), nullable=False), + sa.Column("thumb_path", sa.Text(), nullable=True), + sa.Column("sha256", sa.String(length=64), nullable=False), + sa.Column("width", sa.Integer(), nullable=True), + sa.Column("height", sa.Integer(), nullable=True), + sa.Column("bytes", sa.BigInteger(), nullable=False), + sa.Column("captured_at_device", sa.DateTime(timezone=True), nullable=True), + sa.Column( + "received_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("trigger", sa.String(length=16), nullable=False), + sa.Column("burst_id", sa.String(length=64), nullable=True), + sa.Column("burst_index", sa.Integer(), nullable=True), + sa.Column("burst_count", sa.Integer(), nullable=True), + sa.Column("pre_trigger", sa.Boolean(), server_default="false", nullable=False), + sa.Column("frame_seq", sa.Integer(), nullable=True), + sa.Column("radar_state", sa.Integer(), nullable=True), + sa.Column("radar_distance_cm", sa.Integer(), nullable=True), + sa.Column("radar_energy", sa.Integer(), nullable=True), + sa.Column("battery_mv", sa.Integer(), nullable=True), + sa.Column("rssi", sa.Integer(), nullable=True), + sa.Column("temp_c", sa.Float(), nullable=True), + sa.Column("reviewed", sa.Boolean(), server_default="false", nullable=False), + sa.Column("kept", sa.Boolean(), server_default="true", nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.CheckConstraint( + "trigger IN ('radar', 'manual', 'timer', 'stream_grab')", + name=op.f("ck_captures_trigger_valid"), + ), + sa.ForeignKeyConstraint( + ["device_id"], + ["devices.id"], + name=op.f("fk_captures_device_id_devices"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_captures")), + ) + op.create_index("ix_captures_burst", "captures", ["burst_id", "burst_index"], unique=False) + op.create_index( + "ix_captures_device_received", "captures", ["device_id", "received_at"], unique=False + ) + op.create_index(op.f("ix_captures_sha256"), "captures", ["sha256"], unique=False) + op.create_index( + "ix_captures_triage", "captures", ["kept", "reviewed", "received_at"], unique=False + ) + op.create_table( + "device_commands", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("device_id", sa.Integer(), nullable=False), + sa.Column("type", sa.String(length=32), nullable=False), + sa.Column("payload", postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column("created_by", sa.Integer(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("acked_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("ack_status", sa.String(length=16), nullable=True), + sa.Column("result", sa.Text(), nullable=True), + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint( + "ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')", + name=op.f("ck_device_commands_ack_status_valid"), + ), + sa.CheckConstraint( + "type IN ('apply_config', 'capture_now', 'report_status', 'wake_and_hold', 'sleep_now', 'stream_start', 'stream_stop', 'ota_update', 'reboot')", + name=op.f("ck_device_commands_type_valid"), + ), + sa.ForeignKeyConstraint( + ["created_by"], + ["users.id"], + name=op.f("fk_device_commands_created_by_users"), + ondelete="SET NULL", + ), + sa.ForeignKeyConstraint( + ["device_id"], + ["devices.id"], + name=op.f("fk_device_commands_device_id_devices"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_device_commands")), + ) + op.create_index( + "ix_device_commands_pending", "device_commands", ["device_id", "created_at"], unique=False + ) + op.create_table( + "device_status", + sa.Column("id", sa.BigInteger(), nullable=False), + sa.Column("device_id", sa.Integer(), nullable=False), + sa.Column( + "at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False + ), + sa.Column("reason", sa.String(length=32), nullable=False), + sa.Column("battery_mv", sa.Integer(), nullable=True), + sa.Column("battery_pct", sa.Integer(), nullable=True), + sa.Column("battery_valid", sa.Boolean(), nullable=True), + sa.Column("awake_ms", sa.BigInteger(), nullable=True), + sa.Column("boot_count", sa.Integer(), nullable=True), + sa.Column("wake_cause", sa.String(length=16), nullable=True), + sa.Column("last_sleep_s", sa.Integer(), nullable=True), + sa.Column("total_sleep_s", sa.BigInteger(), nullable=True), + sa.Column("captured_today", sa.Integer(), nullable=True), + sa.Column("delivered_today", sa.Integer(), nullable=True), + sa.Column("failed_today", sa.Integer(), nullable=True), + sa.Column("events_today", sa.Integer(), nullable=True), + sa.Column("day_index", sa.Integer(), nullable=True), + sa.Column("is_night", sa.Boolean(), nullable=True), + sa.Column("nightlight_on", sa.Boolean(), nullable=True), + sa.Column("cam_profile", sa.String(length=16), nullable=True), + sa.Column("radar_baud", sa.Integer(), nullable=True), + sa.Column("radar_uart_ok", sa.Boolean(), nullable=True), + sa.Column("stream_active", sa.Boolean(), nullable=True), + sa.Column("rssi", sa.Integer(), nullable=True), + sa.Column("ip", sa.String(length=45), nullable=True), + sa.Column("free_heap", sa.BigInteger(), nullable=True), + sa.Column("free_psram", sa.BigInteger(), nullable=True), + sa.Column("ring_depth", sa.Integer(), nullable=True), + sa.Column("time_synced", sa.Boolean(), nullable=True), + sa.Column("device_time", sa.DateTime(timezone=True), nullable=True), + sa.Column("fw_version", sa.String(length=32), nullable=True), + sa.Column("config_version", sa.Integer(), nullable=True), + sa.Column("raw", postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.CheckConstraint( + "reason IN ('heartbeat', 'periodic', 'after_event', 'before_sleep', 'before_night_sleep', 'on_request')", + name=op.f("ck_device_status_reason_valid"), + ), + sa.ForeignKeyConstraint( + ["device_id"], + ["devices.id"], + name=op.f("fk_device_status_device_id_devices"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_device_status")), + ) + op.create_index( + "ix_device_status_device_at", "device_status", ["device_id", "at"], unique=False + ) + op.create_table( + "firmware", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("version", sa.String(length=32), nullable=False), + sa.Column("semver", sa.String(length=32), nullable=True), + sa.Column("file_path", sa.Text(), nullable=False), + sa.Column("sha256", sa.String(length=64), nullable=False), + sa.Column("size_bytes", sa.BigInteger(), nullable=False), + sa.Column("release_notes", sa.Text(), nullable=True), + sa.Column("min_battery_pct", sa.Integer(), server_default="50", nullable=False), + sa.Column("uploaded_by", sa.Integer(), nullable=True), + sa.Column( + "uploaded_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("is_target", sa.Boolean(), server_default="false", nullable=False), + sa.ForeignKeyConstraint( + ["uploaded_by"], + ["users.id"], + name=op.f("fk_firmware_uploaded_by_users"), + ondelete="SET NULL", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_firmware")), + sa.UniqueConstraint("version", name=op.f("uq_firmware_version")), + ) + op.create_table( + "sessions", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("ip", sa.String(length=45), nullable=True), + sa.Column("user_agent", sa.String(length=255), nullable=True), + sa.ForeignKeyConstraint( + ["user_id"], ["users.id"], name=op.f("fk_sessions_user_id_users"), ondelete="CASCADE" + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_sessions")), + ) + op.create_index(op.f("ix_sessions_expires_at"), "sessions", ["expires_at"], unique=False) + op.create_index(op.f("ix_sessions_user_id"), "sessions", ["user_id"], unique=False) + op.create_table( + "settings", + sa.Column("key", sa.String(length=64), nullable=False), + sa.Column("value", sa.Text(), nullable=True), + sa.Column("value_type", sa.String(length=16), server_default="str", nullable=False), + sa.Column("scope", sa.String(length=16), server_default="server", nullable=False), + sa.Column("updated_by", sa.Integer(), nullable=True), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.CheckConstraint("scope IN ('server', 'device')", name=op.f("ck_settings_scope_valid")), + sa.ForeignKeyConstraint( + ["updated_by"], + ["users.id"], + name=op.f("fk_settings_updated_by_users"), + ondelete="SET NULL", + ), + sa.PrimaryKeyConstraint("key", name=op.f("pk_settings")), + ) + op.create_table( + "capture_tags", + sa.Column("capture_id", sa.Uuid(), nullable=False), + sa.Column("tag_id", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint( + ["capture_id"], + ["captures.id"], + name=op.f("fk_capture_tags_capture_id_captures"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["tag_id"], ["tags.id"], name=op.f("fk_capture_tags_tag_id_tags"), ondelete="CASCADE" + ), + sa.PrimaryKeyConstraint("capture_id", "tag_id", name=op.f("pk_capture_tags")), + ) + op.create_table( + "observations", + sa.Column("id", sa.BigInteger(), nullable=False), + sa.Column("capture_id", sa.Uuid(), nullable=False), + sa.Column("taxon_id", sa.Integer(), nullable=True), + sa.Column("individuals", sa.Integer(), server_default="1", nullable=False), + sa.Column("age", sa.String(length=16), server_default="unknown", nullable=False), + sa.Column("sex", sa.String(length=16), server_default="unknown", nullable=False), + sa.Column("behaviour", sa.String(length=16), nullable=True), + sa.Column("certainty", sa.String(length=16), server_default="certain", nullable=False), + sa.Column("notes", sa.Text(), nullable=True), + sa.Column("source", sa.String(length=8), server_default="human", nullable=False), + sa.Column("model_version", sa.String(length=64), nullable=True), + sa.Column("confidence", sa.Float(), nullable=True), + sa.Column("bbox", postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column("created_by", sa.Integer(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.CheckConstraint( + "age IN ('adult', 'juvenile', 'unknown')", name=op.f("ck_observations_age_valid") + ), + sa.CheckConstraint( + "behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')", + name=op.f("ck_observations_behaviour_valid"), + ), + sa.CheckConstraint( + "certainty IN ('certain', 'probable', 'uncertain')", + name=op.f("ck_observations_certainty_valid"), + ), + sa.CheckConstraint( + "sex IN ('male', 'female', 'unknown')", name=op.f("ck_observations_sex_valid") + ), + sa.CheckConstraint( + "source IN ('human', 'model')", name=op.f("ck_observations_source_valid") + ), + sa.ForeignKeyConstraint( + ["capture_id"], + ["captures.id"], + name=op.f("fk_observations_capture_id_captures"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["created_by"], + ["users.id"], + name=op.f("fk_observations_created_by_users"), + ondelete="SET NULL", + ), + sa.ForeignKeyConstraint( + ["taxon_id"], + ["taxa.id"], + name=op.f("fk_observations_taxon_id_taxa"), + ondelete="RESTRICT", + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_observations")), + ) + op.create_index( + op.f("ix_observations_capture_id"), "observations", ["capture_id"], unique=False + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + op.drop_index(op.f("ix_observations_capture_id"), table_name="observations") + op.drop_table("observations") + op.drop_table("capture_tags") + op.drop_table("settings") + op.drop_index(op.f("ix_sessions_user_id"), table_name="sessions") + op.drop_index(op.f("ix_sessions_expires_at"), table_name="sessions") + op.drop_table("sessions") + op.drop_table("firmware") + op.drop_index("ix_device_status_device_at", table_name="device_status") + op.drop_table("device_status") + op.drop_index("ix_device_commands_pending", table_name="device_commands") + op.drop_table("device_commands") + op.drop_index("ix_captures_triage", table_name="captures") + op.drop_index(op.f("ix_captures_sha256"), table_name="captures") + op.drop_index("ix_captures_device_received", table_name="captures") + op.drop_index("ix_captures_burst", table_name="captures") + op.drop_table("captures") + op.drop_index("ix_audit_log_entity", table_name="audit_log") + op.drop_table("audit_log") + op.drop_table("users") + op.drop_index(op.f("ix_taxa_name_en"), table_name="taxa") + op.drop_index(op.f("ix_taxa_name_de"), table_name="taxa") + op.drop_table("taxa") + op.drop_table("tags") + op.drop_index("ix_jobs_claimable", table_name="jobs") + op.drop_table("jobs") + op.drop_index(op.f("ix_devices_token_hash"), table_name="devices") + op.drop_index(op.f("ix_devices_device_uid"), table_name="devices") + op.drop_table("devices") + op.drop_table("backup_runs") + # ### end Alembic commands ### diff --git a/server/migrations/versions/c00181d246b9_session_token_hash_and_csrf_token.py b/server/migrations/versions/c00181d246b9_session_token_hash_and_csrf_token.py new file mode 100644 index 0000000..ad85441 --- /dev/null +++ b/server/migrations/versions/c00181d246b9_session_token_hash_and_csrf_token.py @@ -0,0 +1,53 @@ +"""session token hash and csrf token + +The cookie stops being the primary key. ``sessions.id`` becomes internal and the +browser carries a separate token of which only the SHA-256 is stored, so a +database dump no longer hands over every live session. ``csrf_token`` is per +session, which is what stops the double-submit check being satisfiable by +someone who can merely set a cookie on the domain. + +Both columns are NOT NULL with no default, and that is deliberate: there is no +value that could be back-filled. A session row without a token hash cannot be +looked up by any request, so it is not a session -- it is a row that would sit +there until it expired. Existing rows are therefore deleted rather than given a +placeholder hash, which would be a credential nobody holds and the unique index +would reject on the second row anyway. + +In practice this table is empty: nothing before Phase 3 ever wrote a session. +The DELETE is here so the migration is also correct on a database where that +turns out not to be true. + +Revision ID: c00181d246b9 +Revises: 0001 +Create Date: 2026-09-21 17:57:33.783616 +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "c00181d246b9" +down_revision: str | None = "0001" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + # Any pre-existing row is unusable under the new scheme; signing those + # browsers out is the correct outcome, not a loss. + op.execute("DELETE FROM sessions") + op.add_column("sessions", sa.Column("token_hash", sa.String(length=64), nullable=False)) + op.add_column("sessions", sa.Column("csrf_token", sa.String(length=64), nullable=False)) + op.create_index(op.f("ix_sessions_token_hash"), "sessions", ["token_hash"], unique=True) + + +def downgrade() -> None: + # Going back makes every session unauthenticatable for the same reason, so + # clear them here too rather than leaving rows that resolve to nothing. + op.drop_index(op.f("ix_sessions_token_hash"), table_name="sessions") + op.drop_column("sessions", "csrf_token") + op.drop_column("sessions", "token_hash") + op.execute("DELETE FROM sessions") diff --git a/server/pyproject.toml b/server/pyproject.toml new file mode 100644 index 0000000..b72a61a --- /dev/null +++ b/server/pyproject.toml @@ -0,0 +1,62 @@ +[project] +name = "poorbird" +version = "0.1.0" +description = "poorBird server — ingest, gallery and device management for a radar-triggered bird camera" +requires-python = ">=3.11" +dependencies = [ + "fastapi>=0.115", + "uvicorn[standard]>=0.32", + "pydantic>=2.9", + "pydantic-settings>=2.6", + "sqlalchemy>=2.0.36", + "psycopg[binary]>=3.2", + "alembic>=1.14", + "apscheduler>=3.11,<4", + # Thumbnails only, and only in the worker. The ingest path deliberately + # does not decode images -- see poorbird/images.py. + "pillow>=11.0", + # Argon2id for user passwords (SPEC 3.1). Device tokens stay on SHA-256 and + # deliberately so -- see api/deps.py.hash_credential for why the two differ. + "argon2-cffi>=23.1", + # TOTP. Hand-rolling RFC 6238 is 30 lines, and the two that matter -- the + # constant-time compare and the clock-skew window -- are the two easiest to + # get quietly wrong. + "pyotp>=2.9", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.3", + "httpx>=0.28", + "ruff>=0.8", +] + +[project.scripts] +poorbird = "poorbird.cli:main" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/poorbird"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +markers = [ + "db: integration test, needs a reachable PostgreSQL (deselect with -m 'not db')", +] + +[tool.ruff] +line-length = 100 +src = ["src"] + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] + +[tool.ruff.lint.per-file-ignores] +# Migrations are generated, then linted like everything else -- except for line +# length. The over-long lines are CHECK constraint bodies, which are SQL string +# literals: wrapping one means editing the constraint, and a migration that has +# already run is not a file to edit for tidiness. +"migrations/versions/*.py" = ["E501"] diff --git a/server/src/poorbird/__init__.py b/server/src/poorbird/__init__.py new file mode 100644 index 0000000..3dc1f76 --- /dev/null +++ b/server/src/poorbird/__init__.py @@ -0,0 +1 @@ +__version__ = "0.1.0" diff --git a/server/src/poorbird/api/__init__.py b/server/src/poorbird/api/__init__.py new file mode 100644 index 0000000..b94a1e8 --- /dev/null +++ b/server/src/poorbird/api/__init__.py @@ -0,0 +1,3 @@ +from .app import create_app + +__all__ = ["create_app"] diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py new file mode 100644 index 0000000..9a1957e --- /dev/null +++ b/server/src/poorbird/api/app.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import logging +from contextlib import asynccontextmanager + +from fastapi import FastAPI + +from .. import __version__ +from ..config import get_settings +from ..logging_setup import configure_logging +from .routes import ( + auth, + captures, + commands, + conditions, + device_config, + enroll, + firmware, + health, + ingest, +) +from .userauth import csrf_middleware + +log = logging.getLogger(__name__) + +API_PREFIX = "/api/v1" + + +@asynccontextmanager +async def lifespan(app: FastAPI): + settings = get_settings() + log.info( + "poorbird api starting", + extra={"version": __version__, "image_root": str(settings.image_root)}, + ) + if not settings.enroll_secret_is_set: + # A warning rather than a refusal to start: an existing camera keeps + # working with the token it already holds, and taking the whole API + # down would also take down the gallery. Only enrollment breaks. + log.warning("POORBIRD_ENROLL_SECRET is not set; device enrollment will refuse requests") + yield + log.info("poorbird api stopping") + + +def create_app() -> FastAPI: + settings = get_settings() + configure_logging(settings.log_level, settings.log_format) + + app = FastAPI( + title="poorBird", + version=__version__, + summary="Ingest, gallery and device management for a radar-triggered bird camera", + lifespan=lifespan, + ) + + # CSRF for cookie-authenticated mutations. Middleware rather than a + # per-route dependency so a new endpoint cannot forget it; it applies only + # to unsafe methods on requests that carry the session cookie, which is why + # the device endpoints -- bearer tokens, no cookies -- are unaffected. See + # userauth.csrf_middleware. + app.middleware("http")(csrf_middleware) + + app.include_router(health.router, prefix=API_PREFIX, tags=["health"]) + app.include_router(health.root_router) + + # Phase 3 WebUI endpoints. + app.include_router(auth.router, prefix=API_PREFIX) + app.include_router(captures.router, prefix=API_PREFIX) + + # Phase 2 device endpoints. See firmware/API.md for the contract. + app.include_router(enroll.router, prefix=API_PREFIX) + app.include_router(conditions.router, prefix=API_PREFIX) + app.include_router(device_config.router, prefix=API_PREFIX) + app.include_router(commands.router, prefix=API_PREFIX) + app.include_router(ingest.router, prefix=API_PREFIX) + app.include_router(firmware.router, prefix=API_PREFIX) + + # The device contract (firmware/API.md) is complete apart from /stream, + # which is Phase 6. Still to come on the operator side: the admin-facing + # POST /firmware and device management, both Phase 4. + + return app + + +app = create_app() diff --git a/server/src/poorbird/api/delivery.py b/server/src/poorbird/api/delivery.py new file mode 100644 index 0000000..7cf5224 --- /dev/null +++ b/server/src/poorbird/api/delivery.py @@ -0,0 +1,111 @@ +"""Auth-checked file delivery (SPEC 3.3). + +"An unguessable URL is not access control." Every image byte goes through a +route that authorises first; only then is the file delivered. What differs +between environments is *who copies the bytes*, and deliberately nothing else: + +* **Production.** The app answers empty with ``X-Accel-Redirect: /images/...`` + and Caddy serves the file from disk (see deploy/Caddyfile, the + ``protected_files`` snippet). Python never touches the payload, so a 3 MB + JPEG does not occupy a worker thread. +* **Development.** There is no Caddy -- the Vite dev server proxies straight to + uvicorn -- so that header would reach the browser as an empty 200 and every + image would silently be blank. With ``POORBIRD_SERVE_IMAGES_DIRECTLY=true`` + the app sends the bytes itself. + +The authorisation is the *same code either way*. This is not a route that +bypasses auth in development: it is one authorised route with two ways of +finishing. That distinction is the whole point -- a separate unauthenticated +file route "only reachable in dev" is exactly the kind of thing that survives +into production because it works. +""" + +from __future__ import annotations + +import logging +from pathlib import Path + +from fastapi import HTTPException, Response, status +from fastapi.responses import FileResponse + +from ..config import Settings + +log = logging.getLogger(__name__) + +# URL prefixes Caddy maps onto disk. These are coupled to deploy/Caddyfile, +# whose file_server root is the PARENT of image_root and thumb_root -- so the +# last segment of each root has to be exactly this. Change one, change both. +IMAGE_URL_PREFIX = "/images" +THUMB_URL_PREFIX = "/thumbs" + + +def _safe_absolute(root: Path, relative: str) -> Path: + """Resolve ``relative`` under ``root``, or 404. + + ``captures.path`` is written by our own ingest code, so this should never + fire. It is here because the cost of being wrong is serving an arbitrary + file off the server, and "should never" is not a security control. A + traversal attempt is answered as a missing file rather than as a refusal, + because confirming that a path is interesting is itself information. + """ + root = root.resolve() + candidate = (root / relative).resolve() + if candidate != root and root not in candidate.parents: + log.error( + "refusing a path that escapes its root", + extra={"root": str(root), "relative": relative}, + ) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found") + return candidate + + +def deliver( + *, + settings: Settings, + root: Path, + url_prefix: str, + relative: str, + media_type: str, + filename: str, +) -> Response: + """Hand an already-authorised file to the client. + + Callers must have checked permission before reaching here; this function + knows nothing about who is asking. + """ + absolute = _safe_absolute(root, relative) + + if settings.serve_images_directly: + if not absolute.is_file(): + # The row says there is a file and there is not. Worth logging + # loudly: it means the database and the disk have diverged, which + # a backup restore or a half-finished retention run can do. + log.error("capture file is missing from disk", extra={"path": str(absolute)}) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found") + return FileResponse( + absolute, + media_type=media_type, + # Long and immutable: the filename contains the capture UUID and + # the bytes at that path never change. Private, because the whole + # point is that this response was authorised for one person. + headers={ + "Cache-Control": "private, max-age=31536000, immutable", + "Content-Disposition": f'inline; filename="{filename}"', + }, + ) + + # Production: Caddy serves it. The body stays empty on purpose -- if this + # reaches a browser directly it is a deployment mistake, and an empty + # response is a louder symptom than a plausible-looking one. + # + # Existence is deliberately not checked here. Doing so would mean a stat() + # on the request path for a file the app is not going to open, and Caddy + # answers 404 by itself if it is gone. + return Response( + status_code=status.HTTP_200_OK, + headers={ + "X-Accel-Redirect": f"{url_prefix}/{relative}", + "Cache-Control": "private, max-age=31536000, immutable", + "Content-Disposition": f'inline; filename="{filename}"', + }, + ) diff --git a/server/src/poorbird/api/deps.py b/server/src/poorbird/api/deps.py new file mode 100644 index 0000000..7e237ad --- /dev/null +++ b/server/src/poorbird/api/deps.py @@ -0,0 +1,171 @@ +"""Shared dependencies: database sessions and device authentication. + +Device auth is two-step (firmware/API.md). ``POST /enroll`` is guarded by a +shared bootstrap secret in ``X-Enroll-Secret``; everything else carries +``Authorization: Bearer ``. Only hashes are stored. + +Two details here are easy to get wrong, and the reference code in +``docs/reviews/server-basic-implementation/REVIEW.AI.md`` got both wrong, so +they are spelled out: + +1. The plaintext token is returned to the device exactly once, at enrollment, + and only its hash is persisted. Returning the stored hash would give the + device a credential the server cannot recognise and 401 every request after. + +2. Re-enrollment must accept the device's *per-device* ``reenroll_secret`` as + well as the shared bootstrap secret. The firmware swaps the shared secret + for the per-device one the first time the server offers it, so from then on + that is what it presents. Checking only the shared secret would lock out + every device that had successfully enrolled, which is the exact failure the + re-enrollment path exists to prevent -- and the camera cannot be reached + over USB once mounted. +""" + +from __future__ import annotations + +import hashlib +import secrets +import time +from collections.abc import Iterator +from typing import Annotated + +from fastapi import Depends, Header, HTTPException, status +from sqlalchemy import select +from sqlalchemy.orm import Session + +from ..config import Settings, get_settings +from ..db import SessionLocal +from ..models.devices import Device +from .schemas import TOKEN_CHARS + + +def get_db() -> Iterator[Session]: + with SessionLocal() as session: + yield session + + +DbDep = Annotated[Session, Depends(get_db)] +SettingsDep = Annotated[Settings, Depends(get_settings)] + + +def server_time_ms() -> int: + """Epoch milliseconds, UTC. + + Authoritative (SPEC C7). The device adopts this whenever it is unsynced or + more than 2 s out, so the endpoint is the clock even where SNTP is not + reachable -- which is why every device response carries it. + """ + return int(time.time() * 1000) + + +# --- credentials ------------------------------------------------------------ + + +def new_credential() -> str: + """A fresh token or re-enrollment secret: exactly 64 hex characters. + + The firmware stores these in ``char[65]`` (app_config.h), so 64 characters + plus a NUL fits exactly and cannot be silently truncated. API.md documents + "64 hex chars" for both. ``secrets.token_urlsafe(32)``, which REVIEW.AI.md + suggests, yields 43 non-hex characters -- it would fit the buffer but would + not match the documented contract. + """ + return secrets.token_hex(TOKEN_CHARS // 2) + + +def hash_credential(value: str) -> str: + """SHA-256 hex. + + A fast hash, deliberately. API.md: "the token is high-entropy, so a fast + hash is defensible here". These are 256 bits of CSPRNG output, not + passwords -- there is no dictionary to attack, and a per-request Argon2 + would cost every heartbeat. Argon2id belongs on ``users.password_hash`` + (SEC-008), which is a different problem. + """ + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def _matches(presented: str | None, stored_hash: str | None) -> bool: + """Constant-time compare of a presented credential against a stored hash.""" + if not presented or not stored_hash: + return False + return secrets.compare_digest(hash_credential(presented), stored_hash) + + +# --- enrollment ------------------------------------------------------------- + + +def enroll_secret_accepted( + presented: str | None, + settings: Settings, + device: Device | None, +) -> bool: + """True if ``presented`` may enroll (or re-enroll) ``device``. + + Accepts the shared bootstrap secret, or -- for a device that has enrolled + before -- that device's own re-enrollment secret. Both comparisons are + constant-time, and both run even when the first has already succeeded, so + the answer takes the same time either way. + """ + if not presented: + return False + + shared = settings.enroll_secret.get_secret_value() + by_shared = bool(shared) and secrets.compare_digest(presented, shared) + by_device = device is not None and _matches(presented, device.reenroll_secret_hash) + return by_shared or by_device + + +def require_enroll_secret_configured(settings: Settings) -> None: + """503 rather than 500 when the server has no bootstrap secret (SEC-001). + + A camera that gets this should retry later, not treat itself as rejected: + a 4xx would make the firmware clear a perfectly good token. + """ + if not settings.enroll_secret_is_set: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="enrollment is not configured on this server", + ) + + +# --- bearer token ----------------------------------------------------------- + + +def verify_device_token( + db: DbDep, + authorization: Annotated[str | None, Header()] = None, +) -> Device: + """Resolve ``Authorization: Bearer `` to a Device, or 401. + + 401 is load-bearing: the firmware treats it as "clear the stored token and + re-enroll", which is how a rotated token heals itself without a ladder. A + disabled device gets 403 instead, precisely so that it does *not* re-enroll + in a loop (API.md, Behaviour the Pi should expect). + """ + unauthorized = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or missing device token", + headers={"WWW-Authenticate": "Bearer"}, + ) + + if not authorization: + raise unauthorized + scheme, _, token = authorization.partition(" ") + if scheme.lower() != "bearer" or not token.strip(): + raise unauthorized + + # Look the device up by hash. The hash is deterministic, so this is an + # indexed equality match, not a scan over every device. + device = db.scalar(select(Device).where(Device.token_hash == hash_credential(token.strip()))) + if device is None: + raise unauthorized + if not device.enabled: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="device is disabled", + ) + return device + + +DeviceDep = Annotated[Device, Depends(verify_device_token)] diff --git a/server/src/poorbird/api/envelope.py b/server/src/poorbird/api/envelope.py new file mode 100644 index 0000000..6fbb942 --- /dev/null +++ b/server/src/poorbird/api/envelope.py @@ -0,0 +1,108 @@ +"""The response envelope shared by /ingest and /heartbeat. + +SPEC 4.1 and firmware/API.md: both endpoints return the *same* shape, so a +capture that was going to happen anyway also delivers the command queue at no +extra cost. ``parseEnvelope`` in firmware/src/api_client.cpp handles both with +one function, which is why they must not drift. + +``/status`` deliberately does not use this. The device posts status +immediately before deep sleep, and handing it commands there would mark them +delivered to a device that is about to be unable to run them. +""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from sqlalchemy import or_, select +from sqlalchemy.orm import Session + +from ..models.devices import Device, DeviceCommand, Firmware +from .deps import server_time_ms +from .schemas import Command, Envelope, FirmwareTarget + + +def _epoch_ms(value: datetime | None) -> int | None: + if value is None: + return None + if value.tzinfo is None: + value = value.replace(tzinfo=UTC) + return int(value.timestamp() * 1000) + + +def take_pending_commands(db: Session, device: Device) -> list[Command]: + """Claim this device's queued commands and mark them delivered. + + Delivery is recorded here rather than on ack, because the ack may never + come: the device runs ``reboot`` and ``sleep_now`` and is gone. ``acked_at`` + is the separate, later signal that it actually ran. + + Expired commands are skipped but left in place; the worker's + ``prune_expired_commands`` job is what removes them, so the admin UI can + still show that a command timed out rather than silently losing it. + """ + now = datetime.now(UTC) + + rows = list( + db.scalars( + select(DeviceCommand) + .where( + DeviceCommand.device_id == device.id, + DeviceCommand.delivered_at.is_(None), + or_(DeviceCommand.expires_at.is_(None), DeviceCommand.expires_at > now), + ) + .order_by(DeviceCommand.created_at) + ) + ) + + for row in rows: + row.delivered_at = now + + return [ + Command( + id=row.id, + type=row.type, + payload=row.payload, + expires_at=_epoch_ms(row.expires_at), + ) + for row in rows + ] + + +def firmware_target(db: Session, device: Device) -> FirmwareTarget | None: + """The image this device should be running, or None when it is on target. + + Naming a different version is itself the instruction to flash + (main.cpp:104); an explicit ``ota_update`` command is only for staged + rollouts. So "on target" must mean the key is absent, not null. + + The URL is relative on purpose. ota_mgr.cpp:86 appends anything that does + not start with "http" to the API base, which already ends in /api/v1, so + "/firmware/0.2.0.bin" resolves to /api/v1/firmware/0.2.0.bin -- the + endpoint API.md documents. + """ + target = db.scalar(select(Firmware).where(Firmware.is_target.is_(True))) + if target is None or target.version == device.fw_version: + return None + + return FirmwareTarget( + version=target.version, + url=f"/firmware/{target.version}.bin", + sha256=target.sha256, + size=target.size_bytes, + ) + + +def build_envelope(db: Session, device: Device, capture_id: str | None = None) -> Envelope: + """Assemble the envelope, claiming any pending commands as a side effect. + + The caller commits. Nothing here flushes, so a handler that fails after + this point does not leave commands marked delivered that never went out. + """ + return Envelope( + capture_id=capture_id, + server_time=server_time_ms(), + config_version=device.config_version, + firmware=firmware_target(db, device), + commands=take_pending_commands(db, device), + ) diff --git a/server/src/poorbird/api/ratelimit.py b/server/src/poorbird/api/ratelimit.py new file mode 100644 index 0000000..fabf306 --- /dev/null +++ b/server/src/poorbird/api/ratelimit.py @@ -0,0 +1,201 @@ +"""Rate limiting (REVIEW SEC-004). + +A token bucket per key, held in memory. No Redis and no slowapi, for the same +reason the job queue has no Redis (SPEC C8): this deployment is one uvicorn +process serving a handful of cameras on a LAN, and slowapi's default storage +is in-process anyway, so a dependency would buy convenience rather than +capability. + +**That is an assumption with a name.** ``poorbird serve`` runs a single +uvicorn process (cli.py passes no ``workers``). If the deployment ever gains +workers, every worker gets its own buckets and the effective limit multiplies +by the worker count. Move the state to PostgreSQL or Redis at that point -- +do not just widen the numbers. + +Buckets allow a burst and then refill steadily, which is the right shape +here: a camera uploads three to five frames back to back when the radar +fires, then goes quiet. A fixed window would reject the tail of a legitimate +burst that happened to straddle a boundary. + +The limits are deliberately loose. A throttled camera stops delivering +photographs, which on a private LAN is a worse outcome than the flooding the +limit is meant to prevent. These are here to stop something pathological -- +a wedged device in a retry loop, or someone grinding at the enrollment +secret -- not to police normal use. +""" + +from __future__ import annotations + +import threading +import time +from collections import OrderedDict +from dataclasses import dataclass + +from fastapi import HTTPException, Request, status + +from ..config import Settings +from .deps import DeviceDep, SettingsDep + +# Enough for a LAN's worth of cameras and then some. Bounded because the +# enrollment limiter keys on client address, and an unbounded dictionary +# keyed by something a caller influences is itself a way to exhaust memory. +MAX_TRACKED_KEYS = 4096 + + +@dataclass(frozen=True) +class Limit: + """``capacity`` requests available at once, refilled at ``per_second``.""" + + capacity: int + per_second: float + + @classmethod + def per_minute(cls, rate: int, *, burst: int | None = None) -> Limit: + return cls(capacity=burst or rate, per_second=rate / 60.0) + + @classmethod + def per_hour(cls, rate: int, *, burst: int | None = None) -> Limit: + return cls(capacity=burst or rate, per_second=rate / 3600.0) + + +class TokenBuckets: + """Thread-safe token buckets with an LRU bound. + + Handlers are sync ``def``, so FastAPI runs them in a threadpool and two + requests really can land here at once. + """ + + def __init__(self, max_keys: int = MAX_TRACKED_KEYS) -> None: + self._lock = threading.Lock() + self._state: OrderedDict[str, tuple[float, float]] = OrderedDict() + self._max_keys = max_keys + + def take(self, key: str, limit: Limit, *, now: float | None = None) -> float | None: + """Spend one token. Returns None if allowed, else seconds to wait.""" + now = time.monotonic() if now is None else now + + with self._lock: + tokens, last = self._state.get(key, (float(limit.capacity), now)) + tokens = min(limit.capacity, tokens + (now - last) * limit.per_second) + + if tokens >= 1.0: + self._state[key] = (tokens - 1.0, now) + allowed: float | None = None + else: + self._state[key] = (tokens, now) + allowed = (1.0 - tokens) / limit.per_second + + self._state.move_to_end(key) + while len(self._state) > self._max_keys: + self._state.popitem(last=False) + + return allowed + + def reset(self) -> None: + with self._lock: + self._state.clear() + + +BUCKETS = TokenBuckets() + + +def client_address(request: Request) -> str: + """The camera's address, not Caddy's. + + Caddy sets X-Real-IP (deploy/Caddyfile, both blocks). Without it every + camera would share one bucket, since they all arrive from 127.0.0.1 via + the proxy. Trusting the header is safe only because uvicorn binds + loopback and nothing but Caddy can reach it. + """ + forwarded = request.headers.get("x-real-ip") + if forwarded: + return forwarded.strip() + + chain = request.headers.get("x-forwarded-for") + if chain: + return chain.split(",")[0].strip() + + return request.client.host if request.client else "unknown" + + +def _enforce(key: str, limit: Limit, settings: Settings) -> None: + if not settings.rate_limit_enabled: + return + + retry_after = BUCKETS.take(key, limit) + if retry_after is None: + return + + # 429 and not 401: the firmware clears its token on a 401, and being busy + # is not a credential problem. Retry-After gives it something better than + # a guess to back off by. + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail="too many requests", + headers={"Retry-After": str(max(1, int(retry_after + 0.5)))}, + ) + + +def by_address(name: str, limit: Limit): + """Limit by caller address. For endpoints with no device yet.""" + + def dependency(request: Request, settings: SettingsDep) -> None: + _enforce(f"{name}:{client_address(request)}", limit, settings) + + return dependency + + +def by_device(name: str, limit: Limit): + """Limit per device. + + Keyed on the authenticated device rather than the address so that one + misbehaving camera cannot spend another's allowance. Depends on + DeviceDep, which FastAPI resolves once per request, so this adds no + second token lookup. + """ + + def dependency(device: DeviceDep, settings: SettingsDep) -> None: + _enforce(f"{name}:{device.id}", limit, settings) + + return dependency + + +# --- the limits ------------------------------------------------------------- +# +# Each is set well above what the firmware does when healthy, with the +# relevant firmware behaviour noted so the number can be re-derived rather +# than guessed at next time. + +# The device tries its stored secret and then the compiled-in bootstrap one, +# so a single enrollment attempt is up to two requests. Enrollment is rare -- +# first boot, and a token rotation - so this is the one place worth being +# strict: it is where a shared secret could be ground at. +ENROLL = Limit.per_hour(20, burst=6) + +# 5000 captures/day is ~3.5/min, arriving in bursts of three to five frames +# when the radar fires. 120/min with a burst of 40 leaves enormous headroom. +INGEST = Limit.per_minute(120, burst=40) + +# heartbeat_interval_s defaults to 300 and the firmware clamps it to 30, so +# the fastest legitimate cadence is 2/min. Ten times that. +CONDITIONS = Limit.per_minute(20, burst=10) + +# Pulled only when config_version changes, which is operator-driven. +CONFIG = Limit.per_minute(10, burst=5) + +# Acks follow commands, which an operator queues by hand. +ACK = Limit.per_minute(30, burst=15) + +# Whole firmware images. Expensive to serve, and a device needs one rarely; +# a loop here would be a device failing verification over and over. +FIRMWARE = Limit.per_hour(12, burst=3) + +# --- people ----------------------------------------------------------------- + +# Login is the one endpoint where the secret is human-chosen and therefore +# guessable, so this is a real control rather than abuse protection. A person +# mistyping a password needs a handful of tries in quick succession; nobody +# needs sixty an hour. Argon2 already makes each attempt cost tens of +# milliseconds of CPU, which is itself a reason to cap the rate: without this, +# the login endpoint is also the cheapest way to spend the server's CPU. +LOGIN = Limit.per_hour(30, burst=8) diff --git a/server/src/poorbird/api/routes/__init__.py b/server/src/poorbird/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/src/poorbird/api/routes/auth.py b/server/src/poorbird/api/routes/auth.py new file mode 100644 index 0000000..5eefafc --- /dev/null +++ b/server/src/poorbird/api/routes/auth.py @@ -0,0 +1,216 @@ +"""Sign in, sign out, and "who am I" (SPEC 3.1, REVIEW SEC-007). + +The three endpoints ``web/src/auth/AuthProvider.tsx`` was written against, and +the ones it distinguishes carefully: a 404 there means "the server has no auth +yet" and shows a banner, whereas a 401 means "not signed in". Now that these +exist, 404 stops happening and the banner goes away. + +There is no registration endpoint, on purpose. Accounts come from +``poorbird user add`` -- see the note in cli.py. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime + +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status +from sqlalchemy import select +from sqlalchemy.orm import Session as DbSession + +from ...models import AuditLog, User +from ...passwords import hash_password, needs_rehash, verify_password +from ...totp import verify as verify_totp +from .. import ratelimit +from ..deps import DbDep, SettingsDep +from ..ratelimit import client_address +from ..sessions import ( + SESSION_COOKIE, + clear_session_cookies, + create_session, + resolve_session, + revoke_session, + set_session_cookies, +) +from ..ui_schemas import LoginRequest, SessionUser +from ..userauth import SessionDep + +log = logging.getLogger(__name__) + +router = APIRouter(prefix="/auth", tags=["auth"]) + + +def _as_session_user(user: User) -> SessionUser: + return SessionUser( + id=user.id, + username=user.username, + role=user.role, + locale=user.locale, + theme=user.theme, + ) + + +def _audit( + db: DbSession, + *, + action: str, + user_id: int | None, + ip: str | None, + detail: dict | None = None, +) -> None: + """Record an auth event (SPEC 3.1: audit_log on every mutation). + + Failed attempts are recorded as well as successful ones. A log of only the + successes cannot answer the one question worth asking afterwards, which is + how many times someone tried before getting in. + """ + db.add( + AuditLog( + user_id=user_id, + action=action, + entity="session", + entity_id=str(user_id) if user_id is not None else None, + after=detail, + ip=ip[:45] if ip else None, + ) + ) + + +@router.post( + "/login", + response_model=SessionUser, + summary="Sign in and open a session", + # By address, not by username: keying on the username would let an attacker + # lock a known account out by failing at it deliberately, turning a rate + # limit into a denial of service against exactly the person it protects. + dependencies=[Depends(ratelimit.by_address("login", ratelimit.LOGIN))], +) +def login( + body: LoginRequest, + request: Request, + response: Response, + db: DbDep, + settings: SettingsDep, +) -> SessionUser: + """Verify a password and optional TOTP code, then set the session cookies. + + Every failure answers with the same 401 and the same message. Saying "no + such user" would confirm which usernames exist, and saying "wrong code" + would confirm that the password was right -- which is most of what an + attacker wanted to know. + """ + ip = client_address(request) + rejected = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid credentials", + ) + + user = db.scalar(select(User).where(User.username == body.username)) + + # Verify against a hash even when there is no such user, by hashing the + # submitted password and throwing it away. Returning early would make a + # missing username measurably faster than a wrong password, which is a + # username oracle built out of timing. + stored = user.password_hash if user is not None else hash_password(body.password) + password_ok = verify_password(body.password, stored) + + if user is None or not password_ok: + _audit( + db, + action="login_failed", + user_id=user.id if user is not None else None, + ip=ip, + detail={"username": body.username, "reason": "credentials"}, + ) + db.commit() + log.warning("login failed", extra={"username": body.username, "ip": ip}) + raise rejected + + if not user.is_active: + _audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "inactive"}) + db.commit() + log.warning("login refused, account inactive", extra={"username": user.username, "ip": ip}) + raise rejected + + # TOTP is required exactly when the account has a secret. The policy that + # admins must have one is enforced at account creation (cli.py), not here: + # enforcing it at login would let the only admin be locked out by their own + # account, with no way back in through the UI. + if user.totp_secret and not verify_totp(user.totp_secret, body.totp): + _audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "totp"}) + db.commit() + log.warning("login failed on second factor", extra={"username": user.username, "ip": ip}) + raise rejected + + # Login is the only moment the plaintext password exists, so it is the only + # moment the hash can be upgraded to current parameters. + if needs_rehash(user.password_hash or ""): + user.password_hash = hash_password(body.password) + log.info("password hash upgraded", extra={"username": user.username}) + + token, csrf = create_session( + db, + user, + settings=settings, + ip=ip, + user_agent=request.headers.get("user-agent"), + ) + user.last_login_at = datetime.now(UTC) + _audit(db, action="login", user_id=user.id, ip=ip, detail={"totp": bool(user.totp_secret)}) + db.commit() + + set_session_cookies(response, token, csrf, settings=settings) + log.info("login", extra={"username": user.username, "role": user.role, "ip": ip}) + return _as_session_user(user) + + +@router.post( + "/logout", + status_code=status.HTTP_204_NO_CONTENT, + summary="End the current session", +) +def logout( + request: Request, + response: Response, + db: DbDep, + settings: SettingsDep, +) -> None: + """Delete the session row and clear both cookies. + + Deliberately succeeds whether or not there was a session. Signing out is + something a client should always be able to do, and a 401 here would leave a + browser holding a cookie it cannot get rid of. + + The row is deleted rather than flagged, which is what makes this immediate: + the next request cannot resolve a session that is gone. That is the whole + reason sessions are server-side rather than a self-contained token. + """ + token = request.cookies.get(SESSION_COOKIE) + resolved = resolve_session(db, token) if token else None + + revoke_session(db, token) + if resolved is not None: + _audit(db, action="logout", user_id=resolved[1].id, ip=client_address(request)) + log.info("logout", extra={"username": resolved[1].username}) + db.commit() + + # Cookies are set on the injected Response, whose headers FastAPI merges + # into the 204 it sends. Returning a fresh Response here instead would + # discard them, and the logout would appear to work without clearing + # anything. + clear_session_cookies(response, settings=settings) + + +@router.get( + "/session", + response_model=SessionUser, + summary="The signed-in user, or 401", +) +def whoami(resolved: SessionDep) -> SessionUser: + """401 when not signed in, which the UI treats as "anonymous". + + Not 200-with-null: the client already distinguishes 401 (signed out) from + 404 (no auth on this server), and a 200 carrying null would collapse a + working server into the same shape as one that has no auth at all. + """ + return _as_session_user(resolved[1]) diff --git a/server/src/poorbird/api/routes/captures.py b/server/src/poorbird/api/routes/captures.py new file mode 100644 index 0000000..fdccb96 --- /dev/null +++ b/server/src/poorbird/api/routes/captures.py @@ -0,0 +1,287 @@ +"""The gallery: listing captures, and serving their bytes (SPEC 3.3). + +Four routes, all behind a session. Any signed-in role may read the gallery -- +that is what a ``viewer`` is for (SPEC 3.1) -- while a *device* never can: a +device token is scoped to the ingest endpoints and cannot resolve to a user at +all (api/deps.py vs api/userauth.py). + +The image routes authorise and then hand off; see api/delivery.py for why the +bytes are Caddy's job in production and the app's in development. +""" + +from __future__ import annotations + +import base64 +import binascii +import logging +import uuid +from datetime import UTC, datetime +from typing import Annotated + +from fastapi import APIRouter, HTTPException, Query, Response, status +from sqlalchemy import Select, select, tuple_ +from sqlalchemy.orm import selectinload + +from ...models import Capture, Device +from ..delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX, deliver +from ..deps import DbDep, SettingsDep +from ..ui_schemas import CaptureDetail, CapturePage, CaptureSummary +from ..userauth import CurrentUser + +log = logging.getLogger(__name__) + +router = APIRouter(prefix="/captures", tags=["gallery"]) + +# A virtualised grid asks for a screenful at a time. 200 is about four +# screens on a large monitor; beyond that the response is bigger than the +# scroll it serves. +DEFAULT_LIMIT = 50 +MAX_LIMIT = 200 + + +def _encode_cursor(capture: Capture) -> str: + """Opaque-ish cursor: the sort key of the last row on this page. + + Base64 so it does not look like something to hand-edit, not because it is + a secret -- it is a timestamp and a UUID the caller was just given. + """ + raw = f"{capture.received_at.astimezone(UTC).isoformat()}|{capture.id}" + return base64.urlsafe_b64encode(raw.encode()).decode() + + +def _decode_cursor(cursor: str) -> tuple[datetime, uuid.UUID]: + """Parse a cursor, or 422. + + Everything here is caller-supplied, so every failure mode is a bad request + rather than a 500: bad base64, bad UTF-8, a missing separator, an + unparseable timestamp, a malformed UUID. + """ + try: + raw = base64.urlsafe_b64decode(cursor.encode()).decode("utf-8") + stamp, _, ident = raw.partition("|") + if not ident: + raise ValueError("cursor has no id") + return datetime.fromisoformat(stamp), uuid.UUID(ident) + except (ValueError, binascii.Error, UnicodeDecodeError) as exc: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail="invalid cursor", + ) from exc + + +def _apply_filters( + stmt: Select, + *, + device_id: int | None, + received_from: datetime | None, + received_to: datetime | None, + kept: bool | None, + reviewed: bool | None, + pre_trigger: bool | None, + trigger: str | None, +) -> Select: + """Filters over columns that exist today. + + Taxon and tag filters are in TODO Phase 3 and are deliberately not here + yet: both need a join, and neither has any data to join to until the + observation editor and a seeded ``taxa`` table exist. A filter that can + only ever return nothing is worse than an absent one, because the UI would + offer it. + + Dates filter on ``received_at``, never ``captured_at_device``, which is + NULL whenever the camera's clock was unsynced. Filtering on it would + silently drop exactly those frames. + """ + if device_id is not None: + stmt = stmt.where(Capture.device_id == device_id) + if received_from is not None: + stmt = stmt.where(Capture.received_at >= received_from) + if received_to is not None: + stmt = stmt.where(Capture.received_at <= received_to) + if kept is not None: + stmt = stmt.where(Capture.kept == kept) + if reviewed is not None: + stmt = stmt.where(Capture.reviewed == reviewed) + if pre_trigger is not None: + stmt = stmt.where(Capture.pre_trigger == pre_trigger) + if trigger is not None: + stmt = stmt.where(Capture.trigger == trigger) + return stmt + + +def _summary(capture: Capture) -> CaptureSummary: + return CaptureSummary( + id=capture.id, + device_id=capture.device_id, + received_at=capture.received_at, + captured_at_device=capture.captured_at_device, + width=capture.width, + height=capture.height, + bytes=capture.bytes, + trigger=capture.trigger, + pre_trigger=capture.pre_trigger, + burst_id=capture.burst_id, + burst_index=capture.burst_index, + burst_count=capture.burst_count, + reviewed=capture.reviewed, + kept=capture.kept, + has_thumb=capture.thumb_path is not None, + ) + + +@router.get( + "", + response_model=CapturePage, + summary="List captures, newest first", +) +def list_captures( + db: DbDep, + _user: CurrentUser, + limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT, + cursor: Annotated[str | None, Query()] = None, + device_id: Annotated[int | None, Query()] = None, + received_from: Annotated[datetime | None, Query()] = None, + received_to: Annotated[datetime | None, Query()] = None, + kept: Annotated[bool | None, Query()] = None, + reviewed: Annotated[bool | None, Query()] = None, + pre_trigger: Annotated[bool | None, Query()] = None, + trigger: Annotated[str | None, Query()] = None, +) -> CapturePage: + """Newest first, keyset-paginated. + + The sort is ``(received_at DESC, id DESC)``. The id is in the key not for + ordering's sake but because a burst arrives within the same fraction of a + second: on ties, a cursor that only carried the timestamp would either + repeat rows or skip them, and a gallery that loses a frame while scrolling + is a gallery you cannot trust. + """ + stmt = select(Capture) + stmt = _apply_filters( + stmt, + device_id=device_id, + received_from=received_from, + received_to=received_to, + kept=kept, + reviewed=reviewed, + pre_trigger=pre_trigger, + trigger=trigger, + ) + + if cursor is not None: + last_received, last_id = _decode_cursor(cursor) + # Row-value comparison, which maps onto the (device_id, received_at) + # index the same way a plain inequality would and needs no OR. + stmt = stmt.where(tuple_(Capture.received_at, Capture.id) < (last_received, last_id)) + + # One more than asked for, purely to learn whether another page exists + # without also running a COUNT over the whole filtered set. + rows = list( + db.scalars( + stmt.order_by(Capture.received_at.desc(), Capture.id.desc()).limit(limit + 1) + ).all() + ) + + has_more = len(rows) > limit + page = rows[:limit] + return CapturePage( + items=[_summary(c) for c in page], + next_cursor=_encode_cursor(page[-1]) if has_more and page else None, + ) + + +def _get_capture(db: DbDep, capture_id: uuid.UUID) -> Capture: + capture = db.get(Capture, capture_id) + if capture is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture") + return capture + + +@router.get( + "/{capture_id}", + response_model=CaptureDetail, + summary="One capture, with its observations and tags", +) +def get_capture(capture_id: uuid.UUID, db: DbDep, _user: CurrentUser) -> CaptureDetail: + capture = db.scalar( + select(Capture) + .where(Capture.id == capture_id) + # Eager, or rendering one capture with three observations is four + # queries and the pattern repeats per row the moment this is reused. + .options( + selectinload(Capture.observations), + selectinload(Capture.tags), + ) + ) + if capture is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture") + + device = db.get(Device, capture.device_id) + return CaptureDetail( + **_summary(capture).model_dump(), + # The device row is ON DELETE CASCADE from captures, so this is only + # None in a torn state. Naming it rather than crashing. + device_name=device.name if device is not None else "unknown", + sha256=capture.sha256, + radar_state=capture.radar_state, + radar_distance_cm=capture.radar_distance_cm, + radar_energy=capture.radar_energy, + battery_mv=capture.battery_mv, + rssi=capture.rssi, + temp_c=capture.temp_c, + frame_seq=capture.frame_seq, + observations=list(capture.observations), + tags=list(capture.tags), + ) + + +@router.get( + "/{capture_id}/image", + summary="The full JPEG, after an authorisation check", + response_class=Response, +) +def get_capture_image( + capture_id: uuid.UUID, + db: DbDep, + settings: SettingsDep, + _user: CurrentUser, +) -> Response: + capture = _get_capture(db, capture_id) + return deliver( + settings=settings, + root=settings.image_root, + url_prefix=IMAGE_URL_PREFIX, + relative=capture.path, + media_type="image/jpeg", + filename=f"{capture.id}.jpg", + ) + + +@router.get( + "/{capture_id}/thumb", + summary="The 400px WebP thumbnail, after an authorisation check", + response_class=Response, +) +def get_capture_thumb( + capture_id: uuid.UUID, + db: DbDep, + settings: SettingsDep, + _user: CurrentUser, +) -> Response: + capture = _get_capture(db, capture_id) + if capture.thumb_path is None: + # Either the job has not run yet or the frame could not be decoded. + # 404 rather than falling back to the full image: a grid that quietly + # served 200 full-size JPEGs would look like it worked and would be a + # hundred times the bytes. + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="no thumbnail for this capture yet", + ) + return deliver( + settings=settings, + root=settings.thumb_root, + url_prefix=THUMB_URL_PREFIX, + relative=capture.thumb_path, + media_type="image/webp", + filename=f"{capture.id}_400.webp", + ) diff --git a/server/src/poorbird/api/routes/commands.py b/server/src/poorbird/api/routes/commands.py new file mode 100644 index 0000000..0d96b2b --- /dev/null +++ b/server/src/poorbird/api/routes/commands.py @@ -0,0 +1,81 @@ +"""POST /api/v1/commands/{command_id}/ack -- the other half of the queue. + +/heartbeat and /ingest hand commands out and mark them delivered. This is +where the device reports what became of one. The two halves are deliberately +separate: delivery is recorded when the command goes out, because the ack may +never arrive -- ``reboot`` and ``sleep_now`` are acked and then the device is +gone, and a device that dies mid-command never acks at all. ``delivered_at`` +therefore means "we handed it over" and ``acked_at`` means "it ran", and the +gap between them is the interesting operational signal. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime + +from fastapi import APIRouter, Depends, HTTPException, Response, status +from sqlalchemy import select + +from ...models.devices import DeviceCommand +from .. import ratelimit +from ..deps import DbDep, DeviceDep +from ..schemas import CommandAck + +log = logging.getLogger(__name__) + +router = APIRouter() + + +@router.post( + "/commands/{command_id}/ack", + status_code=status.HTTP_204_NO_CONTENT, + response_class=Response, + summary="Report the outcome of a command", + tags=["devices"], + dependencies=[Depends(ratelimit.by_device("ack", ratelimit.ACK))], +) +def ack_command( + command_id: int, + body: CommandAck, + db: DbDep, + device: DeviceDep, +) -> Response: + command = db.scalar( + select(DeviceCommand).where( + DeviceCommand.id == command_id, + # Scoped to the calling device. Command ids are sequential, so + # without this a device could ack -- and probe for -- every other + # device's queue. + DeviceCommand.device_id == device.id, + ) + ) + + # 404 rather than 403 for someone else's command: a different code here + # would confirm that the id exists, which is the thing worth not saying. + if command is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such command") + + # Re-acking is allowed and the last word wins. The device retries on a + # timeout, and it cannot tell a lost response from a lost request, so + # refusing the second attempt would strand a command that did in fact run. + command.acked_at = datetime.now(UTC) + command.ack_status = body.status + # The firmware always sends the key, empty when it has nothing to say. + command.result = body.detail or None + + db.commit() + + log.info( + "command acked", + extra={ + "device_id": device.id, + "command_id": command.id, + "type": command.type, + "ack_status": command.ack_status, + }, + ) + + # Liveness stays with /heartbeat on purpose, so the device list has one + # source of truth for "when did we last hear from it". + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/src/poorbird/api/routes/conditions.py b/server/src/poorbird/api/routes/conditions.py new file mode 100644 index 0000000..d24d246 --- /dev/null +++ b/server/src/poorbird/api/routes/conditions.py @@ -0,0 +1,141 @@ +"""POST /api/v1/heartbeat and POST /api/v1/status -- one body, two endpoints. + +Both take the identical conditions payload (firmware/src/api_client.cpp builds +it once, in ``buildConditions``). They differ only in the response: + +* ``/heartbeat`` -> 200 and the envelope: commands, config version, firmware + target. +* ``/status`` -> 204 and nothing. + +The split is not cosmetic. The device posts status immediately before deep +sleep, and pulling down a command queue at that moment would mark commands +delivered that the device is about to become unable to execute. So /status +deliberately returns nothing actionable (API.md). + +A heartbeat the endpoint *accepts* is also what confirms an OTA trial boot: +the device calls esp_ota_mark_app_valid only after one succeeds. Returning 5xx +to a device on a trial image will roll it back -- correct behaviour, but worth +knowing before restarting the server mid-rollout. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime + +from fastapi import APIRouter, Depends, Response, status + +from ...models.devices import DeviceStatus +from .. import ratelimit +from ..deps import DbDep, DeviceDep +from ..envelope import build_envelope +from ..schemas import DeviceConditions, Envelope + +log = logging.getLogger(__name__) + +router = APIRouter() + +# Reasons that mean "this is the last thing I will say for a while". +_GOING_QUIET = {"before_sleep", "before_night_sleep"} + + +def _record(db: DbDep, device, body: DeviceConditions) -> None: + """Append a telemetry row and refresh the device's last-known conditions. + + The row is the time series; the columns on ``devices`` are a denormalised + copy so the device list does not need a correlated subquery per row. + """ + raw = body.model_dump(mode="json") + + db.add( + DeviceStatus( + device_id=device.id, + reason=body.reason, + battery_mv=body.battery.mv, + battery_pct=body.battery.pct, + battery_valid=body.battery.valid, + awake_ms=body.power.awake_ms, + boot_count=body.power.boot_count, + wake_cause=body.power.wake_cause, + last_sleep_s=body.power.last_sleep_s, + total_sleep_s=body.power.total_sleep_s, + captured_today=body.counters.captured_today, + delivered_today=body.counters.delivered_today, + failed_today=body.counters.failed_today, + events_today=body.counters.events_today, + day_index=body.counters.day_index, + is_night=body.night.is_night, + nightlight_on=body.night.nightlight_on, + cam_profile=body.camera.profile, + radar_baud=body.radar.baud, + radar_uart_ok=body.radar.uart_ok, + stream_active=body.stream.active, + rssi=body.system.rssi, + ip=body.system.ip, + free_heap=body.system.free_heap, + free_psram=body.system.free_psram, + ring_depth=body.system.ring_depth, + time_synced=body.time_synced, + device_time=body.device_time, + fw_version=body.fw_version, + config_version=body.config_version, + # Everything as posted, including keys this server does not know + # about yet. The flat columns above are what is worth charting. + raw=raw, + ) + ) + + device.last_seen_at = datetime.now(UTC) + + # Only overwrite a denormalised value when the device actually reported + # one. None means "not sent", which must not erase a good earlier reading. + if body.battery.mv is not None: + device.battery_mv = body.battery.mv + if body.battery.pct is not None: + device.battery_pct = body.battery.pct + if body.battery.valid is not None: + # false means NOT MEASURED, not empty. Stored as reported so the UI can + # render an em dash instead of inventing a low-battery alarm. + device.battery_valid = body.battery.valid + if body.system.rssi is not None: + device.rssi = body.system.rssi + if body.fw_version is not None: + device.fw_version = body.fw_version + + # A device that has just announced it is going to sleep will not answer + # commands, and the UI should say so rather than show it as reachable. + device.awake = body.reason not in _GOING_QUIET + + # device.config_version is the server's intent and is NOT touched here. + # body.config_version is what the device currently runs; the difference is + # exactly what tells it to GET /config. + + +@router.post( + "/heartbeat", + response_model=Envelope, + response_model_exclude_none=True, + summary="Device conditions; returns the command envelope", + tags=["devices"], + dependencies=[Depends(ratelimit.by_device("heartbeat", ratelimit.CONDITIONS))], +) +def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope: + _record(db, device, body) + envelope = build_envelope(db, device) + db.commit() + return envelope + + +@router.post( + "/status", + status_code=status.HTTP_204_NO_CONTENT, + response_class=Response, + summary="Device conditions; returns nothing actionable", + tags=["devices"], + dependencies=[Depends(ratelimit.by_device("status", ratelimit.CONDITIONS))], +) +def device_status(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Response: + _record(db, device, body) + db.commit() + # Deliberately no envelope: see the module docstring. + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/src/poorbird/api/routes/device_config.py b/server/src/poorbird/api/routes/device_config.py new file mode 100644 index 0000000..f715987 --- /dev/null +++ b/server/src/poorbird/api/routes/device_config.py @@ -0,0 +1,72 @@ +"""GET /api/v1/config -- the device's settings document. + +Named device_config.py so it does not read as poorbird.config, which is the +server's own settings. The route is /config, as API.md specifies. + +The response is a free-form JSON object by design. ``devices.config`` is one +JSONB document rather than forty columns because the firmware grows tunables +faster than a schema should change, and the device merges and clamps whatever +arrives: keys it does not know are ignored, keys that are absent leave its +current value alone, and dangerous values are clamped on the device itself +(app_config.cpp, configApplyJson). Partial documents are therefore not a +degraded case -- they are the normal one. + +That is also why there is no response model. Validating this shape belongs on +the write path, when the admin UI saves a config, not on the way out to a +device that is going to re-validate it anyway. + +This is a read. It deliberately does not touch last_seen_at: a GET should not +have side effects, and /heartbeat is what records liveness (API.md). +""" + +from __future__ import annotations + +import logging +from typing import Any + +from fastapi import APIRouter, Depends + +from .. import ratelimit +from ..deps import DeviceDep + +log = logging.getLogger(__name__) + +router = APIRouter() + +# Settings that live in real columns on `devices` rather than in the JSONB, +# because the server queries and lists on them. They are still config keys as +# far as the firmware is concerned, so they have to be merged into the +# document on the way out or a change to the column would never reach the +# camera. +# +# device_name is the interesting one: enrollment deliberately does not let a +# device overwrite an operator's rename, and this is the path by which that +# rename actually reaches the device (app_config.cpp:307). +_COLUMN_BACKED = ( + ("device_name", "name"), + ("heartbeat_interval_s", "heartbeat_interval_s"), + ("status_interval_s", "status_interval_s"), +) + + +@router.get( + "/config", + summary="The device's full settings document", + tags=["devices"], + dependencies=[Depends(ratelimit.by_device("config", ratelimit.CONFIG))], +) +def get_config(device: DeviceDep) -> dict[str, Any]: + # Start from the stored document, then let the column-backed keys win. + # The columns are the modelled source of truth; a stale copy of one of + # them inside the JSONB must not shadow it. + document: dict[str, Any] = dict(device.config or {}) + + for key, attr in _COLUMN_BACKED: + document[key] = getattr(device, attr) + + # Last, mirroring configApplyJson, which applies config_version only after + # the rest of the payload has been processed. This is the only value the + # device compares, so it must describe the document it arrived with. + document["config_version"] = device.config_version + + return document diff --git a/server/src/poorbird/api/routes/enroll.py b/server/src/poorbird/api/routes/enroll.py new file mode 100644 index 0000000..296c769 --- /dev/null +++ b/server/src/poorbird/api/routes/enroll.py @@ -0,0 +1,127 @@ +"""POST /api/v1/enroll -- device enrollment and re-enrollment. + +The only device endpoint not guarded by a bearer token, because it is where +the token comes from. It is guarded by ``X-Enroll-Secret`` instead: either the +shared bootstrap secret, or the device's own re-enrollment secret once it has +one (firmware/API.md, Authentication). + +Re-enrollment is a normal, expected operation, not an error path. The firmware +re-enrolls on any 401, which is how a token rotated in the admin UI heals +itself without anyone climbing to the camera. API.md is explicit that a known +``device_uid`` must return the existing row with a fresh token rather than a +duplicate -- expect it on every rotation and after any database restore. +""" + +from __future__ import annotations + +import logging + +from fastapi import APIRouter, Depends, Header, HTTPException, status +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError + +from ...models.devices import Device +from .. import ratelimit +from ..deps import ( + DbDep, + SettingsDep, + enroll_secret_accepted, + hash_credential, + new_credential, + require_enroll_secret_configured, + server_time_ms, +) +from ..schemas import EnrollRequest, EnrollResponse + +log = logging.getLogger(__name__) + +router = APIRouter() + + +@router.post( + "/enroll", + status_code=status.HTTP_201_CREATED, + response_model=EnrollResponse, + summary="Enroll a device, or re-issue its token", + tags=["devices"], + # Keyed by caller address: there is no device to key on yet, and this is + # the one endpoint where a shared secret could be ground at (SEC-004). + dependencies=[Depends(ratelimit.by_address("enroll", ratelimit.ENROLL))], +) +def enroll( + body: EnrollRequest, + db: DbDep, + settings: SettingsDep, + x_enroll_secret: str | None = Header(default=None), +) -> EnrollResponse: + # 503 before anything else: a server with no bootstrap secret is + # misconfigured, not rejecting this particular device. A 4xx here would + # make the firmware discard a token that is probably still good. + require_enroll_secret_configured(settings) + + device = db.scalar(select(Device).where(Device.device_uid == body.device_uid)) + + # The lookup has to come first, because a returning device presents its own + # per-device secret rather than the shared one. + if not enroll_secret_accepted(x_enroll_secret, settings, device): + log.warning("enrollment refused", extra={"device_uid": body.device_uid}) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid enrollment secret", + ) + + # A disabled device must not be able to re-enroll its way back in, or + # disabling it in the admin UI would mean nothing: it would simply collect + # a fresh token on its next 401. + if device is not None and not device.enabled: + log.warning("enrollment refused for disabled device", extra={"device_uid": body.device_uid}) + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="device is disabled") + + token = new_credential() + reenroll_secret = new_credential() + returning = device is not None + + if device is None: + device = Device(device_uid=body.device_uid, name=body.device_name) + db.add(device) + + # Hardware facts always follow the device: it is the authority on what it + # is running. The name deliberately does not -- it is set once at first + # enrollment and is an operator-facing label after that, so a re-enrollment + # must not silently undo a rename made in the admin UI. + device.mac = body.mac + device.hw_revision = body.hw_revision + device.fw_version = body.fw_version + + device.token_hash = hash_credential(token) + device.reenroll_secret_hash = hash_credential(reenroll_secret) + + try: + db.commit() + except IntegrityError: + # Two enrollments of the same device_uid racing each other. 503 rather + # than 409: it is transient and the firmware already retries, whereas a + # 4xx reads as "this device is not welcome". + db.rollback() + log.warning("enrollment raced", extra={"device_uid": body.device_uid}) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="enrollment is busy, retry", + ) from None + + db.refresh(device) + log.info( + "device re-enrolled" if returning else "device enrolled", + extra={"device_uid": device.device_uid, "device_id": device.id}, + ) + + # The plaintext token and secret exist here and nowhere else. Only their + # hashes were stored, so this response is the single opportunity to hand + # them to the device. + return EnrollResponse( + token=token, + device_id=device.id, + reenroll_secret=reenroll_secret, + server_time=server_time_ms(), + config_version=device.config_version, + ) diff --git a/server/src/poorbird/api/routes/firmware.py b/server/src/poorbird/api/routes/firmware.py new file mode 100644 index 0000000..1032f86 --- /dev/null +++ b/server/src/poorbird/api/routes/firmware.py @@ -0,0 +1,112 @@ +"""GET /api/v1/firmware/{version}.bin -- the OTA image. + +Bearer auth, like every other device endpoint. Three things the device +requires of this response, all checked before it erases a partition +(firmware/src/ota_mgr.cpp:110-128): + +1. status exactly 200, +2. a ``Content-Length`` header -- it refuses a chunked response, because it + wants to size-check before committing to an erase, +3. that length equal to the ``size`` the envelope advertised. + +So this must not be compressed or chunked on the way out. The camera talks to +the :8080 Caddy block, which has no ``encode`` directive, and FileResponse +sets an exact Content-Length from the file itself. + +The admin-facing ``POST /api/v1/firmware`` from API.md is not here: it needs +user authentication and an admin role, neither of which exists yet +(REVIEW SEC-007). Rows are expected to arrive by other means until then. +""" + +from __future__ import annotations + +import logging +from pathlib import Path + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.responses import FileResponse +from sqlalchemy import select + +from ...config import Settings +from ...models.devices import Firmware +from .. import ratelimit +from ..deps import DbDep, DeviceDep, SettingsDep + +log = logging.getLogger(__name__) + +router = APIRouter() + + +def _resolve(file_path: str, settings: Settings) -> Path: + """Where the image actually lives. + + An absolute path is used as given; a relative one resolves under the + state directory. The value comes from the firmware row, which only an + administrator can write -- it is never built from anything in the + request, so there is no traversal to defend against here. The upload + endpoint that eventually writes it is where that check belongs. + """ + candidate = Path(file_path) + return candidate if candidate.is_absolute() else settings.state_dir / "firmware" / candidate + + +@router.get( + "/firmware/{version}.bin", + response_class=FileResponse, + summary="Download an OTA image", + tags=["firmware"], + dependencies=[Depends(ratelimit.by_device("firmware", ratelimit.FIRMWARE))], +) +def download_firmware( + version: str, + db: DbDep, + device: DeviceDep, + settings: SettingsDep, +) -> FileResponse: + row = db.scalar(select(Firmware).where(Firmware.version == version)) + if row is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such firmware") + + path = _resolve(row.file_path, settings) + + if not path.is_file(): + # The row promises an image that is not there. 503 rather than 404: + # the firmware genuinely exists as far as the operator is concerned, + # and this is a server fault worth shouting about rather than a + # missing resource. + log.error( + "firmware row points at a missing file", + extra={"version": row.version, "path": str(path)}, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="firmware image unavailable", + ) + + # The device compares Content-Length against the size the envelope gave + # it and aborts on a mismatch. Catching that here turns a confusing + # device-side abort into one clear line in the server log. + actual = path.stat().st_size + if actual != row.size_bytes: + log.error( + "firmware size does not match its row", + extra={"version": row.version, "recorded": row.size_bytes, "on_disk": actual}, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="firmware image does not match its manifest", + ) + + log.info( + "serving firmware", + extra={"version": row.version, "device_id": device.id, "bytes": actual}, + ) + + return FileResponse( + path, + media_type="application/octet-stream", + filename=f"{row.version}.bin", + # The image is immutable for a given version, and the device verifies + # SHA-256 over the whole thing before activating the slot anyway. + headers={"Cache-Control": "public, max-age=31536000, immutable"}, + ) diff --git a/server/src/poorbird/api/routes/health.py b/server/src/poorbird/api/routes/health.py new file mode 100644 index 0000000..69fb70e --- /dev/null +++ b/server/src/poorbird/api/routes/health.py @@ -0,0 +1,82 @@ +"""Health. + +Two endpoints on purpose: + +* ``/api/v1/health`` always answers 200 with detail, because the WebUI banner + wants to *render* a degraded system, not fail to load. +* ``/healthz`` answers 503 when the database is unreachable, because that is + what a proxy or a monitor should act on. +""" + +from __future__ import annotations + +import shutil +import time +from typing import Any + +from fastapi import APIRouter, Response +from sqlalchemy import func, select, text + +from ... import __version__ +from ...config import get_settings +from ...db import SessionLocal +from ...models import BackupRun, Capture, Device + +router = APIRouter() +# Mounted at the root, not under /api/v1: proxies and monitors expect /healthz +# where it has always been. +root_router = APIRouter() +_STARTED = time.monotonic() + + +def _db_probe() -> tuple[bool, str | None, dict[str, Any]]: + facts: dict[str, Any] = {} + try: + with SessionLocal() as s: + s.execute(text("SELECT 1")) + facts["devices"] = s.scalar(select(func.count()).select_from(Device)) + facts["captures"] = s.scalar(select(func.count()).select_from(Capture)) + last_backup = s.scalar(select(func.max(BackupRun.finished_at))) + facts["last_backup_at"] = last_backup.isoformat() if last_backup else None + return True, None, facts + except Exception as exc: # noqa: BLE001 - the point is to report, not raise + return False, f"{type(exc).__name__}: {exc}", facts + + +def _disk() -> dict[str, Any]: + settings = get_settings() + try: + usage = shutil.disk_usage(settings.image_root) + except OSError: + # Not yet created, or not mounted. Both are real conditions to report. + return {"available": False, "path": str(settings.image_root)} + return { + "available": True, + "path": str(settings.image_root), + "total_bytes": usage.total, + "free_bytes": usage.free, + "used_pct": round(100 * usage.used / usage.total, 1) if usage.total else None, + } + + +@router.get("/health", summary="System health, always 200") +def health() -> dict[str, Any]: + db_ok, db_error, facts = _db_probe() + settings = get_settings() + return { + "status": "ok" if db_ok else "degraded", + "version": __version__, + "uptime_s": round(time.monotonic() - _STARTED, 1), + "database": {"ok": db_ok, "error": db_error, **facts}, + "disk": _disk(), + "enroll_secret_configured": settings.enroll_secret_is_set, + } + + +@root_router.get("/healthz", include_in_schema=False) +def healthz(response: Response) -> dict[str, str]: + db_ok, _, _ = _db_probe() + if not db_ok: + response.status_code = 503 + return {"status": "unavailable"} + return {"status": "ok"} diff --git a/server/src/poorbird/api/routes/ingest.py b/server/src/poorbird/api/routes/ingest.py new file mode 100644 index 0000000..1098b59 --- /dev/null +++ b/server/src/poorbird/api/routes/ingest.py @@ -0,0 +1,220 @@ +"""POST /api/v1/ingest -- a captured frame. + +**Deviation from SPEC 4.1, and a deliberate one.** The spec says +multipart/form-data with the image and a JSON metadata part. The firmware +sends the raw JPEG as the body with the metadata in headers, because +multipart would make the device assemble a second buffer purely to add a +wrapper the server strips immediately; the raw body hands the framebuffer +pointer straight to the HTTP client (firmware/API.md). REVIEW.AI.md's +reference code implemented the multipart version and would not have matched +the firmware at all. + +Returns the same envelope as /heartbeat, so a capture that was going to +happen anyway also delivers the command queue at no extra cost. +""" + +from __future__ import annotations + +import hashlib +import logging +import uuid +from datetime import UTC, datetime +from typing import Annotated + +from fastapi import APIRouter, Body, Depends, Header, HTTPException, status +from pydantic import ValidationError +from sqlalchemy import select + +from ...images import ( + MAX_IMAGE_BYTES, + jpeg_dimensions, + looks_like_jpeg, + relative_image_path, + write_atomically, +) +from ...models.captures import Capture +from ...worker.queue import enqueue +from .. import ratelimit +from ..deps import DbDep, DeviceDep, SettingsDep +from ..envelope import build_envelope +from ..schemas import Envelope, IngestMeta + +log = logging.getLogger(__name__) + +router = APIRouter() + + +def ingest_meta( + x_trigger: Annotated[str, Header()] = "radar", + x_burst_id: Annotated[str | None, Header()] = None, + x_burst_index: Annotated[int | None, Header()] = None, + x_burst_count: Annotated[int | None, Header()] = None, + x_pre_trigger: Annotated[int, Header()] = 0, + x_captured_at: Annotated[int, Header()] = 0, + x_frame_seq: Annotated[int | None, Header()] = None, + x_radar_state: Annotated[int | None, Header()] = None, + x_radar_distance_cm: Annotated[int | None, Header()] = None, + x_radar_energy: Annotated[int | None, Header()] = None, + x_rssi: Annotated[int | None, Header()] = None, +) -> IngestMeta: + """Validate the header metadata into one model (REVIEW SEC-003).""" + try: + return IngestMeta( + trigger=x_trigger, + burst_id=x_burst_id or None, + burst_index=x_burst_index, + burst_count=x_burst_count, + pre_trigger=bool(x_pre_trigger), + # X-Captured-At: 0 means the device clock is unsynced. That is + # NULL, not 1970 -- storing an epoch date here would put the frame + # at the bottom of every chronological view forever (API.md). + captured_at=( + datetime.fromtimestamp(x_captured_at / 1000, UTC) if x_captured_at > 0 else None + ), + frame_seq=x_frame_seq, + radar_state=x_radar_state, + radar_distance_cm=x_radar_distance_cm, + radar_energy=x_radar_energy, + rssi=x_rssi, + ) + except ValidationError as exc: + # A dependency raising ValidationError would otherwise surface as a + # 500. The metadata is client input; it deserves a 422. + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail=exc.errors(include_url=False), + ) from None + + +@router.post( + "/ingest", + status_code=status.HTTP_201_CREATED, + response_model=Envelope, + response_model_exclude_none=True, + summary="Accept a captured frame; returns the command envelope", + tags=["captures"], + dependencies=[Depends(ratelimit.by_device("ingest", ratelimit.INGEST))], +) +def ingest( + db: DbDep, + device: DeviceDep, + settings: SettingsDep, + meta: Annotated[IngestMeta, Depends(ingest_meta)], + body: Annotated[bytes, Body(media_type="image/jpeg")] = b"", +) -> Envelope: + if not body: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="empty body") + if len(body) > MAX_IMAGE_BYTES: + raise HTTPException( + status_code=status.HTTP_413_CONTENT_TOO_LARGE, + detail=f"image exceeds {MAX_IMAGE_BYTES} bytes", + ) + # Trust the bytes, not the Content-Type. 400 and not 401: the device must + # not read this as a credential problem and clear a perfectly good token. + if not looks_like_jpeg(body): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="body is not a JPEG") + + digest = hashlib.sha256(body).hexdigest() + + # The device retries an upload whose response was lost, and it cannot tell + # that case from a genuine failure. Identical bytes from the same device + # are that retry -- two real frames never collide, since sensor noise + # alone makes every capture unique. Returning the original capture keeps + # ingest idempotent instead of filling the gallery with duplicates. + # + # Scoped to the device, and checked in the application rather than with a + # unique constraint: a genuine collision should lose a frame, not 500. + # Burst uploads are sequential (API.md), so there is no race to lose. + existing = db.scalar( + select(Capture).where(Capture.device_id == device.id, Capture.sha256 == digest) + ) + if existing is not None: + log.info( + "ingest de-duplicated", + extra={"device_id": device.id, "capture_id": str(existing.id)}, + ) + envelope = build_envelope(db, device, capture_id=str(existing.id)) + db.commit() + return envelope + + capture_id = uuid.uuid4() + received_at = datetime.now(UTC) + relative = relative_image_path(capture_id, received_at) + destination = settings.image_root / relative + + try: + write_atomically(destination, body) + except OSError as exc: + # Disk full, root not mounted, permissions. 503 rather than 500: it is + # transient from the device's point of view and it should retry. + log.error("cannot write capture", extra={"path": str(destination), "error": str(exc)}) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="image storage unavailable", + ) from None + + dimensions = jpeg_dimensions(body) + + capture = Capture( + id=capture_id, + device_id=device.id, + path=relative, + # Filled in by the thumbnail job below. NULL means "not yet", which + # the gallery has to handle regardless: a capture is visible the + # moment it lands, not once it has been processed. + thumb_path=None, + sha256=digest, + width=dimensions[0] if dimensions else None, + height=dimensions[1] if dimensions else None, + bytes=len(body), + captured_at_device=meta.captured_at, + received_at=received_at, + trigger=meta.trigger, + burst_id=meta.burst_id, + burst_index=meta.burst_index, + burst_count=meta.burst_count, + pre_trigger=meta.pre_trigger, + frame_seq=meta.frame_seq, + radar_state=meta.radar_state, + radar_distance_cm=meta.radar_distance_cm, + radar_energy=meta.radar_energy, + rssi=meta.rssi, + ) + db.add(capture) + + device.last_seen_at = received_at + if meta.rssi is not None: + device.rssi = meta.rssi + + # Off the request path on purpose: decoding a frame to resize it is the + # one genuinely expensive thing about a capture, and the device is + # waiting on this response with a burst still to upload. Enqueued in the + # same transaction as the row, so the worker never sees a job for a + # capture that was rolled back. + enqueue(db, "thumbnail", {"capture_id": str(capture_id)}) + + envelope = build_envelope(db, device, capture_id=str(capture_id)) + + try: + db.commit() + except Exception: + # The file is already on disk. Remove it rather than leave an orphan + # that nothing references. The reverse order -- row first, file second + # -- would be worse: a row pointing at a missing image is a broken + # gallery entry, whereas a stray file is invisible and sweepable. + db.rollback() + destination.unlink(missing_ok=True) + raise + + log.info( + "capture ingested", + extra={ + "device_id": device.id, + "capture_id": str(capture_id), + "bytes": len(body), + "trigger": meta.trigger, + "pre_trigger": meta.pre_trigger, + }, + ) + + return envelope diff --git a/server/src/poorbird/api/schemas.py b/server/src/poorbird/api/schemas.py new file mode 100644 index 0000000..bc189d5 --- /dev/null +++ b/server/src/poorbird/api/schemas.py @@ -0,0 +1,283 @@ +"""Request and response shapes for the device API (REVIEW SEC-003). + +The contract is ``firmware/API.md``, and where it disagrees with SPEC.md the +firmware wins, because the firmware is what is actually on the camera. Two +places where that matters are called out inline: ``/ingest`` carries a raw JPEG +body with metadata in headers, not multipart, and the enrollment body field is +``device_name``, not ``name``. + +Nothing here talks to the database. These models exist so that a malformed or +hostile request is rejected at the edge with a 422, before any handler reaches +for a session. + +One deliberate looseness: the conditions models accept unknown keys. The +firmware grows fields faster than the server learns about them, and +``device_status.raw`` exists precisely to keep the whole posted body. Rejecting +a camera because it reports something new would be the wrong failure. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from ..models.captures import TRIGGERS +from ..models.devices import COMMAND_TYPES, STATUS_REASONS + +Trigger = Literal[TRIGGERS] # type: ignore[valid-type] +StatusReason = Literal[STATUS_REASONS] # type: ignore[valid-type] +CommandType = Literal[COMMAND_TYPES] # type: ignore[valid-type] + +# The firmware holds these in char[65], so 64 characters plus a NUL. Issue +# exactly 64 hex characters and a token can never be silently truncated on the +# device (firmware/include/app_config.h). +TOKEN_CHARS = 64 + + +class _Loose(BaseModel): + """Base for anything the firmware posts: keep unknown keys, do not 422.""" + + model_config = ConfigDict(extra="allow") + + +# --- enrollment ------------------------------------------------------------- + + +class EnrollRequest(BaseModel): + model_config = ConfigDict(extra="ignore") + + # eFuse MAC in hex. Survives reflashing, which is what makes it an identity + # rather than a name (API.md, Enrollment). + device_uid: Annotated[str, Field(min_length=6, max_length=32, pattern=r"^[0-9a-fA-F]+$")] + # API.md calls this device_name. REVIEW.AI.md calls it name; the firmware + # sends device_name, so that is what this is. + device_name: Annotated[str, Field(min_length=1, max_length=64)] + hw_revision: Annotated[str | None, Field(max_length=64)] = None + fw_version: Annotated[str | None, Field(max_length=32)] = None + mac: Annotated[str | None, Field(max_length=32)] = None + + +class EnrollResponse(BaseModel): + """201. The token is returned in the clear exactly once, here. + + Only its hash is stored. Returning the stored hash instead would hand the + device a credential the server cannot recognise, and every later request + would 401. + """ + + token: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)] + device_id: int + reenroll_secret: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)] + server_time: int # epoch ms, UTC, authoritative (SPEC C7) + config_version: int + + +# --- the shared response envelope ------------------------------------------- + + +class FirmwareTarget(BaseModel): + version: str + url: str + sha256: Annotated[str, Field(min_length=64, max_length=64)] + size: int + + +class Command(BaseModel): + id: int + type: CommandType + payload: dict[str, Any] | None = None + expires_at: int | None = None # epoch ms; the firmware ignores it, the server prunes on it + + +class Envelope(BaseModel): + """Returned by /ingest and /heartbeat, identically (API.md, SPEC 4.1). + + ``capture_id`` is documented as an integer in API.md's example, but + ``captures.id`` is a UUID and the firmware never reads the field back + (verified in firmware/src/api_client.cpp::parseEnvelope, which pulls only + server_time, config_version, firmware and commands). Sent as a UUID string. + """ + + capture_id: str | None = None + server_time: int + config_version: int + # Omit the key entirely when the device is on target: present-and-different + # is itself the signal to flash (API.md). Omission is a serialisation + # concern, so the routes set response_model_exclude_none=True rather than + # anything here. + firmware: FirmwareTarget | None = None + commands: list[Command] = Field(default_factory=list) + + +# --- ingest ----------------------------------------------------------------- + + +class IngestMeta(BaseModel): + """Metadata for POST /ingest, which arrives in headers, not a body. + + Deviation from SPEC 4.1, and a deliberate one: the raw JPEG is the body, so + the device hands over its framebuffer pointer without assembling a second + multipart buffer (API.md). REVIEW.AI.md's reference code used multipart and + would not have matched the firmware. + """ + + model_config = ConfigDict(extra="ignore") + + trigger: Trigger + burst_id: Annotated[str | None, Field(max_length=64)] = None + burst_index: int | None = None + burst_count: int | None = None + pre_trigger: bool = False + # epoch ms UTC. 0 means the device clock is unsynced: that is NULL, not + # 1970 (API.md). received_at stays authoritative either way (SPEC C7). + captured_at: datetime | None = None + frame_seq: int | None = None + radar_state: Annotated[int | None, Field(ge=0, le=3)] = None + radar_distance_cm: int | None = None + radar_energy: Annotated[int | None, Field(ge=0, le=100)] = None + # From X-Rssi, one of the common headers on every authenticated request + # rather than an ingest-specific one, but captures.rssi is the column it + # belongs in: signal strength at the moment this frame was uploaded. + rssi: int | None = None + + +# --- device conditions: one body, two endpoints ----------------------------- +# +# POST /heartbeat -> 200 + Envelope, POST /status -> 204 and nothing. +# The split is not cosmetic: the device posts status immediately before deep +# sleep, and handing it commands at that moment would mark them delivered to a +# device that is about to be unable to run them (API.md). + + +class PowerBlock(_Loose): + uptime_ms: int | None = None + # Resets on every wake, unlike uptime_ms which resets only on reboot. + awake_ms: int | None = None + boot_count: int | None = None + wake_cause: Annotated[str | None, Field(max_length=16)] = None + last_sleep_s: int | None = None + total_sleep_s: int | None = None + sleep_enabled: bool | None = None + sleep_allowed: bool | None = None + inhibits: str | None = None + + +class BatteryBlock(_Loose): + # false means NOT MEASURED, not empty: no divider is wired by default. + # Render as an em dash, never as a low-battery alarm (API.md). + valid: bool | None = None + mv: int | None = None + pct: Annotated[int | None, Field(ge=0, le=100)] = None + raw_mv: int | None = None + # 0 means pct is meaningless; show the voltage only. + chemistry: int | None = None + low: bool | None = None + + +class CountersBlock(_Loose): + """The device's opinion, not the truth: RTC memory, reset on power loss. + + ``captures`` is authoritative. What these are genuinely good for is the gap + between captured_today and delivered_today, which is an upload-health + signal you would otherwise only notice as a quiet camera. + """ + + captured_today: int | None = None + delivered_today: int | None = None + failed_today: int | None = None + events_today: int | None = None + # Days since epoch in local time. Stays 0 until the clock syncs, so the + # pre-sync bucket is a phantom day that rolls over once. Do not chart it. + day_index: int | None = None + captured_boot: int | None = None + delivered_boot: int | None = None + + +class CameraBlock(_Loose): + # Send names, not indices: entries have been inserted into the middle of + # framesize_t between driver releases, so a stored index silently means a + # different resolution after a firmware update (API.md). + frame_size: str | int | None = None + frame_size_id: int | None = None + width: int | None = None + height: int | None = None + # 0x2640 OV2640, 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have + # shipped with OV3660, so do not assume from the product listing. + sensor_pid: int | None = None + jpeg_quality: int | None = None + profile: Annotated[str | None, Field(max_length=16)] = None + ready: bool | None = None + + +class NightBlock(_Loose): + is_night: bool | None = None + nightlight_on: bool | None = None + behaviour: int | None = None + capture_allowed: bool | None = None + + +class StreamBlock(_Loose): + enabled: bool | None = None + active: bool | None = None + frames_sent: int | None = None + seconds_left: int | None = None + + +class RadarBlock(_Loose): + # 0 here means no valid frame decoded at any rate: wiring or a dead module, + # and worth an alert (API.md). + baud: int | None = None + uart_ok: bool | None = None + out_pin: bool | None = None + state: Annotated[int | None, Field(ge=0, le=3)] = None + moving_cm: int | None = None + moving_energy: int | None = None + stationary_cm: int | None = None + stationary_energy: int | None = None + + +class SystemBlock(_Loose): + rssi: int | None = None + ip: Annotated[str | None, Field(max_length=45)] = None + free_heap: int | None = None + free_psram: int | None = None + ring_depth: int | None = None + ring_bytes: int | None = None + + +class DeviceConditions(_Loose): + """The body of both POST /heartbeat and POST /status.""" + + reason: StatusReason + fw_version: Annotated[str | None, Field(max_length=32)] = None + hw_revision: Annotated[str | None, Field(max_length=64)] = None + config_version: int | None = None + + power: PowerBlock = Field(default_factory=PowerBlock) + battery: BatteryBlock = Field(default_factory=BatteryBlock) + counters: CountersBlock = Field(default_factory=CountersBlock) + camera: CameraBlock = Field(default_factory=CameraBlock) + night: NightBlock = Field(default_factory=NightBlock) + stream: StreamBlock = Field(default_factory=StreamBlock) + radar: RadarBlock = Field(default_factory=RadarBlock) + system: SystemBlock = Field(default_factory=SystemBlock) + + time_synced: bool | None = None + device_time: datetime | None = None + + @field_validator("device_time", mode="before") + @classmethod + def _empty_is_none(cls, v: Any) -> Any: + return None if v in ("", 0) else v + + +# --- commands --------------------------------------------------------------- + + +class CommandAck(BaseModel): + model_config = ConfigDict(extra="ignore") + + status: Literal["done", "failed", "rejected"] + detail: Annotated[str | None, Field(max_length=1000)] = None diff --git a/server/src/poorbird/api/sessions.py b/server/src/poorbird/api/sessions.py new file mode 100644 index 0000000..54ad704 --- /dev/null +++ b/server/src/poorbird/api/sessions.py @@ -0,0 +1,181 @@ +"""Server-side sessions for the WebUI (SPEC 3.1, REVIEW SEC-007). + +Cookies, not JWTs, and the session state lives in Postgres. The reason is +revocation: signing a user out, or ending every session when their password +changes, has to take effect immediately. A self-contained token cannot be +withdrawn before it expires without keeping a deny-list, which is the database +lookup it was supposed to avoid. + +The cookie value is a 64-hex token; only its SHA-256 is stored. It reuses +``deps.new_credential``/``hash_credential`` rather than growing a second +implementation of the same idea -- device tokens and session tokens have the +same shape and the same reasoning behind a fast hash: both are CSPRNG output, +not passwords. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime, timedelta + +from fastapi import Response +from sqlalchemy import delete, select +from sqlalchemy.orm import Session as DbSession + +from ..config import Settings +from ..models import Session as UserSession +from ..models import User +from .deps import hash_credential, new_credential + +log = logging.getLogger(__name__) + +SESSION_COOKIE = "poorbird_session" +CSRF_COOKIE = "poorbird_csrf" +CSRF_HEADER = "x-csrf-token" + +# Lax, not Strict. Strict would also suppress the cookie when someone follows +# an ordinary link into the app from anywhere else, so they arrive apparently +# signed out and sign in again for no reason. Lax still withholds the cookie +# from cross-site POST, which is the CSRF case that matters, and the per-session +# token below covers the rest. +SAMESITE = "lax" + + +def create_session( + db: DbSession, + user: User, + *, + settings: Settings, + ip: str | None = None, + user_agent: str | None = None, +) -> tuple[str, str]: + """Open a session for ``user``. Returns ``(session_token, csrf_token)``. + + Both are returned in plaintext exactly once, here, and only hashes or + per-session values are persisted. The caller is responsible for putting + them in cookies and for committing. + """ + token = new_credential() + csrf = new_credential() + + db.add( + UserSession( + user_id=user.id, + token_hash=hash_credential(token), + csrf_token=csrf, + expires_at=datetime.now(UTC) + timedelta(hours=settings.session_lifetime_h), + # Truncated to the column width rather than allowed to raise: a + # long or hostile User-Agent must not be able to fail a login. + ip=ip[:45] if ip else None, + user_agent=user_agent[:255] if user_agent else None, + ) + ) + db.flush() + return token, csrf + + +def resolve_session(db: DbSession, token: str | None) -> tuple[UserSession, User] | None: + """Look up a live session and its user, or None. + + None covers every failure the caller should treat identically: no cookie, an + unknown token, an expired session, a deleted or deactivated user. They are + deliberately not distinguished in the return value -- the endpoint answers + 401 for all of them, because telling a caller *which* one it was is telling + them whether a token was ever real. + """ + if not token: + return None + + row = db.execute( + select(UserSession, User) + .join(User, User.id == UserSession.user_id) + .where(UserSession.token_hash == hash_credential(token)) + ).first() + if row is None: + return None + + session, user = row + if session.expires_at <= datetime.now(UTC): + # Clear it out on the way past. Nothing else would, between the + # scheduled purge below and the row's own irrelevance. + db.delete(session) + db.commit() + return None + if not user.is_active: + return None + return session, user + + +def revoke_session(db: DbSession, token: str | None) -> None: + """End one session. Idempotent: signing out twice is not an error.""" + if not token: + return + db.execute(delete(UserSession).where(UserSession.token_hash == hash_credential(token))) + + +def revoke_all_for_user(db: DbSession, user_id: int) -> int: + """End every session for one user, and return how many. + + Used when a password changes: otherwise the old credential keeps working + through any browser that is already signed in, which is usually the reason + it was changed. + """ + result = db.execute(delete(UserSession).where(UserSession.user_id == user_id)) + return result.rowcount or 0 + + +# Deleting expired rows is deliberately *not* here. Expiry is enforced on read +# above, so a leftover row is inert, and the sweep is a scheduled job -- it +# lives with the worker's other housekeeping in worker/handlers.py. Putting it +# here would mean the worker importing from api/, which is the wrong way round +# for the same reason images.py sits at the package root. + + +# --- cookies ---------------------------------------------------------------- + + +def set_session_cookies(response: Response, token: str, csrf: str, *, settings: Settings) -> None: + """Attach both cookies to a login response. + + The session cookie is HttpOnly so script cannot read it. The CSRF cookie + deliberately is **not**: the whole mechanism depends on the app's own + JavaScript reading it and echoing it in a header, which an attacker on + another origin cannot do. + """ + max_age = settings.session_lifetime_h * 3600 + + response.set_cookie( + SESSION_COOKIE, + token, + max_age=max_age, + httponly=True, + secure=settings.session_cookie_secure, + samesite=SAMESITE, + path="/", + ) + response.set_cookie( + CSRF_COOKIE, + csrf, + max_age=max_age, + httponly=False, + secure=settings.session_cookie_secure, + samesite=SAMESITE, + path="/", + ) + + +def clear_session_cookies(response: Response, *, settings: Settings) -> None: + """Remove both cookies. + + The attributes have to match the ones they were set with or the browser + treats it as a different cookie and leaves the original in place -- a logout + that appears to work and does not. + """ + for name, httponly in ((SESSION_COOKIE, True), (CSRF_COOKIE, False)): + response.delete_cookie( + name, + httponly=httponly, + secure=settings.session_cookie_secure, + samesite=SAMESITE, + path="/", + ) diff --git a/server/src/poorbird/api/ui_schemas.py b/server/src/poorbird/api/ui_schemas.py new file mode 100644 index 0000000..a613e93 --- /dev/null +++ b/server/src/poorbird/api/ui_schemas.py @@ -0,0 +1,166 @@ +"""Request and response shapes for the WebUI (Phase 3). + +Separate from ``schemas.py``, which is the device contract in +``firmware/API.md`` and is not free to change. These are ours on both sides: the +server and ``web/`` are versioned together and ship together, so a field can be +renamed here in one commit. + +The shapes are pinned to what ``web/src/auth/AuthProvider.tsx`` already expects, +because the scaffold was written first and there is no reason to make it move. +""" + +from __future__ import annotations + +import uuid +from datetime import datetime +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field + +from ..models.captures import TRIGGERS +from ..models.users import ROLES, THEMES + +Role = Literal[ROLES] # type: ignore[valid-type] +Theme = Literal[THEMES] # type: ignore[valid-type] +Trigger = Literal[TRIGGERS] # type: ignore[valid-type] + + +class LoginRequest(BaseModel): + model_config = ConfigDict(extra="ignore") + + # Bounded, but not validated against a character set. Usernames are matched + # exactly against the database, so there is nothing to sanitise; a length cap + # is here only so an enormous body cannot reach Argon2. + username: Annotated[str, Field(min_length=1, max_length=64)] + # The password floor lives in passwords.validate_password_strength and is + # applied when a password is *set*. Applying it here too would refuse to + # even check a password that predates the rule, which is a lockout rather + # than a policy. Only an upper bound, matching MAX_PASSWORD_LENGTH. + password: Annotated[str, Field(min_length=1, max_length=1024)] + # Six digits when the account has TOTP. Absent, not empty, when it does not. + totp: Annotated[str | None, Field(max_length=16)] = None + + +class SessionUser(BaseModel): + """What ``GET /auth/session`` and ``POST /auth/login`` both return. + + Deliberately small. It is what the UI needs to render a shell and make role + decisions, and nothing else -- no email, no TOTP state, no password + metadata. A response shape is a place things accumulate, and the browser is + where they end up. + """ + + id: int + username: str + role: Role + locale: str + theme: Theme + + +# --- gallery ---------------------------------------------------------------- + + +class CaptureSummary(BaseModel): + """One tile in the grid. + + Kept deliberately small, because a page of these is 50-200 rows and the + grid re-fetches on every filter change. Anything only the detail view + needs -- radar energy, battery, observations, tags -- is in + :class:`CaptureDetail` instead. + + No image URLs. The client builds those from the id in lib/api.ts, which is + already the one place that knows the API prefix; putting them here would + duplicate that knowledge in every response. + """ + + model_config = ConfigDict(from_attributes=True) + + id: uuid.UUID + device_id: int + # SPEC C7: server time, always authoritative. captured_at_device is NULL + # when the camera's clock was unsynced, and the UI must not present it as + # 1970 -- see API.md on X-Captured-At: 0. + received_at: datetime + captured_at_device: datetime | None + width: int | None + height: int | None + bytes: int + trigger: Trigger + pre_trigger: bool + burst_id: str | None + burst_index: int | None + burst_count: int | None + reviewed: bool + kept: bool + # False while the thumbnail job is still queued, or permanently for a frame + # that could not be decoded. The grid shows a placeholder rather than a + # broken image, so it has to be able to tell. + has_thumb: bool + + +class CapturePage(BaseModel): + """A keyset page, not an offset page. + + At 5000 captures a day, OFFSET gets slower the further back you scroll, + which is precisely the direction a gallery scrolls. The cursor carries the + last row's ``(received_at, id)``; ``next_cursor`` is null at the end. + """ + + items: list[CaptureSummary] + next_cursor: str | None + + +class TagOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + label: str + colour: str | None + + +class TaxonOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + scientific_name: str + name_de: str | None + name_en: str | None + + +class ObservationOut(BaseModel): + """A label on a capture. + + ``source`` separates human labels from model predictions in one table + (SPEC 3.2), so the edit UI is already the training-data pipeline. The UI + must show which is which -- a prediction presented as a human label would + poison exactly that. + """ + + model_config = ConfigDict(from_attributes=True) + + id: int + taxon: TaxonOut | None + individuals: int + age: str + sex: str + behaviour: str | None + certainty: str + notes: str | None + source: Literal["human", "model"] + confidence: float | None + + +class CaptureDetail(CaptureSummary): + """Everything about one capture, for the full-screen view.""" + + device_name: str + sha256: str + radar_state: int | None + radar_distance_cm: int | None + radar_energy: int | None + battery_mv: int | None + rssi: int | None + temp_c: float | None + frame_seq: int | None + observations: list[ObservationOut] + tags: list[TagOut] diff --git a/server/src/poorbird/api/userauth.py b/server/src/poorbird/api/userauth.py new file mode 100644 index 0000000..4fa4b41 --- /dev/null +++ b/server/src/poorbird/api/userauth.py @@ -0,0 +1,153 @@ +"""User authentication and authorization for the WebUI. + +Separate from ``deps.py`` on purpose. That file is device auth: bearer tokens, +no cookies, no CSRF, and a 401 there means "clear your token and re-enroll". +This file is people: session cookies, CSRF, and roles. Mixing them is how a +device ends up able to read the gallery, which SPEC 3.1 forbids outright. +""" + +from __future__ import annotations + +import logging +import secrets +from typing import Annotated + +from fastapi import Depends, HTTPException, Request, status + +from ..models import Session as UserSession +from ..models import User +from .deps import DbDep +from .ratelimit import client_address +from .sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE, resolve_session + +log = logging.getLogger(__name__) + +# Methods that can change state. A GET must never need CSRF, and must never +# change anything -- if one did, no CSRF scheme would protect it. +UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"}) + +_UNAUTHENTICATED = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="not signed in", +) + + +def current_session(request: Request, db: DbDep) -> tuple[UserSession, User]: + """Resolve the session cookie to a live session and user, or 401.""" + resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE)) + if resolved is None: + raise _UNAUTHENTICATED + return resolved + + +def current_user( + resolved: Annotated[tuple[UserSession, User], Depends(current_session)], +) -> User: + return resolved[1] + + +SessionDep = Annotated[tuple[UserSession, User], Depends(current_session)] +CurrentUser = Annotated[User, Depends(current_user)] + + +def require_role(*roles: str): + """Dependency factory: allow only these roles (SPEC 3.1). + + ``admin`` is not implicitly granted everything -- each route names the roles + it accepts, so widening one route cannot silently widen another. Where admin + should be included, it is listed. + + 403, not 404: the caller is authenticated, and pretending the route does not + exist would only make a permission problem look like a bug. + """ + + def guard(user: CurrentUser) -> User: + if user.role not in roles: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"requires one of: {', '.join(sorted(roles))}", + ) + return user + + return guard + + +# --- CSRF ------------------------------------------------------------------- + + +async def csrf_middleware(request: Request, call_next): + """Reject mutating cookie-authenticated requests without a valid CSRF token. + + Applied as middleware rather than per-route so a new endpoint cannot forget + it. The condition is what keeps it correct: + + * Only unsafe methods. A GET needing this would mean a GET that mutates. + * Only requests that **carry the session cookie**. Device endpoints + authenticate with a bearer token and never send cookies, so they are + untouched -- which matters, because a camera has no way to obtain a CSRF + token and blocking /ingest would take the whole system down. + * Logging in is therefore exempt without a special case: there is no session + cookie yet. Logging out is not exempt, and should not be -- an attacker + signing someone out is a nuisance worth preventing. + + The header is compared against the token stored on the session row, not + merely against the cookie. Plain double-submit would let an attacker who can + write a cookie on the domain set both sides to a value they chose; the + victim's session token, which they cannot read, is what they would also + need. + """ + if request.method not in UNSAFE_METHODS or SESSION_COOKIE not in request.cookies: + return await call_next(request) + + presented = request.headers.get(CSRF_HEADER) + if not presented: + return _csrf_failure(request, "missing") + + # Middleware runs outside the dependency system, so it opens its own + # session. This is one indexed lookup, on mutating requests only. + from ..db import SessionLocal + + with SessionLocal() as db: + resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE)) + if resolved is None: + # Not signed in after all. Let the route's own dependency produce + # the 401, so the answer stays consistent with every other route. + return await call_next(request) + session, _user = resolved + if not secrets.compare_digest(presented, session.csrf_token): + return _csrf_failure(request, "mismatch") + + return await call_next(request) + + +def _csrf_failure(request: Request, why: str): + from fastapi.responses import JSONResponse + + log.warning( + "csrf check failed", + extra={ + "reason": why, + "path": request.url.path, + "method": request.method, + "ip": client_address(request), + }, + ) + return JSONResponse( + status_code=status.HTTP_403_FORBIDDEN, + content={ + "detail": ( + f"CSRF token {why}. Send the value of the {CSRF_COOKIE} cookie " + f"in the {CSRF_HEADER} header." + ) + }, + ) + + +__all__ = [ + "CurrentUser", + "SessionDep", + "csrf_middleware", + "current_session", + "current_user", + "require_role", +] diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py new file mode 100644 index 0000000..fcdc474 --- /dev/null +++ b/server/src/poorbird/cli.py @@ -0,0 +1,410 @@ +"""Entry points. + +``poorbird check`` is the one to reach for first on a fresh machine: it +validates config, storage paths and database connectivity and prints what it +found, without starting anything. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +from . import __version__ +from .config import get_settings +from .logging_setup import configure_logging + + +def _alembic_config(): + from alembic.config import Config + + candidate = Path(os.environ.get("POORBIRD_ALEMBIC_INI", "alembic.ini")) + if not candidate.is_absolute(): + candidate = Path.cwd() / candidate + if not candidate.exists(): + raise SystemExit( + f"alembic.ini not found at {candidate}. Run from the server/ directory, " + "or set POORBIRD_ALEMBIC_INI." + ) + cfg = Config(str(candidate)) + cfg.set_main_option("script_location", str(candidate.parent / "migrations")) + return cfg + + +def cmd_serve(args: argparse.Namespace) -> int: + import uvicorn + + settings = get_settings() + uvicorn.run( + "poorbird.api.app:app", + host=args.host or settings.api_host, + port=args.port or settings.api_port, + reload=args.reload, + log_config=None, # our own stdout logging, see logging_setup + ) + return 0 + + +def cmd_worker(_args: argparse.Namespace) -> int: + from .worker import run + + return run() + + +def cmd_migrate(_args: argparse.Namespace) -> int: + from alembic import command + + command.upgrade(_alembic_config(), "head") + return 0 + + +def cmd_enqueue(args: argparse.Namespace) -> int: + from .db import SessionLocal + from .worker.queue import enqueue + + payload = json.loads(args.payload) if args.payload else {} + with SessionLocal() as session: + job = enqueue(session, args.kind, payload) + session.commit() + print(f"queued job {job.id} ({args.kind})") + return 0 + + +# --- users ------------------------------------------------------------------ +# +# Accounts are created here, not over HTTP. There is no public registration and +# no "first run" web form: both are bootstrap paths that stay reachable forever +# and have to be defended forever. A CLI command needs shell access on the +# server, which is already the trust boundary. + + +def _read_new_password(from_stdin: bool) -> str: + """Prompt twice, or read one line from stdin. + + Never a command-line argument: that lands in shell history, in the process + table, and in any log that records commands. + """ + import getpass + + from .passwords import WeakPassword, validate_password_strength + + if from_stdin: + # Two line-ending hazards, both silent, both only discoverable by + # failing to log in with a password you know is right: + # + # rstrip("\r\n") rather than rstrip("\n"), or a CRLF pipe leaves the + # carriage return inside the password. + # + # lstrip("") because Windows PowerShell prepends a UTF-8 BOM + # when it pipes to a native executable. A BOM is never part of an + # intended password, and this cost a debugging session to find. + password = sys.stdin.readline().rstrip("\r\n").lstrip("") + else: + password = getpass.getpass("password: ") + if password != getpass.getpass("repeat: "): + raise SystemExit("passwords did not match") + + try: + validate_password_strength(password) + except WeakPassword as exc: + raise SystemExit(f"{exc}") from exc + return password + + +def cmd_user_add(args: argparse.Namespace) -> int: + from sqlalchemy import select + + from .db import SessionLocal + from .models import User + from .passwords import hash_password + from .totp import new_secret, provisioning_uri + + password = _read_new_password(args.password_stdin) + + # TODO 3.0: 2FA is enforced for admin. Enforcing that at login instead + # would mean the only admin could be locked out by their own account -- so + # it is enforced at creation, where the secret can still be handed over. + with_totp = args.totp + if with_totp is None: + with_totp = args.role == "admin" + if args.role == "admin" and not with_totp: + print("warning: creating an admin without TOTP, against the TODO 3.0 policy") + + with SessionLocal() as session: + if session.scalar(select(User).where(User.username == args.username)) is not None: + raise SystemExit(f"user {args.username!r} already exists") + + secret = new_secret() if with_totp else None + session.add( + User( + username=args.username, + email=args.email, + password_hash=hash_password(password), + role=args.role, + totp_secret=secret, + ) + ) + session.commit() + + print(f"created {args.role} {args.username!r}") + if secret is not None: + # Shown exactly once. It is stored so the server can verify codes, but + # printing it again later would turn a one-time handover into a + # standing way to mint a second authenticator. + print("\nScan this in an authenticator app now -- it is not shown again:") + print(f" {provisioning_uri(secret, args.username)}") + print(f"\n (manual entry key: {secret})") + return 0 + + +def cmd_user_list(_args: argparse.Namespace) -> int: + from sqlalchemy import select + + from .db import SessionLocal + from .models import User + + with SessionLocal() as session: + users = session.scalars(select(User).order_by(User.id)).all() + + if not users: + print("no users. Create one with: poorbird user add --role admin") + return 0 + + print(f"{'id':>4} {'username':<20} {'role':<8} {'2fa':<4} {'active':<7} last login") + for u in users: + last = u.last_login_at.strftime("%Y-%m-%d %H:%M") if u.last_login_at else "never" + print( + f"{u.id:>4} {u.username:<20} {u.role:<8} " + f"{'yes' if u.totp_secret else 'no':<4} " + f"{'yes' if u.is_active else 'NO':<7} {last}" + ) + return 0 + + +def cmd_user_passwd(args: argparse.Namespace) -> int: + from sqlalchemy import select + + from .db import SessionLocal + from .models import Session as UserSession + from .models import User + from .passwords import hash_password + + password = _read_new_password(args.password_stdin) + + with SessionLocal() as session: + user = session.scalar(select(User).where(User.username == args.username)) + if user is None: + raise SystemExit(f"no such user: {args.username!r}") + user.password_hash = hash_password(password) + + # A password change has to end existing sessions, or the old + # credential effectively still works through any browser that is + # already signed in -- which is the main reason people change it. + killed = ( + session.query(UserSession) + .filter(UserSession.user_id == user.id) + .delete(synchronize_session=False) + ) + session.commit() + + print(f"password updated for {args.username!r}; {killed} session(s) signed out") + return 0 + + +def cmd_seed(args: argparse.Namespace) -> int: + from .db import SessionLocal + from .seed import clear, generate + + with SessionLocal() as session: + if args.clear: + captures, devices = clear(session) + print(f"removed {captures} seeded capture(s) and {devices} seed device(s)") + return 0 + + print(f"generating {args.captures} capture(s) over {args.days} day(s)...") + made = generate( + session, + count=args.captures, + days=args.days, + device_name=args.device_name, + thumbnails=not args.no_thumbnails, + ) + + print(f"\ndone: {made} capture(s) on device {args.device_name!r}") + print("Remove them again with: poorbird seed --clear") + return 0 + + +def cmd_check(_args: argparse.Namespace) -> int: + settings = get_settings() + problems: list[str] = [] + + print(f"poorbird {__version__}") + print(f" python {sys.version.split()[0]}") + + # Never print the password. + if not settings.database_url_is_set: + print(" database_url NOT SET (POORBIRD_DATABASE_URL)") + problems.append("POORBIRD_DATABASE_URL not set") + else: + url = settings.database_url + if "@" in url: + scheme, _, rest = url.partition("://") + url = f"{scheme}://***@{rest.rpartition('@')[2]}" + print(f" database_url {url}") + + try: + from sqlalchemy import text + + from .db import engine + + with engine.connect() as conn: + version = conn.execute(text("SHOW server_version")).scalar() + print(f" database reachable (PostgreSQL {version})") + except Exception as exc: # noqa: BLE001 + print(f" database UNREACHABLE: {type(exc).__name__}: {exc}") + problems.append("database unreachable") + + try: + from alembic import command + + print(" migrations ", end="") + command.current(_alembic_config()) + except SystemExit as exc: + print(f"not checked ({exc})") + except Exception as exc: # noqa: BLE001 + print(f"error: {type(exc).__name__}: {exc}") + + for path in settings.storage_paths(): + if not path.exists(): + print(f" path {path} MISSING") + problems.append(f"{path} missing") + elif not os.access(path, os.W_OK): + print(f" path {path} NOT WRITABLE") + problems.append(f"{path} not writable") + else: + print(f" path {path} ok") + + if not settings.enroll_secret_is_set: + print(" enroll_secret NOT SET (device enrollment will refuse requests)") + + # The Caddy handoff (SPEC 3.3) needs the app and the proxy to agree on the + # layout: Caddy serves the PARENT of both roots and the app sends paths + # under /images and /thumbs. If the directories are not siblings with + # those names, every image 404s from Caddy with nothing in the app's log + # to explain it -- so it is worth saying here rather than discovering in a + # browser. + if settings.serve_images_directly: + print(" images served by the app (development only)") + else: + from .api.delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX + + image_root, thumb_root = settings.image_root, settings.thumb_root + expected_image = IMAGE_URL_PREFIX.lstrip("/") + expected_thumb = THUMB_URL_PREFIX.lstrip("/") + if ( + image_root.parent != thumb_root.parent + or image_root.name != expected_image + or thumb_root.name != expected_thumb + ): + print( + f" images LAYOUT MISMATCH: Caddy expects " + f"/{expected_image} and /{expected_thumb}, " + f"got {image_root} and {thumb_root}" + ) + problems.append("image/thumb roots do not match the Caddy handoff layout") + else: + print(f" images handed off to Caddy from {image_root.parent}") + + if problems: + print(f"\n{len(problems)} problem(s): " + "; ".join(problems)) + return 1 + print("\nall checks passed") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="poorbird", description="poorBird server") + parser.add_argument("--version", action="version", version=__version__) + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("serve", help="run the HTTP API") + p.add_argument("--host") + p.add_argument("--port", type=int) + p.add_argument("--reload", action="store_true", help="development only") + p.set_defaults(func=cmd_serve) + + p = sub.add_parser("worker", help="run the job queue worker and scheduler") + p.set_defaults(func=cmd_worker) + + p = sub.add_parser("migrate", help="apply migrations (alembic upgrade head)") + p.set_defaults(func=cmd_migrate) + + p = sub.add_parser("check", help="validate config, storage and database") + p.set_defaults(func=cmd_check) + + p = sub.add_parser("enqueue", help="put a job on the queue (smoke test)") + p.add_argument("kind") + p.add_argument("payload", nargs="?", help="JSON object") + p.set_defaults(func=cmd_enqueue) + + p = sub.add_parser( + "seed", + help="generate synthetic captures for gallery development", + description=( + "Creates captures on a dedicated seed device, with real JPEGs on disk. " + "--clear removes them again, and is scoped to seed devices only, so a " + "real camera's captures are never in scope." + ), + ) + p.add_argument("--captures", type=int, default=500, help="how many frames (default 500)") + p.add_argument("--days", type=int, default=14, help="spread them over this many days") + p.add_argument("--device-name", default="seed-cam") + p.add_argument( + "--no-thumbnails", + action="store_true", + help="leave thumb_path NULL so the worker generates them, which is how to " + "exercise the queue at volume", + ) + p.add_argument("--clear", action="store_true", help="delete all seeded data instead") + p.set_defaults(func=cmd_seed) + + p = sub.add_parser("user", help="manage UI accounts (there is no web signup)") + usersub = p.add_subparsers(dest="user_command", required=True) + + q = usersub.add_parser("add", help="create an account") + q.add_argument("username") + q.add_argument("--role", choices=["admin", "editor", "viewer"], default="viewer") + q.add_argument("--email") + q.add_argument( + "--totp", + dest="totp", + action="store_true", + default=None, + help="enable TOTP (the default for --role admin)", + ) + q.add_argument("--no-totp", dest="totp", action="store_false", help="disable TOTP") + q.add_argument( + "--password-stdin", action="store_true", help="read the password from stdin, not a prompt" + ) + q.set_defaults(func=cmd_user_add) + + q = usersub.add_parser("list", help="list accounts") + q.set_defaults(func=cmd_user_list) + + q = usersub.add_parser("passwd", help="set a password and sign out that user's sessions") + q.add_argument("username") + q.add_argument("--password-stdin", action="store_true") + q.set_defaults(func=cmd_user_passwd) + + args = parser.parse_args(argv) + settings = get_settings() + configure_logging(settings.log_level, settings.log_format) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/server/src/poorbird/config.py b/server/src/poorbird/config.py new file mode 100644 index 0000000..a73f314 --- /dev/null +++ b/server/src/poorbird/config.py @@ -0,0 +1,154 @@ +"""Configuration. + +Every value comes from the environment (TODO.md Phase 1.2). Nothing is read +from a committed config file, and no path, host or secret is baked into code. +systemd supplies these via ``EnvironmentFile=/etc/poorbird/poorbird.env``; for +local development a ``.env`` in the working directory is picked up as well. +""" + +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import Literal + +from pydantic import SecretStr, field_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + +# Values that mean "nobody filled this in". The .example files ship with these, +# and a copied-but-unedited example must not boot as if it were configured. +_PLACEHOLDERS = frozenset({"change_me", "changeme", "todo", "xxx", "secret"}) + + +class Settings(BaseSettings): + model_config = SettingsConfigDict( + env_prefix="POORBIRD_", + env_file=".env", + env_file_encoding="utf-8", + extra="ignore", + ) + + # --- database --------------------------------------------------------- + # Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket + # is the one genuinely container-hostile choice (TODO.md Phase 1.2). + # + # No default. A working URL in code means real credentials in code, and the + # module docstring above already promises none (REVIEW SEC-006). Absence is + # reported by ``poorbird check`` and raised with a readable message by db.py, + # rather than silently connecting to whatever happens to be on localhost. + database_url: str = "" + # FastAPI runs this app's ``def`` handlers in anyio's threadpool (40 threads + # by default), and each one holds a session for the whole request. A pool of + # 5 meant the 6th concurrent request waited on ``pool_timeout`` before it + # even reached the database (REVIEW §7). The real ceiling is + # pool_size + db_max_overflow, so both are named here rather than left to + # SQLAlchemy's invisible default of 10. + db_pool_size: int = 15 + db_max_overflow: int = 10 + db_echo: bool = False + + # --- http ------------------------------------------------------------- + api_host: str = "127.0.0.1" + api_port: int = 8080 + + # --- storage ---------------------------------------------------------- + # A small number of explicit top-level directories, never scattered under + # the app dir: these are the future volume mounts. + # + # image_root is the single source of truth for the image path. Caddy reads + # the same value, because the auth-checked handoff (SPEC 3.3) needs the app + # and the proxy to agree on where the bytes live. + image_root: Path = Path("/srv/poorbird/images") + thumb_root: Path = Path("/srv/poorbird/thumbs") + state_dir: Path = Path("/var/lib/poorbird") + + # Who copies the image bytes (SPEC 3.3, api/delivery.py). + # + # False in production: the app authorises and answers with + # X-Accel-Redirect, and Caddy reads the file. Python never handles the + # payload. True for local development, where there is no Caddy to honour + # that header and every image would otherwise arrive empty. + # + # This does NOT relax the authorisation -- the same check runs either way. + # It only changes how an already-authorised response is finished. + serve_images_directly: bool = False + + # --- devices ---------------------------------------------------------- + # Shared bootstrap secret presented by a device in X-Enroll-Secret. + # See firmware/API.md: do NOT rotate this without shipping new firmware, + # or you remove the last-resort recovery path for a mounted camera. + # + # Environment only, never a literal here (REVIEW SEC-001). Empty is allowed + # so the Phase 1 commands still run on a fresh clone; the device endpoints + # refuse to serve without it. + enroll_secret: SecretStr = SecretStr("") + + # --- user sessions (Phase 3) ------------------------------------------ + # SPEC 3.4 lists session lifetime as a UI-editable server setting. It lives + # here until the settings UI exists; promoting it to the settings table then + # is a read, not a redesign. + session_lifetime_h: int = 24 * 14 + + # Secure cookies require HTTPS, which Caddy always terminates in production. + # It must be false for local development, because the Vite dev server is + # plain http on localhost and a Secure cookie is silently dropped there -- + # which presents as "login succeeds but I am never signed in", with nothing + # in any log. Hence a setting rather than a hardcoded True. + session_cookie_secure: bool = True + + # --- rate limiting ---------------------------------------------------- + # In-process token buckets (api/ratelimit.py), sized for one uvicorn + # process. Off by default in tests, which would otherwise exhaust a + # bucket and start asserting against 429s. + rate_limit_enabled: bool = True + + # --- worker ----------------------------------------------------------- + # Idle polling only: the loop drains a non-empty queue back to back without + # sleeping, so this is the delay before a *newly* enqueued job is noticed, + # not a per-job cost. 5s trades latency nobody can perceive on a bird camera + # for 12 idle queries a minute instead of 30. + worker_poll_interval_s: float = 5.0 + job_max_attempts: int = 3 + + # --- logging ---------------------------------------------------------- + # Always to stdout/stderr. journald catches it now; a log driver would + # catch it later. Never app-managed log files. + log_level: str = "INFO" + log_format: Literal["text", "json"] = "text" + + @field_validator("database_url") + @classmethod + def _reject_unedited_example(cls, v: str) -> str: + if any(p in v.lower() for p in _PLACEHOLDERS): + raise ValueError( + "POORBIRD_DATABASE_URL still contains a placeholder from the " + "example file. Put the real password in, or leave the variable " + "unset." + ) + return v + + @field_validator("enroll_secret") + @classmethod + def _reject_placeholder_secret(cls, v: SecretStr) -> SecretStr: + if v.get_secret_value().strip().lower() in _PLACEHOLDERS: + raise ValueError( + "POORBIRD_ENROLL_SECRET is a placeholder. Generate one with " + "'openssl rand -hex 32', or leave it unset until Phase 2." + ) + return v + + @property + def database_url_is_set(self) -> bool: + return bool(self.database_url.strip()) + + @property + def enroll_secret_is_set(self) -> bool: + return bool(self.enroll_secret.get_secret_value()) + + def storage_paths(self) -> list[Path]: + return [self.image_root, self.thumb_root, self.state_dir] + + +@lru_cache +def get_settings() -> Settings: + return Settings() diff --git a/server/src/poorbird/db.py b/server/src/poorbird/db.py new file mode 100644 index 0000000..5b0cdaf --- /dev/null +++ b/server/src/poorbird/db.py @@ -0,0 +1,50 @@ +"""Engine and session factory. + +Synchronous SQLAlchemy, deliberately. At one camera and a few thousand frames a +day the async machinery buys nothing and costs clarity, and the worker's +``FOR UPDATE SKIP LOCKED`` loop is far easier to reason about synchronously. +FastAPI runs ``def`` handlers in a threadpool, so this does not block the loop. +Revisit only if the MJPEG relay (Phase 6) turns out to want it. +""" + +from __future__ import annotations + +from collections.abc import Iterator + +from sqlalchemy import create_engine +from sqlalchemy.orm import Session, sessionmaker + +from .config import get_settings + +_settings = get_settings() + +if not _settings.database_url_is_set: + # create_engine("") raises "Could not parse SQLAlchemy URL from string ''", + # which sends people looking in the wrong place. Say what to actually do. + raise RuntimeError( + "POORBIRD_DATABASE_URL is not set. Export it, or put it in server/.env:\n" + " POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:" + "@127.0.0.1:5432/poorbird\n" + "See server/deploy/poorbird.env.example. Run 'poorbird check' to verify." + ) + +engine = create_engine( + _settings.database_url, + pool_size=_settings.db_pool_size, + max_overflow=_settings.db_max_overflow, + # Past pool_size + max_overflow a caller waits rather than failing. It has + # to be finite: without a timeout a pool leak presents as requests hanging + # forever instead of as an error naming the pool. + pool_timeout=30, + pool_pre_ping=True, + echo=_settings.db_echo, + future=True, +) + +SessionLocal = sessionmaker(bind=engine, expire_on_commit=False, future=True) + + +def session_scope() -> Iterator[Session]: + """Context-managed session for scripts and the worker.""" + with SessionLocal() as session: + yield session diff --git a/server/src/poorbird/images.py b/server/src/poorbird/images.py new file mode 100644 index 0000000..7187f64 --- /dev/null +++ b/server/src/poorbird/images.py @@ -0,0 +1,171 @@ +"""Where capture bytes go, and what can be read back out of them. + +Lives at package level rather than under ``api`` because both sides use it: +the ingest route writes frames, and the worker reads them back to build +thumbnails. A worker importing from ``api`` would be the wrong way round. + +Split by cost, deliberately. Everything above the thumbnail section runs on +the ingest path, once per frame, and must never be the reason a burst is +slow -- so it reads nine bytes of JPEG header rather than decoding an image. +Pillow appears only below, in the worker, where the frame has to be decoded +anyway. +""" + +from __future__ import annotations + +import os +import uuid +from datetime import datetime +from pathlib import Path + +# Matches `request_body max_size 12MB` in deploy/Caddyfile. Enforced here too, +# because Caddy is not in front of the app in development and a limit that +# only exists in the proxy is not a limit. +MAX_IMAGE_BYTES = 12 * 1024 * 1024 + +# SOI. A JPEG always starts FF D8 FF; anything else is not one, whatever the +# Content-Type header claims. +_JPEG_MAGIC = b"\xff\xd8\xff" + +# Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG) and +# CC (DAC) share the range but are not SOF. +_SOF_MARKERS = frozenset( + {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} +) + + +def looks_like_jpeg(data: bytes) -> bool: + return data.startswith(_JPEG_MAGIC) + + +def jpeg_dimensions(data: bytes) -> tuple[int, int] | None: + """(width, height) from the JPEG header, or None if it cannot be read. + + Walks the segment chain to the first SOF. None is not an error: a frame + whose dimensions we cannot parse is still a frame worth keeping, and the + columns are nullable for exactly that reason. + """ + i, n = 2, len(data) + + while i + 3 < n: + if data[i] != 0xFF: + i += 1 + continue + + marker = data[i + 1] + + # Standalone markers: no length field follows. + if marker == 0x01 or 0xD0 <= marker <= 0xD8: + i += 2 + continue + if marker == 0xD9: # EOI + break + + segment_length = int.from_bytes(data[i + 2 : i + 4], "big") + if segment_length < 2: + break # malformed; a shorter length would not advance + + if marker in _SOF_MARKERS: + if i + 9 > n: + break + height = int.from_bytes(data[i + 5 : i + 7], "big") + width = int.from_bytes(data[i + 7 : i + 9], "big") + return (width, height) if width and height else None + + i += 2 + segment_length + + return None + + +def relative_image_path(capture_id: uuid.UUID, received_at: datetime) -> str: + """``YYYY/MM/DD/.jpg`` (SPEC 3.3). + + Dated by ``received_at``, never by the device clock: the device may be + unsynced and report nothing at all, and SPEC C7 makes server time + authoritative. Stored relative to POORBIRD_IMAGE_ROOT so the root stays a + deployment concern -- Caddy resolves the same relative path against the + same configured root when it serves the bytes. + """ + return f"{received_at:%Y/%m/%d}/{capture_id}.jpg" + + +def write_atomically(destination: Path, data: bytes) -> None: + """Write via a temporary file in the same directory, then rename. + + A half-written JPEG is indistinguishable from a whole one until something + tries to decode it, so the file must never be visible at its final path + until it is complete. Same directory keeps the rename on one filesystem, + which is what makes it atomic. + """ + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name(f".{destination.name}.part") + + try: + temporary.write_bytes(data) + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +# --- thumbnails ------------------------------------------------------------- +# +# Worker only. Nothing above this line imports Pillow, so the ingest path +# never pays for it. + +# 400px on the long edge, WebP, matching the /thumbs/_400.webp pattern +# in SPEC 3.3. The number is in the filename, so changing it means writing to +# a new name rather than silently serving a differently-sized image from the +# old one. +THUMB_EDGE = 400 +THUMB_QUALITY = 80 + + +class UndecodableImage(Exception): + """The bytes are not an image this build of Pillow can read. + + Distinct from an I/O error on purpose: a frame that cannot be decoded + will never decode, so retrying is pointless and the worker should record + the fact rather than burn its attempts. + """ + + +def relative_thumb_path(capture_id: uuid.UUID) -> str: + """``_400.webp`` (SPEC 3.3), flat rather than dated. + + Thumbnails are addressed by capture id alone and there are far fewer of + them per byte, so the dated tree that keeps the image directories to a + sane size buys nothing here. + """ + return f"{capture_id}_{THUMB_EDGE}.webp" + + +def make_thumbnail(source: Path) -> tuple[bytes, tuple[int, int]]: + """Encode a WebP thumbnail. Returns the bytes and the SOURCE dimensions. + + The source size is returned because the worker is the first place that + truly decodes the frame: ingest reads the JPEG header, which can be + absent or unparseable, and this is the chance to fill in what it missed. + """ + import io + + from PIL import Image, UnidentifiedImageError + + try: + with Image.open(source) as img: + img.load() + original = (img.width, img.height) + + # Never upscale. A frame smaller than the thumbnail box should + # stay its own size rather than be blown up into a blurry one. + thumb = img.convert("RGB") + thumb.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS) + + buffer = io.BytesIO() + thumb.save(buffer, format="WEBP", quality=THUMB_QUALITY, method=4) + return buffer.getvalue(), original + except (UnidentifiedImageError, OSError, ValueError) as exc: + # Pillow raises OSError for a truncated file as well as for a real + # I/O fault, and the two are not worth separating here: either way + # this frame is not going to produce a thumbnail. + raise UndecodableImage(f"{type(exc).__name__}: {exc}") from exc diff --git a/server/src/poorbird/logging_setup.py b/server/src/poorbird/logging_setup.py new file mode 100644 index 0000000..0f63c6c --- /dev/null +++ b/server/src/poorbird/logging_setup.py @@ -0,0 +1,55 @@ +"""Logging to stdout only. + +journald captures stdout for the systemd units today; a container log driver +would capture the same stream unchanged. Nothing writes log files. +""" + +from __future__ import annotations + +import json +import logging +import sys +from datetime import UTC, datetime + +_RESERVED = set(logging.LogRecord("", 0, "", 0, "", None, None).__dict__) | { + "message", + "asctime", + "taskName", +} + + +class JsonFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + payload = { + "ts": datetime.fromtimestamp(record.created, UTC).isoformat(), + "level": record.levelname, + "logger": record.name, + "msg": record.getMessage(), + } + for key, value in record.__dict__.items(): + if key not in _RESERVED and not key.startswith("_"): + payload[key] = value + if record.exc_info: + payload["exc"] = self.formatException(record.exc_info) + return json.dumps(payload, default=str) + + +def configure_logging(level: str = "INFO", fmt: str = "text") -> None: + handler = logging.StreamHandler(sys.stdout) + if fmt == "json": + handler.setFormatter(JsonFormatter()) + else: + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")) + + root = logging.getLogger() + root.handlers.clear() + root.addHandler(handler) + root.setLevel(level.upper()) + + # uvicorn installs its own handlers; make them use ours instead. + for name in ("uvicorn", "uvicorn.error", "uvicorn.access"): + lg = logging.getLogger(name) + lg.handlers.clear() + lg.propagate = True + + logging.getLogger("apscheduler").setLevel("WARNING") diff --git a/server/src/poorbird/models/__init__.py b/server/src/poorbird/models/__init__.py new file mode 100644 index 0000000..ffc3ae9 --- /dev/null +++ b/server/src/poorbird/models/__init__.py @@ -0,0 +1,29 @@ +"""All models, imported here so ``Base.metadata`` is complete. + +Alembic's env.py and the drift test both rely on importing this one module. +""" + +from .base import Base +from .captures import Capture, Observation, Tag, Taxon, capture_tags +from .devices import Device, DeviceCommand, DeviceStatus, Firmware +from .ops import AuditLog, BackupRun, Job, Setting +from .users import Session, User + +__all__ = [ + "AuditLog", + "BackupRun", + "Base", + "Capture", + "Device", + "DeviceCommand", + "DeviceStatus", + "Firmware", + "Job", + "Observation", + "Session", + "Setting", + "Tag", + "Taxon", + "User", + "capture_tags", +] diff --git a/server/src/poorbird/models/base.py b/server/src/poorbird/models/base.py new file mode 100644 index 0000000..c815f35 --- /dev/null +++ b/server/src/poorbird/models/base.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from sqlalchemy import MetaData +from sqlalchemy.orm import DeclarativeBase + +# Explicit names for every constraint. Without this, Alembic autogenerate +# cannot drop or alter constraints Postgres named for itself, and migrations +# start needing hand-written DDL. +NAMING_CONVENTION = { + "ix": "ix_%(table_name)s_%(column_0_N_name)s", + "uq": "uq_%(table_name)s_%(column_0_N_name)s", + "ck": "ck_%(table_name)s_%(constraint_name)s", + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", + "pk": "pk_%(table_name)s", +} + + +class Base(DeclarativeBase): + metadata = MetaData(naming_convention=NAMING_CONVENTION) diff --git a/server/src/poorbird/models/captures.py b/server/src/poorbird/models/captures.py new file mode 100644 index 0000000..cd07b77 --- /dev/null +++ b/server/src/poorbird/models/captures.py @@ -0,0 +1,186 @@ +"""Captures, observations, taxonomy and tags. + +Two structural decisions from SPEC 3, both load-bearing: + +1. ``captures`` 1--n ``observations``. One photo can hold two species, and can + legitimately hold none (a false trigger, an empty frame). A single + ``species`` column on the image would have to be undone later. +2. Human labels and model predictions share one table, separated by + ``source``. The edit UI is therefore already the training-data pipeline for + any future detection model, with no migration when that day comes. +""" + +from __future__ import annotations + +import uuid +from datetime import datetime + +from sqlalchemy import ( + BigInteger, + Boolean, + CheckConstraint, + Column, + DateTime, + Float, + ForeignKey, + Index, + Integer, + String, + Table, + Text, + Uuid, + func, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from .base import Base + +# API.md sends 'radar'; SPEC 3 predates the LD2410 decision and says 'pir'. +TRIGGERS = ("radar", "manual", "timer", "stream_grab") + + +class Capture(Base): + __tablename__ = "captures" + __table_args__ = ( + CheckConstraint("trigger IN " + str(TRIGGERS), name="trigger_valid"), + Index("ix_captures_device_received", "device_id", "received_at"), + Index("ix_captures_burst", "burst_id", "burst_index"), + Index("ix_captures_triage", "kept", "reviewed", "received_at"), + ) + + # UUID rather than a serial, because it is also the filename: + # /srv/poorbird/images/2026/09/08/.jpg (SPEC 3.3). + id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4) + device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE")) + + path: Mapped[str] = mapped_column(Text) + thumb_path: Mapped[str | None] = mapped_column(Text) + sha256: Mapped[str] = mapped_column(String(64), index=True) + width: Mapped[int | None] = mapped_column(Integer) + height: Mapped[int | None] = mapped_column(Integer) + bytes: Mapped[int] = mapped_column(BigInteger) + + # NULL when the device clock was unsynced. X-Captured-At: 0 means unsynced, + # NOT 1970 -- never store an epoch date for it (API.md). + captured_at_device: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + # SPEC C7: authoritative, always. + received_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + + trigger: Mapped[str] = mapped_column(String(16)) + burst_id: Mapped[str | None] = mapped_column(String(64)) + burst_index: Mapped[int | None] = mapped_column(Integer) + burst_count: Mapped[int | None] = mapped_column(Integer) + # SPEC 0 / API.md: this frame was captured BEFORE the trigger fired, out of + # the PSRAM ring. Usually the good ones -- the bird is still arriving. + pre_trigger: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") + frame_seq: Mapped[int | None] = mapped_column(Integer) + + radar_state: Mapped[int | None] = mapped_column(Integer) # 0 none 1 moving 2 stationary 3 both + radar_distance_cm: Mapped[int | None] = mapped_column(Integer) + radar_energy: Mapped[int | None] = mapped_column(Integer) + + battery_mv: Mapped[int | None] = mapped_column(Integer) + rssi: Mapped[int | None] = mapped_column(Integer) + temp_c: Mapped[float | None] = mapped_column(Float) + + reviewed: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") + # Soft reject. Drives retention -- see TODO Phase 5 and open question 8. + kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") + + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + + observations: Mapped[list[Observation]] = relationship( + back_populates="capture", cascade="all, delete-orphan" + ) + tags: Mapped[list[Tag]] = relationship(secondary="capture_tags", back_populates="captures") + + +class Observation(Base): + __tablename__ = "observations" + __table_args__ = ( + CheckConstraint("age IN ('adult', 'juvenile', 'unknown')", name="age_valid"), + CheckConstraint("sex IN ('male', 'female', 'unknown')", name="sex_valid"), + CheckConstraint( + "behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')", + name="behaviour_valid", + ), + CheckConstraint( + "certainty IN ('certain', 'probable', 'uncertain')", name="certainty_valid" + ), + CheckConstraint("source IN ('human', 'model')", name="source_valid"), + ) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + capture_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("captures.id", ondelete="CASCADE"), index=True + ) + taxon_id: Mapped[int | None] = mapped_column(ForeignKey("taxa.id", ondelete="RESTRICT")) + + individuals: Mapped[int] = mapped_column(Integer, default=1, server_default="1") + age: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'") + sex: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'") + behaviour: Mapped[str | None] = mapped_column(String(16)) + certainty: Mapped[str] = mapped_column( + String(16), default="certain", server_default="'certain'" + ) + notes: Mapped[str | None] = mapped_column(Text) + + source: Mapped[str] = mapped_column(String(8), default="human", server_default="'human'") + # Populated only when source = 'model'. Schema is ready; the pipeline is + # explicitly not built (SPEC Option C). + model_version: Mapped[str | None] = mapped_column(String(64)) + confidence: Mapped[float | None] = mapped_column(Float) + bbox: Mapped[dict | None] = mapped_column(JSONB) + + created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), onupdate=func.now() + ) + + capture: Mapped[Capture] = relationship(back_populates="observations") + taxon: Mapped[Taxon | None] = relationship() + + +class Taxon(Base): + """Seeded, never free text. + + This is what makes "species, biologically" real rather than a string + column that accumulates Kohlmeise, kohlmeise, Parus major and Kohlmeise? + as four distinct species (SPEC 3.2). + """ + + __tablename__ = "taxa" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + gbif_key: Mapped[int | None] = mapped_column(BigInteger, unique=True) + scientific_name: Mapped[str] = mapped_column(String(128), unique=True) + name_de: Mapped[str | None] = mapped_column(String(128), index=True) + name_en: Mapped[str | None] = mapped_column(String(128), index=True) + family: Mapped[str | None] = mapped_column(String(64)) + # "order" is reserved in SQL; SQLAlchemy quotes it. + order: Mapped[str | None] = mapped_column("order", String(64)) + iucn_status: Mapped[str | None] = mapped_column(String(8)) + # Ranks the autocomplete. The local garden list comes first. + is_local_common: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") + + +class Tag(Base): + __tablename__ = "tags" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + label: Mapped[str] = mapped_column(String(64), unique=True) + colour: Mapped[str | None] = mapped_column(String(16)) + + captures: Mapped[list[Capture]] = relationship(secondary="capture_tags", back_populates="tags") + + +capture_tags = Table( + "capture_tags", + Base.metadata, + Column("capture_id", ForeignKey("captures.id", ondelete="CASCADE"), primary_key=True), + Column("tag_id", ForeignKey("tags.id", ondelete="CASCADE"), primary_key=True), +) diff --git a/server/src/poorbird/models/devices.py b/server/src/poorbird/models/devices.py new file mode 100644 index 0000000..14882e5 --- /dev/null +++ b/server/src/poorbird/models/devices.py @@ -0,0 +1,230 @@ +"""Devices, their command queue, their telemetry and the firmware images. + +Field names follow firmware/API.md, which is the contract the firmware +actually implements. Where SPEC.md 3 and API.md disagree, API.md wins and the +difference is noted inline. +""" + +from __future__ import annotations + +from datetime import datetime + +from sqlalchemy import ( + BigInteger, + Boolean, + CheckConstraint, + DateTime, + Float, + ForeignKey, + Index, + Integer, + String, + Text, + func, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from .base import Base + +COMMAND_TYPES = ( + "apply_config", + "capture_now", + "report_status", + "wake_and_hold", + "sleep_now", + "stream_start", + "stream_stop", + "ota_update", + "reboot", +) + +STATUS_REASONS = ( + "heartbeat", + "periodic", + "after_event", + "before_sleep", + "before_night_sleep", + "on_request", +) + + +class Device(Base): + __tablename__ = "devices" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + + # eFuse MAC in hex. Survives reflashing, which is what makes it an + # identity rather than a name (API.md, Enrollment). + device_uid: Mapped[str] = mapped_column(String(32), unique=True, index=True) + name: Mapped[str] = mapped_column(String(64)) + mac: Mapped[str | None] = mapped_column(String(32)) + hw_revision: Mapped[str | None] = mapped_column(String(64)) + fw_version: Mapped[str | None] = mapped_column(String(32)) + + # Only the hash is stored. The token is high-entropy, so a fast hash is + # defensible here (API.md). + # + # Indexed because every authenticated device request resolves a bearer + # token by this column: it is the hottest lookup in the device API. + # + # Unique so that two devices can never end up sharing a token. NULLs stay + # distinct in Postgres, so any number of devices may sit here un-enrolled + # or revoked. + token_hash: Mapped[str | None] = mapped_column(String(128), unique=True, index=True) + # Per-device re-enrollment credential, so a rotated token cannot strand a + # camera that has no USB access once mounted (SPEC 0). + reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128)) + + # --- last-known conditions, denormalised from device_status for the list view + last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + battery_mv: Mapped[int | None] = mapped_column(Integer) + battery_pct: Mapped[int | None] = mapped_column(Integer) + # false means NOT MEASURED, not empty. No divider is wired by default. + # Render as an em dash, never as a low-battery alarm (API.md, SPEC 0). + battery_valid: Mapped[bool] = mapped_column(Boolean, default=False) + rssi: Mapped[int | None] = mapped_column(Integer) + temp_c: Mapped[float | None] = mapped_column(Float) + # Reported every heartbeat so the UI can show command latency honestly (SPEC 0). + awake: Mapped[bool] = mapped_column(Boolean, default=True) + + # --- settings surface + # One JSONB document rather than forty columns. This mirrors GET /config + # exactly: every key is optional and the device merges and clamps partial + # documents, so a strict column-per-key schema would be a migration every + # time the firmware gains a tunable. The UI edits it as a form; validation + # lives in a Pydantic model, not in the DDL. + config: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}") + # The only thing the device compares. Bump on every config change. + config_version: Mapped[int] = mapped_column(Integer, default=1, server_default="1") + + heartbeat_interval_s: Mapped[int] = mapped_column(Integer, default=300, server_default="300") + status_interval_s: Mapped[int] = mapped_column(Integer, default=900, server_default="900") + responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") + + enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + + commands: Mapped[list[DeviceCommand]] = relationship( + back_populates="device", cascade="all, delete-orphan" + ) + + +class DeviceCommand(Base): + """SPEC C1: the device is never pushed to, it drains this queue. + + Commands ride along on the /ingest and /heartbeat response, so a capture + that was going to happen anyway also delivers the queue at no extra cost. + /status deliberately returns nothing actionable (API.md). + """ + + __tablename__ = "device_commands" + __table_args__ = ( + CheckConstraint( + "type IN " + str(COMMAND_TYPES), + name="type_valid", + ), + CheckConstraint( + "ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')", + name="ack_status_valid", + ), + Index("ix_device_commands_pending", "device_id", "created_at"), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE")) + type: Mapped[str] = mapped_column(String(32)) + payload: Mapped[dict | None] = mapped_column(JSONB) + + created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + ack_status: Mapped[str | None] = mapped_column(String(16)) + result: Mapped[str | None] = mapped_column(Text) + expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + device: Mapped[Device] = relationship(back_populates="commands") + + +class Firmware(Base): + __tablename__ = "firmware" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + version: Mapped[str] = mapped_column(String(32), unique=True) + semver: Mapped[str | None] = mapped_column(String(32)) + file_path: Mapped[str] = mapped_column(Text) + sha256: Mapped[str] = mapped_column(String(64)) + size_bytes: Mapped[int] = mapped_column(BigInteger) + release_notes: Mapped[str | None] = mapped_column(Text) + # SPEC C6 / API.md: the device refuses to flash below this. + min_battery_pct: Mapped[int] = mapped_column(Integer, default=50, server_default="50") + uploaded_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) + uploaded_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + is_target: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") + + +class DeviceStatus(Base): + """Time series, one row per conditions report (SPEC 0). + + The flat columns are the ones worth querying and charting. ``raw`` keeps + the whole posted body so nothing is lost when the firmware grows a field + before the server learns about it. + """ + + __tablename__ = "device_status" + __table_args__ = ( + CheckConstraint("reason IN " + str(STATUS_REASONS), name="reason_valid"), + Index("ix_device_status_device_at", "device_id", "at"), + ) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE")) + at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + reason: Mapped[str] = mapped_column(String(32)) + + battery_mv: Mapped[int | None] = mapped_column(Integer) + battery_pct: Mapped[int | None] = mapped_column(Integer) + battery_valid: Mapped[bool | None] = mapped_column(Boolean) + + awake_ms: Mapped[int | None] = mapped_column(BigInteger) + boot_count: Mapped[int | None] = mapped_column(Integer) + wake_cause: Mapped[str | None] = mapped_column(String(16)) + last_sleep_s: Mapped[int | None] = mapped_column(Integer) + total_sleep_s: Mapped[int | None] = mapped_column(BigInteger) + + # The device's opinion, not the truth: these live in RTC memory and reset + # on power loss. `captures` is authoritative. Their real value is the GAP + # between captured and delivered, which is an upload-health signal. + captured_today: Mapped[int | None] = mapped_column(Integer) + delivered_today: Mapped[int | None] = mapped_column(Integer) + failed_today: Mapped[int | None] = mapped_column(Integer) + events_today: Mapped[int | None] = mapped_column(Integer) + # Days since epoch, local time; stays 0 until the clock syncs, so the + # pre-sync bucket is a phantom day. Do not chart it (API.md). + day_index: Mapped[int | None] = mapped_column(Integer) + + is_night: Mapped[bool | None] = mapped_column(Boolean) + nightlight_on: Mapped[bool | None] = mapped_column(Boolean) + cam_profile: Mapped[str | None] = mapped_column(String(16)) + + # 0 here means no valid frame was decoded at any rate: wiring or a dead + # module, and worth an alert (API.md). + radar_baud: Mapped[int | None] = mapped_column(Integer) + radar_uart_ok: Mapped[bool | None] = mapped_column(Boolean) + stream_active: Mapped[bool | None] = mapped_column(Boolean) + + rssi: Mapped[int | None] = mapped_column(Integer) + ip: Mapped[str | None] = mapped_column(String(45)) + free_heap: Mapped[int | None] = mapped_column(BigInteger) + free_psram: Mapped[int | None] = mapped_column(BigInteger) + ring_depth: Mapped[int | None] = mapped_column(Integer) + + time_synced: Mapped[bool | None] = mapped_column(Boolean) + device_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + fw_version: Mapped[str | None] = mapped_column(String(32)) + config_version: Mapped[int | None] = mapped_column(Integer) + + raw: Mapped[dict | None] = mapped_column(JSONB) diff --git a/server/src/poorbird/models/ops.py b/server/src/poorbird/models/ops.py new file mode 100644 index 0000000..124fa44 --- /dev/null +++ b/server/src/poorbird/models/ops.py @@ -0,0 +1,108 @@ +"""Operational tables: settings, audit log, backup runs, and the job queue.""" + +from __future__ import annotations + +from datetime import datetime + +from sqlalchemy import ( + BigInteger, + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + String, + Text, + func, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base + +JOB_STATUSES = ("queued", "running", "done", "failed") + + +class Setting(Base): + """SPEC 3.4. "Fully configurable" needs a boundary or it never finishes. + + Server scope: retention policy, thumbnail size, backup schedule + target, + alarm thresholds and channels, default theme, default locale, session + lifetime. Anything not on that list is a code change, deliberately. + + Backup schedule lives here rather than in a systemd timer, which is why + scheduling runs in the worker (TODO Phase 1.2). + """ + + __tablename__ = "settings" + __table_args__ = (CheckConstraint("scope IN ('server', 'device')", name="scope_valid"),) + + key: Mapped[str] = mapped_column(String(64), primary_key=True) + value: Mapped[str | None] = mapped_column(Text) + value_type: Mapped[str] = mapped_column(String(16), default="str", server_default="'str'") + scope: Mapped[str] = mapped_column(String(16), default="server", server_default="'server'") + updated_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), onupdate=func.now() + ) + + +class AuditLog(Base): + __tablename__ = "audit_log" + __table_args__ = (Index("ix_audit_log_entity", "entity", "entity_id", "at"),) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) + action: Mapped[str] = mapped_column(String(64)) + entity: Mapped[str] = mapped_column(String(64)) + entity_id: Mapped[str | None] = mapped_column(String(64)) + before: Mapped[dict | None] = mapped_column(JSONB) + after: Mapped[dict | None] = mapped_column(JSONB) + ip: Mapped[str | None] = mapped_column(String(45)) + + +class BackupRun(Base): + __tablename__ = "backup_runs" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + status: Mapped[str] = mapped_column(String(16), default="running") + bytes: Mapped[int | None] = mapped_column(BigInteger) + snapshot_id: Mapped[str | None] = mapped_column(String(64)) + # A backup you have never restored is a hypothesis: set by the monthly + # restore test (TODO Phase 5). + restore_tested_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + error: Mapped[str | None] = mapped_column(Text) + + +class Job(Base): + """Postgres-backed queue, claimed with FOR UPDATE SKIP LOCKED. No Redis. + + This second writer is the concrete reason SPEC C8 pushed past SQLite. + """ + + __tablename__ = "jobs" + __table_args__ = ( + CheckConstraint("status IN " + str(JOB_STATUSES), name="status_valid"), + # The claim query's covering index. + Index("ix_jobs_claimable", "status", "run_at", "priority"), + ) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + kind: Mapped[str] = mapped_column(String(64)) + payload: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}") + status: Mapped[str] = mapped_column(String(16), default="queued", server_default="'queued'") + priority: Mapped[int] = mapped_column(Integer, default=0, server_default="0") + + run_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0") + max_attempts: Mapped[int] = mapped_column(Integer, default=3, server_default="3") + + locked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + locked_by: Mapped[str | None] = mapped_column(String(128)) + last_error: Mapped[str | None] = mapped_column(Text) + + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/server/src/poorbird/models/users.py b/server/src/poorbird/models/users.py new file mode 100644 index 0000000..4acf399 --- /dev/null +++ b/server/src/poorbird/models/users.py @@ -0,0 +1,79 @@ +"""Users and sessions. + +Devices are NOT users (SPEC 3.1). A device authenticates with a bearer token +scoped to /ingest, /heartbeat, /status, /config, /commands/*/ack, /firmware/* +and /stream/*. It can never read the gallery. +""" + +from __future__ import annotations + +import uuid +from datetime import datetime + +from sqlalchemy import ( + Boolean, + CheckConstraint, + DateTime, + ForeignKey, + String, + Uuid, + func, +) +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base + +ROLES = ("admin", "editor", "viewer") +THEMES = ("light", "dark", "blue") + + +class User(Base): + __tablename__ = "users" + __table_args__ = ( + CheckConstraint("role IN " + str(ROLES), name="role_valid"), + CheckConstraint("theme IN " + str(THEMES), name="theme_valid"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(64), unique=True) + email: Mapped[str | None] = mapped_column(String(255)) + # Argon2id. Populated in Phase 3; nothing writes it yet. + password_hash: Mapped[str | None] = mapped_column(String(255)) + role: Mapped[str] = mapped_column(String(16), default="viewer", server_default="'viewer'") + totp_secret: Mapped[str | None] = mapped_column(String(64)) + is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") + + theme: Mapped[str] = mapped_column(String(16), default="light", server_default="'light'") + locale: Mapped[str] = mapped_column(String(8), default="de", server_default="'de'") + + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + +class Session(Base): + """A signed-in browser. + + ``id`` is internal and never leaves the server. The cookie carries a + separate high-entropy token of which only the SHA-256 is stored, exactly as + device tokens work (api/deps.py). Using ``id`` as the cookie value would be + simpler and would mean a database dump handed over every live session. + + ``csrf_token`` is per session rather than global, so the double-submit check + cannot be satisfied by an attacker who can merely set a cookie on the + domain -- they would also need this session's token, which is what they do + not have. + """ + + __tablename__ = "sessions" + + id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + # SHA-256 hex of the cookie value. Unique so a collision is a constraint + # error rather than two users sharing a session, and indexed because this + # is the lookup on every authenticated request. + token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True) + csrf_token: Mapped[str] = mapped_column(String(64)) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True) + ip: Mapped[str | None] = mapped_column(String(45)) + user_agent: Mapped[str | None] = mapped_column(String(255)) diff --git a/server/src/poorbird/passwords.py b/server/src/poorbird/passwords.py new file mode 100644 index 0000000..52190f9 --- /dev/null +++ b/server/src/poorbird/passwords.py @@ -0,0 +1,97 @@ +"""User password hashing (SPEC 3.1, REVIEW SEC-009). + +Argon2id, via ``argon2-cffi``. Lives at the package root rather than under +``api/`` because the CLI creates the first user before any HTTP request exists, +and a CLI importing from ``api`` would be the wrong way round -- the same reason +``images.py`` sits here. + +**Why not the SHA-256 in api/deps.py.** That one hashes device tokens, which are +256 bits of CSPRNG output: there is no dictionary to attack, and a per-request +Argon2 would cost every heartbeat. A password is a human-chosen secret from a +very small space, so the hash has to be deliberately slow. Same word, opposite +requirements. +""" + +from __future__ import annotations + +import logging + +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError + +log = logging.getLogger(__name__) + +# argon2-cffi's defaults track the RFC 9106 guidance and move with the library, +# which is the point of not pinning our own numbers here. At the time of writing +# that is time_cost=3, memory_cost=64 MiB, parallelism=4 -- tens of milliseconds +# on this hardware, which is the intended cost. +_hasher = PasswordHasher() + +# A floor, not a policy engine. Length is the only property that reliably +# correlates with strength; composition rules mostly produce "Passw0rd!". +MIN_PASSWORD_LENGTH = 12 + +# Argon2 reads at most this much, and a huge body should not become a CPU cost. +# 1 KiB is far past any real passphrase. +MAX_PASSWORD_LENGTH = 1024 + + +class WeakPassword(ValueError): + """Raised by :func:`validate_password_strength`.""" + + +def validate_password_strength(password: str) -> None: + """Raise :class:`WeakPassword` if the password is unusable. + + Deliberately minimal: a length floor and a check that it is not entirely + whitespace. Anything more opinionated belongs in the UI, where it can give + feedback as the user types instead of rejecting after the fact. + """ + if len(password) < MIN_PASSWORD_LENGTH: + raise WeakPassword(f"password must be at least {MIN_PASSWORD_LENGTH} characters") + if len(password) > MAX_PASSWORD_LENGTH: + raise WeakPassword(f"password must be at most {MAX_PASSWORD_LENGTH} characters") + if not password.strip(): + raise WeakPassword("password must not be only whitespace") + + +def hash_password(password: str) -> str: + """Hash a password for storage in ``users.password_hash``. + + The result carries its own parameters, so raising the cost later does not + invalidate existing hashes -- see :func:`needs_rehash`. + """ + return _hasher.hash(password) + + +def verify_password(password: str, stored_hash: str | None) -> bool: + """True if ``password`` matches ``stored_hash``. + + Never raises for an ordinary wrong password, a NULL hash or a corrupt one: + all three are simply "no". A user row with ``password_hash IS NULL`` is one + that has never had a password set, and it must not be loggable-in rather + than crashing the login route. + """ + if not stored_hash: + return False + try: + return _hasher.verify(stored_hash, password) + except (VerifyMismatchError, VerificationError): + return False + except InvalidHashError: + # The stored value is not an Argon2 hash at all. Worth saying out loud, + # because it means something wrote that column by hand. + log.error("stored password hash is not a valid Argon2 hash") + return False + + +def needs_rehash(stored_hash: str) -> bool: + """True if this hash was made with weaker parameters than current defaults. + + Login is the only moment the plaintext is available, so it is the only + moment a hash can be upgraded. Call this after a successful verify. + """ + try: + return _hasher.check_needs_rehash(stored_hash) + except InvalidHashError: + return False diff --git a/server/src/poorbird/schema_compare.py b/server/src/poorbird/schema_compare.py new file mode 100644 index 0000000..0ae6bae --- /dev/null +++ b/server/src/poorbird/schema_compare.py @@ -0,0 +1,49 @@ +"""Shared Alembic comparison options. + +Used by both ``migrations/env.py`` and the schema-drift test, so autogenerate +and the test can never disagree about what counts as a difference. +""" + +from __future__ import annotations + +from typing import Any + + +def _normalise_default(value: Any) -> str: + """Strip a Postgres type cast and the SQL quoting from a default. + + Postgres reflects a varchar default as ``'viewer'::character varying`` + while the model's metadata renders it as ``'viewer'``. Compared literally, + every string default in the schema looks like drift, forever -- which + trains you to ignore the one time it isn't. + """ + text = str(value).strip() + if "::" in text: + text = text.split("::", 1)[0] + return text.strip().strip("'").strip().lower() + + +def compare_server_default( + context: Any, + inspected_column: Any, + metadata_column: Any, + inspected_default: Any, + metadata_default: Any, + rendered_metadata_default: Any, +) -> bool | None: + """Return True when the defaults genuinely differ. + + Returning None hands the decision back to Alembic, which is what we want + whenever one side has no default at all -- that IS a real difference and + Alembic's own logic reports it correctly. + """ + if inspected_default is None or rendered_metadata_default is None: + return None + return _normalise_default(inspected_default) != _normalise_default(rendered_metadata_default) + + +# One place to define what "compare the schema" means. +COMPARE_OPTS: dict[str, Any] = { + "compare_type": True, + "compare_server_default": compare_server_default, +} diff --git a/server/src/poorbird/seed.py b/server/src/poorbird/seed.py new file mode 100644 index 0000000..05edb0a --- /dev/null +++ b/server/src/poorbird/seed.py @@ -0,0 +1,257 @@ +"""Synthetic captures for developing the gallery (TODO 3.0). + +Generated, not downloaded. Three reasons, from the recorded decision: + +* no image licensing question at all, and no binary blobs in git; +* it can produce the *volume* a virtualised grid has to be tested against, + which no set of real photos on hand would; and +* a real photo proves nothing about a gallery that a generated one does not. + +**Seeded data is confined to its own device**, whose ``device_uid`` starts with +``SEED_UID_PREFIX``. That is what makes ``--clear`` safe: it deletes captures +belonging to seed devices and nothing else, so a real camera's frames are never +in scope. Without that boundary a convenience command sits next to real data +holding a delete, which is not a risk worth carrying for test rows. +""" + +from __future__ import annotations + +import logging +import random +import secrets +import uuid +from datetime import UTC, datetime, timedelta + +from sqlalchemy import delete, select +from sqlalchemy.orm import Session + +from .config import get_settings +from .images import ( + make_thumbnail, + relative_image_path, + relative_thumb_path, + write_atomically, +) +from .models import Capture, Device, Job + +log = logging.getLogger(__name__) + +# Deliberately hex-looking, so it is a plausible device_uid, while still being +# unmistakable in a listing. "5eed". +SEED_UID_PREFIX = "5eed" + +# A burst is what the firmware actually sends: a handful of frames around one +# radar trigger, the first of them pulled from the PSRAM pre-trigger ring. +BURST_MIN, BURST_MAX = 3, 5 + +# Realistic per API.md/SPEC: UXGA frames of a few hundred KB. +FRAME_WIDTH, FRAME_HEIGHT = 1600, 1200 + +# Birds are diurnal, and a gallery grouped by day looks wrong if captures are +# spread evenly around the clock. Weight toward daylight. +_DAY_HOURS = list(range(5, 21)) + + +def _synthetic_jpeg(width: int, height: int, seed: int) -> bytes: + """A distinct, cheap JPEG per capture. + + Distinct matters more than pretty: identical tiles make it impossible to + see whether the grid is actually scrolling, and a flat colour compresses to + a few hundred bytes, which would not exercise the thumbnail path at a + realistic size. A coarse gradient plus noise blocks gives both. + """ + import io + + from PIL import Image, ImageDraw + + rng = random.Random(seed) + image = Image.new("RGB", (width, height)) + draw = ImageDraw.Draw(image) + + base = (rng.randint(40, 140), rng.randint(70, 170), rng.randint(40, 120)) + # Coarse bands rather than per-pixel work: 500 frames at 1600x1200 is + # enough to notice, and the point is bytes on disk, not art. + band = max(8, height // 48) + for y in range(0, height, band): + shade = y / height + draw.rectangle( + [0, y, width, y + band], + fill=( + min(255, int(base[0] * (0.6 + shade))), + min(255, int(base[1] * (0.6 + shade))), + min(255, int(base[2] * (0.6 + shade))), + ), + ) + + for _ in range(60): + x, y = rng.randint(0, width), rng.randint(0, height) + size = rng.randint(20, 90) + draw.ellipse( + [x, y, x + size, y + size], + fill=(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)), + ) + + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=78) + return buffer.getvalue() + + +def seed_device(db: Session, name: str) -> Device: + """The device seeded captures hang off. Reused if it already exists.""" + device = db.scalar( + select(Device).where(Device.name == name, Device.device_uid.startswith(SEED_UID_PREFIX)) + ) + if device is not None: + return device + + device = Device( + device_uid=f"{SEED_UID_PREFIX}{secrets.token_hex(6)}", + name=name, + # No token. A seed device is a row for the gallery to point at, not a + # camera that can authenticate -- issuing it a working credential + # would be creating a real way in for the sake of test data. + token_hash=None, + enabled=True, + battery_valid=False, + ) + db.add(device) + db.commit() + db.refresh(device) + return device + + +def generate( + db: Session, + *, + count: int, + days: int, + device_name: str, + thumbnails: bool, + progress: bool = True, +) -> int: + """Create ``count`` captures spread over the last ``days``. Returns how many. + + Frames are written to disk for real, because a gallery whose rows point at + files that do not exist tests nothing about the delivery path -- which is + the half most likely to be wrong. + """ + settings = get_settings() + device = seed_device(db, device_name) + rng = random.Random() + + made = 0 + while made < count: + remaining = count - made + burst_size = min(rng.randint(BURST_MIN, BURST_MAX), remaining) + # Absorb a tail too short to be a burst. Plain truncation leaves a + # final burst of one or two frames with burst_count=1, which no camera + # sends -- and a one-frame burst is entirely pre-trigger, so it also + # makes that flag meaningless. Bursts here are 3-7 rather than 3-5, + # which is a better trade than inventing data the firmware cannot + # produce. (This was a flaky test before it was a comment: whether it + # happened depended on the random sizes.) + if 0 < remaining - burst_size < BURST_MIN: + burst_size = remaining + burst_id = str(uuid.uuid4()) + + # One trigger event, somewhere in the window, at a plausible hour. + moment = datetime.now(UTC) - timedelta( + days=rng.uniform(0, days), + ) + moment = moment.replace(hour=rng.choice(_DAY_HOURS), minute=rng.randint(0, 59)) + + for index in range(burst_size): + capture_id = uuid.uuid4() + # Frames within a burst are milliseconds apart, which is exactly + # the received_at tie the gallery cursor has to survive. + captured = moment + timedelta(milliseconds=index * 120) + received = captured + timedelta(milliseconds=rng.randint(200, 1500)) + + data = _synthetic_jpeg(FRAME_WIDTH, FRAME_HEIGHT, seed=capture_id.int % (2**31)) + relative = relative_image_path(capture_id, received) + write_atomically(settings.image_root / relative, data) + + capture = Capture( + id=capture_id, + device_id=device.id, + path=relative, + sha256=secrets.token_hex(32), + width=FRAME_WIDTH, + height=FRAME_HEIGHT, + bytes=len(data), + captured_at_device=captured, + received_at=received, + trigger="radar" if rng.random() < 0.9 else "manual", + burst_id=burst_id, + burst_index=index, + burst_count=burst_size, + # The first frame or two come out of the pre-trigger ring, and + # are usually the good ones -- the bird is still arriving. + pre_trigger=index < (1 if burst_size < 4 else 2), + frame_seq=made + index, + radar_state=rng.choice([1, 2, 3]), + radar_distance_cm=rng.randint(60, 320), + radar_energy=rng.randint(20, 100), + battery_mv=None, + rssi=rng.randint(-82, -45), + temp_c=round(rng.uniform(2.0, 26.0), 1), + reviewed=rng.random() < 0.2, + kept=rng.random() > 0.1, + ) + + if thumbnails: + thumb_relative = relative_thumb_path(capture_id) + thumb_bytes, _ = make_thumbnail(settings.image_root / relative) + write_atomically(settings.thumb_root / thumb_relative, thumb_bytes) + capture.thumb_path = thumb_relative + + db.add(capture) + + made += burst_size + # Commit per burst, so interrupting a long run leaves whole bursts + # rather than a half-written one, and so 500 rows are not one + # transaction held open across 500 image encodes. + db.commit() + if progress and made % 50 < burst_size: + print(f" {made}/{count}") + + return made + + +def clear(db: Session) -> tuple[int, int]: + """Delete every seeded capture and device. Returns (captures, devices). + + Scoped to seed devices by ``device_uid`` prefix, which is the whole reason + that prefix exists. A real camera's captures are never in scope, and this + command therefore cannot be the thing that loses them. + """ + devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() + if not devices: + return 0, 0 + + settings = get_settings() + device_ids = [d.id for d in devices] + captures = db.scalars(select(Capture).where(Capture.device_id.in_(device_ids))).all() + + for capture in captures: + (settings.image_root / capture.path).unlink(missing_ok=True) + if capture.thumb_path: + (settings.thumb_root / capture.thumb_path).unlink(missing_ok=True) + + # Thumbnail jobs reference captures that are about to stop existing. The + # handler already tolerates a missing capture -- retention will do this + # routinely in Phase 5 -- but leaving them means the worker waking up to do + # pointless work and logging about it, which looks like a fault later. + capture_ids = [str(c.id) for c in captures] + if capture_ids: + db.execute( + delete(Job).where( + Job.kind == "thumbnail", + Job.payload["capture_id"].astext.in_(capture_ids), + ) + ) + + db.execute(delete(Capture).where(Capture.device_id.in_(device_ids))) + db.execute(delete(Device).where(Device.id.in_(device_ids))) + db.commit() + return len(captures), len(devices) diff --git a/server/src/poorbird/totp.py b/server/src/poorbird/totp.py new file mode 100644 index 0000000..c5ad0d0 --- /dev/null +++ b/server/src/poorbird/totp.py @@ -0,0 +1,65 @@ +"""TOTP second factor (TODO 3.0, SPEC Q14). + +Built now rather than later, on purpose. Retrofitting 2FA means reopening the +login flow, the session model, the user model and the audit log at once, and +``users.totp_secret`` was in the schema from Phase 1 for exactly this. + +Policy, from TODO 3.0: **enforced for ``admin``, opt-in for everyone else.** +Over Tailscale the network layer already demands an enrolled device, so UI 2FA +is belt-and-braces; the day this is served from a public domain it stops being +optional. A ``require_2fa`` server setting flips the whole thing. +""" + +from __future__ import annotations + +import pyotp + +# RFC 6238 defaults, which is also what every authenticator app assumes. +DIGITS = 6 +PERIOD_S = 30 + +# Accept the adjacent 30-second steps as well as the current one, so a phone +# clock a few seconds out still works. One step either side is the usual +# compromise: three windows is 90 seconds of exposure rather than 30, and +# anything wider starts to matter. +VALID_WINDOW = 1 + +ISSUER = "poorBird" + + +def new_secret() -> str: + """A fresh base32 secret for ``users.totp_secret``.""" + return pyotp.random_base32() + + +def provisioning_uri(secret: str, username: str) -> str: + """The ``otpauth://`` URI an authenticator app scans as a QR code.""" + return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).provisioning_uri( + name=username, issuer_name=ISSUER + ) + + +def verify(secret: str | None, code: str | None) -> bool: + """True if ``code`` is currently valid for ``secret``. + + Returns False rather than raising for a missing secret, a missing code or a + malformed one. pyotp compares with ``hmac.compare_digest`` internally, so a + wrong code does not leak its position through timing. + + **Known limitation:** a code stays valid for its whole window, so it can be + replayed within ~90 seconds by someone who observed it. Preventing that + needs the last-accepted counter persisted per user, which is a column this + schema does not have yet. Worth adding if this is ever exposed publicly; + on a Tailscale-only LAN the observer has already had to get onto the + network. Not silently ignored -- just not paid for yet. + """ + if not secret or not code: + return False + + code = code.strip().replace(" ", "") + if not code.isdigit() or len(code) != DIGITS: + return False + + return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).verify( + code, valid_window=VALID_WINDOW + ) diff --git a/server/src/poorbird/worker/__init__.py b/server/src/poorbird/worker/__init__.py new file mode 100644 index 0000000..9c4f0db --- /dev/null +++ b/server/src/poorbird/worker/__init__.py @@ -0,0 +1,3 @@ +from .main import run + +__all__ = ["run"] diff --git a/server/src/poorbird/worker/handlers.py b/server/src/poorbird/worker/handlers.py new file mode 100644 index 0000000..e7f155a --- /dev/null +++ b/server/src/poorbird/worker/handlers.py @@ -0,0 +1,156 @@ +"""Job handlers. + +A handler takes a session and a payload, and either returns (success) or +raises (retry, then park). Register with ``@handler("kind")``. + +Phase 2 adds ``thumbnail``. Phase 5 adds ``backup``, ``retention`` and +``restore_test``. +""" + +from __future__ import annotations + +import logging +import uuid +from collections.abc import Callable +from datetime import UTC, datetime +from typing import Any + +from pydantic import BaseModel, ValidationError +from sqlalchemy import delete, text +from sqlalchemy.orm import Session + +from ..config import get_settings +from ..images import UndecodableImage, make_thumbnail, relative_thumb_path, write_atomically +from ..models import Capture +from ..models import Session as UserSession + +log = logging.getLogger(__name__) + +Handler = Callable[[Session, dict[str, Any]], None] +HANDLERS: dict[str, Handler] = {} + + +def handler(kind: str) -> Callable[[Handler], Handler]: + def register(fn: Handler) -> Handler: + if kind in HANDLERS: + raise RuntimeError(f"duplicate handler for {kind!r}") + HANDLERS[kind] = fn + return fn + + return register + + +@handler("noop") +def _noop(session: Session, payload: dict[str, Any]) -> None: + """Smoke test for the queue. `poorbird enqueue noop` exercises the path.""" + log.info("noop job ran", extra={"payload": payload}) + + +class ThumbnailPayload(BaseModel): + """Validated job payload (REVIEW SEC-003). + + Job payloads are JSONB and nothing stops a malformed one being enqueued, + so a handler that indexes straight into the dict fails with a KeyError + three retries later instead of saying what was wrong. + """ + + capture_id: uuid.UUID + + +@handler("thumbnail") +def _thumbnail(session: Session, payload: dict[str, Any]) -> None: + """Build the WebP thumbnail for one capture. + + Enqueued by /ingest after the frame is on disk and in the same + transaction as the capture row, so by the time this runs both exist. + """ + try: + job = ThumbnailPayload.model_validate(payload) + except ValidationError as exc: + # Permanently wrong, not transient. Raising would spend three + # attempts rediscovering that the payload is still malformed. + log.error("thumbnail job payload is invalid", extra={"payload": payload, "error": str(exc)}) + return + + capture = session.get(Capture, job.capture_id) + if capture is None: + # Deleted between enqueue and now. Retention will do this routinely + # once Phase 5 exists, and it is not a failure. + log.info("thumbnail skipped, capture is gone", extra={"capture_id": str(job.capture_id)}) + return + + settings = get_settings() + source = settings.image_root / capture.path + + if not source.is_file(): + # The file should be there: ingest writes it before committing the + # row. Its absence is a real fault, and transient causes (a mount + # that has not come back yet) are worth retrying for. + raise FileNotFoundError(f"capture file missing: {source}") + + try: + data, (width, height) = make_thumbnail(source) + except UndecodableImage as exc: + # A frame that cannot be decoded will never decode. Record it and + # finish, rather than retrying twice more to learn the same thing. + log.warning( + "capture could not be decoded, leaving it without a thumbnail", + extra={"capture_id": str(capture.id), "path": capture.path, "error": str(exc)}, + ) + return + + relative = relative_thumb_path(capture.id) + write_atomically(settings.thumb_root / relative, data) + + capture.thumb_path = relative + # Ingest reads dimensions from the JPEG header, which can be missing or + # unparseable. This is the first full decode, so fill in what it missed. + if capture.width is None or capture.height is None: + capture.width, capture.height = width, height + + session.commit() + + log.info( + "thumbnail written", + extra={"capture_id": str(capture.id), "path": relative, "bytes": len(data)}, + ) + + +@handler("purge_expired_sessions") +def _purge_expired_sessions(session: Session, payload: dict[str, Any]) -> None: + """Delete expired WebUI sessions. + + Housekeeping, not security: expiry is already enforced on every read + (api/sessions.resolve_session), so a row left here is inert and cannot + authenticate anything. This only stops the table growing for as long as the + server runs. + """ + result = session.execute(delete(UserSession).where(UserSession.expires_at <= datetime.now(UTC))) + session.commit() + if result.rowcount: + log.info("purged expired sessions", extra={"count": result.rowcount}) + + +@handler("prune_expired_commands") +def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None: + """Expire commands the device never came back for. + + A queued wake_and_hold from three days ago should not fire the moment a + camera reconnects after an outage. + """ + result = session.execute( + text( + """ + UPDATE device_commands + SET ack_status = 'failed', + acked_at = now(), + result = 'expired before delivery' + WHERE expires_at IS NOT NULL + AND expires_at < now() + AND acked_at IS NULL + """ + ) + ) + session.commit() + if result.rowcount: + log.info("expired stale device commands", extra={"count": result.rowcount}) diff --git a/server/src/poorbird/worker/main.py b/server/src/poorbird/worker/main.py new file mode 100644 index 0000000..d7b7d4c --- /dev/null +++ b/server/src/poorbird/worker/main.py @@ -0,0 +1,140 @@ +"""Worker process: job queue consumer plus the scheduler. + +Scheduling lives here rather than in systemd timers. SPEC 3.4 makes the backup +schedule and the retention policy UI-editable server settings, and a +UI-editable timer would mean the app writing unit files and calling +``daemon-reload`` behind a polkit rule. In-app, a schedule is a settings row. +(TODO Phase 1.2.) +""" + +from __future__ import annotations + +import logging +import signal +import threading +from typing import Any + +from apscheduler.schedulers.background import BackgroundScheduler + +from ..config import get_settings +from ..db import SessionLocal +from ..logging_setup import configure_logging +from . import queue +from .handlers import HANDLERS + +log = logging.getLogger(__name__) + +_stop = threading.Event() + + +def _run_one(job: dict[str, Any]) -> None: + kind = job["kind"] + fn = HANDLERS.get(kind) + with SessionLocal() as session: + if fn is None: + queue.fail(session, job["id"], f"no handler registered for {kind!r}") + log.error("unknown job kind", extra={"kind": kind, "job_id": job["id"]}) + return + try: + fn(session, job["payload"] or {}) + except Exception as exc: # noqa: BLE001 - a handler must not kill the worker + session.rollback() + log.exception("job failed", extra={"kind": kind, "job_id": job["id"]}) + queue.fail(session, job["id"], f"{type(exc).__name__}: {exc}") + else: + queue.complete(session, job["id"]) + log.info("job done", extra={"kind": kind, "job_id": job["id"]}) + + +def _build_scheduler() -> BackgroundScheduler: + """Periodic work, enqueued rather than executed inline. + + The scheduler only ever *enqueues*. That keeps every unit of work in one + place -- the queue -- where it is visible, retried and auditable, instead + of some jobs running inside a timer callback where a failure disappears. + """ + scheduler = BackgroundScheduler(timezone="UTC") + + def _enqueue(kind: str) -> None: + with SessionLocal() as session: + queue.enqueue(session, kind) + session.commit() + + scheduler.add_job( + lambda: _enqueue("prune_expired_commands"), + "interval", + minutes=15, + id="prune_expired_commands", + max_instances=1, + coalesce=True, + ) + + # Hourly is plenty: expired sessions are already refused on read, so this + # is only stopping the table from growing. + scheduler.add_job( + lambda: _enqueue("purge_expired_sessions"), + "interval", + hours=1, + id="purge_expired_sessions", + max_instances=1, + coalesce=True, + ) + + def _reclaim() -> None: + with SessionLocal() as session: + queue.requeue_stale(session) + + scheduler.add_job( + _reclaim, "interval", minutes=5, id="requeue_stale", max_instances=1, coalesce=True + ) + + # Phase 5 adds: backup (schedule from the settings table), retention, + # restore_test (monthly). + return scheduler + + +def run() -> int: + settings = get_settings() + configure_logging(settings.log_level, settings.log_format) + + def _handle_signal(signum: int, _frame: Any) -> None: + log.info("shutdown requested", extra={"signal": signum}) + _stop.set() + + signal.signal(signal.SIGTERM, _handle_signal) + signal.signal(signal.SIGINT, _handle_signal) + + scheduler = _build_scheduler() + scheduler.start() + log.info( + "poorbird worker started", + extra={"worker": queue.WORKER_ID, "handlers": sorted(HANDLERS)}, + ) + + try: + # One job per claim, deliberately. The review suggested claiming in + # batches of 5, but this loop already runs jobs back to back without + # sleeping while the queue has work, so a batch would only save claim + # round-trips -- and it would cost crash safety. Claiming 5 marks all 5 + # 'running'; dying after the first leaves four locked by a process that + # no longer exists, invisible until requeue_stale gets to them up to 15 + # minutes later. Single claims keep exactly one job at risk. + while not _stop.is_set(): + try: + with SessionLocal() as session: + job = queue.claim(session) + except Exception: # noqa: BLE001 - a DB blip must not end the worker + log.exception("could not reach the database; backing off") + _stop.wait(5.0) + continue + + if job is None: + _stop.wait(settings.worker_poll_interval_s) + continue + + _run_one(job) + finally: + scheduler.shutdown(wait=False) + log.info("poorbird worker stopped") + + return 0 diff --git a/server/src/poorbird/worker/queue.py b/server/src/poorbird/worker/queue.py new file mode 100644 index 0000000..5f1dbb5 --- /dev/null +++ b/server/src/poorbird/worker/queue.py @@ -0,0 +1,131 @@ +"""The job queue. + +One statement claims a job: an UPDATE whose WHERE clause is a +``FOR UPDATE SKIP LOCKED`` subselect. Two workers racing for the same row +never block each other -- the loser skips to the next row rather than waiting. +This is the entire reason no Redis is needed (SPEC 6). +""" + +from __future__ import annotations + +import logging +import os +import socket +from datetime import UTC, datetime, timedelta +from typing import Any + +from sqlalchemy import text +from sqlalchemy.orm import Session + +from ..models import Job + +log = logging.getLogger(__name__) + +WORKER_ID = f"{socket.gethostname()}:{os.getpid()}" + +_CLAIM_SQL = text( + """ + UPDATE jobs + SET status = 'running', + locked_at = now(), + locked_by = :worker, + attempts = attempts + 1 + WHERE id = ( + SELECT id + FROM jobs + WHERE status = 'queued' + AND run_at <= now() + ORDER BY priority DESC, run_at + FOR UPDATE SKIP LOCKED + LIMIT 1 + ) + RETURNING id, kind, payload, attempts, max_attempts + """ +) + + +def enqueue( + session: Session, + kind: str, + payload: dict[str, Any] | None = None, + *, + priority: int = 0, + delay_s: float = 0, + max_attempts: int | None = None, +) -> Job: + job = Job( + kind=kind, + payload=payload or {}, + priority=priority, + run_at=datetime.now(UTC) + timedelta(seconds=delay_s), + ) + if max_attempts is not None: + job.max_attempts = max_attempts + session.add(job) + session.flush() + return job + + +def claim(session: Session) -> dict[str, Any] | None: + """Claim one job, or return None. Commits so the lock is released promptly.""" + row = session.execute(_CLAIM_SQL, {"worker": WORKER_ID}).mappings().first() + session.commit() + return dict(row) if row else None + + +def complete(session: Session, job_id: int) -> None: + session.execute( + text( + "UPDATE jobs SET status = 'done', finished_at = now(), last_error = NULL WHERE id = :id" + ), + {"id": job_id}, + ) + session.commit() + + +def fail(session: Session, job_id: int, error: str, *, retry_in_s: float = 60) -> None: + """Retry with a delay until max_attempts, then park the job as failed.""" + session.execute( + text( + """ + UPDATE jobs + SET status = CASE WHEN attempts >= max_attempts + THEN 'failed' ELSE 'queued' END, + finished_at = CASE WHEN attempts >= max_attempts + THEN now() ELSE NULL END, + run_at = CASE WHEN attempts >= max_attempts + THEN run_at + ELSE now() + make_interval(secs => :retry) END, + locked_at = NULL, + locked_by = NULL, + last_error = :error + WHERE id = :id + """ + ), + {"id": job_id, "error": error[:4000], "retry": retry_in_s}, + ) + session.commit() + + +def requeue_stale(session: Session, older_than_s: int = 900) -> int: + """Reclaim jobs whose worker died mid-run. + + A SIGKILL or a power cut leaves rows in 'running' with nobody holding + them. Nothing else would ever pick those up. + """ + result = session.execute( + text( + """ + UPDATE jobs + SET status = 'queued', locked_at = NULL, locked_by = NULL, + last_error = 'reclaimed: worker vanished' + WHERE status = 'running' + AND locked_at < now() - make_interval(secs => :age) + """ + ), + {"age": older_than_s}, + ) + session.commit() + if result.rowcount: + log.warning("reclaimed stale jobs", extra={"count": result.rowcount}) + return result.rowcount or 0 diff --git a/server/tests/conftest.py b/server/tests/conftest.py new file mode 100644 index 0000000..829ac08 --- /dev/null +++ b/server/tests/conftest.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import os + +import pytest + +# Set before anything imports poorbird.config, whose Settings are cached. +os.environ.setdefault("POORBIRD_LOG_LEVEL", "WARNING") +os.environ.setdefault("POORBIRD_IMAGE_ROOT", "/tmp/poorbird-test/images") +os.environ.setdefault("POORBIRD_THUMB_ROOT", "/tmp/poorbird-test/thumbs") +os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state") +# Off by default: the suite fires far more requests at an endpoint than any +# camera would, and would otherwise spend its own budget and start asserting +# against 429s. tests/test_ratelimit.py turns it back on deliberately. +os.environ.setdefault("POORBIRD_RATE_LIMIT_ENABLED", "false") +# The test client speaks http://testserver, and a Secure cookie is not stored +# for an http origin -- so with this left at its production default every +# session test would fail with "not signed in" and nothing to show why. The +# same trap catches local development against the Vite dev server, which is +# why this is a setting at all. See config.session_cookie_secure. +os.environ.setdefault("POORBIRD_SESSION_COOKIE_SECURE", "false") +# Pin the production default. A developer's server/.env sets this true so the +# Vite dev server can show images, and an untracked file must not be able to +# change what the suite asserts. Tests that care about either mode name it +# explicitly -- see test_captures.py. +os.environ.setdefault("POORBIRD_SERVE_IMAGES_DIRECTLY", "false") + + +def database_is_reachable() -> bool: + try: + from sqlalchemy import text + + from poorbird.db import engine + + with engine.connect() as conn: + conn.execute(text("SELECT 1")) + return True + except Exception: + return False + + +needs_db = pytest.mark.skipif( + not database_is_reachable(), + reason="no reachable PostgreSQL (set POORBIRD_DATABASE_URL)", +) + + +@pytest.fixture(scope="session") +def client(): + from fastapi.testclient import TestClient + + from poorbird.api.app import create_app + + with TestClient(create_app()) as c: + yield c diff --git a/server/tests/test_auth.py b/server/tests/test_auth.py new file mode 100644 index 0000000..b18245c --- /dev/null +++ b/server/tests/test_auth.py @@ -0,0 +1,524 @@ +"""Sessions, login, logout and CSRF (SPEC 3.1, REVIEW SEC-007). + +Needs a real PostgreSQL: sessions are rows, and the point of server-side +sessions is that deleting the row takes effect immediately. Mocking that away +would test the mock. + +The ``client`` fixture is session-scoped and its cookie jar therefore outlives +a single test, so every fixture here clears it. A signed-in cookie leaking into +the next test would make that test pass for the wrong reason, which is worse +than failing. +""" + +from __future__ import annotations + +import secrets +import uuid +from datetime import UTC, datetime, timedelta + +import pyotp +import pytest +from conftest import needs_db +from sqlalchemy import delete, func, select, text + +from poorbird.api.sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE +from poorbird.models import AuditLog, User +from poorbird.models import Session as UserSession +from poorbird.passwords import hash_password +from poorbird.totp import new_secret + +pytestmark = [pytest.mark.db, needs_db] + +PASSWORD = "a-perfectly-usable-passphrase" + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture(autouse=True) +def clean_cookies(client): + """No test starts signed in, and none leaves a cookie behind.""" + client.cookies.clear() + yield + client.cookies.clear() + + +@pytest.fixture(autouse=True) +def no_audit_leaks(db): + """Sweep audit rows by id, not by user. + + audit_log.user_id is ON DELETE SET NULL on purpose -- a trail that vanished + with the account would be useless -- so deleting a test's user does not + delete its audit rows. Worse, a failed login for a username that never + existed writes user_id NULL from the start, which no user-scoped cleanup + can ever match. Seven suite runs had quietly left eight such rows behind + before this fixture existed. + + A high-water mark catches every row any test in this file creates, + whichever user it is attributed to, including none. + """ + high_water = db.scalar(select(func.coalesce(func.max(AuditLog.id), 0))) + yield + db.execute(delete(AuditLog).where(AuditLog.id > high_water)) + db.commit() + + +@pytest.fixture +def make_user(db): + """Users that are removed even when the test fails. + + Teardown belongs in a fixture: a failing assertion skips the rest of the + test body, so cleanup written at the end of it silently never runs. This + has bitten this suite three times already. + + Sessions cascade from the user, but audit_log rows are ON DELETE SET NULL + by design -- an audit trail that vanished when the account did would be + useless -- so they are removed explicitly here. + """ + created: list[int] = [] + + def make( + *, + role: str = "viewer", + password: str | None = PASSWORD, + totp: bool = False, + is_active: bool = True, + ) -> User: + user = User( + username=f"t_{secrets.token_hex(6)}", + password_hash=hash_password(password) if password is not None else None, + role=role, + totp_secret=new_secret() if totp else None, + is_active=is_active, + ) + db.add(user) + db.commit() + db.refresh(user) + created.append(user.id) + return user + + yield make + + for user_id in created: + db.execute(text("DELETE FROM audit_log WHERE user_id = :i"), {"i": user_id}) + db.execute(text("DELETE FROM sessions WHERE user_id = :i"), {"i": user_id}) + db.execute(text("DELETE FROM users WHERE id = :i"), {"i": user_id}) + db.commit() + + +def login(client, user: User, *, password: str = PASSWORD, totp: str | None = None): + body: dict[str, object] = {"username": user.username, "password": password} + if totp is not None: + body["totp"] = totp + return client.post("/api/v1/auth/login", json=body) + + +def csrf_headers(client) -> dict[str, str]: + """What the browser does: read the readable cookie, echo it in the header.""" + return {CSRF_HEADER: client.cookies.get(CSRF_COOKIE, "")} + + +# --- signing in ------------------------------------------------------------- + + +def test_a_correct_password_signs_you_in(client, make_user): + user = make_user(role="editor") + response = login(client, user) + + assert response.status_code == 200 + body = response.json() + assert body == { + "id": user.id, + "username": user.username, + "role": "editor", + "locale": "de", + "theme": "light", + } + + +def test_the_response_carries_no_password_or_secret_material(client, make_user): + """A response shape is where things accumulate, and this one goes to a + browser. Assert the absence, not just the presence.""" + user = make_user(totp=True) + body = login(client, user, totp=pyotp.TOTP(user.totp_secret).now()).json() + + assert set(body) == {"id", "username", "role", "locale", "theme"} + serialised = str(body) + assert PASSWORD not in serialised + assert user.totp_secret not in serialised + + +def test_both_cookies_are_set_with_the_right_visibility(client, make_user): + response = login(client, make_user()) + + cookies = response.headers.get_list("set-cookie") + session_cookie = next(c for c in cookies if c.startswith(SESSION_COOKIE)) + csrf_cookie = next(c for c in cookies if c.startswith(CSRF_COOKIE)) + + # The session cookie must be unreadable by script; the CSRF cookie must be + # readable, because the whole mechanism is the app's own JS echoing it. + assert "HttpOnly" in session_cookie + assert "HttpOnly" not in csrf_cookie + # Lax, not Strict: Strict would also drop the cookie when someone follows an + # ordinary link into the app and they would arrive apparently signed out. + assert "SameSite=lax" in session_cookie.lower() or "samesite=lax" in session_cookie.lower() + + +def test_a_wrong_password_is_refused(client, make_user): + assert login(client, make_user(), password="not the password").status_code == 401 + + +def test_an_unknown_username_is_refused_identically(client, make_user): + """Same status and same message as a wrong password. + + A distinguishable answer is a username oracle: it tells an attacker which + accounts exist, which is the first half of the work. + """ + user = make_user() + wrong_password = login(client, user, password="not the password") + no_such_user = client.post( + "/api/v1/auth/login", json={"username": "nobody-here", "password": PASSWORD} + ) + + assert wrong_password.status_code == no_such_user.status_code == 401 + assert wrong_password.json() == no_such_user.json() + + +def test_a_user_with_no_password_set_cannot_sign_in(client, make_user): + """Every row seeded before Phase 3 has password_hash IS NULL. None of them + may be loggable-in, and the route must not 500 trying.""" + assert login(client, make_user(password=None)).status_code == 401 + + +def test_an_inactive_account_is_refused(client, make_user): + assert login(client, make_user(is_active=False)).status_code == 401 + + +def test_a_deactivated_user_loses_an_existing_session(client, make_user, db): + """Deactivating an account has to take effect now, not at expiry.""" + user = make_user() + assert login(client, user).status_code == 200 + assert client.get("/api/v1/auth/session").status_code == 200 + + user.is_active = False + db.commit() + + assert client.get("/api/v1/auth/session").status_code == 401 + + +# --- second factor ---------------------------------------------------------- + + +def test_totp_is_required_when_the_account_has_a_secret(client, make_user): + user = make_user(totp=True) + assert login(client, user).status_code == 401 + + +def test_a_wrong_totp_code_is_refused(client, make_user): + user = make_user(totp=True) + assert login(client, user, totp="000000").status_code == 401 + + +def test_a_correct_totp_code_signs_you_in(client, make_user): + user = make_user(totp=True) + assert login(client, user, totp=pyotp.TOTP(user.totp_secret).now()).status_code == 200 + + +def test_a_totp_code_alone_is_not_enough(client, make_user): + """The second factor is second, not alternative.""" + user = make_user(totp=True) + response = login(client, user, password="wrong", totp=pyotp.TOTP(user.totp_secret).now()) + assert response.status_code == 401 + + +def test_an_account_without_totp_ignores_a_supplied_code(client, make_user): + """Sending a code to an account that has no secret must not fail closed in + the other direction -- it is simply irrelevant.""" + assert login(client, make_user(), totp="123456").status_code == 200 + + +# --- the session itself ----------------------------------------------------- + + +def test_session_returns_401_when_not_signed_in(client): + """401, not 404. The UI reads 404 as "this server has no auth at all" and + shows a banner; now that the endpoint exists, that must stop.""" + assert client.get("/api/v1/auth/session").status_code == 401 + + +def test_session_returns_the_user_when_signed_in(client, make_user): + user = make_user(role="admin", totp=True) + login(client, user, totp=pyotp.TOTP(user.totp_secret).now()) + + response = client.get("/api/v1/auth/session") + assert response.status_code == 200 + assert response.json()["username"] == user.username + assert response.json()["role"] == "admin" + + +def test_only_the_hash_of_the_session_token_is_stored(client, make_user, db): + """The cookie value must not be findable in the database. + + This is the whole reason sessions.id is internal and the cookie is a + separate token: a database dump should not hand over every live session. + """ + user = make_user() + login(client, user) + cookie = client.cookies.get(SESSION_COOKIE) + + rows = db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() + assert len(rows) == 1 + assert rows[0].token_hash != cookie + assert cookie not in rows[0].token_hash + # And the token must actually resolve, or the hash is of the wrong thing. + assert client.get("/api/v1/auth/session").status_code == 200 + + +def test_an_unknown_session_cookie_is_refused(client, make_user): + make_user() + client.cookies.set(SESSION_COOKIE, secrets.token_hex(32)) + assert client.get("/api/v1/auth/session").status_code == 401 + + +def test_an_expired_session_is_refused_and_cleaned_up(client, make_user, db): + user = make_user() + login(client, user) + + db.execute( + text("UPDATE sessions SET expires_at = :t WHERE user_id = :i"), + {"t": datetime.now(UTC) - timedelta(minutes=1), "i": user.id}, + ) + db.commit() + + assert client.get("/api/v1/auth/session").status_code == 401 + # Enforced on read, and swept on the way past. + assert db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() == [] + + +def test_each_login_opens_a_separate_session(client, make_user, db): + """Two browsers, two rows. Signing out of one must not sign out the other, + which is only possible if they are distinct.""" + user = make_user() + login(client, user) + first = client.cookies.get(SESSION_COOKIE) + client.cookies.clear() + login(client, user) + second = client.cookies.get(SESSION_COOKIE) + + assert first != second + assert len(db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()) == 2 + + +# --- signing out ------------------------------------------------------------ + + +def test_logout_ends_the_session(client, make_user, db): + user = make_user() + login(client, user) + + assert client.post("/api/v1/auth/logout", headers=csrf_headers(client)).status_code == 204 + assert db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() == [] + + +def test_the_old_cookie_stops_working_after_logout(client, make_user): + """The row is deleted, not flagged, so this is immediate. It is the reason + sessions are server-side rather than a self-contained token.""" + user = make_user() + login(client, user) + cookie = client.cookies.get(SESSION_COOKIE) + csrf = csrf_headers(client) + + client.post("/api/v1/auth/logout", headers=csrf) + client.cookies.set(SESSION_COOKIE, cookie) + + assert client.get("/api/v1/auth/session").status_code == 401 + + +def test_logout_without_a_session_is_not_an_error(client): + """A client must always be able to sign out. A 401 here would leave a + browser holding a cookie it cannot get rid of.""" + assert client.post("/api/v1/auth/logout").status_code == 204 + + +def test_logging_out_one_session_leaves_the_other_alone(client, make_user, db): + user = make_user() + login(client, user) + first_cookie = client.cookies.get(SESSION_COOKIE) + + client.cookies.clear() + login(client, user) + client.post("/api/v1/auth/logout", headers=csrf_headers(client)) + + client.cookies.clear() + client.cookies.set(SESSION_COOKIE, first_cookie) + assert client.get("/api/v1/auth/session").status_code == 200 + + +def test_changing_a_password_ends_every_session(client, make_user, db): + """Otherwise the old password keeps working through any browser already + signed in, which is usually why it was changed.""" + from poorbird.api.sessions import revoke_all_for_user + + user = make_user() + login(client, user) + assert client.get("/api/v1/auth/session").status_code == 200 + + assert revoke_all_for_user(db, user.id) == 1 + db.commit() + + assert client.get("/api/v1/auth/session").status_code == 401 + + +# --- CSRF ------------------------------------------------------------------- + + +def test_a_mutating_request_without_a_csrf_header_is_refused(client, make_user): + user = make_user() + login(client, user) + + response = client.post("/api/v1/auth/logout") + assert response.status_code == 403 + assert "csrf" in response.json()["detail"].lower() + + +def test_a_mutating_request_with_a_wrong_csrf_token_is_refused(client, make_user): + user = make_user() + login(client, user) + + response = client.post("/api/v1/auth/logout", headers={CSRF_HEADER: secrets.token_hex(32)}) + assert response.status_code == 403 + + +def test_a_csrf_token_from_a_different_session_is_refused(client, make_user): + """The check is against the token on *this* session's row, not merely + against the cookie. Plain double-submit would accept any self-consistent + pair, so someone able to write a cookie on the domain could satisfy it. + """ + user = make_user() + login(client, user) + victim_session_cookie = client.cookies.get(SESSION_COOKIE) + + client.cookies.clear() + login(client, user) + other_csrf = client.cookies.get(CSRF_COOKIE) + + # The victim's session, with an attacker-chosen (but real) CSRF value in + # both the cookie and the header -- which is exactly what a cookie-writing + # attacker could arrange. + client.cookies.clear() + client.cookies.set(SESSION_COOKIE, victim_session_cookie) + client.cookies.set(CSRF_COOKIE, other_csrf) + + response = client.post("/api/v1/auth/logout", headers={CSRF_HEADER: other_csrf}) + assert response.status_code == 403 + + +def test_a_matching_csrf_token_is_accepted(client, make_user): + user = make_user() + login(client, user) + assert client.post("/api/v1/auth/logout", headers=csrf_headers(client)).status_code == 204 + + +def test_reading_never_needs_a_csrf_token(client, make_user): + """A GET that needed one would be a GET that mutates.""" + login(client, make_user()) + assert client.get("/api/v1/auth/session").status_code == 200 + + +def test_logging_in_needs_no_csrf_token(client, make_user): + """There is no session cookie yet, so it is exempt without a special case + -- which is why the middleware keys on the cookie rather than the path.""" + assert login(client, make_user()).status_code == 200 + + +def test_device_endpoints_are_not_subject_to_csrf(client): + """A camera has no way to obtain a CSRF token, and blocking /ingest would + take the whole system down. Device requests carry a bearer token and no + cookies, which is what the middleware keys on. + """ + response = client.post( + "/api/v1/ingest", + content=b"\xff\xd8\xff not really a jpeg", + headers={"Authorization": "Bearer nonsense", "Content-Type": "image/jpeg"}, + ) + # 401 for the bad token -- the point is that it is not 403-for-CSRF. + assert response.status_code == 401 + + +# --- audit trail ------------------------------------------------------------ + + +def test_a_successful_login_is_audited(client, make_user, db): + user = make_user() + login(client, user) + + actions = db.scalars( + select(AuditLog.action).where(AuditLog.user_id == user.id).order_by(AuditLog.id) + ).all() + assert "login" in actions + + +def test_a_failed_login_is_audited_too(client, make_user, db): + """A log of only the successes cannot answer the question worth asking + afterwards, which is how many times someone tried first.""" + user = make_user() + login(client, user, password="wrong") + login(client, user, password="wrong again") + + actions = db.scalars(select(AuditLog.action).where(AuditLog.user_id == user.id)).all() + assert actions.count("login_failed") == 2 + + +def test_the_audit_record_never_contains_the_password(client, make_user, db): + user = make_user() + login(client, user, password="hunter2-and-then-some") + + rows = db.scalars(select(AuditLog).where(AuditLog.user_id == user.id)).all() + assert rows + for row in rows: + assert "hunter2" not in str(row.after) + + +def test_logout_is_audited(client, make_user, db): + user = make_user() + login(client, user) + client.post("/api/v1/auth/logout", headers=csrf_headers(client)) + + actions = db.scalars(select(AuditLog.action).where(AuditLog.user_id == user.id)).all() + assert "logout" in actions + + +# --- housekeeping ----------------------------------------------------------- + + +def test_purge_expired_removes_only_expired_sessions(client, make_user, db): + """The sweep lives with the worker's other scheduled housekeeping, not in + api/, so that the worker never imports from the HTTP layer.""" + from poorbird.worker.handlers import HANDLERS + + user = make_user() + live = UserSession( + user_id=user.id, + token_hash=uuid.uuid4().hex + uuid.uuid4().hex, + csrf_token=secrets.token_hex(16), + expires_at=datetime.now(UTC) + timedelta(days=1), + ) + dead = UserSession( + user_id=user.id, + token_hash=uuid.uuid4().hex + uuid.uuid4().hex, + csrf_token=secrets.token_hex(16), + expires_at=datetime.now(UTC) - timedelta(days=1), + ) + db.add_all([live, dead]) + db.commit() + live_id = live.id + + HANDLERS["purge_expired_sessions"](db, {}) + + remaining = db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() + assert [r.id for r in remaining] == [live_id] diff --git a/server/tests/test_captures.py b/server/tests/test_captures.py new file mode 100644 index 0000000..0ad81a5 --- /dev/null +++ b/server/tests/test_captures.py @@ -0,0 +1,646 @@ +"""The gallery: listing, paging, filtering and auth-checked delivery (SPEC 3.3). + +Needs a real PostgreSQL. The paging is a row-value comparison against a real +index, and the thing most worth testing about it -- that a burst arriving +within one millisecond does not lose or repeat a frame -- only happens with +real ordering semantics. +""" + +from __future__ import annotations + +import secrets +import uuid +from datetime import UTC, datetime, timedelta + +import pytest +from conftest import needs_db +from sqlalchemy import delete, func, select, text + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import Settings, get_settings +from poorbird.models import AuditLog, Capture, Device, Observation, Tag, User +from poorbird.passwords import hash_password + +pytestmark = [pytest.mark.db, needs_db] + +PASSWORD = "gallery-test-passphrase" + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture(autouse=True) +def clean_cookies(client): + client.cookies.clear() + yield + client.cookies.clear() + + +@pytest.fixture(autouse=True) +def no_audit_leaks(db): + """Logging in writes an audit row; sweep by id so none survive the test.""" + high_water = db.scalar(select(func.coalesce(func.max(AuditLog.id), 0))) + yield + db.execute(delete(AuditLog).where(AuditLog.id > high_water)) + db.commit() + + +@pytest.fixture +def make_user(db): + created: list[int] = [] + + def make(role: str = "viewer") -> User: + user = User( + username=f"g_{secrets.token_hex(6)}", + password_hash=hash_password(PASSWORD), + role=role, + ) + db.add(user) + db.commit() + db.refresh(user) + created.append(user.id) + return user + + yield make + for user_id in created: + db.execute(text("DELETE FROM audit_log WHERE user_id = :i"), {"i": user_id}) + db.execute(text("DELETE FROM sessions WHERE user_id = :i"), {"i": user_id}) + db.execute(text("DELETE FROM users WHERE id = :i"), {"i": user_id}) + db.commit() + + +@pytest.fixture +def signed_in(client, make_user): + """A signed-in viewer. Returns the user.""" + + def sign_in(role: str = "viewer") -> User: + user = make_user(role) + response = client.post( + "/api/v1/auth/login", json={"username": user.username, "password": PASSWORD} + ) + assert response.status_code == 200, response.text + return user + + return sign_in + + +@pytest.fixture +def make_device(db): + """Devices, and everything that hangs off them. + + Teardown in a fixture, not at the end of the test body: a failing + assertion skips the rest of the body and leaves rows behind. Observations + and tag links cascade from captures, but the thumbnail *jobs* /ingest + enqueues do not, so they are cleared explicitly -- that exact omission + broke test_queue.py once already. + """ + created: list[int] = [] + + def make(name: str = "cam") -> Device: + device = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(new_credential()), + enabled=True, + ) + db.add(device) + db.commit() + db.refresh(device) + created.append(device.id) + return device + + yield make + + for device_id in created: + db.execute( + text( + "DELETE FROM jobs WHERE kind = 'thumbnail' AND (payload->>'capture_id') IN " + "(SELECT id::text FROM captures WHERE device_id = :i)" + ), + {"i": device_id}, + ) + db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device_id}) + db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device_id}) + db.commit() + + +@pytest.fixture +def make_capture(db): + def make( + device: Device, + *, + received_at: datetime | None = None, + thumb: bool = True, + kept: bool = True, + reviewed: bool = False, + pre_trigger: bool = False, + trigger: str = "radar", + path: str | None = None, + ) -> Capture: + capture_id = uuid.uuid4() + capture = Capture( + id=capture_id, + device_id=device.id, + path=path if path is not None else f"2026/09/20/{capture_id}.jpg", + thumb_path=f"{capture_id}_400.webp" if thumb else None, + sha256=secrets.token_hex(32), + width=1600, + height=1200, + bytes=123456, + received_at=received_at or datetime.now(UTC), + trigger=trigger, + pre_trigger=pre_trigger, + kept=kept, + reviewed=reviewed, + ) + db.add(capture) + db.commit() + return capture + + return make + + +def _delivery_mode(client, *, directly: bool): + """Pin the delivery mode for one test. + + Both modes are named explicitly rather than inherited from whatever + server/.env happens to say. These two tests failed the moment + POORBIRD_SERVE_IMAGES_DIRECTLY=true was added to a developer's .env for + the dev server's benefit -- a test that changes answer because of an + untracked file is not testing the code. + """ + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, + serve_images_directly=directly, + session_cookie_secure=False, + ) + + +@pytest.fixture +def direct_delivery(client): + """Serve bytes from the app, as local development does.""" + _delivery_mode(client, directly=True) + yield + client.app.dependency_overrides.clear() + + +@pytest.fixture +def handoff_delivery(client): + """Authorise and let Caddy serve, as production does.""" + _delivery_mode(client, directly=False) + yield + client.app.dependency_overrides.clear() + + +# --- who may read the gallery ----------------------------------------------- + + +def test_listing_requires_a_session(client): + assert client.get("/api/v1/captures").status_code == 401 + + +def test_a_device_token_does_not_open_the_gallery(client, make_device): + """SPEC 3.1: a device is not a user. Its token is scoped to ingest and + cannot resolve to a person, so it must not read captures -- the camera + uploads, it does not browse.""" + token = new_credential() + device = make_device() + from poorbird.db import SessionLocal + + with SessionLocal() as s: + row = s.get(Device, device.id) + row.token_hash = hash_credential(token) + s.commit() + + response = client.get("/api/v1/captures", headers={"Authorization": f"Bearer {token}"}) + assert response.status_code == 401 + + +def test_a_viewer_may_read_the_gallery(client, signed_in, make_device, make_capture): + """The lowest role is exactly the one the gallery exists for.""" + signed_in("viewer") + make_capture(make_device()) + assert client.get("/api/v1/captures").status_code == 200 + + +def test_the_image_route_requires_a_session(client, make_device, make_capture): + """An unguessable URL is not access control (SPEC 3.3). The id is a UUID, + and that is still not a reason to serve it to anyone who has it.""" + capture = make_capture(make_device()) + assert client.get(f"/api/v1/captures/{capture.id}/image").status_code == 401 + assert client.get(f"/api/v1/captures/{capture.id}/thumb").status_code == 401 + + +# --- listing ---------------------------------------------------------------- + + +def test_captures_come_back_newest_first(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + now = datetime.now(UTC) + oldest = make_capture(device, received_at=now - timedelta(hours=2)) + newest = make_capture(device, received_at=now) + middle = make_capture(device, received_at=now - timedelta(hours=1)) + + items = client.get(f"/api/v1/captures?device_id={device.id}").json()["items"] + assert [i["id"] for i in items] == [str(newest.id), str(middle.id), str(oldest.id)] + + +def test_the_summary_carries_what_a_tile_needs(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + capture = make_capture(device) + + item = client.get(f"/api/v1/captures?device_id={device.id}").json()["items"][0] + assert item["id"] == str(capture.id) + assert item["width"] == 1600 + assert item["has_thumb"] is True + assert item["trigger"] == "radar" + # received_at is authoritative (SPEC C7) and always present. + assert item["received_at"] is not None + + +def test_has_thumb_is_false_while_the_job_has_not_run(client, signed_in, make_device, make_capture): + """The grid needs to tell "not yet" from "never" without fetching, or it + shows a broken image instead of a placeholder.""" + signed_in() + device = make_device() + make_capture(device, thumb=False) + + item = client.get(f"/api/v1/captures?device_id={device.id}").json()["items"][0] + assert item["has_thumb"] is False + + +def test_an_empty_gallery_is_an_empty_page_not_an_error(client, signed_in, make_device): + signed_in() + device = make_device() + body = client.get(f"/api/v1/captures?device_id={device.id}").json() + assert body == {"items": [], "next_cursor": None} + + +# --- paging ----------------------------------------------------------------- + + +def test_paging_walks_every_row_exactly_once(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + now = datetime.now(UTC) + expected = { + str(make_capture(device, received_at=now - timedelta(minutes=i)).id) for i in range(7) + } + + seen: list[str] = [] + cursor = None + for _ in range(20): # generous bound; the loop should end on its own + url = f"/api/v1/captures?device_id={device.id}&limit=2" + if cursor: + url += f"&cursor={cursor}" + body = client.get(url).json() + seen.extend(i["id"] for i in body["items"]) + cursor = body["next_cursor"] + if cursor is None: + break + + assert cursor is None, "paging did not terminate" + assert len(seen) == len(set(seen)), "a row was returned on two pages" + assert set(seen) == expected + + +def test_paging_does_not_lose_frames_from_the_same_burst( + client, signed_in, make_device, make_capture +): + """The real reason the cursor carries the id as well as the timestamp. + + A burst arrives within the same fraction of a second, so received_at ties + are normal rather than exotic. With a timestamp-only cursor these rows + would be skipped or repeated, and a gallery that drops a frame while you + scroll is one you cannot trust. + """ + signed_in() + device = make_device() + same_instant = datetime.now(UTC) + expected = {str(make_capture(device, received_at=same_instant).id) for _ in range(5)} + + seen: list[str] = [] + cursor = None + for _ in range(20): + url = f"/api/v1/captures?device_id={device.id}&limit=1" + if cursor: + url += f"&cursor={cursor}" + body = client.get(url).json() + seen.extend(i["id"] for i in body["items"]) + cursor = body["next_cursor"] + if cursor is None: + break + + assert set(seen) == expected + assert len(seen) == len(set(seen)) + + +def test_the_last_page_has_no_cursor(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + make_capture(device) + body = client.get(f"/api/v1/captures?device_id={device.id}&limit=50").json() + assert len(body["items"]) == 1 + assert body["next_cursor"] is None + + +def test_a_full_page_with_nothing_after_it_still_ends(client, signed_in, make_device, make_capture): + """limit=2 with exactly 2 rows must not offer a cursor to an empty page. + + This is the off-by-one the "fetch limit + 1" trick exists to avoid, and + the one a COUNT would have hidden. + """ + signed_in() + device = make_device() + now = datetime.now(UTC) + make_capture(device, received_at=now) + make_capture(device, received_at=now - timedelta(minutes=1)) + + body = client.get(f"/api/v1/captures?device_id={device.id}&limit=2").json() + assert len(body["items"]) == 2 + assert body["next_cursor"] is None + + +@pytest.mark.parametrize( + "cursor", + ["not-base64!!", "", "Zm9v", "MjAyNi0wMS0wMXxub3QtYS11dWlk", "fDEyMw=="], +) +def test_a_malformed_cursor_is_422_not_500(client, signed_in, cursor): + """Every part of a cursor is caller-supplied, so every failure is a bad + request: bad base64, bad UTF-8, no separator, bad date, bad UUID.""" + signed_in() + assert client.get(f"/api/v1/captures?cursor={cursor}").status_code == 422 + + +def test_limit_is_bounded(client, signed_in): + signed_in() + assert client.get("/api/v1/captures?limit=0").status_code == 422 + assert client.get("/api/v1/captures?limit=9999").status_code == 422 + + +# --- filters ---------------------------------------------------------------- + + +def test_filtering_by_device(client, signed_in, make_device, make_capture): + signed_in() + mine, other = make_device("mine"), make_device("other") + make_capture(mine) + make_capture(other) + + items = client.get(f"/api/v1/captures?device_id={mine.id}").json()["items"] + assert len(items) == 1 + assert items[0]["device_id"] == mine.id + + +def test_filtering_by_received_date_range(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + now = datetime.now(UTC) + recent = make_capture(device, received_at=now - timedelta(hours=1)) + make_capture(device, received_at=now - timedelta(days=5)) + + # params=, not an f-string: an ISO timestamp ends in "+00:00" and a raw "+" + # in a query string means a space, so the interpolated version arrives + # unparseable and answers 422. A real client encodes it; this test has to + # as well, rather than testing its own URL building. + response = client.get( + "/api/v1/captures", + params={ + "device_id": device.id, + "received_from": (now - timedelta(hours=3)).isoformat(), + }, + ) + assert response.status_code == 200, response.text + assert [i["id"] for i in response.json()["items"]] == [str(recent.id)] + + +def test_a_date_range_can_also_exclude_the_newest(client, signed_in, make_device, make_capture): + """The other end of the range, so a one-sided bug cannot pass both.""" + signed_in() + device = make_device() + now = datetime.now(UTC) + make_capture(device, received_at=now) + older = make_capture(device, received_at=now - timedelta(days=5)) + + response = client.get( + "/api/v1/captures", + params={ + "device_id": device.id, + "received_to": (now - timedelta(days=1)).isoformat(), + }, + ) + assert [i["id"] for i in response.json()["items"]] == [str(older.id)] + + +@pytest.mark.parametrize( + ("field", "query"), + [ + ("kept", "kept=false"), + ("reviewed", "reviewed=true"), + ("pre_trigger", "pre_trigger=true"), + ], +) +def test_filtering_by_triage_flags(client, signed_in, make_device, make_capture, field, query): + signed_in() + device = make_device() + wanted = make_capture(device, **{field: field != "kept"}) + make_capture(device, **{field: field == "kept"}) + + items = client.get(f"/api/v1/captures?device_id={device.id}&{query}").json()["items"] + assert [i["id"] for i in items] == [str(wanted.id)] + + +def test_filtering_by_trigger(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + manual = make_capture(device, trigger="manual") + make_capture(device, trigger="radar") + + items = client.get(f"/api/v1/captures?device_id={device.id}&trigger=manual").json()["items"] + assert [i["id"] for i in items] == [str(manual.id)] + + +# --- detail ----------------------------------------------------------------- + + +def test_an_unknown_capture_is_404(client, signed_in): + signed_in() + assert client.get(f"/api/v1/captures/{uuid.uuid4()}").status_code == 404 + + +def test_detail_includes_the_device_name_and_radar_fields( + client, signed_in, make_device, make_capture, db +): + signed_in() + device = make_device("garden") + capture = make_capture(device) + row = db.get(Capture, capture.id) + row.radar_distance_cm = 180 + db.commit() + + body = client.get(f"/api/v1/captures/{capture.id}").json() + assert body["device_name"] == "garden" + assert body["radar_distance_cm"] == 180 + assert body["observations"] == [] + assert body["tags"] == [] + + +def test_detail_includes_observations_and_marks_their_source( + client, signed_in, make_device, make_capture, db +): + """A model prediction shown as a human label would poison the very + training data this table exists to collect (SPEC 3.2).""" + signed_in() + capture = make_capture(make_device()) + db.add(Observation(capture_id=capture.id, source="model", confidence=0.8, individuals=2)) + db.commit() + + body = client.get(f"/api/v1/captures/{capture.id}").json() + assert len(body["observations"]) == 1 + assert body["observations"][0]["source"] == "model" + assert body["observations"][0]["confidence"] == 0.8 + assert body["observations"][0]["individuals"] == 2 + + +def test_detail_includes_tags(client, signed_in, make_device, make_capture, db): + signed_in() + capture = make_capture(make_device()) + tag = Tag(label=f"t_{secrets.token_hex(4)}", colour="#0066cc") + db.add(tag) + db.commit() + db.execute( + text("INSERT INTO capture_tags (capture_id, tag_id) VALUES (:c, :t)"), + {"c": capture.id, "t": tag.id}, + ) + db.commit() + + try: + body = client.get(f"/api/v1/captures/{capture.id}").json() + assert [t["label"] for t in body["tags"]] == [tag.label] + finally: + db.execute(text("DELETE FROM capture_tags WHERE tag_id = :t"), {"t": tag.id}) + db.execute(text("DELETE FROM tags WHERE id = :t"), {"t": tag.id}) + db.commit() + + +# --- delivery --------------------------------------------------------------- + + +def test_production_hands_off_to_caddy_without_reading_the_file( + client, signed_in, make_device, make_capture, handoff_delivery +): + """The default: authorise, then let Caddy serve the bytes (SPEC 3.3). + + The body must be empty. Python never opening the file is the point -- a + 3 MB JPEG should not occupy a worker thread. + """ + signed_in() + capture = make_capture(make_device()) + + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 200 + assert response.content == b"" + assert response.headers["x-accel-redirect"] == f"/images/2026/09/20/{capture.id}.jpg" + + +def test_the_thumbnail_hands_off_from_the_thumb_root( + client, signed_in, make_device, make_capture, handoff_delivery +): + signed_in() + capture = make_capture(make_device()) + + response = client.get(f"/api/v1/captures/{capture.id}/thumb") + assert response.status_code == 200 + assert response.headers["x-accel-redirect"] == f"/thumbs/{capture.id}_400.webp" + + +def test_development_serves_the_bytes_itself( + client, signed_in, make_device, make_capture, direct_delivery +): + """Without this the Vite dev server would proxy an empty 200 and every + image in the gallery would be blank, with nothing to explain why.""" + signed_in() + capture = make_capture(make_device()) + + source = get_settings().image_root / capture.path + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(b"\xff\xd8\xffnot a real jpeg but bytes") + + try: + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 200 + assert response.content == b"\xff\xd8\xffnot a real jpeg but bytes" + assert response.headers["content-type"] == "image/jpeg" + assert "x-accel-redirect" not in response.headers + finally: + source.unlink(missing_ok=True) + + +def test_a_missing_file_is_404_when_the_app_serves_it( + client, signed_in, make_device, make_capture, direct_delivery +): + """The row says there is a file and there is not -- the database and the + disk have diverged. 404, and logged loudly.""" + signed_in() + capture = make_capture(make_device()) + assert client.get(f"/api/v1/captures/{capture.id}/image").status_code == 404 + + +def test_a_capture_with_no_thumbnail_is_404_not_the_full_image( + client, signed_in, make_device, make_capture +): + """Falling back to the full JPEG would make a grid of 200 tiles quietly + fetch a hundred times the bytes and still look like it worked.""" + signed_in() + capture = make_capture(make_device(), thumb=False) + + response = client.get(f"/api/v1/captures/{capture.id}/thumb") + assert response.status_code == 404 + assert "x-accel-redirect" not in response.headers + + +def test_a_stored_path_cannot_escape_the_image_root( + client, signed_in, make_device, make_capture, direct_delivery +): + """captures.path is written by our own ingest code, so this should never + happen. "Should never" is not a security control, and the cost of being + wrong is serving an arbitrary file off the server. + + The escape target is a file that really exists just outside the root, not + /etc/passwd: on Windows that path is absent anyway, so the test would pass + for the wrong reason and would not notice the check being removed. + """ + signed_in() + root = get_settings().image_root + outside = root.parent / "not-for-the-web.txt" + outside.parent.mkdir(parents=True, exist_ok=True) + outside.write_bytes(b"SECRET-CANARY") + + capture = make_capture(make_device(), path=f"../{outside.name}") + + try: + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 404 + assert b"SECRET-CANARY" not in response.content + finally: + outside.unlink(missing_ok=True) + + +def test_the_handoff_path_cannot_escape_either( + client, signed_in, make_device, make_capture, handoff_delivery +): + """The production path must refuse it too. A traversal in the header would + make *Caddy* read the file, where the app never touches it at all.""" + signed_in() + capture = make_capture(make_device(), path="../../etc/passwd") + + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 404 + assert "x-accel-redirect" not in response.headers diff --git a/server/tests/test_commands_ack.py b/server/tests/test_commands_ack.py new file mode 100644 index 0000000..a41558a --- /dev/null +++ b/server/tests/test_commands_ack.py @@ -0,0 +1,224 @@ +"""POST /api/v1/commands/{id}/ack, and the full command lifecycle with it.""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +def _make_device(db, name="cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + return d, {"Authorization": f"Bearer {token}"} + + +def _cleanup(db, *devices): + for d in devices: + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def device(db): + d, auth = _make_device(db) + yield d, auth + _cleanup(db, d) + + +@pytest.fixture +def queued(db, device): + d, auth = device + cmd = DeviceCommand(device_id=d.id, type="capture_now") + db.add(cmd) + db.commit() + db.refresh(cmd) + return d, auth, cmd + + +CONDITIONS = {"reason": "heartbeat"} + + +# --- the lifecycle ---------------------------------------------------------- + + +@needs_db +def test_delivered_then_acked(client, queued, db): + """The whole round trip: queued -> delivered by heartbeat -> acked.""" + d, auth, cmd = queued + + assert cmd.delivered_at is None and cmd.acked_at is None + + envelope = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() + assert [c["id"] for c in envelope["commands"]] == [cmd.id] + + db.refresh(cmd) + assert cmd.delivered_at is not None + assert cmd.acked_at is None # delivered is not the same as done + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", + json={"status": "done", "detail": "captured 3 frames"}, + headers=auth, + ) + assert r.status_code == 204 + assert r.content == b"" + + db.refresh(cmd) + assert cmd.acked_at is not None + assert cmd.ack_status == "done" + assert cmd.result == "captured 3 frames" + + +@needs_db +@pytest.mark.parametrize("outcome", ["done", "failed", "rejected"]) +def test_every_documented_outcome_is_accepted(client, queued, db, outcome): + d, auth, cmd = queued + r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": outcome}, headers=auth) + assert r.status_code == 204 + + db.refresh(cmd) + assert cmd.ack_status == outcome + + +@needs_db +def test_an_unknown_outcome_is_422(client, queued): + d, auth, cmd = queued + r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "maybe"}, headers=auth) + assert r.status_code == 422 + + +@needs_db +def test_an_empty_detail_is_stored_as_null(client, queued, db): + """The firmware always sends the key, empty when it has nothing to say.""" + d, auth, cmd = queued + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done", "detail": ""}, headers=auth + ) + + db.refresh(cmd) + assert cmd.result is None + + +@needs_db +def test_a_command_can_be_acked_without_having_been_delivered(client, queued, db): + """Odd but harmless, and refusing it would strand a real ack if delivery + bookkeeping ever went wrong.""" + d, auth, cmd = queued + assert cmd.delivered_at is None + + assert ( + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth + ).status_code + == 204 + ) + + +# --- retries ---------------------------------------------------------------- + + +@needs_db +def test_re_acking_is_allowed_and_the_last_word_wins(client, queued, db): + """The device cannot tell a lost response from a lost request, so it + retries. Refusing the second attempt would strand a command that ran.""" + d, auth, cmd = queued + + client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "failed"}, headers=auth) + db.refresh(cmd) + first = cmd.acked_at + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", + json={"status": "done", "detail": "worked on retry"}, + headers=auth, + ) + assert r.status_code == 204 + + db.refresh(cmd) + assert cmd.ack_status == "done" + assert cmd.result == "worked on retry" + assert cmd.acked_at >= first + + +@needs_db +def test_acking_does_not_put_the_command_back_in_the_queue(client, queued, db): + d, auth, cmd = queued + client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth) + client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth) + + again = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() + assert again["commands"] == [] + + +# --- scoping ---------------------------------------------------------------- + + +@needs_db +def test_another_devices_command_is_404_not_403(client, queued, db): + """Command ids are sequential. A distinct status code would confirm that + an id exists, which is the thing worth not saying.""" + d, auth, cmd = queued + intruder, intruder_auth = _make_device(db, name="intruder") + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=intruder_auth + ) + assert r.status_code == 404 + + db.refresh(cmd) + assert cmd.acked_at is None, "an intruder must not be able to close a command" + + _cleanup(db, intruder) + + +@needs_db +def test_an_unknown_command_id_is_404(client, device): + _, auth = device + assert ( + client.post( + "/api/v1/commands/999999999/ack", json={"status": "done"}, headers=auth + ).status_code + == 404 + ) + + +@needs_db +def test_ack_requires_a_bearer_token(client, queued): + d, auth, cmd = queued + assert client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}).status_code == 401 + + +@needs_db +def test_a_disabled_device_cannot_ack(client, queued, db): + d, auth, cmd = queued + d.enabled = False + db.commit() + assert ( + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth + ).status_code + == 403 + ) diff --git a/server/tests/test_conditions.py b/server/tests/test_conditions.py new file mode 100644 index 0000000..bdb0281 --- /dev/null +++ b/server/tests/test_conditions.py @@ -0,0 +1,361 @@ +"""POST /api/v1/heartbeat and POST /api/v1/status. + +One body, two endpoints. The tests that matter most are the ones pinning the +difference between them, because the split exists for a reason that is not +obvious from the payload. +""" + +from __future__ import annotations + +import secrets +from datetime import UTC, datetime, timedelta + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus, Firmware + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + """A live, enrolled device, removed again afterwards.""" + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="test-cam", + token_hash=hash_credential(token), + fw_version="0.1.0", + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def firmware(db): + """Create firmware rows that are removed even when the test fails. + + Teardown has to live in a fixture, not at the end of the test body: a + failing assertion skips the rest of the function, and a leftover + is_target row then picks itself as the OTA target for every later test. + """ + created: list[Firmware] = [] + + def make(version: str, *, is_target: bool = True) -> Firmware: + row = Firmware( + version=version, + file_path=f"/srv/poorbird/fw/{version}.bin", + sha256="a" * 64, + size_bytes=1148320, + is_target=is_target, + ) + db.add(row) + db.commit() + db.refresh(row) + created.append(row) + return row + + yield make + + for row in created: + existing = db.get(Firmware, row.id) + if existing is not None: + db.delete(existing) + db.commit() + + +def body(reason: str = "periodic", **over) -> dict: + b = { + "reason": reason, + "fw_version": "0.1.0", + "config_version": 8, + "power": {"awake_ms": 91204, "boot_count": 37, "wake_cause": "radar"}, + "battery": {"valid": True, "mv": 3912, "pct": 74}, + "counters": {"captured_today": 412, "delivered_today": 407, "day_index": 20716}, + "camera": {"profile": "day", "ready": True}, + "night": {"is_night": False}, + "stream": {"active": False}, + "radar": {"baud": 256000, "uart_ok": True}, + "system": {"rssi": -61, "ip": "192.168.1.88", "free_heap": 184320}, + "time_synced": True, + "device_time": "2026-09-20T14:31:07Z", + } + b.update(over) + return b + + +# --- the split between the two endpoints ------------------------------------ + + +@needs_db +def test_heartbeat_returns_the_envelope(client, device): + _, auth = device + r = client.post("/api/v1/heartbeat", json=body(), headers=auth) + + assert r.status_code == 200 + e = r.json() + assert e["server_time"] > 1_700_000_000_000 + assert "config_version" in e + assert e["commands"] == [] + + +@needs_db +def test_status_returns_204_and_no_body(client, device): + _, auth = device + r = client.post("/api/v1/status", json=body("before_sleep"), headers=auth) + + assert r.status_code == 204 + assert r.content == b"" + + +@needs_db +def test_status_does_not_hand_out_commands(client, device, db): + """The whole reason the two endpoints exist. + + The device posts status immediately before deep sleep. Delivering commands + there would mark them delivered to a device about to be unable to run them. + """ + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="capture_now")) + db.commit() + + assert client.post("/api/v1/status", json=body("before_sleep"), headers=auth).status_code == 204 + + cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) + db.refresh(cmd) + assert cmd.delivered_at is None, "status must not claim commands" + + # ... but the next heartbeat still gets it. + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["capture_now"] + + +# --- commands --------------------------------------------------------------- + + +@needs_db +def test_heartbeat_claims_commands_and_marks_them_delivered(client, device, db): + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="reboot")) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["reboot"] + + cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) + db.refresh(cmd) + assert cmd.delivered_at is not None + + # Not handed out twice. + again = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert again["commands"] == [] + + +@needs_db +def test_expired_commands_are_not_delivered_but_are_kept(client, device, db): + """Kept so the admin UI can show that a command timed out.""" + d, auth = device + db.add( + DeviceCommand( + device_id=d.id, + type="capture_now", + expires_at=datetime.now(UTC) - timedelta(minutes=1), + ) + ) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["commands"] == [] + assert db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) is not None + + +@needs_db +def test_commands_come_back_in_creation_order(client, device, db): + d, auth = device + for t in ("wake_and_hold", "capture_now", "reboot"): + db.add(DeviceCommand(device_id=d.id, type=t)) + db.commit() # distinct created_at + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["wake_and_hold", "capture_now", "reboot"] + + +@needs_db +def test_one_devices_commands_do_not_leak_to_another(client, device, db): + d, auth = device + other = Device(device_uid=secrets.token_hex(6), name="other") + db.add(other) + db.commit() + db.add(DeviceCommand(device_id=other.id, type="reboot")) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["commands"] == [] + + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == other.id)) + db.delete(db.get(Device, other.id)) + db.commit() + + +# --- firmware target -------------------------------------------------------- + + +@needs_db +def test_firmware_key_is_absent_when_the_device_is_on_target(client, device, firmware): + """Absent, not null: present-and-different is itself the flash instruction.""" + d, auth = device + firmware("0.1.0") # same version the device reports + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert "firmware" not in e + + +@needs_db +def test_a_different_target_is_offered_with_a_relative_url(client, device, firmware): + """ota_mgr.cpp appends a non-http url to the API base, which already ends + in /api/v1 -- so this must not carry the prefix itself.""" + d, auth = device + firmware("0.2.0") + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["firmware"]["version"] == "0.2.0" + assert e["firmware"]["url"] == "/firmware/0.2.0.bin" + assert not e["firmware"]["url"].startswith("/api/v1") + assert e["firmware"]["size"] == 1148320 + + +# --- telemetry recording ---------------------------------------------------- + + +@needs_db +def test_a_row_is_appended_per_report(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + client.post("/api/v1/status", json=body("after_event"), headers=auth) + + rows = db.scalars( + select(DeviceStatus).where(DeviceStatus.device_id == d.id).order_by(DeviceStatus.at) + ).all() + assert [r.reason for r in rows] == ["periodic", "after_event"] + assert rows[0].battery_mv == 3912 + assert rows[0].rssi == -61 + assert rows[0].day_index == 20716 + assert rows[0].free_heap == 184320 + + +@needs_db +def test_unknown_fields_survive_in_raw(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(quantum_flux=42), headers=auth) + + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.raw["quantum_flux"] == 42 + + +@needs_db +def test_last_known_conditions_are_denormalised_onto_the_device(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + + db.refresh(d) + assert d.battery_mv == 3912 + assert d.battery_pct == 74 + assert d.battery_valid is True + assert d.rssi == -61 + assert d.last_seen_at is not None + + +@needs_db +def test_a_field_the_device_omits_does_not_erase_the_last_good_value(client, device, db): + """None means 'not sent', not 'zero'.""" + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + client.post("/api/v1/heartbeat", json=body(battery={}, system={}), headers=auth) + + db.refresh(d) + assert d.battery_mv == 3912 + assert d.rssi == -61 + + +@needs_db +def test_battery_valid_false_is_recorded_as_false(client, device, db): + """false means NOT MEASURED. It must reach the UI as false, not as missing.""" + d, auth = device + client.post("/api/v1/heartbeat", json=body(battery={"valid": False}), headers=auth) + + db.refresh(d) + assert d.battery_valid is False + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.battery_valid is False + + +@needs_db +def test_the_device_is_marked_asleep_when_it_says_it_is_going_quiet(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + db.refresh(d) + assert d.awake is True + + client.post("/api/v1/status", json=body("before_night_sleep"), headers=auth) + db.refresh(d) + assert d.awake is False + + +@needs_db +def test_the_devices_reported_config_version_does_not_overwrite_the_servers(client, device, db): + """The difference between the two is exactly what tells the device to + GET /config. Letting the report win would erase the instruction.""" + d, auth = device + d.config_version = 9 + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(config_version=3), headers=auth).json() + + db.refresh(d) + assert d.config_version == 9 + assert e["config_version"] == 9 + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.config_version == 3 # what the device said, kept as telemetry + + +# --- auth ------------------------------------------------------------------- + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_both_endpoints_require_a_bearer_token(client, path): + assert client.post(path, json=body()).status_code == 401 + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_a_disabled_device_is_refused(client, device, db, path): + d, auth = device + d.enabled = False + db.commit() + assert client.post(path, json=body(), headers=auth).status_code == 403 + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_an_unknown_reason_is_422(client, device, path): + _, auth = device + assert client.post(path, json=body("whenever"), headers=auth).status_code == 422 diff --git a/server/tests/test_config.py b/server/tests/test_config.py new file mode 100644 index 0000000..005abf4 --- /dev/null +++ b/server/tests/test_config.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import pytest +from conftest import needs_db +from pydantic import ValidationError + +from poorbird.config import Settings + + +def test_every_setting_reads_from_the_environment(monkeypatch): + """Phase 1.2: no path, host or secret may be baked into code.""" + monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@10.0.0.5:5432/db") + monkeypatch.setenv("POORBIRD_IMAGE_ROOT", "/mnt/elsewhere/images") + monkeypatch.setenv("POORBIRD_API_PORT", "9999") + monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "deadbeef") + + s = Settings(_env_file=None) + + assert s.database_url.endswith("@10.0.0.5:5432/db") + assert str(s.image_root).endswith("images") + assert s.api_port == 9999 + assert s.enroll_secret_is_set + + +def test_database_url_is_tcp_not_a_unix_socket(monkeypatch): + """A Unix socket is the one genuinely container-hostile choice.""" + monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@127.0.0.1:5432/poorbird") + s = Settings(_env_file=None) + assert "@" in s.database_url and ":" in s.database_url.rpartition("@")[2] + assert "/var/run/postgresql" not in s.database_url + + +def test_enroll_secret_is_not_leaked_by_repr(): + s = Settings(_env_file=None, enroll_secret="hunter2") + assert "hunter2" not in repr(s) + + +# --- SEC-006: no credentials baked into code -------------------------------- + + +def test_no_database_credentials_are_baked_in(monkeypatch): + """A default URL in code is a password in code, however harmless it looks.""" + monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False) + s = Settings(_env_file=None) + assert s.database_url == "" + assert not s.database_url_is_set + + +def test_unset_database_url_fails_with_a_readable_message(monkeypatch): + """Graceful, not a SQLAlchemy URL parse error from three frames down.""" + monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False) + monkeypatch.setattr("poorbird.config.get_settings", lambda: Settings(_env_file=None)) + + import importlib + import sys + + sys.modules.pop("poorbird.db", None) + with pytest.raises(RuntimeError, match="POORBIRD_DATABASE_URL is not set"): + importlib.import_module("poorbird.db") + sys.modules.pop("poorbird.db", None) + + +def test_placeholder_database_url_is_rejected(monkeypatch): + monkeypatch.setenv( + "POORBIRD_DATABASE_URL", "postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird" + ) + with pytest.raises(ValidationError, match="placeholder"): + Settings(_env_file=None) + + +# --- SEC-001: enroll secret comes from the environment only ----------------- + + +def test_enroll_secret_has_no_value_baked_in(monkeypatch): + monkeypatch.delenv("POORBIRD_ENROLL_SECRET", raising=False) + s = Settings(_env_file=None) + assert s.enroll_secret.get_secret_value() == "" + assert not s.enroll_secret_is_set + + +def test_placeholder_enroll_secret_is_rejected(monkeypatch): + monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "CHANGE_ME") + with pytest.raises(ValidationError, match="placeholder"): + Settings(_env_file=None) + + +# --- REVIEW section 7: pool sizing ----------------------------------------- + + +@needs_db +def test_pool_settings_reach_the_engine(monkeypatch): + """A setting nothing reads is worse than no setting at all. + + worker_batch_size sat in Settings for a whole phase looking like it tuned + something while the worker claimed one job at a time regardless. So this + asserts against the pool an engine really built, rather than comparing a + literal with itself. + + The values have to differ from SQLAlchemy's own defaults (pool_size 5, + max_overflow 10) or the test cannot tell a wired setting from an ignored + one -- which is the entire failure it is here to catch. Hence 17 and 7, + and hence re-importing db.py rather than reading the module-level engine, + whose numbers happen to coincide with the library's. + """ + import importlib + import sys + + from poorbird.config import get_settings + + monkeypatch.setattr( + "poorbird.config.get_settings", + lambda: Settings( + _env_file=None, + database_url=get_settings().database_url, + db_pool_size=17, + db_max_overflow=7, + ), + ) + + sys.modules.pop("poorbird.db", None) + try: + db = importlib.import_module("poorbird.db") + assert db.engine.pool.size() == 17 + # No public accessor for this one, and leaving half the connection + # ceiling unverified is the worse trade. + assert db.engine.pool._max_overflow == 7 + finally: + # Drop the throwaway engine and let the next importer rebuild the real + # one. It never opened a connection: the pool fills lazily. + sys.modules.pop("poorbird.db", None) diff --git a/server/tests/test_device_auth.py b/server/tests/test_device_auth.py new file mode 100644 index 0000000..c211473 --- /dev/null +++ b/server/tests/test_device_auth.py @@ -0,0 +1,192 @@ +"""Device authentication plumbing (REVIEW SEC-002). + +The cases that matter most here are the two REVIEW.AI.md's reference code got +wrong: the token handed to the device must be the one the server can verify, +and re-enrollment must accept the per-device secret. +""" + +from __future__ import annotations + +import pytest +from conftest import needs_db +from fastapi import HTTPException + +from poorbird.api.deps import ( + enroll_secret_accepted, + hash_credential, + new_credential, + require_enroll_secret_configured, + verify_device_token, +) +from poorbird.config import Settings +from poorbird.models.devices import Device + +# --- credential shape ------------------------------------------------------- + + +def test_credential_is_64_hex_chars(): + """The firmware stores these in char[65]; 64 + NUL fits exactly. + + A longer credential would be silently truncated on the device and every + request after enrollment would 401. + """ + c = new_credential() + assert len(c) == 64 + assert all(ch in "0123456789abcdef" for ch in c) + assert len(c) + 1 <= 65 # app_config.h: char device_token[65] + + +def test_credentials_do_not_repeat(): + assert len({new_credential() for _ in range(100)}) == 100 + + +def test_hash_is_stable_and_not_the_input(): + c = new_credential() + assert hash_credential(c) == hash_credential(c) + assert hash_credential(c) != c + assert len(hash_credential(c)) == 64 + + +# --- the bug in REVIEW.AI.md's reference code ------------------------------- + + +def test_token_given_to_the_device_verifies_against_what_is_stored(): + """Store the hash, hand back the plaintext. + + REVIEW.AI.md's /enroll example returns ``device.token_hash`` to the device. + The device would then present the hash, the server would hash it again, and + the comparison could never match. Guard against reintroducing that. + """ + token = new_credential() + stored = hash_credential(token) + + assert hash_credential(token) == stored # what the device presents resolves + assert hash_credential(stored) != stored # handing back the hash would not + + +# --- enrollment secret ------------------------------------------------------ + + +def _settings(secret: str = "") -> Settings: + return Settings(_env_file=None, enroll_secret=secret) + + +def test_shared_bootstrap_secret_is_accepted(): + assert enroll_secret_accepted("s3cret", _settings("s3cret"), None) + + +def test_wrong_secret_is_rejected(): + assert not enroll_secret_accepted("nope", _settings("s3cret"), None) + + +def test_missing_secret_is_rejected(): + assert not enroll_secret_accepted(None, _settings("s3cret"), None) + assert not enroll_secret_accepted("", _settings("s3cret"), None) + + +def test_unset_server_secret_never_accepts_anything(): + """An unconfigured server must not treat an empty presented secret as a match.""" + assert not enroll_secret_accepted("", _settings(""), None) + assert not enroll_secret_accepted("anything", _settings(""), None) + + +def test_per_device_reenroll_secret_is_accepted(): + """The firmware swaps the shared secret for this one after first enrollment. + + Accepting only the shared secret would lock out every device that had + already enrolled -- the exact failure re-enrollment exists to prevent. + """ + per_device = new_credential() + device = Device(device_uid="a0b7651f2c3d", name="cam-1") + device.reenroll_secret_hash = hash_credential(per_device) + + assert enroll_secret_accepted(per_device, _settings("shared"), device) + # and the shared one still works as the last-resort path + assert enroll_secret_accepted("shared", _settings("shared"), device) + assert not enroll_secret_accepted("neither", _settings("shared"), device) + + +def test_one_devices_secret_cannot_enroll_another(): + mine = new_credential() + other = Device(device_uid="ffffffffffff", name="cam-2") + other.reenroll_secret_hash = hash_credential(new_credential()) + + assert not enroll_secret_accepted(mine, _settings("shared"), other) + + +def test_unconfigured_server_returns_503_not_500(): + """A 4xx would make the firmware clear a perfectly good token.""" + with pytest.raises(HTTPException) as exc: + require_enroll_secret_configured(_settings("")) + assert exc.value.status_code == 503 + + require_enroll_secret_configured(_settings("set")) # does not raise + + +# --- bearer token ----------------------------------------------------------- + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + session.rollback() + + +@pytest.fixture +def enrolled(db): + token = new_credential() + device = Device( + device_uid="dead" + new_credential()[:8], + name="test-cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(device) + db.flush() # rolled back by the db fixture; nothing is committed + yield device, token + + +@needs_db +def test_valid_bearer_token_resolves_to_its_device(db, enrolled): + device, token = enrolled + assert verify_device_token(db=db, authorization=f"Bearer {token}").id == device.id + + +@needs_db +@pytest.mark.parametrize( + "header", + [None, "", "Bearer", "Bearer ", "Basic abc", "abc", "Bearer wrong-token"], +) +def test_bad_authorization_headers_are_401(db, enrolled, header): + """401 specifically: the firmware reads it as 'clear token and re-enroll'.""" + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=header) + assert exc.value.status_code == 401 + + +@needs_db +def test_bearer_scheme_is_case_insensitive(db, enrolled): + _, token = enrolled + assert verify_device_token(db=db, authorization=f"bearer {token}") is not None + + +@needs_db +def test_disabled_device_is_403_not_401(db, enrolled): + """403 stops it re-enrolling in a loop; 401 would invite exactly that.""" + device, token = enrolled + device.enabled = False + db.flush() + + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=f"Bearer {token}") + assert exc.value.status_code == 403 + + +@needs_db +def test_401_carries_www_authenticate(db, enrolled): + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=None) + assert exc.value.headers.get("WWW-Authenticate") == "Bearer" diff --git a/server/tests/test_device_config.py b/server/tests/test_device_config.py new file mode 100644 index 0000000..47d30b7 --- /dev/null +++ b/server/tests/test_device_config.py @@ -0,0 +1,171 @@ +"""GET /api/v1/config. + +The contract is a merge contract, not a schema contract: the device applies +only the keys that are present and clamps what it does not like, so what +matters here is which keys appear and which value wins. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="poorbird-cam-1", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.delete(db.get(Device, d.id)) + db.commit() + + +@needs_db +def test_config_version_is_always_present(client, device): + """It is the only value the device compares, so it can never be missing.""" + d, auth = device + r = client.get("/api/v1/config", headers=auth) + + assert r.status_code == 200 + assert r.json()["config_version"] == d.config_version + + +@needs_db +def test_an_empty_config_still_returns_the_column_backed_keys(client, device, db): + """A device that has never been configured must still learn its name and + its intervals, which live in columns rather than in the JSONB.""" + d, auth = device + assert d.config == {} + + body = client.get("/api/v1/config", headers=auth).json() + assert body["device_name"] == "poorbird-cam-1" + assert body["heartbeat_interval_s"] == d.heartbeat_interval_s + assert body["status_interval_s"] == d.status_interval_s + + +@needs_db +def test_the_stored_document_is_returned(client, device, db): + d, auth = device + d.config = { + "frame_size": "SVGA", + "jpeg_quality": 12, + "night_behaviour": 2, + "cam_day": {"ae_level": 1, "gainceiling": 2}, + } + db.commit() + + body = client.get("/api/v1/config", headers=auth).json() + assert body["frame_size"] == "SVGA" + assert body["jpeg_quality"] == 12 + assert body["cam_day"] == {"ae_level": 1, "gainceiling": 2} + + +@needs_db +def test_a_column_wins_over_a_stale_copy_in_the_json(client, device, db): + """The column is the modelled source of truth. A leftover key in the JSONB + must not shadow it, or changing the column would not reach the device.""" + d, auth = device + d.config = {"heartbeat_interval_s": 30, "device_name": "stale-name"} + d.heartbeat_interval_s = 600 + db.commit() + + body = client.get("/api/v1/config", headers=auth).json() + assert body["heartbeat_interval_s"] == 600 + assert body["device_name"] == "poorbird-cam-1" + + +@needs_db +def test_an_operator_rename_reaches_the_device_through_config(client, device, db): + """Closes the loop left open at enrollment. + + Enrollment refuses to let a device overwrite a rename made in the admin + UI. This is the path by which that rename actually gets to the camera: + configApplyJson merges device_name like any other key (app_config.cpp:307). + """ + d, auth = device + d.name = "Feeder by the shed" + db.commit() + + assert client.get("/api/v1/config", headers=auth).json()["device_name"] == "Feeder by the shed" + + +@needs_db +def test_keys_the_server_does_not_know_are_passed_through(client, device, db): + """The firmware gains tunables faster than the server learns them, and the + device ignores what it does not recognise. Dropping them would make the + admin UI unable to push a setting until the server caught up.""" + d, auth = device + d.config = {"some_future_tunable": 7} + db.commit() + + assert client.get("/api/v1/config", headers=auth).json()["some_future_tunable"] == 7 + + +@needs_db +def test_the_read_has_no_side_effects(client, device, db): + """A GET must not record liveness; /heartbeat is what does that.""" + d, auth = device + assert d.last_seen_at is None + + client.get("/api/v1/config", headers=auth) + + db.refresh(d) + assert d.last_seen_at is None + + +@needs_db +def test_config_requires_a_bearer_token(client): + assert client.get("/api/v1/config").status_code == 401 + + +@needs_db +def test_a_disabled_device_is_refused(client, device, db): + d, auth = device + d.enabled = False + db.commit() + assert client.get("/api/v1/config", headers=auth).status_code == 403 + + +@needs_db +def test_one_device_cannot_read_anothers_config(client, device, db): + """The token identifies the device; there is no device_id parameter to + tamper with, and this pins that there never is one.""" + d, auth = device + other_token = new_credential() + other = Device( + device_uid=secrets.token_hex(6), + name="other-cam", + token_hash=hash_credential(other_token), + enabled=True, + ) + db.add(other) + db.commit() + + body = client.get("/api/v1/config", headers={"Authorization": f"Bearer {other_token}"}).json() + assert body["device_name"] == "other-cam" + + db.delete(db.get(Device, other.id)) + db.commit() diff --git a/server/tests/test_enroll.py b/server/tests/test_enroll.py new file mode 100644 index 0000000..2050799 --- /dev/null +++ b/server/tests/test_enroll.py @@ -0,0 +1,264 @@ +"""POST /api/v1/enroll (firmware/API.md, Authentication). + +The server has no enroll secret configured by default, so every test that +expects to get past the door overrides it. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, verify_device_token +from poorbird.config import Settings, get_settings +from poorbird.models.devices import Device + +SHARED = "test-bootstrap-secret" + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def uid(): + """A device_uid no other test will collide with.""" + return secrets.token_hex(6) + + +@pytest.fixture +def api(client, db): + """`client`, with an enroll secret configured and created rows cleaned up.""" + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, enroll_secret=SHARED + ) + created: list[str] = [] + + class Api: + def enroll(self, uid, secret=SHARED, **over): + created.append(uid) + body = { + "device_uid": uid, + "device_name": "poorbird-cam-1", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "fw_version": "0.1.0", + "mac": "A0:B7:65:1F:2C:3D", + } + body.update(over) + headers = {"X-Enroll-Secret": secret} if secret is not None else {} + return client.post("/api/v1/enroll", json=body, headers=headers) + + def unconfigured(self): + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, enroll_secret="" + ) + + yield Api() + + client.app.dependency_overrides.clear() + for u in created: + for d in db.scalars(select(Device).where(Device.device_uid == u)): + db.delete(d) + db.commit() + + +# --- first enrollment ------------------------------------------------------- + + +@needs_db +def test_first_enrollment_returns_201_and_the_documented_shape(api, uid): + r = api.enroll(uid) + assert r.status_code == 201 + + body = r.json() + assert set(body) == { + "token", + "device_id", + "reenroll_secret", + "server_time", + "config_version", + } + assert len(body["token"]) == 64 + assert len(body["reenroll_secret"]) == 64 + assert body["token"] != body["reenroll_secret"] + assert isinstance(body["device_id"], int) + assert body["server_time"] > 1_700_000_000_000 # epoch ms, not seconds + assert body["config_version"] >= 1 + + +@needs_db +def test_the_issued_token_actually_authenticates(api, uid, db): + """The regression that REVIEW.AI.md's reference code would have shipped. + + Its /enroll hands back devices.token_hash. The device would present that, + the server would hash it again, and every request after enrollment would + 401. This is the round trip that proves it does not. + """ + token = api.enroll(uid).json()["token"] + + device = verify_device_token(db=db, authorization=f"Bearer {token}") + assert device.device_uid == uid + + +@needs_db +def test_only_hashes_are_persisted(api, uid, db): + body = api.enroll(uid).json() + device = db.scalar(select(Device).where(Device.device_uid == uid)) + + assert device.token_hash == hash_credential(body["token"]) + assert device.reenroll_secret_hash == hash_credential(body["reenroll_secret"]) + # The plaintext must appear nowhere on the row. + stored = " ".join(str(v) for v in device.__dict__.values()) + assert body["token"] not in stored + assert body["reenroll_secret"] not in stored + + +# --- re-enrollment ---------------------------------------------------------- + + +@needs_db +def test_re_enrollment_reuses_the_row_and_rotates_the_token(api, uid, db): + """API.md: a known device_uid returns the existing device, not a duplicate. + + Expected on every token rotation and after any database restore. + """ + first = api.enroll(uid).json() + second = api.enroll(uid).json() + + assert second["device_id"] == first["device_id"] + assert second["token"] != first["token"] + assert db.scalars(select(Device).where(Device.device_uid == uid)).all().__len__() == 1 + + +@needs_db +def test_the_old_token_stops_working_after_rotation(api, uid, db): + from fastapi import HTTPException + + old = api.enroll(uid).json()["token"] + new = api.enroll(uid).json()["token"] + + assert verify_device_token(db=db, authorization=f"Bearer {new}") is not None + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=f"Bearer {old}") + assert exc.value.status_code == 401 + + +@needs_db +def test_a_device_can_re_enroll_with_its_own_secret(api, uid): + """The firmware swaps the shared secret for this one after first enrollment, + so from then on it is the only credential it has.""" + per_device = api.enroll(uid).json()["reenroll_secret"] + + again = api.enroll(uid, secret=per_device) + assert again.status_code == 201 + # and it is rotated in turn, so a captured secret is good for one use + assert again.json()["reenroll_secret"] != per_device + + +@needs_db +def test_one_devices_secret_cannot_enroll_a_different_uid(api, uid): + mine = api.enroll(uid).json()["reenroll_secret"] + assert api.enroll(secrets.token_hex(6), secret=mine).status_code == 401 + + +@needs_db +def test_hardware_facts_follow_the_device(api, uid, db): + api.enroll(uid) + api.enroll(uid, fw_version="0.2.0", hw_revision="rev-b") + + device = db.scalar(select(Device).where(Device.device_uid == uid)) + db.refresh(device) + assert device.fw_version == "0.2.0" + assert device.hw_revision == "rev-b" + + +@needs_db +def test_re_enrollment_does_not_undo_an_operator_rename(api, uid, db): + """The name is an operator-facing label after first enrollment. + + A camera that re-enrolls on every token rotation must not keep reverting a + rename made in the admin UI. + """ + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.name = "Feeder by the shed" + db.commit() + + api.enroll(uid, device_name="poorbird-cam-1") + + db.refresh(device) + assert device.name == "Feeder by the shed" + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +@pytest.mark.parametrize("secret", ["wrong", "", None]) +def test_bad_or_missing_secret_is_401(api, uid, secret): + assert api.enroll(uid, secret=secret).status_code == 401 + + +@needs_db +def test_unconfigured_server_is_503_not_401(api, uid): + """A 4xx would tell the camera it is unwelcome and make it clear its token. + The server being misconfigured is not the device's fault.""" + api.unconfigured() + assert api.enroll(uid).status_code == 503 + + +@needs_db +def test_a_disabled_device_cannot_re_enroll_its_way_back_in(api, uid, db): + """Otherwise disabling a device in the admin UI would mean nothing.""" + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.enabled = False + db.commit() + + assert api.enroll(uid).status_code == 403 + + +@needs_db +def test_a_disabled_devices_token_is_not_rotated_by_the_refusal(api, uid, db): + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.enabled = False + db.commit() + before = device.token_hash + + api.enroll(uid) + + db.refresh(device) + assert device.token_hash == before + + +@needs_db +@pytest.mark.parametrize( + "bad", + [ + {"device_uid": "not-hex!"}, + {"device_uid": ""}, + {"device_name": ""}, + {"device_name": "x" * 65}, + ], +) +def test_malformed_bodies_are_422(api, uid, bad): + assert api.enroll(uid, **bad).status_code == 422 + + +@needs_db +def test_the_legacy_name_field_is_not_accepted(api, uid, client): + """REVIEW.AI.md's model calls it `name`; the firmware sends `device_name`.""" + r = client.post( + "/api/v1/enroll", + json={"device_uid": uid, "name": "cam-1"}, + headers={"X-Enroll-Secret": SHARED}, + ) + assert r.status_code == 422 diff --git a/server/tests/test_firmware.py b/server/tests/test_firmware.py new file mode 100644 index 0000000..9a1cdd3 --- /dev/null +++ b/server/tests/test_firmware.py @@ -0,0 +1,224 @@ +"""GET /api/v1/firmware/{version}.bin. + +The device checks the response before it erases a partition, so the tests +here are mostly about the headers being exactly right rather than about the +bytes. +""" + +from __future__ import annotations + +import hashlib +import secrets +from pathlib import Path + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import get_settings +from poorbird.models.devices import Device, Firmware + +IMAGE = b"\xe9" + secrets.token_bytes(4095) # stands in for an .bin, 4096 bytes + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def make_image(db): + """Build firmware rows with real files, and clean both up unconditionally. + + Teardown belongs here rather than at the end of a test body: a failing + assertion skips the rest of the function, and a leftover is_target row + then picks itself as the OTA target for every later test. That is exactly + how a deliberate mutation once poisoned two unrelated suites. + """ + created: list[tuple[Firmware, Path]] = [] + folder = get_settings().state_dir / "firmware" + folder.mkdir(parents=True, exist_ok=True) + + def make(version: str | None = None, *, is_target: bool = False): + version = version or f"9.{secrets.randbelow(100000)}.0" + path = folder / f"{version}.bin" + path.write_bytes(IMAGE) + row = Firmware( + version=version, + file_path=str(path), + sha256=hashlib.sha256(IMAGE).hexdigest(), + size_bytes=len(IMAGE), + is_target=is_target, + ) + db.add(row) + db.commit() + db.refresh(row) + created.append((row, path)) + return row, path + + yield make + + for row, path in created: + path.unlink(missing_ok=True) + existing = db.get(Firmware, row.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def image(make_image): + """One firmware row with a real file behind it.""" + return make_image() + + +# --- what the device needs -------------------------------------------------- + + +@needs_db +def test_the_image_comes_back_intact(client, device, image): + _, auth = device + row, _ = image + + r = client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth) + + assert r.status_code == 200 + assert r.content == IMAGE + assert hashlib.sha256(r.content).hexdigest() == row.sha256 + + +@needs_db +def test_content_length_is_present_and_exact(client, device, image): + """The device refuses a chunked response: it size-checks against the + manifest before erasing a partition (ota_mgr.cpp:111-120).""" + _, auth = device + row, _ = image + + r = client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth) + + assert "content-length" in r.headers + assert int(r.headers["content-length"]) == len(IMAGE) + assert int(r.headers["content-length"]) == row.size_bytes + assert "transfer-encoding" not in r.headers + + +@needs_db +def test_the_response_is_not_compressed(client, device, image): + """Compression would change Content-Length and the device would refuse.""" + _, auth = device + row, _ = image + + r = client.get( + f"/api/v1/firmware/{row.version}.bin", + headers={**auth, "Accept-Encoding": "gzip, deflate, br"}, + ) + + assert r.headers.get("content-encoding") in (None, "identity") + assert int(r.headers["content-length"]) == len(IMAGE) + + +@needs_db +def test_a_dotted_version_is_parsed_out_of_the_path(client, device, make_image): + """Versions are semver-ish, so the path has several dots before .bin.""" + _, auth = device + make_image("1.2.3-rc.1") + + r = client.get("/api/v1/firmware/1.2.3-rc.1.bin", headers=auth) + assert r.status_code == 200 + assert r.content == IMAGE + + +# --- the envelope names it, this serves it ---------------------------------- + + +@needs_db +def test_the_url_the_envelope_advertises_actually_resolves(client, device, db, image): + """End to end: heartbeat names a target, that URL downloads it. + + The envelope sends a relative URL because ota_mgr.cpp appends it to the + API base, which already ends in /api/v1. This proves the two halves agree. + """ + d, auth = device + row, _ = image + row.is_target = True + d.fw_version = "0.0.1" # not the target, so the key is present + db.commit() + + envelope = client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).json() + advertised = envelope["firmware"]["url"] + assert advertised == f"/firmware/{row.version}.bin" + + # What the device builds: apiBaseUrl() + url, where the base ends /api/v1. + r = client.get(f"/api/v1{advertised}", headers=auth) + assert r.status_code == 200 + assert int(r.headers["content-length"]) == envelope["firmware"]["size"] + assert hashlib.sha256(r.content).hexdigest() == envelope["firmware"]["sha256"] + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +def test_an_unknown_version_is_404(client, device): + _, auth = device + assert client.get("/api/v1/firmware/0.0.0-nope.bin", headers=auth).status_code == 404 + + +@needs_db +def test_a_row_whose_file_is_missing_is_503_not_404(client, device, image): + """The firmware exists as far as the operator is concerned; this is a + server fault worth shouting about, not a missing resource.""" + _, auth = device + row, path = image + path.unlink() + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 503 + + +@needs_db +def test_a_size_mismatch_is_caught_here_rather_than_on_the_device(client, device, db, image): + """The device would abort on the Content-Length check anyway. Failing + here turns a confusing remote abort into one clear server log line.""" + _, auth = device + row, path = image + path.write_bytes(IMAGE + b"extra") + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 503 + + +@needs_db +def test_firmware_requires_a_bearer_token(client, image): + row, _ = image + assert client.get(f"/api/v1/firmware/{row.version}.bin").status_code == 401 + + +@needs_db +def test_a_disabled_device_cannot_download(client, device, db, image): + d, auth = device + row, _ = image + d.enabled = False + db.commit() + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 403 diff --git a/server/tests/test_health.py b/server/tests/test_health.py new file mode 100644 index 0000000..3b2ed7f --- /dev/null +++ b/server/tests/test_health.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from conftest import needs_db + + +def test_health_answers_even_without_a_database(client): + """The WebUI banner must be able to render a degraded system.""" + r = client.get("/api/v1/health") + assert r.status_code == 200 + body = r.json() + assert body["status"] in {"ok", "degraded"} + assert "database" in body + assert "disk" in body + assert body["version"] + + +@needs_db +def test_health_is_ok_with_a_database(client): + body = client.get("/api/v1/health").json() + assert body["status"] == "ok" + assert body["database"]["ok"] is True + + +@needs_db +def test_healthz_is_200_when_the_database_is_up(client): + assert client.get("/healthz").status_code == 200 + + +def test_openapi_is_served(client): + assert client.get("/openapi.json").status_code == 200 diff --git a/server/tests/test_ingest.py b/server/tests/test_ingest.py new file mode 100644 index 0000000..48183df --- /dev/null +++ b/server/tests/test_ingest.py @@ -0,0 +1,403 @@ +"""POST /api/v1/ingest -- raw JPEG body, metadata in headers.""" + +from __future__ import annotations + +import hashlib +import io +import secrets +import struct +from pathlib import Path + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import get_settings +from poorbird.images import jpeg_dimensions, looks_like_jpeg +from poorbird.models.captures import Capture +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus +from poorbird.models.ops import Job + + +def make_jpeg(width: int = 800, height: int = 600, noise: bytes = b"") -> bytes: + """A byte string with a valid SOI and SOF0, enough to be parsed as a JPEG. + + Not a decodable image: nothing on the ingest path decodes one, which is + the point of parsing the header rather than pulling in Pillow. + """ + out = io.BytesIO() + out.write(b"\xff\xd8\xff") # SOI + start of the next marker + out.write(b"\xe0") # APP0 + out.write(struct.pack(">H", 16)) + out.write(b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00") + out.write(b"\xff\xc0") # SOF0 + out.write(struct.pack(">H", 17)) + out.write(b"\x08") # precision + out.write(struct.pack(">HH", height, width)) + out.write(b"\x03\x01\x11\x00\x02\x11\x01\x03\x11\x01") + out.write(b"\xff\xd9") # EOI + out.write(noise) # makes the sha256 differ between frames + return out.getvalue() + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def make_device(db): + """Devices, their captures, their frames and their jobs -- all cleaned up. + + Every device a test makes goes through here, so a test that needs a + second one does not have to hand-roll teardown and forget half of it. + """ + created: list[Device] = [] + + def make(name: str = "cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + created.append(d) + return d, {"Authorization": f"Bearer {token}"} + + yield make + + root = get_settings().image_root + for d in created: + capture_ids = [] + for cap in db.scalars(select(Capture).where(Capture.device_id == d.id)): + (root / cap.path).unlink(missing_ok=True) + capture_ids.append(str(cap.id)) + + # Ingest enqueues a thumbnail job per capture. Leaving those behind + # breaks test_queue.py, which claims from the same shared queue. + # Matched on payload so this never touches a job it did not create. + if capture_ids: + db.query(Job).filter( + Job.kind == "thumbnail", + Job.payload["capture_id"].astext.in_(capture_ids), + ).delete(synchronize_session=False) + + db.execute(Capture.__table__.delete().where(Capture.device_id == d.id)) + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + existing = db.get(Device, d.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def device(make_device): + return make_device() + + +def post(client, auth, data=None, **headers): + h = {"Content-Type": "image/jpeg", **auth} + h.update({k.replace("_", "-"): str(v) for k, v in headers.items()}) + return client.post( + "/api/v1/ingest", content=data if data is not None else make_jpeg(), headers=h + ) + + +# --- the header parser, in isolation ---------------------------------------- + + +def test_jpeg_dimensions_reads_the_header(): + assert jpeg_dimensions(make_jpeg(1600, 1200)) == (1600, 1200) + assert jpeg_dimensions(make_jpeg(320, 240)) == (320, 240) + + +def test_jpeg_dimensions_gives_up_quietly_on_rubbish(): + """None is not an error: a frame we cannot measure is still worth keeping.""" + assert jpeg_dimensions(b"\xff\xd8\xff") is None + assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x10" + b"\x00" * 14) is None + assert jpeg_dimensions(b"") is None + + +def test_jpeg_dimensions_terminates_on_hostile_input(): + """A zero-length segment must not loop forever.""" + assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x00" + b"\x41" * 100) is None + assert jpeg_dimensions(b"\xff\xd8" + b"\xff" * 5000) is None + + +def test_magic_bytes_are_what_decide_it_is_a_jpeg(): + assert looks_like_jpeg(make_jpeg()) + assert not looks_like_jpeg(b"GIF89a") + assert not looks_like_jpeg(b"") + + +# --- the happy path --------------------------------------------------------- + + +@needs_db +def test_a_frame_is_stored_and_the_envelope_comes_back(client, device, db): + d, auth = device + r = post(client, auth, X_Trigger="radar", X_Burst_Id="a0b765-3-91204", X_Burst_Index=0) + + assert r.status_code == 201 + envelope = r.json() + assert envelope["capture_id"] + assert envelope["server_time"] > 1_700_000_000_000 + assert envelope["commands"] == [] + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert str(cap.id) == envelope["capture_id"] + assert cap.trigger == "radar" + assert cap.burst_id == "a0b765-3-91204" + assert cap.width == 800 and cap.height == 600 + + +@needs_db +def test_the_bytes_land_on_disk_under_a_dated_path(client, device, db): + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + assert post(client, auth, data=body).status_code == 201 + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + # Relative to the configured root, dated by received_at (SPEC 3.3). + assert cap.path == f"{cap.received_at:%Y/%m/%d}/{cap.id}.jpg" + assert not Path(cap.path).is_absolute() + + on_disk = get_settings().image_root / cap.path + assert on_disk.is_file() + assert on_disk.read_bytes() == body + assert cap.bytes == len(body) + assert cap.sha256 == hashlib.sha256(body).hexdigest() + + +@needs_db +def test_no_part_file_is_left_behind(client, device, db): + d, auth = device + post(client, auth) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + folder = (get_settings().image_root / cap.path).parent + assert not list(folder.glob(".*.part")) + + +@needs_db +def test_ingest_delivers_commands_like_heartbeat_does(client, device, db): + """Same envelope on purpose: a capture that was going to happen anyway + also drains the queue at no extra cost (SPEC 4.1).""" + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="capture_now")) + db.commit() + + envelope = post(client, auth).json() + assert [c["type"] for c in envelope["commands"]] == ["capture_now"] + + +# --- the clock --------------------------------------------------------------- + + +@needs_db +def test_captured_at_zero_means_unsynced_not_1970(client, device, db): + """Storing an epoch date would bury the frame at the bottom of every + chronological view forever.""" + d, auth = device + post(client, auth, X_Captured_At=0) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.captured_at_device is None + assert cap.received_at is not None # server time stays authoritative + + +@needs_db +def test_a_synced_device_clock_is_recorded(client, device, db): + d, auth = device + post(client, auth, X_Captured_At=1758376267123) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.captured_at_device is not None + assert cap.captured_at_device.year == 2025 or cap.captured_at_device.year == 2026 + + +@needs_db +def test_received_at_is_server_time_regardless(client, device, db): + """SPEC C7. Even a device claiming to be in 1998.""" + d, auth = device + post(client, auth, X_Captured_At=915148800000) # 1999 + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.received_at.year >= 2026 + assert cap.path.startswith(f"{cap.received_at:%Y}") + + +# --- metadata --------------------------------------------------------------- + + +@needs_db +def test_pre_trigger_is_recorded(client, device, db): + """1 means the frame predates the trigger, out of the PSRAM ring -- often + the good one, because the bird is still arriving.""" + d, auth = device + post(client, auth, X_Pre_Trigger=1) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.pre_trigger is True + + +@needs_db +def test_radar_and_signal_metadata_are_recorded(client, device, db): + d, auth = device + post( + client, + auth, + X_Radar_State=2, + X_Radar_Distance_Cm=180, + X_Radar_Energy=77, + X_Frame_Seq=42, + X_Rssi=-61, + ) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert (cap.radar_state, cap.radar_distance_cm, cap.radar_energy) == (2, 180, 77) + assert cap.frame_seq == 42 + assert cap.rssi == -61 + + db.refresh(d) + assert d.rssi == -61 + assert d.last_seen_at is not None + + +@needs_db +def test_an_unknown_trigger_is_422(client, device): + _, auth = device + assert post(client, auth, X_Trigger="motion").status_code == 422 + + +@needs_db +def test_an_out_of_range_radar_state_is_422(client, device): + _, auth = device + assert post(client, auth, X_Radar_State=9).status_code == 422 + + +@needs_db +def test_the_trigger_defaults_when_the_header_is_absent(client, device, db): + d, auth = device + r = client.post( + "/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg", **auth} + ) + assert r.status_code == 201 + + +# --- retries ---------------------------------------------------------------- + + +@needs_db +def test_the_same_frame_twice_is_one_capture(client, device, db): + """The device retries an upload whose response was lost and cannot tell + that case from a real failure.""" + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + + first = post(client, auth, data=body).json() + second = post(client, auth, data=body).json() + + assert second["capture_id"] == first["capture_id"] + assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 1 + + +@needs_db +def test_a_retry_still_receives_pending_commands(client, device, db): + """The retry is still the device asking; it must not lose the queue.""" + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + post(client, auth, data=body) + + db.add(DeviceCommand(device_id=d.id, type="reboot")) + db.commit() + + envelope = post(client, auth, data=body).json() + assert [c["type"] for c in envelope["commands"]] == ["reboot"] + + +@needs_db +def test_different_frames_are_separate_captures(client, device, db): + """Frames in a burst differ by sensor noise alone, so they must not + collapse into one.""" + d, auth = device + post(client, auth, data=make_jpeg(noise=b"frame-one")) + post(client, auth, data=make_jpeg(noise=b"frame-two")) + + assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 2 + + +@needs_db +def test_one_devices_frame_does_not_deduplicate_against_anothers(client, device, make_device): + _, auth = device + _, other_auth = make_device("other") + + body = make_jpeg(noise=b"identical") + a = post(client, auth, data=body).json() + b = post(client, other_auth, data=body).json() + + assert a["capture_id"] != b["capture_id"] + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +def test_an_empty_body_is_400(client, device): + _, auth = device + assert post(client, auth, data=b"").status_code == 400 + + +@needs_db +def test_a_body_that_is_not_a_jpeg_is_400_not_401(client, device): + """400 specifically: a 401 would make the device clear a good token.""" + _, auth = device + r = post(client, auth, data=b"GIF89a" + b"\x00" * 100) + assert r.status_code == 400 + + +@needs_db +def test_an_oversized_body_is_413(client, device): + """Mirrors `request_body max_size 12MB` in the Caddyfile, because a limit + that only exists in the proxy is not a limit.""" + _, auth = device + assert post(client, auth, data=make_jpeg() + b"\x00" * (12 * 1024 * 1024)).status_code == 413 + + +@needs_db +def test_nothing_is_written_when_the_body_is_rejected(client, device, db): + """No row, and nothing left on disk either.""" + d, auth = device + before = set(get_settings().image_root.rglob("*.jpg")) + + assert post(client, auth, data=b"not a jpeg at all").status_code == 400 + + assert db.scalars(select(Capture).where(Capture.device_id == d.id)).all() == [] + assert set(get_settings().image_root.rglob("*.jpg")) == before + + +@needs_db +def test_ingest_requires_a_bearer_token(client): + assert ( + client.post( + "/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg"} + ).status_code + == 401 + ) + + +@needs_db +def test_a_disabled_device_cannot_ingest(client, device, db): + d, auth = device + d.enabled = False + db.commit() + assert post(client, auth).status_code == 403 diff --git a/server/tests/test_passwords.py b/server/tests/test_passwords.py new file mode 100644 index 0000000..c77afb7 --- /dev/null +++ b/server/tests/test_passwords.py @@ -0,0 +1,148 @@ +"""Argon2id password hashing and TOTP (REVIEW SEC-009, TODO 3.0). + +No database needed: these are pure functions. +""" + +from __future__ import annotations + +import pytest + +from poorbird.passwords import ( + MIN_PASSWORD_LENGTH, + WeakPassword, + hash_password, + needs_rehash, + validate_password_strength, + verify_password, +) +from poorbird.totp import DIGITS, new_secret, provisioning_uri, verify + +GOOD = "a-perfectly-fine-passphrase" + + +# --- hashing ---------------------------------------------------------------- + + +def test_a_password_verifies_against_its_own_hash(): + assert verify_password(GOOD, hash_password(GOOD)) is True + + +def test_a_wrong_password_does_not_verify(): + assert verify_password("something else entirely", hash_password(GOOD)) is False + + +def test_the_hash_is_argon2id_and_not_something_faster(): + """SPEC 3.1 says Argon2id specifically. + + A SHA-256 here would pass every other test in this file while leaving the + passwords brute-forceable, so the algorithm is asserted directly. + """ + assert hash_password(GOOD).startswith("$argon2id$") + + +def test_the_same_password_hashes_differently_every_time(): + """Per-hash salt. Equal hashes would mean equal passwords are visible.""" + assert hash_password(GOOD) != hash_password(GOOD) + + +def test_the_plaintext_never_appears_in_the_hash(): + assert GOOD not in hash_password(GOOD) + + +@pytest.mark.parametrize("stored", [None, "", "not-a-hash", "$argon2id$truncated"]) +def test_an_unusable_stored_hash_is_a_no_not_a_crash(stored): + """A user row that has never had a password set must not be loggable-in. + + It must also not take the login route down: NULL is the Phase 1 state of + every seeded row, and a 500 on the login endpoint is worse than a 401. + """ + assert verify_password(GOOD, stored) is False + + +def test_a_current_hash_does_not_need_rehashing(): + assert needs_rehash(hash_password(GOOD)) is False + + +def test_a_weaker_hash_is_flagged_for_rehash(): + """Login is the only moment the plaintext exists, so it is the only moment + a hash can be upgraded. This is what makes raising the cost possible.""" + from argon2 import PasswordHasher + + weak = PasswordHasher(time_cost=1, memory_cost=8, parallelism=1).hash(GOOD) + assert needs_rehash(weak) is True + # ...and it must still verify, or raising the cost would lock everyone out. + assert verify_password(GOOD, weak) is True + + +# --- strength floor --------------------------------------------------------- + + +def test_a_long_enough_password_is_accepted(): + validate_password_strength("x" * MIN_PASSWORD_LENGTH) + + +def test_a_short_password_is_rejected(): + with pytest.raises(WeakPassword, match="at least"): + validate_password_strength("x" * (MIN_PASSWORD_LENGTH - 1)) + + +def test_whitespace_is_not_a_password(): + with pytest.raises(WeakPassword, match="whitespace"): + validate_password_strength(" " * (MIN_PASSWORD_LENGTH + 4)) + + +def test_an_absurdly_long_password_is_rejected_rather_than_hashed(): + """Argon2 is deliberately expensive; an unbounded body should not become a + way to spend the server's CPU.""" + with pytest.raises(WeakPassword, match="at most"): + validate_password_strength("x" * 5000) + + +# --- totp ------------------------------------------------------------------- + + +def test_a_generated_code_verifies(): + import pyotp + + secret = new_secret() + assert verify(secret, pyotp.TOTP(secret).now()) is True + + +def test_a_code_for_a_different_secret_does_not_verify(): + import pyotp + + assert verify(new_secret(), pyotp.TOTP(new_secret()).now()) is False + + +@pytest.mark.parametrize("code", [None, "", "abcdef", "12345", "1234567", "12 34 56 78"]) +def test_a_malformed_code_is_rejected_without_raising(code): + assert verify(new_secret(), code) is False + + +def test_a_user_without_a_secret_can_never_pass_totp(): + """The check has to fail closed. If a missing secret verified, enabling 2FA + for one user would effectively disable it for everyone else.""" + import pyotp + + assert verify(None, pyotp.TOTP(new_secret()).now()) is False + + +def test_spaces_in_a_code_are_tolerated(): + """Authenticator apps display "123 456"; people paste what they see.""" + import pyotp + + secret = new_secret() + code = pyotp.TOTP(secret).now() + assert verify(secret, f"{code[:3]} {code[3:]}") is True + + +def test_the_provisioning_uri_carries_the_issuer_and_account(): + uri = provisioning_uri(new_secret(), "alice") + assert uri.startswith("otpauth://totp/") + assert "issuer=poorBird" in uri + assert "alice" in uri + + +def test_codes_are_six_digits(): + """Changing this silently would break every already-enrolled authenticator.""" + assert DIGITS == 6 diff --git a/server/tests/test_queue.py b/server/tests/test_queue.py new file mode 100644 index 0000000..8ddf644 --- /dev/null +++ b/server/tests/test_queue.py @@ -0,0 +1,125 @@ +"""Queue behaviour. Needs a real PostgreSQL: SKIP LOCKED has no equivalent +anywhere else, and mocking it would test nothing. + +These share the ``jobs`` table with everything else, including /ingest, which +enqueues a thumbnail job per capture. So nothing here may assume it owns the +queue: test jobs are enqueued at a priority that puts them first, and every +claim is checked to be one of ours before anything is done to it. Acting on a +claim without that check could fail somebody else's job. +""" + +from __future__ import annotations + +import pytest +from conftest import needs_db + +pytestmark = [pytest.mark.db, needs_db] + +# claim() orders by priority DESC, so this wins against anything real. +TEST_PRIORITY = 1000 + + +@pytest.fixture +def session(): + from poorbird.db import SessionLocal + from poorbird.models import Job + + with SessionLocal() as s: + yield s + s.query(Job).filter(Job.kind.like("test_%")).delete(synchronize_session=False) + s.commit() + + +def claim_ours(queue, session, kind: str) -> dict: + """Claim, and insist it is the job this test enqueued.""" + claimed = queue.claim(session) + assert claimed is not None, "our own job should have been claimable" + assert claimed["kind"] == kind, f"claimed {claimed['kind']!r}, not our {kind!r}" + return claimed + + +def test_claim_returns_a_queued_job_then_nothing(session): + from poorbird.worker import queue + + queue.enqueue(session, "test_noop", {"n": 1}, priority=TEST_PRIORITY) + session.commit() + + claimed = claim_ours(queue, session, "test_noop") + assert claimed["payload"] == {"n": 1} + assert claimed["attempts"] == 1 + + queue.complete(session, claimed["id"]) + + # Same job must not come back. Anything else that turns up belongs to + # another test, so put it back rather than stranding it in 'running' -- + # a claim that is never released is invisible until something else + # mysteriously stops being processed. + again = queue.claim(session) + assert again is None or again["kind"] != "test_noop" + if again is not None: + queue.fail(session, again["id"], "released by test", retry_in_s=0) + + +def test_a_second_worker_skips_a_locked_row_instead_of_blocking(session): + """The whole point of FOR UPDATE SKIP LOCKED. + + The invariant is that the second worker is not blocked by the first and + never gets the same row -- not that the queue is otherwise empty, which + is not something a shared table can promise. + """ + from poorbird.db import SessionLocal + from poorbird.worker import queue + + queue.enqueue(session, "test_only_one", priority=TEST_PRIORITY) + session.commit() + + first = claim_ours(queue, session, "test_only_one") + + with SessionLocal() as other: + second = queue.claim(other) + assert second is None or second["id"] != first["id"] + if second is not None: + queue.fail(other, second["id"], "released by test", retry_in_s=0) + + queue.complete(session, first["id"]) + + +def test_failure_retries_until_max_attempts_then_parks(session): + from poorbird.models import Job + from poorbird.worker import queue + + job = queue.enqueue(session, "test_doomed", max_attempts=2, priority=TEST_PRIORITY) + session.commit() + job_id = job.id + + for _ in range(2): + claimed = claim_ours(queue, session, "test_doomed") + queue.fail(session, claimed["id"], "boom", retry_in_s=0) + + session.expire_all() + parked = session.get(Job, job_id) + assert parked.status == "failed" + assert parked.attempts == 2 + assert "boom" in parked.last_error + + +def test_stale_running_jobs_are_reclaimed(session): + from sqlalchemy import text + + from poorbird.models import Job + from poorbird.worker import queue + + job = queue.enqueue(session, "test_orphan", priority=TEST_PRIORITY) + session.commit() + claim_ours(queue, session, "test_orphan") + + # Pretend the worker died an hour ago. + session.execute( + text("UPDATE jobs SET locked_at = now() - interval '1 hour' WHERE id = :id"), + {"id": job.id}, + ) + session.commit() + + assert queue.requeue_stale(session, older_than_s=60) >= 1 + session.expire_all() + assert session.get(Job, job.id).status == "queued" diff --git a/server/tests/test_ratelimit.py b/server/tests/test_ratelimit.py new file mode 100644 index 0000000..fa8384f --- /dev/null +++ b/server/tests/test_ratelimit.py @@ -0,0 +1,270 @@ +"""Rate limiting (REVIEW SEC-004). + +The rest of the suite runs with limiting off, so this is the one place that +turns it on and proves the buckets are actually wired to the routes. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api import ratelimit +from poorbird.api.deps import hash_credential, new_credential +from poorbird.api.ratelimit import BUCKETS, Limit, TokenBuckets +from poorbird.config import Settings, get_settings +from poorbird.models.devices import Device, DeviceStatus + +# --- the bucket itself ------------------------------------------------------ + + +def test_a_bucket_allows_its_burst_then_refuses(): + b = TokenBuckets() + limit = Limit(capacity=3, per_second=1.0) + + assert [b.take("k", limit, now=0.0) for _ in range(3)] == [None, None, None] + assert b.take("k", limit, now=0.0) is not None + + +def test_it_says_how_long_to_wait(): + b = TokenBuckets() + limit = Limit(capacity=1, per_second=0.5) # one every two seconds + + assert b.take("k", limit, now=0.0) is None + retry = b.take("k", limit, now=0.0) + assert retry == pytest.approx(2.0) + + +def test_tokens_come_back_over_time(): + b = TokenBuckets() + limit = Limit(capacity=2, per_second=1.0) + + b.take("k", limit, now=0.0) + b.take("k", limit, now=0.0) + assert b.take("k", limit, now=0.0) is not None + + assert b.take("k", limit, now=1.0) is None # one second, one token + + +def test_a_bucket_never_fills_past_its_capacity(): + """An idle week must not buy a week's worth of burst.""" + b = TokenBuckets() + limit = Limit(capacity=2, per_second=1.0) + + b.take("k", limit, now=0.0) + for _ in range(2): + assert b.take("k", limit, now=100_000.0) is None + assert b.take("k", limit, now=100_000.0) is not None + + +def test_keys_do_not_share_an_allowance(): + b = TokenBuckets() + limit = Limit(capacity=1, per_second=1.0) + + assert b.take("a", limit, now=0.0) is None + assert b.take("b", limit, now=0.0) is None + assert b.take("a", limit, now=0.0) is not None + + +def test_the_key_table_is_bounded(): + """It is keyed partly on caller address; unbounded growth would itself be + a way to exhaust memory.""" + b = TokenBuckets(max_keys=10) + limit = Limit(capacity=1, per_second=1.0) + + for i in range(100): + b.take(f"key-{i}", limit, now=0.0) + + assert len(b._state) == 10 + + +def test_the_documented_limits_are_the_shape_they_claim(): + assert ratelimit.ENROLL.capacity == 6 + assert ratelimit.INGEST.per_second == pytest.approx(2.0) # 120/min + # Ingest must comfortably clear a radar burst of three to five frames. + assert ratelimit.INGEST.capacity >= 10 + + +# --- the client address ----------------------------------------------------- + + +class _Req: + def __init__(self, headers=None, host="127.0.0.1"): + self.headers = headers or {} + self.client = type("C", (), {"host": host})() + + +def test_the_proxy_header_wins_over_the_socket(): + """Every camera reaches the app from 127.0.0.1 via Caddy. Without this + they would all share one bucket.""" + assert ratelimit.client_address(_Req({"x-real-ip": "192.168.1.88"})) == "192.168.1.88" + + +def test_forwarded_for_is_read_as_a_fallback(): + req = _Req({"x-forwarded-for": "192.168.1.88, 10.0.0.1"}) + assert ratelimit.client_address(req) == "192.168.1.88" + + +def test_the_socket_address_is_the_last_resort(): + assert ratelimit.client_address(_Req(host="10.1.2.3")) == "10.1.2.3" + + +# --- wired to the routes ---------------------------------------------------- + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def limited(client, db): + """Turn limiting on for one test, and leave no buckets behind.""" + BUCKETS.reset() + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, + enroll_secret="test-secret", + rate_limit_enabled=True, + ) + yield + client.app.dependency_overrides.clear() + BUCKETS.reset() + + +@pytest.fixture +def make_device(db): + """Devices that are removed even when the test fails. + + Teardown belongs in a fixture: a failing assertion skips the rest of the + test body, and cleanup written down there silently never runs. + """ + created: list[Device] = [] + + def make(name: str = "cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + created.append(d) + return d, {"Authorization": f"Bearer {token}"} + + yield make + + for d in created: + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + existing = db.get(Device, d.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def device(make_device): + return make_device() + + +@needs_db +def test_enrollment_is_limited_by_address(client, limited): + """The one endpoint where a shared secret could be ground at.""" + codes = [ + client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.90"}, + ).status_code + for _ in range(ratelimit.ENROLL.capacity + 2) + ] + + assert 429 in codes, "grinding at the enroll secret must eventually be refused" + assert codes.count(401) == ratelimit.ENROLL.capacity + + +@needs_db +def test_a_429_carries_retry_after(client, limited): + for _ in range(ratelimit.ENROLL.capacity + 1): + r = client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.91"}, + ) + + assert r.status_code == 429 + assert int(r.headers["Retry-After"]) >= 1 + + +@needs_db +def test_one_address_cannot_spend_anothers_budget(client, limited): + for _ in range(ratelimit.ENROLL.capacity + 1): + client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.92"}, + ) + + other = client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.93"}, + ) + assert other.status_code == 401, "a second camera must not inherit the first's throttle" + + +@needs_db +def test_heartbeat_is_limited_per_device(client, limited, device): + _, auth = device + codes = [ + client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).status_code + for _ in range(ratelimit.CONDITIONS.capacity + 2) + ] + + assert codes[0] == 200 + assert 429 in codes + + +@needs_db +def test_one_device_cannot_spend_anothers_budget(client, limited, device, make_device): + _, auth = device + for _ in range(ratelimit.CONDITIONS.capacity + 2): + client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth) + + _, other_auth = make_device("other") + + r = client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=other_auth) + assert r.status_code == 200, "one wedged camera must not starve the others" + + +@needs_db +def test_a_throttled_request_is_429_and_never_401(client, limited, device): + """401 makes the firmware clear its token. Being busy is not a credential + problem, and throwing away a good token over it would be a real fault.""" + _, auth = device + seen = set() + for _ in range(ratelimit.CONDITIONS.capacity + 3): + seen.add( + client.post("/api/v1/status", json={"reason": "periodic"}, headers=auth).status_code + ) + + assert 429 in seen + assert 401 not in seen + + +@needs_db +def test_limiting_off_means_off(client, device): + """The default for the rest of the suite, and for local development.""" + _, auth = device + codes = [ + client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).status_code + for _ in range(ratelimit.CONDITIONS.capacity + 5) + ] + assert set(codes) == {200} diff --git a/server/tests/test_schema_matches_models.py b/server/tests/test_schema_matches_models.py new file mode 100644 index 0000000..5fb8941 --- /dev/null +++ b/server/tests/test_schema_matches_models.py @@ -0,0 +1,68 @@ +"""Guard the baseline migration against the models. + +Migration 0001 builds the schema from ``Base.metadata`` (see its docstring). +That is only safe if something checks it, so: migrate a scratch database, then +ask Alembic to autogenerate against it and assert the diff is empty. + +This test keeps working after 0001 is replaced by explicit DDL, and it is what +catches "added a column to the model, forgot the migration" from Phase 2 on. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from conftest import needs_db + +pytestmark = [pytest.mark.db, needs_db] + + +def test_migrated_schema_matches_the_models(): + from alembic.autogenerate import compare_metadata + from alembic.migration import MigrationContext + from sqlalchemy import create_engine, text + + from poorbird.config import get_settings + from poorbird.db import engine + from poorbird.models import Base + from poorbird.schema_compare import COMPARE_OPTS + + scratch = "poorbird_schema_check" + + # CREATE DATABASE cannot run inside a transaction block. + with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"')) + conn.execute(text(f'CREATE DATABASE "{scratch}"')) + + url = get_settings().database_url + scratch_url = url.rsplit("/", 1)[0] + "/" + scratch + scratch_engine = create_engine(scratch_url) + + try: + # Apply the real migration chain, exactly as `poorbird migrate` would. + with scratch_engine.begin() as conn: + from alembic import command + from alembic.config import Config + + cfg = Config() + cfg.set_main_option( + "script_location", str(Path(__file__).resolve().parents[1] / "migrations") + ) + cfg.set_main_option("sqlalchemy.url", scratch_url) + cfg.attributes["connection"] = conn + command.upgrade(cfg, "head") + + with scratch_engine.connect() as conn: + # The same options autogenerate uses, so the test and the tool can + # never disagree about what counts as a difference. + ctx = MigrationContext.configure(conn, opts=dict(COMPARE_OPTS)) + diff = compare_metadata(ctx, Base.metadata) + + # alembic_version is Alembic's own bookkeeping, not part of the models. + diff = [d for d in diff if "alembic_version" not in str(d)] + assert diff == [], f"schema has drifted from the models:\n{diff}" + finally: + scratch_engine.dispose() + with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"')) diff --git a/server/tests/test_schemas.py b/server/tests/test_schemas.py new file mode 100644 index 0000000..77538c2 --- /dev/null +++ b/server/tests/test_schemas.py @@ -0,0 +1,277 @@ +"""Device API request/response shapes (REVIEW SEC-003). + +These assert against firmware/API.md and, where the two disagree, against what +firmware/src/api_client.cpp actually sends. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from poorbird.api.schemas import ( + Command, + DeviceConditions, + EnrollRequest, + Envelope, + IngestMeta, +) + +# --- enrollment ------------------------------------------------------------- + + +def test_enroll_accepts_what_the_firmware_sends(): + """Exactly the body built in api_client.cpp::enrollWith.""" + r = EnrollRequest.model_validate( + { + "device_uid": "a0b7651f2c3d", + "device_name": "poorbird-cam-1", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "fw_version": "0.1.0", + "mac": "A0:B7:65:1F:2C:3D", + } + ) + assert r.device_uid == "a0b7651f2c3d" + assert r.device_name == "poorbird-cam-1" + + +def test_the_field_is_device_name_not_name(): + """REVIEW.AI.md calls it 'name'. The firmware sends 'device_name'.""" + with pytest.raises(ValidationError): + EnrollRequest.model_validate({"device_uid": "a0b7651f2c3d", "name": "cam-1"}) + + +def test_device_uid_must_be_hex(): + """It is the eFuse MAC in hex; anything else is not a device identity.""" + for bad in ["not-hex!", "zzzz", "", "ab"]: + with pytest.raises(ValidationError): + EnrollRequest.model_validate({"device_uid": bad, "device_name": "cam"}) + + +def test_oversized_fields_are_rejected_before_the_database_sees_them(): + """devices.name is String(64); a 422 beats a DataError from psycopg.""" + with pytest.raises(ValidationError): + EnrollRequest.model_validate({"device_uid": "a0b765", "device_name": "x" * 65}) + + +# --- ingest ----------------------------------------------------------------- + + +def test_ingest_trigger_enum_matches_the_database_constraint(): + for t in ("radar", "manual", "timer", "stream_grab"): + assert IngestMeta(trigger=t).trigger == t + with pytest.raises(ValidationError): + IngestMeta(trigger="motion") + + +def test_radar_fields_are_range_checked(): + IngestMeta(trigger="radar", radar_state=3, radar_energy=100) + with pytest.raises(ValidationError): + IngestMeta(trigger="radar", radar_state=4) + with pytest.raises(ValidationError): + IngestMeta(trigger="radar", radar_energy=101) + + +def test_captured_at_defaults_to_none(): + """X-Captured-At: 0 means the clock is unsynced -- NULL, not 1970.""" + assert IngestMeta(trigger="radar").captured_at is None + + +# --- conditions ------------------------------------------------------------- + + +def _example_body() -> dict: + """The status payload from firmware/API.md, verbatim.""" + return { + "reason": "periodic", + "fw_version": "0.1.0", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "config_version": 8, + "power": { + "uptime_ms": 91204, + "awake_ms": 91204, + "boot_count": 37, + "wake_cause": "radar", + "last_sleep_s": 300, + "total_sleep_s": 10800, + "sleep_enabled": False, + "sleep_allowed": False, + "inhibits": "stream,upload", + }, + "battery": { + "valid": True, + "mv": 3912, + "pct": 74, + "raw_mv": 1956, + "chemistry": 1, + "low": False, + }, + "counters": { + "captured_today": 412, + "delivered_today": 407, + "failed_today": 5, + "events_today": 41, + "day_index": 20716, + "captured_boot": 88, + "delivered_boot": 88, + }, + "camera": {"frame_size": 8, "jpeg_quality": 12, "profile": "day", "ready": True}, + "night": { + "is_night": False, + "nightlight_on": False, + "behaviour": 2, + "capture_allowed": True, + }, + "stream": {"enabled": False, "active": False, "frames_sent": 0, "seconds_left": 0}, + "radar": { + "baud": 256000, + "uart_ok": True, + "out_pin": False, + "state": 0, + "moving_cm": 0, + "moving_energy": 0, + "stationary_cm": 0, + "stationary_energy": 0, + }, + "system": { + "rssi": -61, + "ip": "192.168.1.88", + "free_heap": 184320, + "free_psram": 6815744, + "ring_depth": 24, + "ring_bytes": 1179648, + }, + "time_synced": True, + "device_time": "2026-09-20T14:31:07Z", + } + + +def test_the_documented_status_payload_validates(): + c = DeviceConditions.model_validate(_example_body()) + assert c.reason == "periodic" + assert c.battery.mv == 3912 + assert c.counters.day_index == 20716 + assert c.system.free_psram == 6815744 + + +def test_reason_enum_matches_the_database_constraint(): + for r in ( + "heartbeat", + "periodic", + "after_event", + "before_sleep", + "before_night_sleep", + "on_request", + ): + assert DeviceConditions(reason=r).reason == r + with pytest.raises(ValidationError): + DeviceConditions(reason="whenever") + + +def test_unknown_firmware_fields_are_kept_not_rejected(): + """The firmware grows fields before the server learns about them. + + device_status.raw exists to keep the whole body; a 422 would take a camera + offline for reporting something new. + """ + body = _example_body() + body["quantum_flux"] = 42 + body["battery"]["future_field"] = "x" + + c = DeviceConditions.model_validate(body) + assert c.reason == "periodic" + assert c.model_dump()["quantum_flux"] == 42 + + +def test_missing_blocks_default_rather_than_failing(): + """Only `reason` is genuinely required; a minimal report still lands.""" + c = DeviceConditions(reason="before_sleep") + assert c.battery.valid is None # None = not reported, distinct from False + assert c.counters.captured_today is None + + +def test_battery_valid_false_is_preserved_as_false(): + """false means NOT MEASURED. It must not collapse into None anywhere.""" + c = DeviceConditions.model_validate({"reason": "periodic", "battery": {"valid": False}}) + assert c.battery.valid is False + + +def test_frame_size_accepts_a_name_as_well_as_an_index(): + """Names are authoritative: framesize_t indices have shifted between + driver releases, so a stored index can mean a different resolution.""" + assert ( + DeviceConditions.model_validate( + {"reason": "periodic", "camera": {"frame_size": "SVGA"}} + ).camera.frame_size + == "SVGA" + ) + assert ( + DeviceConditions.model_validate( + {"reason": "periodic", "camera": {"frame_size": 8}} + ).camera.frame_size + == 8 + ) + + +# --- envelope --------------------------------------------------------------- + + +def test_envelope_omits_firmware_when_the_device_is_on_target(): + """Present-and-different is itself the signal to flash, so absent must + mean absent -- not null.""" + e = Envelope(server_time=1758376267000, config_version=7) + assert "firmware" not in e.model_dump(exclude_none=True) + + +def test_envelope_matches_the_documented_example(): + e = Envelope( + capture_id="3f786850-e387-550f-dab8-36ed7e6dc881", + server_time=1758376267000, + config_version=7, + firmware={ + "version": "0.2.0", + "url": "/firmware/0.2.0.bin", + "sha256": "3f786850e387550fdab836ed7e6dc881de23001b" + "0" * 24, + "size": 1148320, + }, + commands=[ + Command( + id=12, + type="stream_start", + payload={"session_id": "s-88f1", "duration_s": 45, "mode": 0}, + expires_at=1758376400000, + ) + ], + ) + dumped = json.loads(e.model_dump_json(exclude_none=True)) + # Exactly the keys parseEnvelope reads, plus capture_id. + assert dumped["server_time"] == 1758376267000 + assert dumped["config_version"] == 7 + assert dumped["firmware"]["version"] == "0.2.0" + assert dumped["commands"][0]["id"] == 12 + assert dumped["commands"][0]["type"] == "stream_start" + + +def test_command_type_enum_matches_the_database_constraint(): + with pytest.raises(ValidationError): + Command(id=1, type="self_destruct") + + +def test_empty_command_list_is_the_default(): + assert Envelope(server_time=0, config_version=1).commands == [] + + +# --- contract drift --------------------------------------------------------- + + +def test_api_md_is_where_we_think_it_is(): + """If this moves, the comments above stop pointing anywhere.""" + api_md = Path(__file__).resolve().parents[2] / "firmware" / "API.md" + assert api_md.is_file(), f"contract not found at {api_md}" + text = api_md.read_text(encoding="utf-8") + # The two deviations from SPEC.md that these schemas encode. + assert "device_name" in text + assert "raw JPEG as the body" in text diff --git a/server/tests/test_seed.py b/server/tests/test_seed.py new file mode 100644 index 0000000..3b439e7 --- /dev/null +++ b/server/tests/test_seed.py @@ -0,0 +1,302 @@ +"""The gallery seed command (TODO 3.0). + +The scoping test here is the one that matters. ``poorbird seed --clear`` holds +a DELETE over the same tables a real camera writes to, so the property worth +pinning is not that it removes seeded rows -- it is that it removes *nothing +else*. + +Counts are deliberately tiny. Each frame is a real 1600x1200 JPEG encode plus +a thumbnail; the behaviour under test is the same at 8 as at 500, and the suite +should not spend half a minute proving it. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db +from sqlalchemy import func, select, text + +from poorbird.config import get_settings +from poorbird.models import Capture, Device +from poorbird.seed import BURST_MIN, SEED_UID_PREFIX, clear, generate, seed_device + +pytestmark = [pytest.mark.db, needs_db] + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture(autouse=True) +def no_seed_left_behind(db): + """Remove seeded rows however the test ends. + + ``clear()`` is the subject of some of these tests, so it cannot be relied + on as the teardown for all of them -- a broken clear() would then leave the + database dirty *and* hide that it was broken. + """ + yield + devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() + for device in devices: + db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device.id}) + db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device.id}) + db.commit() + + +@pytest.fixture +def real_device(db): + """A device that is NOT seeded, with a capture, to prove clear() misses it.""" + device = Device(device_uid=secrets.token_hex(6), name="real-camera", enabled=True) + db.add(device) + db.commit() + db.refresh(device) + + capture = Capture( + device_id=device.id, + path="2026/09/20/real.jpg", + sha256=secrets.token_hex(32), + bytes=1234, + trigger="radar", + ) + db.add(capture) + db.commit() + device_id = device.id + + yield device + + db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device_id}) + db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device_id}) + db.commit() + + +def _seeded_captures(db, device: Device) -> list[Capture]: + return list( + db.scalars( + select(Capture).where(Capture.device_id == device.id).order_by(Capture.frame_seq) + ).all() + ) + + +# --- generating -------------------------------------------------------------- + + +def test_it_makes_the_requested_number_of_captures(db): + made = generate(db, count=6, days=3, device_name="t-seed", thumbnails=False, progress=False) + assert made == 6 + + device = seed_device(db, "t-seed") + assert len(_seeded_captures(db, device)) == 6 + + +def test_the_count_is_exact_even_though_bursts_are_random_sized(db): + """Bursts are 3-5 frames, so a naive loop overshoots. 7 is not a multiple + of any burst size, which is the point of asking for it.""" + made = generate(db, count=7, days=2, device_name="t-seed", thumbnails=False, progress=False) + assert made == 7 + assert len(_seeded_captures(db, seed_device(db, "t-seed"))) == 7 + + +def test_the_frames_really_exist_on_disk(db): + """A gallery whose rows point at missing files tests nothing about the + delivery path, which is the half most likely to be wrong.""" + generate(db, count=4, days=1, device_name="t-seed", thumbnails=False, progress=False) + root = get_settings().image_root + + for capture in _seeded_captures(db, seed_device(db, "t-seed")): + path = root / capture.path + assert path.is_file(), f"missing {path}" + assert path.read_bytes().startswith(b"\xff\xd8\xff"), "not a JPEG" + assert capture.bytes == path.stat().st_size + + +def test_thumbnails_are_generated_when_asked(db): + generate(db, count=3, days=1, device_name="t-seed", thumbnails=True, progress=False) + thumb_root = get_settings().thumb_root + + for capture in _seeded_captures(db, seed_device(db, "t-seed")): + assert capture.thumb_path is not None + thumb = thumb_root / capture.thumb_path + assert thumb.is_file() + # WebP, per SPEC 3.3. RIFF magic rather than trusting the extension. + assert thumb.read_bytes()[:4] == b"RIFF" + + +def test_without_thumbnails_the_worker_still_has_something_to_do(db): + """--no-thumbnails is how the queue gets exercised at volume, so the rows + must be left in exactly the state /ingest leaves them.""" + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + assert captures + assert all(c.thumb_path is None for c in captures) + + +def test_frames_are_grouped_into_consistent_bursts(db): + generate(db, count=8, days=2, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + + by_burst: dict[str, list[Capture]] = {} + for capture in captures: + by_burst.setdefault(capture.burst_id, []).append(capture) + + assert len(by_burst) >= 2, "8 frames should not be one burst" + for frames in by_burst.values(): + indexes = sorted(f.burst_index for f in frames) + assert indexes == list(range(len(frames))), "burst_index must be dense from 0" + # burst_count is what the device claims it sent, so every frame in a + # burst has to agree on it. + assert len({f.burst_count for f in frames}) == 1 + + +def test_every_burst_has_pre_trigger_frames(db): + """SPEC 0: the first frames come out of the PSRAM ring and are usually the + good ones. A seed with none would hide whatever the UI does with them.""" + generate(db, count=8, days=2, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + + by_burst: dict[str, list[Capture]] = {} + for capture in captures: + by_burst.setdefault(capture.burst_id, []).append(capture) + + assert by_burst + for frames in by_burst.values(): + assert any(f.pre_trigger for f in frames) + # ...and not all of them, or the flag would carry no information. + # Stated with its precondition: a single-frame burst is necessarily + # all pre-trigger, so the generator is expected not to produce one. + assert len(frames) >= BURST_MIN, "a burst this short is not something a camera sends" + assert not all(f.pre_trigger for f in frames) + + +def test_frames_in_a_burst_arrive_close_enough_to_tie(db): + """The reason the gallery cursor carries the id as well as the timestamp. + + If the seed spread a burst over minutes, it would never reproduce the + received_at collision that real bursts cause, and the paging bug that + collision triggers would only ever appear against a real camera. + """ + generate(db, count=5, days=1, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + + by_burst: dict[str, list[Capture]] = {} + for capture in captures: + by_burst.setdefault(capture.burst_id, []).append(capture) + + burst = max(by_burst.values(), key=len) + span = max(f.received_at for f in burst) - min(f.received_at for f in burst) + assert span.total_seconds() < 5, "a burst should arrive within seconds, not minutes" + + +def test_the_seed_device_cannot_authenticate(db): + """It is a row for the gallery to point at, not a camera. Giving it a + working token would be creating a real way in for test data's sake.""" + device = seed_device(db, "t-seed") + assert device.token_hash is None + assert device.device_uid.startswith(SEED_UID_PREFIX) + + +def test_seeding_twice_reuses_the_same_device(db): + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + + devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() + assert len(devices) == 1 + assert len(_seeded_captures(db, devices[0])) == 6 + + +# --- clearing ---------------------------------------------------------------- + + +def test_clear_removes_seeded_captures_and_the_device(db): + generate(db, count=4, days=1, device_name="t-seed", thumbnails=True, progress=False) + + captures, devices = clear(db) + assert captures == 4 + assert devices == 1 + assert ( + db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() == [] + ) + + +def test_clear_leaves_a_real_camera_completely_alone(db, real_device): + """The property this command lives or dies by. + + It holds a DELETE over the same tables a real camera writes to. Scoping it + by device_uid prefix is what makes that safe, and a change that widened the + scope has to fail here rather than in someone's photo library. + """ + generate(db, count=4, days=1, device_name="t-seed", thumbnails=False, progress=False) + before = db.scalar( + select(func.count()).select_from(Capture).where(Capture.device_id == real_device.id) + ) + assert before == 1 + + clear(db) + + assert db.get(Device, real_device.id) is not None + assert ( + db.scalar( + select(func.count()).select_from(Capture).where(Capture.device_id == real_device.id) + ) + == 1 + ) + + +def test_clear_deletes_the_files_too(db): + """Otherwise the image root grows every time the seed is regenerated, and + nothing ever points at the leftovers.""" + generate(db, count=3, days=1, device_name="t-seed", thumbnails=True, progress=False) + settings = get_settings() + device = seed_device(db, "t-seed") + paths = [ + (settings.image_root / c.path, settings.thumb_root / c.thumb_path) + for c in _seeded_captures(db, device) + ] + assert all(image.is_file() and thumb.is_file() for image, thumb in paths) + + clear(db) + + for image, thumb in paths: + assert not image.exists(), f"left behind {image}" + assert not thumb.exists(), f"left behind {thumb}" + + +def test_clear_on_an_unseeded_database_is_not_an_error(db): + assert clear(db) == (0, 0) + + +def test_clear_removes_the_thumbnail_jobs_as_well(db): + """A job pointing at a capture that no longer exists is not a failure -- + the handler tolerates it -- but it is the worker waking up to do nothing + and logging about it, which looks like a fault later.""" + from poorbird.models import Job + from poorbird.worker.queue import enqueue + + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + device = seed_device(db, "t-seed") + captures = _seeded_captures(db, device) + for capture in captures: + enqueue(db, "thumbnail", {"capture_id": str(capture.id)}) + db.commit() + + ids = [str(c.id) for c in captures] + assert ( + db.scalar( + select(func.count()).select_from(Job).where(Job.payload["capture_id"].astext.in_(ids)) + ) + == 3 + ) + + clear(db) + + assert ( + db.scalar( + select(func.count()).select_from(Job).where(Job.payload["capture_id"].astext.in_(ids)) + ) + == 0 + ) diff --git a/server/tests/test_thumbnails.py b/server/tests/test_thumbnails.py new file mode 100644 index 0000000..40bcd68 --- /dev/null +++ b/server/tests/test_thumbnails.py @@ -0,0 +1,326 @@ +"""The thumbnail worker job. + +Unlike the ingest path, this really decodes the frame, so these tests use +real JPEGs rather than the hand-built headers in test_ingest.py. +""" + +from __future__ import annotations + +import io +import secrets +import uuid + +import pytest +from conftest import needs_db +from PIL import Image + +from poorbird.config import get_settings +from poorbird.images import ( + THUMB_EDGE, + UndecodableImage, + make_thumbnail, + relative_thumb_path, +) +from poorbird.models.captures import Capture +from poorbird.models.devices import Device +from poorbird.worker.handlers import HANDLERS + + +def real_jpeg(width: int = 1600, height: int = 1200) -> bytes: + """An actual decodable JPEG, not just a plausible header.""" + img = Image.new("RGB", (width, height)) + for x in range(0, width, 64): # some structure, so it is not a solid block + for y in range(0, height, 64): + img.putpixel((x, y), (x % 256, y % 256, 128)) + out = io.BytesIO() + img.save(out, format="JPEG", quality=85) + return out.getvalue() + + +# --- the encoder ------------------------------------------------------------ + + +def test_the_long_edge_is_capped_and_the_aspect_ratio_is_kept(tmp_path): + source = tmp_path / "wide.jpg" + source.write_bytes(real_jpeg(1600, 1200)) + + data, original = make_thumbnail(source) + + assert original == (1600, 1200) + with Image.open(io.BytesIO(data)) as thumb: + assert max(thumb.size) == THUMB_EDGE + assert thumb.size == (400, 300) # 4:3 preserved + + +def test_a_portrait_frame_is_capped_on_its_own_long_edge(tmp_path): + source = tmp_path / "tall.jpg" + source.write_bytes(real_jpeg(600, 1200)) + + data, _ = make_thumbnail(source) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.size == (200, 400) + + +def test_a_small_frame_is_never_upscaled(tmp_path): + """Blowing a 100px frame up to 400px produces a blurry lie.""" + source = tmp_path / "small.jpg" + source.write_bytes(real_jpeg(100, 80)) + + data, original = make_thumbnail(source) + + assert original == (100, 80) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.size == (100, 80) + + +def test_the_output_is_webp(tmp_path): + source = tmp_path / "x.jpg" + source.write_bytes(real_jpeg(800, 600)) + + data, _ = make_thumbnail(source) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.format == "WEBP" + + +def test_a_thumbnail_is_much_smaller_than_its_source(tmp_path): + source = tmp_path / "x.jpg" + source.write_bytes(real_jpeg(1600, 1200)) + + data, _ = make_thumbnail(source) + assert len(data) < source.stat().st_size + + +def test_rubbish_raises_undecodable_rather_than_something_generic(tmp_path): + """The distinction matters: undecodable is permanent, so the worker must + not spend three attempts rediscovering it.""" + source = tmp_path / "not-an-image.jpg" + source.write_bytes(b"\xff\xd8\xff" + b"garbage" * 100) + + with pytest.raises(UndecodableImage): + make_thumbnail(source) + + +def test_a_truncated_jpeg_is_also_undecodable(tmp_path): + source = tmp_path / "half.jpg" + source.write_bytes(real_jpeg(1600, 1200)[:200]) + + with pytest.raises(UndecodableImage): + make_thumbnail(source) + + +def test_the_thumb_name_carries_its_size(tmp_path): + """The size is in the filename, so changing it writes a new name rather + than silently serving a different image from the old one.""" + cid = uuid.uuid4() + assert relative_thumb_path(cid) == f"{cid}_400.webp" + + +# --- the handler ------------------------------------------------------------ + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def capture(db): + """A capture with its frame genuinely on disk, cleaned up either way.""" + settings = get_settings() + device = Device(device_uid=secrets.token_hex(6), name="cam") + db.add(device) + db.commit() + db.refresh(device) + + created: list[Capture] = [] + + def make(data: bytes | None = None, *, width=None, height=None): + cid = uuid.uuid4() + relative = f"2026/09/21/{cid}.jpg" + path = settings.image_root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(real_jpeg(1600, 1200) if data is None else data) + + cap = Capture( + id=cid, + device_id=device.id, + path=relative, + sha256="0" * 64, + bytes=path.stat().st_size, + trigger="radar", + width=width, + height=height, + ) + db.add(cap) + db.commit() + db.refresh(cap) + created.append(cap) + return cap + + yield make + + for cap in created: + (settings.image_root / cap.path).unlink(missing_ok=True) + if cap.thumb_path: + (settings.thumb_root / cap.thumb_path).unlink(missing_ok=True) + db.execute(Capture.__table__.delete().where(Capture.device_id == device.id)) + db.delete(db.get(Device, device.id)) + db.commit() + + +def run_job(db, capture_id) -> None: + HANDLERS["thumbnail"](db, {"capture_id": str(capture_id)}) + + +@needs_db +def test_the_handler_writes_a_thumbnail_and_records_it(db, capture): + cap = capture() + assert cap.thumb_path is None + + run_job(db, cap.id) + + db.refresh(cap) + assert cap.thumb_path == f"{cap.id}_400.webp" + + on_disk = get_settings().thumb_root / cap.thumb_path + assert on_disk.is_file() + with Image.open(on_disk) as thumb: + assert thumb.format == "WEBP" + assert max(thumb.size) == THUMB_EDGE + + +@needs_db +def test_it_fills_in_dimensions_ingest_could_not_read(db, capture): + """Ingest reads the JPEG header, which can be absent or unparseable. + This is the first full decode, so it is the chance to fix that.""" + cap = capture(width=None, height=None) + + run_job(db, cap.id) + + db.refresh(cap) + assert (cap.width, cap.height) == (1600, 1200) + + +@needs_db +def test_it_does_not_overwrite_dimensions_ingest_already_had(db, capture): + cap = capture(width=1600, height=1200) + + run_job(db, cap.id) + + db.refresh(cap) + assert (cap.width, cap.height) == (1600, 1200) + + +@needs_db +def test_running_it_twice_is_harmless(db, capture): + """Jobs get retried, and a partially written thumbnail must not survive.""" + cap = capture() + + run_job(db, cap.id) + first = (get_settings().thumb_root / cap.thumb_path).read_bytes() + run_job(db, cap.id) + second = (get_settings().thumb_root / cap.thumb_path).read_bytes() + + assert first == second + + +@needs_db +def test_no_part_file_is_left_behind(db, capture): + cap = capture() + run_job(db, cap.id) + + assert not list(get_settings().thumb_root.glob(".*.part")) + + +@needs_db +def test_an_undecodable_frame_is_recorded_not_retried(db, capture): + """Returning rather than raising is the point: the handler contract makes + a raise mean 'retry', and this will never decode.""" + cap = capture(data=b"\xff\xd8\xff" + b"garbage" * 100) + + run_job(db, cap.id) # must not raise + + db.refresh(cap) + assert cap.thumb_path is None + + +@needs_db +def test_a_missing_source_raises_so_the_job_retries(db, capture): + """The opposite case: the file should be there, and a mount that has not + come back yet is worth retrying for.""" + cap = capture() + (get_settings().image_root / cap.path).unlink() + + with pytest.raises(FileNotFoundError): + run_job(db, cap.id) + + +@needs_db +def test_a_capture_that_has_since_been_deleted_is_not_an_error(db): + """Retention will do this routinely once Phase 5 exists.""" + run_job(db, uuid.uuid4()) # must not raise + + +@needs_db +def test_a_malformed_payload_is_recorded_not_retried(db): + """SEC-003. Raising would spend three attempts rediscovering that the + payload is still malformed.""" + HANDLERS["thumbnail"](db, {}) + HANDLERS["thumbnail"](db, {"capture_id": "not-a-uuid"}) + HANDLERS["thumbnail"](db, {"wrong_key": 1}) + + +# --- wired to ingest -------------------------------------------------------- + + +@needs_db +def test_ingest_enqueues_the_job(client, db): + """Off the request path: decoding to resize is the one genuinely + expensive part of a capture, and the device is waiting with a burst + still to upload.""" + from sqlalchemy import text + + from poorbird.api.deps import hash_credential, new_credential + + token = new_credential() + device = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(device) + db.commit() + db.refresh(device) + + r = client.post( + "/api/v1/ingest", + content=real_jpeg(800, 600), + headers={"Content-Type": "image/jpeg", "Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 201 + capture_id = r.json()["capture_id"] + + queued = db.execute( + text( + "SELECT kind, status FROM jobs " + "WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid" + ), + {"cid": capture_id}, + ).first() + assert queued is not None, "ingest must queue the thumbnail" + assert queued.status == "queued" + + settings = get_settings() + cap = db.get(Capture, uuid.UUID(capture_id)) + (settings.image_root / cap.path).unlink(missing_ok=True) + db.execute( + text("DELETE FROM jobs WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid"), + {"cid": capture_id}, + ) + db.execute(Capture.__table__.delete().where(Capture.device_id == device.id)) + db.delete(db.get(Device, device.id)) + db.commit() diff --git a/web/.gitignore b/web/.gitignore new file mode 100644 index 0000000..4609e81 --- /dev/null +++ b/web/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +*.local +.vite/ diff --git a/web/README.md b/web/README.md new file mode 100644 index 0000000..0615a1e --- /dev/null +++ b/web/README.md @@ -0,0 +1,157 @@ +# poorBird web + +Phase 3: shell, themes, i18n, login and the gallery. Built on the dev machine +and shipped to the server as static files — nothing here runs on the server +(SPEC §6). + +```bash +cd web +npm install +npm run dev # http://localhost:5173 +``` + +The dev server proxies `/api` to `http://127.0.0.1:8090`, so start the API +too (see [`../server/README.md`](../server/README.md)). Both must be running +or the System page shows "cannot reach the server", which is the honest +answer rather than a blank screen. + +**Two things the server side needs before you can sign in:** + +```bash +cd ../server +# 1. Secure cookies are dropped over plain http, and this dev server is http. +# Without this, login returns 200 and you are never signed in. +echo 'POORBIRD_SESSION_COOKIE_SECURE=false' >> .env + +# 2. There is no sign-up page. Accounts are created on the server. +.venv/Scripts/poorbird user add me --role admin +``` + +`--role admin` enables TOTP and prints an `otpauth://` URI once — scan it +before pressing on, because the app will ask for a code and the URI is not +shown again. `--no-totp` skips it and says why that is a bad idea. + +| Script | Does | +|---|---| +| `npm run dev` | Vite dev server with HMR | +| `npm run build` | typecheck, then production bundle into `dist/` | +| `npm run typecheck` | `tsc --noEmit` on its own | +| `npm run check:contrast` | assert WCAG contrast for all three themes | + +> On Windows, Vite binds IPv6 `localhost`. Use `http://localhost:5173`, not +> `http://127.0.0.1:5173`. + +--- + +## What is real and what is not + +**Authentication is real and enforced.** `/auth/session`, `/auth/login` and +`/auth/logout` exist, so every route is now behind `RequireAuth`: + +- the gallery needs any signed-in user; **Devices and System need `admin`** + (SPEC §3.1), so a `viewer` account sees a "no access" message there +- TOTP is required whenever the account has a secret, which `user add --role + admin` sets up by default +- signing out is in the header, next to the theme and language switchers +- **there is still no development bypass**, and there never was one — a bypass + that works is the kind of code that survives into production + +The guard here decides what to *render*. It is not access control: the server +authorises every request on its own, and deleting `RequireAuth.tsx` would +expose no data, it would only render pages whose requests then 401. + +**The gallery is real.** It reads `GET /api/v1/captures`, pages by cursor, +and loads thumbnails through the auth-checked route — so an image is only +served to a request that carried a valid session. + +To have something to look at: + +```bash +cd ../server +.venv/Scripts/poorbird seed --captures 500 +.venv/Scripts/poorbird seed --clear # when you are done +``` + +`--clear` only ever removes seeded data. It is scoped to its own device, so a +real camera's captures are never in scope. + +**Devices still renders an honest empty state.** It needs a device listing +endpoint, which is Phase 4. It is deliberately not filled with mock rows — +fake data hides exactly the layout problems real data exposes. + +The grid is virtualised, which matters at the scale this reaches rather than +the scale it starts at: 5000 captures a day is past a million DOM nodes within +a year, and the browser gives up long before the database does. Only visible +rows exist, and the column count is computed from the measured container width +rather than from media queries. + +--- + +## Conventions + +**No user-facing string literal in a component. Ever.** Every one goes +through `useT()`. `src/i18n/en.ts` defines the key set; `de.ts` is typed as +`Catalogue`, so a missing or misspelled German key fails `npm run build` +rather than showing English to a German user at runtime. + +**No colour literal outside `src/styles/tokens.css`.** Components reference +tokens, which is what makes a fourth theme a single CSS block. Run +`npm run check:contrast` after touching any colour — it caught three failing +`--border-strong` values the first time it ran. + +**`lib/api.ts` is the only place that calls `fetch`,** and the only place that +knows about CSRF. It reads the `poorbird_csrf` cookie and echoes it in +`X-CSRF-Token` on every POST/PUT/PATCH/DELETE; the server compares it against +the token stored on the session row. A new mutating call needs nothing extra, +which is the point of there being one such place. + +**Themes** are `data-theme` on ``: `light`, `dark`, `blue` (dark navy). +An inline script in `index.html` applies the stored choice before first paint +to avoid a flash of the wrong theme; it must stay in sync with +`theme/ThemeProvider.tsx` — same storage key, same attribute, same default. +Once accounts exist, `users.theme` becomes the source of truth and +localStorage stays as the pre-login default. + +--- + +## Layout + +``` +src/ + main.tsx providers, in order + router.tsx the whole route table, one flat file + i18n/ en.ts (source of truth), de.ts (typed against it) + theme/ data-theme on + auth/ provider, login form, route guard + lib/api.ts the only place that calls fetch, and the only one + that knows about CSRF or builds image URLs + components/ layout, shared pieces, CaptureGrid, CaptureViewer, + GalleryFilters + pages/ one per route + styles/ tokens.css (themes), global.css (everything else) +scripts/check-contrast.mjs +``` + +--- + +## Notes on the stack + +**TypeScript is strict**, including `noUncheckedIndexedAccess` and +`verbatimModuleSyntax`. Learning TypeScript with the checks off teaches a +different language than the one everyone else writes. The error messages say +what to do. + +**i18n is hand-written, not `react-i18next`.** Two languages and a few hundred +strings do not need a library, and the typed catalogue gives compile-time +completeness that i18next does not provide by default. If real plural grammar +is ever needed, ICU MessageFormat is the upgrade and the call sites keep their +shape. + +**TanStack Router with code-based routes**, per SPEC §6, rather than the +file-based convention — one visible route table, no codegen step. Its payoff +is that `` is typechecked, so a typo in a path is a build +error instead of a 404 found later. + +**No ESLint yet.** `tsc --noEmit` catches the important class of mistakes; +ESLint is worth adding but its flat-config setup is a distraction during +scaffolding. diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..386eec5 --- /dev/null +++ b/web/index.html @@ -0,0 +1,34 @@ + + + + + + + poorBird + + + +
+ + + diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..1cb4cdd --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,2067 @@ +{ + "name": "poorbird-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "poorbird-web", + "version": "0.1.0", + "dependencies": { + "@tanstack/react-query": "^5.62.0", + "@tanstack/react-router": "^1.95.0", + "@tanstack/react-virtual": "^3.14.13", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.0", + "vite": "^6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", + "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.8", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.4.tgz", + "integrity": "sha512-I+BSHzTAhKN2n7ZwGZsegGcZjDpLqFOMAtJz/u6uFGe0pUFbq56dEHjqJV/ZUdRJtNXNxA+hREUatZBvMR3Oiw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.4.tgz", + "integrity": "sha512-pu3BdjS2LtEzRu2elmGzS3fIeWSZy4BMDIaLNwjorO76+k2d0LMluijhsDx3KQyQBQ/lLUZCQA9/s6csvUfuhw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.4.tgz", + "integrity": "sha512-xfSrj9MHnWK9GaSqT9U0ImHtH/N8WZlHLx4cZHiuLcqs640hvZ3hLPd5UR2AZS57FaE8HrRUSpltbZdWRxHiDA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.4.tgz", + "integrity": "sha512-bqU99PLJb/dqb3S0GIMdeuyAEETSUgZBoqXYd3Sd+WCsV+MmPhnN6JrotWyir31+QgH7EvvE5/mwGJlEoci8Fw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.4.tgz", + "integrity": "sha512-JinsFZ5G40oXQb+sUuiA5x689vhr6dDYK0H0NL+rwKdL6CqnmYN8PE4ZwfRSoIjrCxqTQG/SLfTtSvHeGxoVlw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.4.tgz", + "integrity": "sha512-GAdA4UxpiNm27cLHr2GqXBpAD0x9FqwYBY7/YSP0Ss0/PNi4k8gbviqpIpYbVSRBaS2ZcegXEzgTQMbRNCwxCw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.4.tgz", + "integrity": "sha512-qDd6NoA1znaLjp4jR5U/KWCdLAKDJNB8W9ChbbDaKbo0xA+Atln5HK6LFCZ4oJQpemtRZA288DCirFRjrspptw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.4.tgz", + "integrity": "sha512-WtB5Tz5KTNINb8ZA+8sQ7bmjuS1JrRT7YverYIhUGdWWDlpzVWmIwuZE+jidkEXUn1l0zrEkaIMa8dHF3NGcsA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.4.tgz", + "integrity": "sha512-VcQ3L1tjnkKzWjryAVaFhHEWcqOfICX9uxVVoDzm2t0DpgKRHd2zOpVrJc0xsWeBZcBFyYROCIBdyR/fS174pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.4.tgz", + "integrity": "sha512-6+ZQX6P5s0cMDN2Ypb8Lbm2+/sZYmZjdaYny992ujUU9UKi/4CWoJWsl1pNvjWJHNHGK51m+jKGLlh1ylb2ifQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.4.tgz", + "integrity": "sha512-D72ZnvkFkBXOfzMMQLcwfPLyGkKb7HZ9/mf97B7v6/P5Lbv4oFOtSY/uHbS8lH6uKUOxoKiuokdb50XZSzzbJw==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.4.tgz", + "integrity": "sha512-piU6BxeqA3O9KSu3kRCIQQtNqFFaTu21SEV4FwaRZowpnj3bLaWPZHw+xFqCs0XlJ+aOH3PTRWGoglH+mKA/OA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.4.tgz", + "integrity": "sha512-/5PGpHwqt2EEEOUs1XwzubE/ucr0dWDQ+to3zqi4Ds7EWpwtQ79wXc4JBoxqj/OwpawTsKWzJxHfSuBOq3DrWA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.4.tgz", + "integrity": "sha512-cX3beZDLWt7G2oJF+nhChiT+qtaihs+S2xi7ziGmVB+2pwPng6D0Ed0HmElQOgv2UsUmSJJLGwpBao/3TDx3VA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.4.tgz", + "integrity": "sha512-1uz2mGWHyptR7DgHHrlbdRAjXK7v7elGZ9lMja910/RP+ZYbX6xAmCiU9UZSX4hqmgtHMv6lr5l3kq1HIOpcag==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.4.tgz", + "integrity": "sha512-nLS8topojxyz7SRpKR2IODRpQ0XPZ+xaOXvT3+hqK/Uy8Lo5HFgkkIBiIrCu5tL5YqzTvgovGw55PwpahTAGig==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.4.tgz", + "integrity": "sha512-gs7DRKotr3l3q+jGPQBjH0ng1FjlEDm5ueQrkw5JtQvtLyEIcLASqAEaor56BhkKRzk+IcQzrcanBdb/bBQn8g==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.4.tgz", + "integrity": "sha512-791ET7W17NnScOZM7h4dX5hYspxE28htPFsb1awY/NRR8+PRNkS53e475rDdxXXDrP+kwnCcNWg9CX5ztn/Aqw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.4.tgz", + "integrity": "sha512-iwZQRcmj7g88g3tzefIrQY7qvmuA/cfYwhrDtTBhsmukO4U2huVO5W+86XacUMRvdSFVAc6kZUZy21JaRwiB9w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.4.tgz", + "integrity": "sha512-dVHFp9gRWrdTpnqQuGfCwd7hOQDatK1VCP2iWhLY/cGrOQs/ucFzJ6A5SRqbXX12ZDI8EUuejSM5kwg+ja7Png==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.4.tgz", + "integrity": "sha512-t3NlauOW6gxZVVFcBEnO62Cb4wbyDFL416gTg1uFI/2tgqYQlf69FbSE115Ajre9I+c26Lk4mcmdFUsS/DGifQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.4.tgz", + "integrity": "sha512-xWuIaSye5FWZF8+UYtVEcHtRJDN5kN9Kfgxx3Kq8XIov9KSKbc1fiqQCm90SKrgQbUXZelbnUhnlUJmfSE7P9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.4.tgz", + "integrity": "sha512-9ALJJUOg/ZflMJepVo2PlgsGxSaxN7SQ4Z8GoZfVlarWr6r3rkHUNsd/zAio7p4YMtChSMXPionxej4Hkf6CXQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.4.tgz", + "integrity": "sha512-blj9z5qx/Pv4WU0W1NMFDB97e0JH5ed+aZGywW8WCvp/NhWX/4PFAq5uu6Q0AebNn+Vo6KzUYDT++JzTT5ojlQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.4.tgz", + "integrity": "sha512-Erx822VRBwLa124shbj+wNXe//BOgMEctDV0m1aqTQdNO1S69DgNUCFKC1RCeZfixs1J31l6igk1ziyXErbigQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tanstack/history": { + "version": "1.162.4", + "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.4.tgz", + "integrity": "sha512-utTS5L2OkeYUzXGohL1Z8sefu1GLNOJcxe8Hd6iIdc/Xo1K1nDB2JEp4iSFhvYh33xKC9V91TxrS8qfrpoKobQ==", + "license": "MIT", + "engines": { + "node": ">=20.19" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/query-core": { + "version": "5.103.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.103.1.tgz", + "integrity": "sha512-rms8HqTGp6zA00dM+cUQ2eBcgzNJefuu5CAMB37i/6MiGT1zulPOytCFu2a0qjLqVR2n1jENPj9woqFQNuCzWA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.103.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.103.1.tgz", + "integrity": "sha512-rmAPPApNEK17VXRJhtE1rja53n23VV5w30C0saCgJhhX+EpdUnVqMGV/s5nnzV43X75KTHKzuoiuxSzGTBIkag==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.103.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^18 || ^19" + } + }, + "node_modules/@tanstack/react-router": { + "version": "1.170.38", + "resolved": "https://registry.npmjs.org/@tanstack/react-router/-/react-router-1.170.38.tgz", + "integrity": "sha512-iHM9b0aDJbuvftmkiQXawzoqsdV68p2Re2safbVLCnxafe+iLKV++2i3hI/BMAP6uR92/Mjw94JKJJfD7pbwHQ==", + "license": "MIT", + "dependencies": { + "@tanstack/history": "1.162.4", + "@tanstack/react-store": "^0.11.0", + "@tanstack/router-core": "1.171.32", + "isbot": "^5.1.22" + }, + "engines": { + "node": ">=20.19" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=18.0.0 || >=19.0.0", + "react-dom": ">=18.0.0 || >=19.0.0" + } + }, + "node_modules/@tanstack/react-store": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-store/-/react-store-0.11.1.tgz", + "integrity": "sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ==", + "license": "MIT", + "dependencies": { + "@tanstack/store": "0.11.1", + "use-sync-external-store": "^1.6.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/@tanstack/react-virtual": { + "version": "3.14.13", + "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.13.tgz", + "integrity": "sha512-JbDTAwtzZ99aOeCrAfW5EsE5KSq5RWh6Af2dtFwyLIIk48Ja7vm6n4axu/43T3vfjFnEGJalxJ1wyYjSQD6bSg==", + "license": "MIT", + "dependencies": { + "@tanstack/virtual-core": "3.17.11" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/@tanstack/router-core": { + "version": "1.171.32", + "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.171.32.tgz", + "integrity": "sha512-X86Jqk3vB2KJcUfS6oLi7B7yxbaa59QEhZRPPP1fRx3k+Jw/Fu1UYVBcRtdwK/OccQnrlQdVoKvNO3QXmyEBOw==", + "license": "MIT", + "dependencies": { + "@tanstack/history": "1.162.4", + "cookie-es": "^3.0.0", + "seroval": "^1.6.2", + "seroval-plugins": "^1.6.2" + }, + "engines": { + "node": ">=20.19" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/store": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.11.1.tgz", + "integrity": "sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/virtual-core": { + "version": "3.17.11", + "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.11.tgz", + "integrity": "sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.25", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz", + "integrity": "sha512-gMmEShwwq7FJqMwvfRwvCl00v4kN+KOfJqXn+f4nrufak5gNHJOksd/60Dvjuz7sI8Y5WiSFBa8FEYr+zoyqCw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz", + "integrity": "sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.23", + "caniuse-lite": "^1.0.30001810", + "electron-to-chromium": "^1.5.427", + "node-releases": "^2.0.55", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001810", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", + "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie-es": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz", + "integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==", + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.433", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.433.tgz", + "integrity": "sha512-5lCAbyZBjtmUt/RAGHRqrL2q0oEFRThDAsZHHDn9XHa89Qw7gMYOeSicBTy+AHfvo0r6vwsZvqNJTQIQy1BLzA==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/isbot": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/isbot/-/isbot-5.2.2.tgz", + "integrity": "sha512-iQcBXcd+Rv/pkubRyGh2utW2j1oPG5hZY6TUhVPpqK4G+o3IbxpJNx04hgksjc/N7GK5pEorUxDeg31cFgEk/w==", + "license": "Unlicense", + "engines": { + "node": ">=18" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.56", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.56.tgz", + "integrity": "sha512-x0InOIyzgdk+eyaWaRJFH5snEtiImgBgblZ2CyPrLmqqcuMQkEvcDPHbzqbD8eDsSeJbVOjn+crzyzHaM4D+/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", + "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.0" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.63.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.4.tgz", + "integrity": "sha512-4U0liVayNIoLp3GFl1FcI8561WepLnZ1rqfraGh7S9B3Ur5F9S283y8Futii7RUU2C/97tOBmBy7nYvhoiOpbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.63.4", + "@rollup/rollup-android-arm64": "4.63.4", + "@rollup/rollup-darwin-arm64": "4.63.4", + "@rollup/rollup-darwin-x64": "4.63.4", + "@rollup/rollup-freebsd-arm64": "4.63.4", + "@rollup/rollup-freebsd-x64": "4.63.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.63.4", + "@rollup/rollup-linux-arm-musleabihf": "4.63.4", + "@rollup/rollup-linux-arm64-gnu": "4.63.4", + "@rollup/rollup-linux-arm64-musl": "4.63.4", + "@rollup/rollup-linux-loong64-gnu": "4.63.4", + "@rollup/rollup-linux-loong64-musl": "4.63.4", + "@rollup/rollup-linux-ppc64-gnu": "4.63.4", + "@rollup/rollup-linux-ppc64-musl": "4.63.4", + "@rollup/rollup-linux-riscv64-gnu": "4.63.4", + "@rollup/rollup-linux-riscv64-musl": "4.63.4", + "@rollup/rollup-linux-s390x-gnu": "4.63.4", + "@rollup/rollup-linux-x64-gnu": "4.63.4", + "@rollup/rollup-linux-x64-musl": "4.63.4", + "@rollup/rollup-openbsd-x64": "4.63.4", + "@rollup/rollup-openharmony-arm64": "4.63.4", + "@rollup/rollup-win32-arm64-msvc": "4.63.4", + "@rollup/rollup-win32-ia32-msvc": "4.63.4", + "@rollup/rollup-win32-x64-gnu": "4.63.4", + "@rollup/rollup-win32-x64-msvc": "4.63.4", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/seroval": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.6.7.tgz", + "integrity": "sha512-AeDcLh0yO2SFm9W71essgnSzLV9DI8ZH0x0knXn2DMnUZj728mpLbxjlbB6IqKCmqh8JA3cEqRyGoNkt584JcQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/seroval-plugins": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.6.7.tgz", + "integrity": "sha512-4Nk35ttD3DTDJW4hgw5StsVAPeU6qnDFnULAouw6tQ7oLTV/ICXrWpsXo2EE52eSP2joUMazbVf52mFEcADqRw==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "seroval": "^1.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", + "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..a9d6bf6 --- /dev/null +++ b/web/package.json @@ -0,0 +1,27 @@ +{ + "name": "poorbird-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "preview": "vite preview", + "check:contrast": "node scripts/check-contrast.mjs" + }, + "dependencies": { + "@tanstack/react-query": "^5.62.0", + "@tanstack/react-router": "^1.95.0", + "@tanstack/react-virtual": "^3.14.13", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.0", + "vite": "^6.0.0" + } +} diff --git a/web/scripts/check-contrast.mjs b/web/scripts/check-contrast.mjs new file mode 100644 index 0000000..fd2cd81 --- /dev/null +++ b/web/scripts/check-contrast.mjs @@ -0,0 +1,126 @@ +/* Assert WCAG contrast for every theme in tokens.css. + * + * Colour contrast is the classic silently-regressing property: you nudge one + * hex value, it still "looks fine" on your monitor, and the muted text is now + * unreadable for someone else. So it gets a test rather than a promise. + * + * No dependencies -- run with `npm run check:contrast`. + */ + +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +const here = dirname(fileURLToPath(import.meta.url)); +const css = readFileSync(join(here, "..", "src", "styles", "tokens.css"), "utf8"); + +/** Extract custom properties per theme from the stylesheet. */ +function parseThemes(source) { + const themes = {}; + const blockRe = /([^{}]+)\{([^}]*)\}/g; + let match; + while ((match = blockRe.exec(source)) !== null) { + const selectors = match[1] + .replace(/\/\*[\s\S]*?\*\//g, "") + .split(",") + .map((s) => s.trim()); + const body = match[2]; + + const props = {}; + const propRe = /(--[\w-]+)\s*:\s*([^;]+);/g; + let prop; + while ((prop = propRe.exec(body)) !== null) { + props[prop[1]] = prop[2].trim(); + } + + for (const selector of selectors) { + const named = selector.match(/\[data-theme="([\w-]+)"\]/); + if (named) { + themes[named[1]] = { ...(themes[named[1]] ?? {}), ...props }; + } + } + } + return themes; +} + +function toLinear(channel) { + const c = channel / 255; + return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); +} + +function luminance(hex) { + const clean = hex.replace("#", "").trim(); + if (!/^[0-9a-fA-F]{6}$/.test(clean)) return null; + const r = parseInt(clean.slice(0, 2), 16); + const g = parseInt(clean.slice(2, 4), 16); + const b = parseInt(clean.slice(4, 6), 16); + return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b); +} + +function contrast(fg, bg) { + const a = luminance(fg); + const b = luminance(bg); + if (a === null || b === null) return null; + const [hi, lo] = a > b ? [a, b] : [b, a]; + return (hi + 0.05) / (lo + 0.05); +} + +/* Each pair: [foreground token, background token, minimum ratio]. + * 4.5 is WCAG AA for body text; 3.0 is AA for large text and for the + * boundaries of interactive components. */ +const PAIRS = [ + ["--text", "--bg", 4.5], + ["--text", "--surface", 4.5], + ["--text", "--surface-raised", 4.5], + ["--text-muted", "--bg", 4.5], + ["--text-muted", "--surface", 4.5], + ["--accent", "--bg", 4.5], + ["--accent", "--surface", 4.5], + ["--text-inverse", "--accent", 4.5], + ["--success", "--surface", 4.5], + ["--warning", "--surface", 4.5], + ["--danger", "--surface", 4.5], + ["--border-strong", "--surface", 3.0], +]; + +const themes = parseThemes(css); +const names = Object.keys(themes); + +if (names.length === 0) { + console.error("no themes found in tokens.css - has the file moved?"); + process.exit(1); +} + +let failures = 0; +let checked = 0; + +for (const name of names) { + const tokens = themes[name]; + console.log(`\n ${name}`); + for (const [fgToken, bgToken, min] of PAIRS) { + const fg = tokens[fgToken]; + const bg = tokens[bgToken]; + if (!fg || !bg) { + console.log(` ? ${fgToken} on ${bgToken} - token missing`); + failures++; + continue; + } + const ratio = contrast(fg, bg); + if (ratio === null) { + console.log(` ? ${fgToken} on ${bgToken} - not a plain hex colour`); + continue; + } + checked++; + const ok = ratio >= min; + if (!ok) failures++; + const mark = ok ? "ok " : "FAIL"; + console.log( + ` ${mark} ${fgToken} on ${bgToken} ${ratio.toFixed(2)}:1 (need ${min})` + ); + } +} + +console.log( + `\n${checked} pairs checked across ${names.length} themes, ${failures} failure(s)\n` +); +process.exit(failures > 0 ? 1 : 0); diff --git a/web/src/auth/AuthProvider.tsx b/web/src/auth/AuthProvider.tsx new file mode 100644 index 0000000..1506d72 --- /dev/null +++ b/web/src/auth/AuthProvider.tsx @@ -0,0 +1,122 @@ +/* The authentication shell. + * + * IMPORTANT, and deliberate: none of the endpoints this talks to exist yet. + * Phase 3 builds /auth/session, /auth/login and /auth/logout on the server. + * Until then `useAuth()` reports "anonymous" and is written but + * NOT wired into the router -- see router.tsx. + * + * There is no development bypass here on purpose. A bypass is the kind of + * code that survives into production because it works, and an auth bypass + * that works is the worst possible bug. The app is simply ungated until the + * real thing lands, which is visible and hard to forget. + * + * TOTP is part of the shape from the start (TODO 3.0): optional per user, + * enforced for admins. Retrofitting it later would mean reopening the login + * flow, the session model, the user model and the audit log at once. + */ + +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { createContext, useCallback, useContext, useMemo } from "react"; +import type { ReactNode } from "react"; + +import { ApiError, apiGet, apiPost } from "../lib/api"; + +export type Role = "admin" | "editor" | "viewer"; + +export interface User { + id: number; + username: string; + role: Role; + locale: string; + theme: string; +} + +export interface Credentials { + username: string; + password: string; + /** Six digits, when the account has TOTP enabled. */ + totp?: string; +} + +export type AuthState = + | { status: "loading" } + /** The server has no auth endpoints yet. Distinct from "signed out". */ + | { status: "unavailable" } + | { status: "anonymous" } + | { status: "authenticated"; user: User }; + +interface AuthValue { + state: AuthState; + signIn: (credentials: Credentials) => Promise; + signOut: () => Promise; + /** Convenience for `state.status === "authenticated" && role check`. */ + can: (...roles: Role[]) => boolean; +} + +const AuthContext = createContext(null); + +function useSessionQuery() { + return useQuery({ + queryKey: ["auth", "session"], + queryFn: async () => { + try { + return await apiGet("/auth/session"); + } catch (error) { + // 401 is the normal "not signed in" answer, not a failure. + if (error instanceof ApiError && error.status === 401) return null; + throw error; + } + }, + retry: false, + staleTime: 60_000, + }); +} + +export function AuthProvider({ children }: { children: ReactNode }) { + const queryClient = useQueryClient(); + const query = useSessionQuery(); + + const state = useMemo(() => { + if (query.isPending) return { status: "loading" }; + if (query.error?.isMissingEndpoint) return { status: "unavailable" }; + if (query.data) return { status: "authenticated", user: query.data }; + return { status: "anonymous" }; + }, [query.isPending, query.error, query.data]); + + const signIn = useCallback( + async (credentials: Credentials) => { + const user = await apiPost("/auth/login", credentials); + queryClient.setQueryData(["auth", "session"], user); + }, + [queryClient] + ); + + const signOut = useCallback(async () => { + await apiPost("/auth/logout"); + queryClient.setQueryData(["auth", "session"], null); + // Anything cached under the old identity must not be shown to the next one. + await queryClient.invalidateQueries(); + }, [queryClient]); + + const can = useCallback( + (...roles: Role[]) => state.status === "authenticated" && roles.includes(state.user.role), + [state] + ); + + const value = useMemo(() => ({ state, signIn, signOut, can }), [ + state, + signIn, + signOut, + can, + ]); + + return {children}; +} + +export function useAuth(): AuthValue { + const value = useContext(AuthContext); + if (value === null) { + throw new Error("useAuth must be used inside "); + } + return value; +} diff --git a/web/src/auth/LoginPage.tsx b/web/src/auth/LoginPage.tsx new file mode 100644 index 0000000..fe01deb --- /dev/null +++ b/web/src/auth/LoginPage.tsx @@ -0,0 +1,93 @@ +import { useState } from "react"; +import type { FormEvent } from "react"; + +import { useT } from "../i18n/I18nProvider"; +import { ApiError } from "../lib/api"; +import { useAuth } from "./AuthProvider"; + +/* The sign-in form. Fully built, and currently talking to an endpoint that + * does not exist -- a 404 is reported honestly rather than dressed up as + * "wrong password". The TOTP field is present from the start because the + * policy is decided (TODO 3.0). */ +export function LoginPage() { + const t = useT(); + const { signIn } = useAuth(); + + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [totp, setTotp] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function onSubmit(event: FormEvent) { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await signIn({ username, password, totp: totp || undefined }); + } catch (cause) { + if (cause instanceof ApiError && cause.isMissingEndpoint) { + setError(t("auth.unavailable")); + } else { + setError(t("auth.failed")); + } + } finally { + setBusy(false); + } + } + + return ( +
+
+

{t("auth.signIn")}

+ + + + + + + + {error !== null && ( +

+ {error} +

+ )} + + +
+
+ ); +} diff --git a/web/src/auth/RequireAuth.tsx b/web/src/auth/RequireAuth.tsx new file mode 100644 index 0000000..cca8578 --- /dev/null +++ b/web/src/auth/RequireAuth.tsx @@ -0,0 +1,59 @@ +import type { ReactNode } from "react"; + +import { useT } from "../i18n/I18nProvider"; +import { LoginPage } from "./LoginPage"; +import { useAuth } from "./AuthProvider"; +import type { Role } from "./AuthProvider"; + +/* Route guard, now wired into router.tsx. + * + * This is the client-side half only. It decides what to *render*; it is not + * access control. The server authorises every request independently, and the + * image bytes go through the auth-checked handoff (SPEC 3.3), because an + * unguessable URL is not access control either. Deleting this file would + * expose no data -- it would only make the app render pages whose requests + * then 401. */ +export function RequireAuth({ + children, + roles, +}: { + children: ReactNode; + /** When given, the signed-in user must hold one of these roles. */ + roles?: Role[]; +}) { + const t = useT(); + const { state, can } = useAuth(); + + if (state.status === "loading") { + return

{t("common.loading")}

; + } + + if (state.status === "anonymous") { + return ; + } + + // Now that /auth/* exists this should not happen. When it does, it means a + // newer UI is being served by an older server, so showing the login form + // would be offering a form that 404s. Say what is actually wrong instead. + if (state.status === "unavailable") { + return ( +
+

+ {t("auth.unavailable")} +

+
+ ); + } + + if (roles !== undefined && !can(...roles)) { + return ( +
+

+ {t("auth.forbidden")} +

+
+ ); + } + + return <>{children}; +} diff --git a/web/src/components/AppLayout.tsx b/web/src/components/AppLayout.tsx new file mode 100644 index 0000000..407dfed --- /dev/null +++ b/web/src/components/AppLayout.tsx @@ -0,0 +1,71 @@ +import { Link, Outlet } from "@tanstack/react-router"; + +import { useAuth } from "../auth/AuthProvider"; +import { useT } from "../i18n/I18nProvider"; +import { LanguageSwitcher } from "./LanguageSwitcher"; +import { ThemeSwitcher } from "./ThemeSwitcher"; + +export function AppLayout() { + const t = useT(); + const { state, signOut } = useAuth(); + + // Signing out clears the cookies server-side and the cached session here. + // A failure is not worth interrupting anyone for: the button is pressed + // again, or the session expires on its own. + function onSignOut() { + void signOut(); + } + + return ( +
+
+ +
+ +
+ +
+
+ ); +} diff --git a/web/src/components/CaptureGrid.tsx b/web/src/components/CaptureGrid.tsx new file mode 100644 index 0000000..9cd7b3d --- /dev/null +++ b/web/src/components/CaptureGrid.tsx @@ -0,0 +1,182 @@ +/* The virtualised capture grid. + * + * Virtualised because the gallery is the one screen that grows without bound: + * 5000 captures a day means a year is well past a million DOM nodes, and the + * browser gives up long before the data does. Only the visible rows exist. + * + * react-virtual virtualises a list, not a grid, so the grid is a list of rows + * and the column count is computed from the measured width. That keeps the + * layout responsive without a media-query ladder, and it is why the container + * width is observed rather than assumed. + */ + +import { useVirtualizer } from "@tanstack/react-virtual"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; + +import { useT } from "../i18n/I18nProvider"; +import type { CaptureSummary } from "../lib/api"; +import { thumbUrl } from "../lib/api"; + +/** Smallest tile that still shows a recognisable bird. */ +const MIN_TILE_PX = 200; +const GAP_PX = 12; + +/* Thumbnails are 400px on the long edge (SPEC 3.3) and the camera shoots 4:3, + * so a 4:3 tile shows the whole frame without cropping. Guessing wrong here + * only costs a reflow, because the row height is derived from it rather than + * measured per image. */ +const TILE_ASPECT = 3 / 4; + +/** Start the next page this many rows before the end. */ +const PREFETCH_ROWS = 3; + +function useColumnCount(ref: React.RefObject): number { + const [columns, setColumns] = useState(1); + + useLayoutEffect(() => { + const element = ref.current; + if (element === null) return; + + const measure = () => { + const width = element.clientWidth; + if (width === 0) return; + setColumns(Math.max(1, Math.floor((width + GAP_PX) / (MIN_TILE_PX + GAP_PX)))); + }; + + measure(); + // ResizeObserver rather than a window resize listener: the sidebar and + // the filter panel change this element's width without the window + // changing size at all. + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, [ref]); + + return columns; +} + +function Tile({ + capture, + onOpen, +}: { + capture: CaptureSummary; + onOpen: (capture: CaptureSummary) => void; +}) { + const t = useT(); + + return ( + + ); +} + +export function CaptureGrid({ + captures, + hasMore, + isLoadingMore, + onLoadMore, + onOpen, +}: { + captures: CaptureSummary[]; + hasMore: boolean; + isLoadingMore: boolean; + onLoadMore: () => void; + onOpen: (capture: CaptureSummary) => void; +}) { + const t = useT(); + const scrollRef = useRef(null); + const columns = useColumnCount(scrollRef); + const rowCount = Math.ceil(captures.length / columns); + + const virtualizer = useVirtualizer({ + count: rowCount, + getScrollElement: () => scrollRef.current, + // Width per tile is (container - gaps) / columns; height follows the + // aspect ratio. Close enough that rows do not need measuring. + estimateSize: useCallback(() => { + const width = scrollRef.current?.clientWidth ?? MIN_TILE_PX * columns; + const tileWidth = (width - GAP_PX * (columns - 1)) / columns; + return tileWidth / TILE_ASPECT + GAP_PX; + }, [columns]), + overscan: 2, + }); + + // Re-measure when the column count changes, or every row keeps the height + // it had at the old width and the grid overlaps itself. + useEffect(() => { + virtualizer.measure(); + }, [columns, virtualizer]); + + const virtualRows = virtualizer.getVirtualItems(); + const lastVisibleRow = virtualRows.at(-1)?.index ?? 0; + + useEffect(() => { + if (hasMore && !isLoadingMore && lastVisibleRow >= rowCount - PREFETCH_ROWS) { + onLoadMore(); + } + }, [hasMore, isLoadingMore, lastVisibleRow, rowCount, onLoadMore]); + + return ( +
+
+ {virtualRows.map((row) => { + const start = row.index * columns; + return ( +
+ {captures.slice(start, start + columns).map((capture) => ( + + ))} +
+ ); + })} +
+ +

+ {isLoadingMore ? t("gallery.loadingMore") : hasMore ? "" : t("gallery.allLoaded")} +

+
+ ); +} diff --git a/web/src/components/CaptureViewer.tsx b/web/src/components/CaptureViewer.tsx new file mode 100644 index 0000000..ef8c366 --- /dev/null +++ b/web/src/components/CaptureViewer.tsx @@ -0,0 +1,208 @@ +/* Full-screen view of one capture. + * + * Keyboard-driven on purpose. Labelling a day of captures is a loop of + * look-decide-next, hundreds of times, and that loop is only bearable from + * the keyboard -- arrows to move, Escape to leave. The mouse is the fallback, + * not the design. + */ + +import { useQuery } from "@tanstack/react-query"; +import { useEffect } from "react"; + +import { useT } from "../i18n/I18nProvider"; +import type { Translate } from "../i18n/I18nProvider"; +import type { CaptureSummary } from "../lib/api"; +import { getCapture, imageUrl } from "../lib/api"; + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +function triggerLabel(t: Translate, trigger: CaptureSummary["trigger"]): string { + switch (trigger) { + case "radar": + return t("capture.trigger.radar"); + case "manual": + return t("capture.trigger.manual"); + case "timer": + return t("capture.trigger.timer"); + case "stream_grab": + return t("capture.trigger.stream_grab"); + } +} + +function Row({ label, value }: { label: string; value: string }) { + return ( +
+ {label} + {value} +
+ ); +} + +export function CaptureViewer({ + capture, + onClose, + onPrevious, + onNext, +}: { + capture: CaptureSummary; + onClose: () => void; + onPrevious: (() => void) | null; + onNext: (() => void) | null; +}) { + const t = useT(); + + // The summary is already in hand from the grid, so the detail query only + // adds the extra fields. Showing the image immediately and filling the + // metadata a moment later beats a spinner over the whole overlay. + const detail = useQuery({ + queryKey: ["capture", capture.id], + queryFn: () => getCapture(capture.id), + staleTime: 60_000, + }); + + useEffect(() => { + function onKey(event: KeyboardEvent) { + if (event.key === "Escape") onClose(); + if (event.key === "ArrowLeft" && onPrevious !== null) onPrevious(); + if (event.key === "ArrowRight" && onNext !== null) onNext(); + } + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onClose, onPrevious, onNext]); + + const full = detail.data; + + return ( + // eslint-disable-next-line -- the overlay is a dialog; the backdrop click + // is a convenience and every action it offers is also a real button. +
+
+
+ {new Date(capture.received_at).toLocaleString()} +
+ + + +
+
+ +
+
+ +
+ + +
+
+
+ ); +} diff --git a/web/src/components/EmptyState.tsx b/web/src/components/EmptyState.tsx new file mode 100644 index 0000000..bdaa300 --- /dev/null +++ b/web/src/components/EmptyState.tsx @@ -0,0 +1,21 @@ +import type { ReactNode } from "react"; + +/** An empty list that explains itself. Used wherever a feature is real but + * has no data yet, which during Phase 3 is most of them. */ +export function EmptyState({ + title, + body, + action, +}: { + title: string; + body: string; + action?: ReactNode; +}) { + return ( +
+

{title}

+

{body}

+ {action} +
+ ); +} diff --git a/web/src/components/GalleryFilters.tsx b/web/src/components/GalleryFilters.tsx new file mode 100644 index 0000000..7644dca --- /dev/null +++ b/web/src/components/GalleryFilters.tsx @@ -0,0 +1,168 @@ +/* Gallery filters. + * + * Only the filters the server can actually answer. Taxon and tag filters are + * in TODO Phase 3 and deliberately absent until there is a seeded taxa table + * and an observation editor to fill them -- offering a control that can only + * ever return nothing is worse than not offering it. + * + * The triage filters are tri-state (any / yes / no) rather than checkboxes, + * because "kept" has three meanings here: show everything, show only kept, + * show only rejected. A checkbox can express two of those. + */ + +import { useT } from "../i18n/I18nProvider"; +import type { CaptureFilters } from "../lib/api"; + +export type { CaptureFilters }; + +/** A { + const raw = event.target.value; + onChange(raw === "" ? undefined : raw === "true"); + }} + > + + + + + + ); +} + +/** A date input carries a local calendar day; the API wants an instant. */ +function dayStart(value: string): string | undefined { + if (value === "") return undefined; + return new Date(`${value}T00:00:00`).toISOString(); +} + +function dayEnd(value: string): string | undefined { + if (value === "") return undefined; + // Inclusive: picking the same day for both ends should return that day, + // which an exclusive midnight boundary would make an empty range. + return new Date(`${value}T23:59:59.999`).toISOString(); +} + +/** Back to what a date input can display, in local time. */ +function toDateInput(iso: string | undefined): string { + if (iso === undefined) return ""; + const date = new Date(iso); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + return `${date.getFullYear()}-${month}-${day}`; +} + +export function GalleryFilters({ + filters, + onChange, + devices, +}: { + filters: CaptureFilters; + onChange: (next: CaptureFilters) => void; + devices: { id: number; name: string }[]; +}) { + const t = useT(); + const active = Object.values(filters).some((value) => value !== undefined); + + return ( +
+ + + + + + + onChange({ ...filters, kept })} + yesLabel={t("filters.onlyKept")} + noLabel={t("filters.onlyRejected")} + /> + + onChange({ ...filters, reviewed })} + yesLabel={t("filters.onlyReviewed")} + noLabel={t("filters.onlyUnreviewed")} + /> + + + + +
+ ); +} diff --git a/web/src/components/LanguageSwitcher.tsx b/web/src/components/LanguageSwitcher.tsx new file mode 100644 index 0000000..586baa7 --- /dev/null +++ b/web/src/components/LanguageSwitcher.tsx @@ -0,0 +1,28 @@ +import { LOCALES, useI18n } from "../i18n/I18nProvider"; +import type { Locale } from "../i18n/I18nProvider"; + +const LABEL: Record = { + de: "lang.de", + en: "lang.en", +}; + +export function LanguageSwitcher() { + const { locale, setLocale, t } = useI18n(); + + return ( + + ); +} diff --git a/web/src/components/ThemeSwitcher.tsx b/web/src/components/ThemeSwitcher.tsx new file mode 100644 index 0000000..aaea568 --- /dev/null +++ b/web/src/components/ThemeSwitcher.tsx @@ -0,0 +1,31 @@ +import { useT } from "../i18n/I18nProvider"; +import { THEMES, useTheme } from "../theme/ThemeProvider"; +import type { Theme } from "../theme/ThemeProvider"; + +const LABEL: Record = { + light: "theme.light", + dark: "theme.dark", + blue: "theme.blue", +}; + +export function ThemeSwitcher() { + const t = useT(); + const { theme, setTheme } = useTheme(); + + return ( + + ); +} diff --git a/web/src/i18n/I18nProvider.tsx b/web/src/i18n/I18nProvider.tsx new file mode 100644 index 0000000..fd3d58b --- /dev/null +++ b/web/src/i18n/I18nProvider.tsx @@ -0,0 +1,96 @@ +/* A small typed translator instead of a library. + * + * Two languages and a few hundred strings do not need i18next, and the + * hand-written catalogue buys something i18next does not give by default: + * a missing German string fails the build rather than falling back silently + * to English in front of the user. + * + * If this ever needs plurals with real grammar, ICU MessageFormat or + * react-i18next is the upgrade path and the call sites do not change shape. + */ + +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; +import type { ReactNode } from "react"; + +import { de } from "./de"; +import { en } from "./en"; +import type { Catalogue, TranslationKey } from "./en"; + +export const LOCALES = ["de", "en"] as const; +export type Locale = (typeof LOCALES)[number]; + +const CATALOGUES: Record = { de, en }; +const STORAGE_KEY = "poorbird.locale"; + +/** Values substituted into `{placeholders}`. */ +export type TranslationVars = Record; + +export type Translate = (key: TranslationKey, vars?: TranslationVars) => string; + +interface I18nValue { + locale: Locale; + setLocale: (locale: Locale) => void; + t: Translate; +} + +const I18nContext = createContext(null); + +function isLocale(value: unknown): value is Locale { + return typeof value === "string" && (LOCALES as readonly string[]).includes(value); +} + +function initialLocale(): Locale { + try { + const stored = localStorage.getItem(STORAGE_KEY); + if (isLocale(stored)) return stored; + } catch { + // Private mode or blocked storage. Fall through to the browser setting. + } + return navigator.language.toLowerCase().startsWith("de") ? "de" : "en"; +} + +function interpolate(template: string, vars?: TranslationVars): string { + if (!vars) return template; + return template.replace(/\{(\w+)\}/g, (whole, name: string) => { + const value = vars[name]; + // Leaving the placeholder visible beats printing "undefined" at a user. + return value === undefined ? whole : String(value); + }); +} + +export function I18nProvider({ children }: { children: ReactNode }) { + const [locale, setLocaleState] = useState(initialLocale); + + useEffect(() => { + document.documentElement.lang = locale; + try { + localStorage.setItem(STORAGE_KEY, locale); + } catch { + // Not worth telling the user about; the choice just will not persist. + } + }, [locale]); + + const setLocale = useCallback((next: Locale) => setLocaleState(next), []); + + const t = useCallback( + (key, vars) => interpolate(CATALOGUES[locale][key], vars), + [locale] + ); + + const value = useMemo(() => ({ locale, setLocale, t }), [locale, setLocale, t]); + + return {children}; +} + +export function useI18n(): I18nValue { + const value = useContext(I18nContext); + if (value === null) { + throw new Error("useI18n must be used inside "); + } + return value; +} + +/** Shorthand for the common case: `const t = useT()`. */ +export function useT(): Translate { + return useI18n().t; +} diff --git a/web/src/i18n/de.ts b/web/src/i18n/de.ts new file mode 100644 index 0000000..5dc7c9c --- /dev/null +++ b/web/src/i18n/de.ts @@ -0,0 +1,128 @@ +import type { Catalogue } from "./en"; + +/* Typed as Catalogue, so a missing or misspelled key fails `npm run build`. + * That is the whole reason this file is hand-written rather than loaded as + * JSON at runtime: a missing German string should never reach a browser. */ +export const de: Catalogue = { + "app.name": "poorBird", + "app.tagline": "Gartenvogel-Kamera", + + "nav.gallery": "Galerie", + "nav.devices": "Geräte", + "nav.system": "System", + + "common.loading": "Wird geladen…", + "common.retry": "Erneut versuchen", + "common.error": "Etwas ist schiefgelaufen", + "common.notMeasured": "—", + "common.yes": "Ja", + "common.no": "Nein", + + "theme.label": "Design", + "theme.light": "Hell", + "theme.dark": "Dunkel", + "theme.blue": "Blau", + + "lang.label": "Sprache", + "lang.en": "Englisch", + "lang.de": "Deutsch", + + "auth.signIn": "Anmelden", + "auth.signOut": "Abmelden", + "auth.signedInAs": "Angemeldet als {username}", + "auth.username": "Benutzername", + "auth.password": "Passwort", + "auth.totp": "Bestätigungscode", + "auth.totpHint": "Sechs Ziffern aus deiner Authenticator-App", + "auth.signingIn": "Anmeldung läuft…", + "auth.failed": "Anmeldung fehlgeschlagen. Benutzername, Passwort und Code prüfen.", + "auth.forbidden": "Dein Konto hat keinen Zugriff auf diese Seite.", + "auth.unavailable": + "Dieser Server hat keinen Anmelde-Endpunkt. UI- und Server-Version passen nicht zusammen.", + + "gallery.title": "Galerie", + "gallery.empty.title": "Noch keine Aufnahmen", + "gallery.empty.body": + "Die Kamera hat noch nichts hochgeladen. Zum Ausprobieren welche erzeugen: poorbird seed --captures 500", + "gallery.empty.filtered.title": "Keine Treffer für diese Filter", + "gallery.empty.filtered.body": "Zeitraum erweitern oder Filter zurücksetzen.", + "gallery.count": "{shown} von {total} geladen", + "gallery.loadingMore": "Lädt weitere…", + "gallery.allLoaded": "Das sind alle.", + "gallery.noThumb": "Keine Vorschau", + "gallery.thumbPending": "Vorschau noch nicht fertig", + + "filters.title": "Filter", + "filters.clear": "Filter zurücksetzen", + "filters.device": "Kamera", + "filters.device.all": "Alle Kameras", + "filters.from": "Von", + "filters.to": "Bis", + "filters.kept": "Behalten", + "filters.reviewed": "Durchgesehen", + "filters.preTrigger": "Nur Pre-Trigger", + "filters.any": "Alle", + "filters.onlyKept": "Nur behaltene", + "filters.onlyRejected": "Nur verworfene", + "filters.onlyReviewed": "Nur durchgesehene", + "filters.onlyUnreviewed": "Nur nicht durchgesehene", + + "capture.title": "Aufnahme", + "capture.close": "Schließen", + "capture.previous": "Zurück", + "capture.next": "Weiter", + "capture.openFull": "In Originalgröße öffnen", + "capture.receivedAt": "Empfangen", + "capture.capturedAt": "Kamerauhr", + "capture.capturedAt.unsynced": "Nicht synchronisiert", + "capture.device": "Kamera", + "capture.dimensions": "Größe", + "capture.fileSize": "Datei", + "capture.trigger": "Auslöser", + "capture.trigger.radar": "Radar", + "capture.trigger.manual": "Manuell", + "capture.trigger.timer": "Timer", + "capture.trigger.stream_grab": "Stream-Bild", + "capture.preTrigger": "Pre-Trigger-Bild", + "capture.preTrigger.hint": + "Vor dem Auslösen aufgenommen, aus dem Ringpuffer der Kamera", + "capture.burst": "Bild {index} von {count}", + "capture.radarDistance": "Radar-Entfernung", + "capture.radarEnergy": "Radar-Energie", + "capture.rssi": "WLAN-Signal", + "capture.temperature": "Temperatur", + "capture.reviewed": "Durchgesehen", + "capture.kept": "Behalten", + "capture.observations": "Beobachtungen", + "capture.observations.none": "Noch nicht bestimmt", + "capture.observations.model": "Modell-Vorhersage", + "capture.tags": "Schlagwörter", + + "devices.title": "Geräte", + "devices.empty.title": "Keine Geräte registriert", + "devices.empty.body": + "Eine Kamera erscheint hier, sobald sie sich registriert hat. Das kommt in Phase 2.", + + "system.title": "System", + "system.status": "Status", + "system.status.ok": "In Ordnung", + "system.status.degraded": "Eingeschränkt", + "system.version": "Version", + "system.uptime": "Laufzeit", + "system.database": "Datenbank", + "system.database.ok": "Verbunden", + "system.database.down": "Nicht erreichbar", + "system.devices": "Geräte", + "system.captures": "Aufnahmen", + "system.lastBackup": "Letzte Sicherung", + "system.lastBackup.never": "Nie", + "system.disk": "Bildspeicher", + "system.disk.free": "{free} frei von {total}", + "system.disk.unavailable": "Pfad nicht verfügbar", + "system.enrollSecret": "Registrierungs-Secret", + "system.enrollSecret.set": "Konfiguriert", + "system.enrollSecret.unset": "Nicht gesetzt", + "system.unreachable.title": "Server nicht erreichbar", + "system.unreachable.body": + "Die API hat nicht geantwortet. Läuft sie auf Port 8090?", +}; diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts new file mode 100644 index 0000000..7f56fa3 --- /dev/null +++ b/web/src/i18n/en.ts @@ -0,0 +1,141 @@ +/* English is the source of truth for the key set. + * + * `as const` makes TypeScript remember every literal key, which is what lets + * de.ts be checked for completeness at build time. Add a key here first. + */ +export const en = { + "app.name": "poorBird", + "app.tagline": "Garden bird camera", + + "nav.gallery": "Gallery", + "nav.devices": "Devices", + "nav.system": "System", + + "common.loading": "Loading…", + "common.retry": "Try again", + "common.error": "Something went wrong", + "common.notMeasured": "—", + "common.yes": "Yes", + "common.no": "No", + + "theme.label": "Theme", + "theme.light": "Light", + "theme.dark": "Dark", + "theme.blue": "Blue", + + "lang.label": "Language", + "lang.en": "English", + "lang.de": "German", + + "auth.signIn": "Sign in", + "auth.signOut": "Sign out", + "auth.signedInAs": "Signed in as {username}", + "auth.username": "Username", + "auth.password": "Password", + "auth.totp": "Authentication code", + "auth.totpHint": "Six digits from your authenticator app", + "auth.signingIn": "Signing in…", + // The server answers every sign-in failure identically, so this message has + // to cover all of them: wrong password, unknown user, wrong or missing + // authentication code, deactivated account. Being more specific here would + // invent a distinction the server deliberately refuses to make. + "auth.failed": "Sign-in failed. Check your username, password and code.", + "auth.forbidden": "Your account does not have access to this page.", + // Should now be unreachable: /auth/* exists. Kept for the one case that + // still produces it -- a new UI build served against an older server. + "auth.unavailable": + "This server has no sign-in endpoint. The UI and the server versions do not match.", + + "gallery.title": "Gallery", + "gallery.empty.title": "No captures yet", + "gallery.empty.body": + "The camera has not uploaded anything yet. Generate some to work with: poorbird seed --captures 500", + "gallery.empty.filtered.title": "Nothing matches these filters", + "gallery.empty.filtered.body": "Widen the date range, or clear the filters.", + "gallery.count": "{shown} of {total} loaded", + "gallery.loadingMore": "Loading more…", + "gallery.allLoaded": "That is all of them.", + "gallery.noThumb": "No preview", + // The thumbnail job has not run yet. Distinct from "cannot be decoded", + // which looks identical to a user and means something very different. + "gallery.thumbPending": "Preview not ready", + + "filters.title": "Filters", + "filters.clear": "Clear filters", + "filters.device": "Camera", + "filters.device.all": "All cameras", + "filters.from": "From", + "filters.to": "To", + "filters.kept": "Kept", + "filters.reviewed": "Reviewed", + "filters.preTrigger": "Pre-trigger only", + "filters.any": "Any", + "filters.onlyKept": "Kept only", + "filters.onlyRejected": "Rejected only", + "filters.onlyReviewed": "Reviewed only", + "filters.onlyUnreviewed": "Not reviewed only", + + "capture.title": "Capture", + "capture.close": "Close", + "capture.previous": "Previous", + "capture.next": "Next", + "capture.openFull": "Open full size", + "capture.receivedAt": "Received", + "capture.capturedAt": "Camera clock", + "capture.capturedAt.unsynced": "Not synced", + "capture.device": "Camera", + "capture.dimensions": "Size", + "capture.fileSize": "File", + "capture.trigger": "Trigger", + "capture.trigger.radar": "Radar", + "capture.trigger.manual": "Manual", + "capture.trigger.timer": "Timer", + "capture.trigger.stream_grab": "Stream grab", + "capture.preTrigger": "Pre-trigger frame", + "capture.preTrigger.hint": "Captured before the trigger fired, from the camera's ring buffer", + "capture.burst": "Frame {index} of {count}", + "capture.radarDistance": "Radar distance", + "capture.radarEnergy": "Radar energy", + "capture.rssi": "WiFi signal", + "capture.temperature": "Temperature", + "capture.reviewed": "Reviewed", + "capture.kept": "Kept", + "capture.observations": "Observations", + "capture.observations.none": "Not labelled yet", + "capture.observations.model": "Model prediction", + "capture.tags": "Tags", + + "devices.title": "Devices", + "devices.empty.title": "No devices enrolled", + "devices.empty.body": + "A camera appears here after it enrolls. Enrollment arrives in Phase 2.", + + "system.title": "System", + "system.status": "Status", + "system.status.ok": "Healthy", + "system.status.degraded": "Degraded", + "system.version": "Version", + "system.uptime": "Uptime", + "system.database": "Database", + "system.database.ok": "Connected", + "system.database.down": "Unreachable", + "system.devices": "Devices", + "system.captures": "Captures", + "system.lastBackup": "Last backup", + "system.lastBackup.never": "Never", + "system.disk": "Image storage", + "system.disk.free": "{free} free of {total}", + "system.disk.unavailable": "Path not available", + "system.enrollSecret": "Enrollment secret", + "system.enrollSecret.set": "Configured", + "system.enrollSecret.unset": "Not set", + "system.unreachable.title": "Cannot reach the server", + "system.unreachable.body": + "The API did not respond. Is it running on port 8090?", +} as const; + +/** Every valid translation key. A typo in `t("...")` is a compile error. */ +export type TranslationKey = keyof typeof en; + +/** The shape every other language must fill completely. */ +export type Catalogue = Record; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts new file mode 100644 index 0000000..adadac3 --- /dev/null +++ b/web/src/lib/api.ts @@ -0,0 +1,253 @@ +/* The one place that talks to the server. + * + * Same-origin by design: in development Vite proxies /api to port 8090, in + * production Caddy serves this bundle and the API from the same hostname. + * That means session cookies behave identically in both, and there is no CORS + * configuration anywhere. + */ + +export class ApiError extends Error { + readonly status: number; + readonly body: unknown; + + constructor(status: number, message: string, body: unknown) { + super(message); + this.name = "ApiError"; + this.status = status; + this.body = body; + } + + /** True when the endpoint is simply not built yet (Phase 2 / Phase 3). */ + get isMissingEndpoint(): boolean { + return this.status === 404; + } +} + +/* CSRF, the browser half. + * + * The server sets `poorbird_csrf` as a readable cookie alongside the HttpOnly + * session cookie, and requires this header to match the token on the session + * row for every mutating request. Reading a cookie is exactly what an attacker + * on another origin cannot do, which is what makes echoing it meaningful. + * + * Deliberately read fresh on each call rather than cached: signing out and back + * in issues a new token, and a stale one in a module variable would produce a + * 403 that looks like a server bug. */ +const CSRF_COOKIE = "poorbird_csrf"; + +/** Methods the server requires a CSRF token for. Must match UNSAFE_METHODS. */ +const UNSAFE = new Set(["POST", "PUT", "PATCH", "DELETE"]); + +function csrfToken(): string | null { + // document.cookie is a flat "a=1; b=2" string; there is no read API for one + // cookie. Split rather than regex so a token containing no special + // characters cannot be mangled by an over-clever pattern. + for (const part of document.cookie.split("; ")) { + const eq = part.indexOf("="); + if (eq > 0 && part.slice(0, eq) === CSRF_COOKIE) { + return decodeURIComponent(part.slice(eq + 1)); + } + } + return null; +} + +async function request(path: string, init?: RequestInit): Promise { + const method = (init?.method ?? "GET").toUpperCase(); + const csrf = UNSAFE.has(method) ? csrfToken() : null; + + let response: Response; + try { + response = await fetch(`/api/v1${path}`, { + // `...init` FIRST, then the values that must win. It used to come last, + // which meant a caller passing any headers at all replaced this whole + // object rather than merging into it -- so apiPost, which always sets + // Content-Type, was silently dropping Accept. Harmless then. Not + // harmless now: it would have dropped the CSRF header on exactly the + // mutating requests that require one, and every POST would answer 403. + ...init, + credentials: "same-origin", + headers: { + Accept: "application/json", + // Omitted when there is no cookie, which is the case for the very + // first request of all: logging in. The server exempts it for the + // same reason -- there is no session to protect yet. + ...(csrf === null ? {} : { "X-CSRF-Token": csrf }), + ...init?.headers, + }, + }); + } catch (cause) { + // fetch only rejects on a network-level failure: server down, DNS, CORS. + throw new ApiError(0, `Cannot reach the server: ${String(cause)}`, null); + } + + const text = await response.text(); + let body: unknown = null; + if (text.length > 0) { + try { + body = JSON.parse(text); + } catch { + body = text; + } + } + + if (!response.ok) { + throw new ApiError(response.status, `${response.status} ${response.statusText}`, body); + } + return body as T; +} + +export function apiGet(path: string): Promise { + return request(path); +} + +export function apiPost(path: string, payload?: unknown): Promise { + return request(path, { + method: "POST", + headers: payload === undefined ? {} : { "Content-Type": "application/json" }, + body: payload === undefined ? undefined : JSON.stringify(payload), + }); +} + +/* --- response types --------------------------------------------------- + * These mirror the server. Keep them in step with the FastAPI handlers; + * generating them from /openapi.json is a worthwhile upgrade once there are + * more than a handful. */ + +export interface HealthResponse { + status: "ok" | "degraded"; + version: string; + uptime_s: number; + database: { + ok: boolean; + error: string | null; + devices?: number; + captures?: number; + last_backup_at?: string | null; + }; + disk: { + available: boolean; + path: string; + total_bytes?: number; + free_bytes?: number; + used_pct?: number | null; + }; + enroll_secret_configured: boolean; +} + +export function getHealth(): Promise { + return apiGet("/health"); +} + +/* --- gallery ---------------------------------------------------------- */ + +export interface CaptureSummary { + id: string; + device_id: number; + /** Server time, and authoritative (SPEC C7). Always present. */ + received_at: string; + /** Null when the camera's clock was unsynced. Never render it as 1970. */ + captured_at_device: string | null; + width: number | null; + height: number | null; + bytes: number; + trigger: "radar" | "manual" | "timer" | "stream_grab"; + pre_trigger: boolean; + burst_id: string | null; + burst_index: number | null; + burst_count: number | null; + reviewed: boolean; + kept: boolean; + /** False while the thumbnail job is queued, or forever if it cannot decode. */ + has_thumb: boolean; +} + +export interface CapturePage { + items: CaptureSummary[]; + /** Null at the end. Opaque -- pass it back, do not parse it. */ + next_cursor: string | null; +} + +export interface TagOut { + id: number; + label: string; + colour: string | null; +} + +export interface TaxonOut { + id: number; + scientific_name: string; + name_de: string | null; + name_en: string | null; +} + +export interface ObservationOut { + id: number; + taxon: TaxonOut | null; + individuals: number; + age: string; + sex: string; + behaviour: string | null; + certainty: string; + notes: string | null; + /** "model" is a prediction. Never present one as a human label. */ + source: "human" | "model"; + confidence: number | null; +} + +export interface CaptureDetail extends CaptureSummary { + device_name: string; + sha256: string; + radar_state: number | null; + radar_distance_cm: number | null; + radar_energy: number | null; + battery_mv: number | null; + rssi: number | null; + temp_c: number | null; + frame_seq: number | null; + observations: ObservationOut[]; + tags: TagOut[]; +} + +export interface CaptureFilters { + device_id?: number; + received_from?: string; + received_to?: string; + kept?: boolean; + reviewed?: boolean; + pre_trigger?: boolean; + trigger?: string; +} + +export function listCaptures( + filters: CaptureFilters, + cursor: string | null, + limit = 60 +): Promise { + // URLSearchParams, not string concatenation: an ISO timestamp ends in + // "+00:00" and a raw "+" in a query string means a space, so the server + // would answer 422 for a date it could otherwise have parsed. + const params = new URLSearchParams({ limit: String(limit) }); + if (cursor !== null) params.set("cursor", cursor); + for (const [key, value] of Object.entries(filters)) { + // A tri-state filter is absent when undefined, and `false` is a real + // value -- so this cannot be a truthiness check. + if (value !== undefined) params.set(key, String(value)); + } + return apiGet(`/captures?${params.toString()}`); +} + +export function getCapture(id: string): Promise { + return apiGet(`/captures/${id}`); +} + +/* Image URLs are built here rather than sent by the server, because this + * module is already the one place that knows the API prefix. They go straight + * into , so they are paths from the site root, and the session cookie + * rides along because it is same-origin. */ +export function thumbUrl(id: string): string { + return `/api/v1/captures/${id}/thumb`; +} + +export function imageUrl(id: string): string { + return `/api/v1/captures/${id}/image`; +} diff --git a/web/src/main.tsx b/web/src/main.tsx new file mode 100644 index 0000000..39f01ee --- /dev/null +++ b/web/src/main.tsx @@ -0,0 +1,43 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { RouterProvider } from "@tanstack/react-router"; +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; + +import { AuthProvider } from "./auth/AuthProvider"; +import { I18nProvider } from "./i18n/I18nProvider"; +import { router } from "./router"; +import "./styles/tokens.css"; +import "./styles/global.css"; +import { ThemeProvider } from "./theme/ThemeProvider"; + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + // A garden bird camera is not a trading desk. Refetching on every + // window focus is noise. + refetchOnWindowFocus: false, + staleTime: 30_000, + retry: 1, + }, + }, +}); + +const container = document.getElementById("root"); +if (container === null) { + throw new Error("#root is missing from index.html"); +} + +createRoot(container).render( + + + + + {/* AuthProvider needs the query client, so it sits inside it. */} + + + + + + + +); diff --git a/web/src/pages/DevicesPage.tsx b/web/src/pages/DevicesPage.tsx new file mode 100644 index 0000000..72ae82f --- /dev/null +++ b/web/src/pages/DevicesPage.tsx @@ -0,0 +1,13 @@ +import { EmptyState } from "../components/EmptyState"; +import { useT } from "../i18n/I18nProvider"; + +export function DevicesPage() { + const t = useT(); + + return ( +
+

{t("devices.title")}

+ +
+ ); +} diff --git a/web/src/pages/GalleryPage.tsx b/web/src/pages/GalleryPage.tsx new file mode 100644 index 0000000..8658e6e --- /dev/null +++ b/web/src/pages/GalleryPage.tsx @@ -0,0 +1,121 @@ +import { useInfiniteQuery } from "@tanstack/react-query"; +import { useMemo, useState } from "react"; + +import { CaptureGrid } from "../components/CaptureGrid"; +import { CaptureViewer } from "../components/CaptureViewer"; +import { GalleryFilters } from "../components/GalleryFilters"; +import type { CaptureFilters } from "../components/GalleryFilters"; +import { EmptyState } from "../components/EmptyState"; +import { useT } from "../i18n/I18nProvider"; +import { ApiError, listCaptures } from "../lib/api"; + +/* The gallery. + * + * Paged by cursor rather than page number, matching the server: at 5000 + * captures a day OFFSET gets slower the further back you scroll, which is the + * direction a gallery scrolls. + * + * The filters are part of the query key, so changing one starts a fresh + * pagination rather than appending to the previous result -- a cursor from the + * old filter set describes a position in a list that no longer exists. + */ +export function GalleryPage() { + const t = useT(); + const [filters, setFilters] = useState({}); + const [openIndex, setOpenIndex] = useState(null); + + const query = useInfiniteQuery({ + queryKey: ["captures", filters], + queryFn: ({ pageParam }) => listCaptures(filters, pageParam), + initialPageParam: null as string | null, + getNextPageParam: (lastPage) => lastPage.next_cursor, + staleTime: 30_000, + }); + + const captures = useMemo( + () => query.data?.pages.flatMap((page) => page.items) ?? [], + [query.data] + ); + + if (query.isPending) { + return ( +
+

{t("gallery.title")}

+

{t("common.loading")}

+
+ ); + } + + if (query.isError) { + const error = query.error; + const message = + error instanceof ApiError && error.status === 0 + ? t("system.unreachable.body") + : t("common.error"); + return ( +
+

{t("gallery.title")}

+

+ {message} +

+ +
+ ); + } + + // Devices to offer in the filter come from what has actually been loaded. + // A device list endpoint is Phase 4; until then this is honest about only + // knowing the cameras it has seen captures from. + const devices = [...new Set(captures.map((capture) => capture.device_id))] + .sort((a, b) => a - b) + .map((id) => ({ id, name: `#${id}` })); + + const filtersActive = Object.values(filters).some((value) => value !== undefined); + const open = openIndex === null ? null : (captures[openIndex] ?? null); + + return ( +
+
+

{t("gallery.title")}

+ + {t("gallery.count", { shown: captures.length, total: captures.length })} + +
+ + + + {captures.length === 0 ? ( + + ) : ( + void query.fetchNextPage()} + onOpen={(capture) => + setOpenIndex(captures.findIndex((candidate) => candidate.id === capture.id)) + } + /> + )} + + {open !== null && openIndex !== null && ( + setOpenIndex(null)} + onPrevious={openIndex > 0 ? () => setOpenIndex(openIndex - 1) : null} + // Only as far as what is loaded. Stepping past the last loaded + // capture would show a blank frame while a page arrives, so the + // button is simply disabled there. + onNext={openIndex < captures.length - 1 ? () => setOpenIndex(openIndex + 1) : null} + /> + )} +
+ ); +} diff --git a/web/src/pages/SystemPage.tsx b/web/src/pages/SystemPage.tsx new file mode 100644 index 0000000..f28d0e8 --- /dev/null +++ b/web/src/pages/SystemPage.tsx @@ -0,0 +1,141 @@ +import { useQuery } from "@tanstack/react-query"; + +import { useT } from "../i18n/I18nProvider"; +import { getHealth } from "../lib/api"; +import type { HealthResponse } from "../lib/api"; +import type { Translate } from "../i18n/I18nProvider"; + +/* The only page wired to real data at Phase 3, because /health is the only + * endpoint that exists. That makes it the end-to-end proof: browser -> + * Vite proxy -> FastAPI -> PostgreSQL and back. */ + +function formatBytes(bytes: number | undefined): string { + if (bytes === undefined) return "—"; + const units = ["B", "KB", "MB", "GB", "TB"]; + let value = bytes; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit += 1; + } + return `${value.toFixed(value < 10 && unit > 0 ? 1 : 0)} ${units[unit]}`; +} + +function formatUptime(seconds: number): string { + const s = Math.floor(seconds); + if (s < 60) return `${s}s`; + const m = Math.floor(s / 60); + if (m < 60) return `${m}m ${s % 60}s`; + const h = Math.floor(m / 60); + if (h < 24) return `${h}h ${m % 60}m`; + return `${Math.floor(h / 24)}d ${h % 24}h`; +} + +function Row({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+
{label}
+
{children}
+
+ ); +} + +function HealthDetail({ health, t }: { health: HealthResponse; t: Translate }) { + const dbOk = health.database.ok; + return ( + <> +
+
+ + + {health.status === "ok" ? t("system.status.ok") : t("system.status.degraded")} + + + + {health.version} + + {formatUptime(health.uptime_s)} + + {health.enroll_secret_configured ? ( + t("system.enrollSecret.set") + ) : ( + {t("system.enrollSecret.unset")} + )} + +
+
+ +
+
+ + + {dbOk ? t("system.database.ok") : t("system.database.down")} + + {health.database.error !== null && ( +
{health.database.error}
+ )} +
+ {health.database.devices ?? "—"} + {health.database.captures ?? "—"} + + {health.database.last_backup_at ? ( + new Date(health.database.last_backup_at).toLocaleString() + ) : ( + /* Not an error yet -- backups are Phase 5 and blocked on the + NAS protocol question. It becomes an alarm then, not now. */ + {t("system.lastBackup.never")} + )} + +
+
+ +
+
+ + {health.disk.available ? ( + <> + {t("system.disk.free", { + free: formatBytes(health.disk.free_bytes), + total: formatBytes(health.disk.total_bytes), + })} +
{health.disk.path}
+ + ) : ( + {t("system.disk.unavailable")} + )} +
+
+
+ + ); +} + +export function SystemPage() { + const t = useT(); + const { data, error, isPending, refetch } = useQuery({ + queryKey: ["health"], + queryFn: getHealth, + refetchInterval: 15_000, + retry: false, + }); + + return ( +
+

{t("system.title")}

+ + {isPending &&

{t("common.loading")}

} + + {error !== null && !isPending && ( +
+

{t("system.unreachable.title")}

+

{t("system.unreachable.body")}

+ +
+ )} + + {data !== undefined && } +
+ ); +} diff --git a/web/src/router.tsx b/web/src/router.tsx new file mode 100644 index 0000000..2e5373e --- /dev/null +++ b/web/src/router.tsx @@ -0,0 +1,71 @@ +/* Routes, defined in code rather than by file convention. + * + * One file, flat, so the whole route table is visible at once. TanStack + * Router's value here is that is type-checked: a typo in + * a path is a build error, not a 404 you find later. + */ + +import { + createRootRoute, + createRoute, + createRouter, +} from "@tanstack/react-router"; + +import { RequireAuth } from "./auth/RequireAuth"; +import { AppLayout } from "./components/AppLayout"; +import { DevicesPage } from "./pages/DevicesPage"; +import { GalleryPage } from "./pages/GalleryPage"; +import { SystemPage } from "./pages/SystemPage"; + +const rootRoute = createRootRoute({ component: AppLayout }); + +/* Every route is gated. This is the client-side half only -- it decides what + * to render, and the server authorises each request independently. A guard + * here that the server did not also enforce would be decoration. + * + * Roles follow SPEC 3.1: the gallery is what a viewer is for, while devices + * and system expose operational state and belong to admins. Listing the roles + * per route rather than granting admin everything implicitly means widening + * one route cannot silently widen another -- the same reasoning as + * api/userauth.require_role. */ +const galleryRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/", + component: () => ( + + + + ), +}); + +const devicesRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/devices", + component: () => ( + + + + ), +}); + +const systemRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/system", + component: () => ( + + + + ), +}); + +const routeTree = rootRoute.addChildren([galleryRoute, devicesRoute, systemRoute]); + +export const router = createRouter({ routeTree }); + +/* Teaches TypeScript about this specific router, which is what makes + * paths checked. Without it, `to` is just a string. */ +declare module "@tanstack/react-router" { + interface Register { + router: typeof router; + } +} diff --git a/web/src/styles/global.css b/web/src/styles/global.css new file mode 100644 index 0000000..84cc38b --- /dev/null +++ b/web/src/styles/global.css @@ -0,0 +1,597 @@ +/* Base styles. Every colour is a token from tokens.css -- no literals here, + * so adding a theme never means touching this file. */ + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body, +#root { + height: 100%; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: var(--font-sans); + font-size: var(--text-base); + line-height: 1.5; + -webkit-font-smoothing: antialiased; +} + +a { + color: var(--accent); +} + +code, +.mono-small { + font-family: var(--font-mono); +} + +.mono-small { + font-size: var(--text-xs); + color: var(--text-muted); + word-break: break-all; +} + +.muted { + color: var(--text-muted); +} + +.warn { + color: var(--warning); +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +/* --- shell ----------------------------------------------------------- */ + +.app { + display: flex; + flex-direction: column; + min-height: 100%; +} + +.header { + display: flex; + align-items: center; + gap: var(--space-5); + height: var(--header-height); + padding: 0 var(--space-4); + background: var(--surface); + border-bottom: 1px solid var(--border); +} + +.brand { + display: inline-flex; + align-items: center; + gap: var(--space-2); + color: var(--text); + font-weight: 600; + text-decoration: none; + white-space: nowrap; +} + +.brand-mark { + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--accent); +} + +.nav { + display: flex; + gap: var(--space-1); + flex: 1; + min-width: 0; + overflow-x: auto; +} + +.nav-link { + padding: var(--space-2) var(--space-3); + border-radius: var(--radius); + color: var(--text-muted); + text-decoration: none; + white-space: nowrap; + transition: background var(--transition), color var(--transition); +} + +.nav-link:hover { + background: var(--surface-sunken); + color: var(--text); +} + +.nav-link.is-active { + background: var(--accent-subtle); + color: var(--accent); +} + +.header-tools { + display: flex; + align-items: center; + gap: var(--space-2); +} + +/* Replaced .banner, which existed only for the "sign-in is not enforced" + notice and went away with it. */ +.signed-in-as { + font-size: var(--text-sm); + white-space: nowrap; +} + +.main { + flex: 1; + width: 100%; + max-width: 1100px; + margin: 0 auto; + padding: var(--space-6) var(--space-4); +} + +.page-title { + margin: 0 0 var(--space-5); + font-size: var(--text-2xl); + font-weight: 650; + letter-spacing: -0.01em; +} + +.centered-page { + display: grid; + place-items: center; + min-height: 60vh; + padding: var(--space-4); +} + +/* --- surfaces -------------------------------------------------------- */ + +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow); + padding: var(--space-5); + margin-bottom: var(--space-4); +} + +.rows { + margin: 0; + display: grid; + gap: var(--space-4); +} + +.row { + display: grid; + grid-template-columns: minmax(140px, 220px) 1fr; + gap: var(--space-4); + align-items: baseline; +} + +.row-label { + color: var(--text-muted); + font-size: var(--text-sm); +} + +.row-value { + margin: 0; + min-width: 0; +} + +.pill { + display: inline-block; + padding: 2px var(--space-2); + border-radius: 999px; + font-size: var(--text-xs); + font-weight: 600; + border: 1px solid currentcolor; +} + +.pill-ok { + color: var(--success); +} +.pill-warn { + color: var(--warning); +} +.pill-danger { + color: var(--danger); +} + +.empty-state { + background: var(--surface); + border: 1px dashed var(--border-strong); + border-radius: var(--radius-lg); + padding: var(--space-7) var(--space-5); + text-align: center; +} + +.empty-title { + margin: 0 0 var(--space-2); + font-size: var(--text-lg); +} + +.empty-body { + margin: 0 auto; + max-width: 46ch; + color: var(--text-muted); +} + +.alert { + padding: var(--space-3); + border-radius: var(--radius); + font-size: var(--text-sm); + margin: 0; +} + +.alert-danger { + color: var(--danger); + border: 1px solid var(--danger); + background: transparent; +} + +/* --- controls -------------------------------------------------------- */ + +.field { + display: grid; + gap: var(--space-1); +} + +.field-label { + font-size: var(--text-sm); + color: var(--text-muted); +} + +.field-hint { + font-size: var(--text-xs); + color: var(--text-muted); +} + +.input, +.select { + width: 100%; + padding: var(--space-2) var(--space-3); + background: var(--surface-raised); + color: var(--text); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + font: inherit; + font-size: var(--text-sm); +} + +.select { + width: auto; +} + +.input:focus-visible, +.select:focus-visible, +.button:focus-visible, +.nav-link:focus-visible, +.brand:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.button { + padding: var(--space-2) var(--space-4); + background: var(--surface-raised); + color: var(--text); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + font: inherit; + font-size: var(--text-sm); + font-weight: 550; + cursor: pointer; + transition: background var(--transition), border-color var(--transition); +} + +.button:hover:not(:disabled) { + border-color: var(--accent); +} + +.button:disabled { + opacity: 0.6; + cursor: default; +} + +.button-primary { + background: var(--accent); + border-color: var(--accent); + color: var(--text-inverse); +} + +.button-primary:hover:not(:disabled) { + background: var(--accent-hover); + border-color: var(--accent-hover); +} + +.login-card { + width: min(380px, 100%); + display: grid; + gap: var(--space-4); + margin: 0; +} + +.login-title { + margin: 0; + font-size: var(--text-xl); +} + +/* --- small screens ---------------------------------------------------- */ + +@media (max-width: 640px) { + .header { + flex-wrap: wrap; + height: auto; + padding: var(--space-3) var(--space-4); + gap: var(--space-3); + } + + .nav { + order: 3; + width: 100%; + } + + .row { + grid-template-columns: 1fr; + gap: var(--space-1); + } + + .main { + padding: var(--space-5) var(--space-4); + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + } +} + +/* --- gallery --------------------------------------------------------------- + Every colour here is a token. A literal would have to be repeated for each + of the three themes, which is the thing tokens.css exists to prevent. */ + +.gallery-header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-4); + flex-wrap: wrap; +} + +.filters { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: var(--space-3); + padding: var(--space-3) 0 var(--space-4); + border-bottom: 1px solid var(--border); + margin-bottom: var(--space-4); +} + +.field-inline { + gap: var(--space-1); +} + +.field-inline .input { + min-width: 9rem; +} + +/* The virtualiser needs a scrolling element with a bounded height, or every + row is "visible" and nothing is virtualised. */ +.grid-scroll { + overflow-y: auto; + max-height: calc(100vh - 20rem); + min-height: 24rem; + /* Keeps the scrollbar from shifting the layout as rows load. */ + scrollbar-gutter: stable; +} + +.grid-sizer { + position: relative; + width: 100%; +} + +.grid-row { + position: absolute; + top: 0; + left: 0; + width: 100%; + display: grid; +} + +.grid-footer { + min-height: 1.5rem; + padding: var(--space-3) 0; + text-align: center; + font-size: var(--text-sm); +} + +.tile { + position: relative; + display: block; + width: 100%; + height: 100%; + padding: 0; + overflow: hidden; + background: var(--surface-sunken); + border: 1px solid var(--border); + border-radius: var(--radius); + cursor: pointer; + transition: border-color var(--transition); +} + +.tile:hover { + border-color: var(--accent); +} + +.tile:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.tile-image { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} + +.tile-placeholder { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + padding: var(--space-2); + font-size: var(--text-xs); + text-align: center; +} + +.tile-badges { + position: absolute; + bottom: var(--space-1); + left: var(--space-1); + display: flex; + flex-wrap: wrap; + gap: var(--space-1); +} + +.badge { + padding: 2px var(--space-2); + background: var(--accent-subtle); + color: var(--accent); + border-radius: var(--radius-sm); + font-size: var(--text-xs); + font-weight: 550; +} + +.badge-danger { + background: var(--surface-raised); + color: var(--danger); +} + +/* --- capture viewer --- */ + +.viewer-backdrop { + position: fixed; + inset: 0; + z-index: 50; + display: flex; + align-items: center; + justify-content: center; + padding: var(--space-4); + /* color-mix keeps this a token too, rather than a hardcoded rgba(). */ + background: color-mix(in srgb, var(--bg) 82%, transparent); + backdrop-filter: blur(2px); +} + +.viewer { + display: flex; + flex-direction: column; + width: min(1200px, 100%); + max-height: 100%; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + overflow: hidden; +} + +.viewer-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-3) var(--space-4); + border-bottom: 1px solid var(--border); + flex-wrap: wrap; +} + +.viewer-actions { + display: flex; + gap: var(--space-2); +} + +.viewer-body { + display: grid; + grid-template-columns: minmax(0, 1fr) 20rem; + min-height: 0; + overflow: hidden; +} + +.viewer-image-wrap { + display: flex; + align-items: center; + justify-content: center; + min-height: 0; + padding: var(--space-3); + background: var(--surface-sunken); +} + +.viewer-image { + max-width: 100%; + max-height: 70vh; + object-fit: contain; +} + +.viewer-meta { + padding: var(--space-4); + overflow-y: auto; + border-left: 1px solid var(--border); + font-size: var(--text-sm); +} + +.detail-row { + display: flex; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-1) 0; + border-bottom: 1px solid var(--border); +} + +.detail-label { + flex: 0 0 auto; +} + +.detail-value { + text-align: right; + word-break: break-word; +} + +.detail-heading { + margin: var(--space-4) 0 var(--space-2); + font-size: var(--text-sm); + font-weight: 600; +} + +.detail-list { + margin: 0; + padding-left: var(--space-4); +} + +@media (max-width: 720px) { + .viewer-body { + grid-template-columns: minmax(0, 1fr); + overflow-y: auto; + } + + .viewer-meta { + border-left: none; + border-top: 1px solid var(--border); + } + + .grid-scroll { + max-height: calc(100vh - 26rem); + } +} diff --git a/web/src/styles/tokens.css b/web/src/styles/tokens.css new file mode 100644 index 0000000..f5ce30e --- /dev/null +++ b/web/src/styles/tokens.css @@ -0,0 +1,126 @@ +/* Design tokens. + * + * Three themes, selected by `data-theme` on : light, dark, blue. + * Components never write a colour literal -- they reference a token, so a + * fourth theme is a block in this file and nothing else. + * + * Contrast: every text/background pair below meets WCAG AA (>= 4.5:1 for body + * text, >= 3:1 for large text and UI borders). `npm run check:contrast` + * asserts it -- run it after touching any colour here, because this is + * exactly the kind of thing that regresses silently. + */ + +:root { + /* --- shape and space (theme-independent) --- */ + --radius-sm: 4px; + --radius: 8px; + --radius-lg: 14px; + + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 24px; + --space-6: 32px; + --space-7: 48px; + + --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, + "Helvetica Neue", Arial, sans-serif; + --font-mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Consolas, + "Liberation Mono", monospace; + + --text-xs: 0.75rem; + --text-sm: 0.875rem; + --text-base: 1rem; + --text-lg: 1.125rem; + --text-xl: 1.5rem; + --text-2xl: 2rem; + + --transition: 120ms ease; + --header-height: 56px; +} + +/* --- light ---------------------------------------------------------- */ +:root, +[data-theme="light"] { + color-scheme: light; + + --bg: #f6f8fb; + --surface: #ffffff; + --surface-raised: #ffffff; + --surface-sunken: #eef2f7; + /* --border is decorative (dividers, card edges) and is exempt from the + contrast rule. --border-strong bounds interactive controls -- inputs, + focus rings -- so WCAG 1.4.11 wants 3:1 against the surface behind it. */ + --border: #dde3ec; + --border-strong: #848f9e; + + --text: #14202e; + --text-muted: #56677d; + --text-inverse: #ffffff; + + --accent: #1257c4; + --accent-hover: #0e46a0; + --accent-subtle: #e4edfb; + + --success: #17724a; + --warning: #8a5a00; + --danger: #b3242c; + + --shadow: 0 1px 2px rgb(16 24 40 / 6%), 0 4px 12px rgb(16 24 40 / 8%); + --overlay: rgb(16 24 40 / 40%); +} + +/* --- dark (neutral) ------------------------------------------------- */ +[data-theme="dark"] { + color-scheme: dark; + + --bg: #121417; + --surface: #191c21; + --surface-raised: #21252b; + --surface-sunken: #0d0f12; + --border: #2e343c; + --border-strong: #656d7a; + + --text: #e8eaed; + --text-muted: #a3adba; + --text-inverse: #10141a; + + --accent: #6ba1ff; + --accent-hover: #8bb6ff; + --accent-subtle: #1b2534; + + --success: #3dd68c; + --warning: #f0b429; + --danger: #ff6b71; + + --shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 8px 24px rgb(0 0 0 / 40%); + --overlay: rgb(0 0 0 / 60%); +} + +/* --- blue (dark navy) ----------------------------------------------- */ +[data-theme="blue"] { + color-scheme: dark; + + --bg: #0b1220; + --surface: #111c2e; + --surface-raised: #17253b; + --surface-sunken: #070d17; + --border: #22344f; + --border-strong: #5a7196; + + --text: #e6edf7; + --text-muted: #9fb3ce; + --text-inverse: #0b1220; + + --accent: #4c8dff; + --accent-hover: #6ba1ff; + --accent-subtle: #152740; + + --success: #3dd68c; + --warning: #f0b429; + --danger: #f2545b; + + --shadow: 0 1px 2px rgb(0 0 0 / 45%), 0 8px 28px rgb(3 8 18 / 55%); + --overlay: rgb(4 9 18 / 65%); +} diff --git a/web/src/theme/ThemeProvider.tsx b/web/src/theme/ThemeProvider.tsx new file mode 100644 index 0000000..d767112 --- /dev/null +++ b/web/src/theme/ThemeProvider.tsx @@ -0,0 +1,64 @@ +/* Theme selection. + * + * The chosen theme is written to `data-theme` on , which is what + * tokens.css keys off. Persistence is localStorage for now; once accounts + * exist (Phase 3) the server-side `users.theme` column becomes the source of + * truth and this stays as the pre-login default and the first-paint value. + * + * The flash-of-wrong-theme is prevented by an inline script in index.html, + * which runs before React and before first paint. Keep the storage key and + * the attribute name in sync with that script. + */ + +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; +import type { ReactNode } from "react"; + +export const THEMES = ["light", "dark", "blue"] as const; +export type Theme = (typeof THEMES)[number]; + +const STORAGE_KEY = "poorbird.theme"; + +interface ThemeValue { + theme: Theme; + setTheme: (theme: Theme) => void; +} + +const ThemeContext = createContext(null); + +function isTheme(value: unknown): value is Theme { + return typeof value === "string" && (THEMES as readonly string[]).includes(value); +} + +function initialTheme(): Theme { + // The inline script has already decided and applied one; read it back so + // React and the DOM never disagree. + const applied = document.documentElement.getAttribute("data-theme"); + if (isTheme(applied)) return applied; + return "blue"; +} + +export function ThemeProvider({ children }: { children: ReactNode }) { + const [theme, setThemeState] = useState(initialTheme); + + useEffect(() => { + document.documentElement.setAttribute("data-theme", theme); + try { + localStorage.setItem(STORAGE_KEY, theme); + } catch { + // Blocked storage: the theme applies, it just will not be remembered. + } + }, [theme]); + + const setTheme = useCallback((next: Theme) => setThemeState(next), []); + const value = useMemo(() => ({ theme, setTheme }), [theme, setTheme]); + + return {children}; +} + +export function useTheme(): ThemeValue { + const value = useContext(ThemeContext); + if (value === null) { + throw new Error("useTheme must be used inside "); + } + return value; +} diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..e2e474f --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + + /* Strict on purpose. Learning TypeScript with the checks off teaches you + a different language than the one everyone else is writing. */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedIndexedAccess": true, + + /* Requires `import type { X }` for type-only imports. The error message + says exactly what to do, and it keeps types out of the JS bundle. */ + "verbatimModuleSyntax": true, + + "skipLibCheck": true, + "noEmit": true, + "isolatedModules": true, + "types": ["vite/client"] + }, + "include": ["src", "vite.config.ts"] +} diff --git a/web/vite.config.ts b/web/vite.config.ts new file mode 100644 index 0000000..3c20636 --- /dev/null +++ b/web/vite.config.ts @@ -0,0 +1,24 @@ +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + // The dev server proxies the API so the browser only ever talks to one + // origin. No CORS config on the server, and cookies behave the same in + // development as they will in production behind Caddy. + proxy: { + "/api": { + target: "http://127.0.0.1:8090", + changeOrigin: true, + }, + }, + }, + build: { + // Caddy serves this directory as static files. Nothing here runs on the + // server; the whole app is built on the dev machine (SPEC 6). + outDir: "dist", + sourcemap: true, + }, +});