web/README.md promised this was "three lines in router.tsx plus deleting the banner". It was nearly true. Every route is now behind RequireAuth: the gallery for any signed-in user, Devices and System for admin (SPEC 3.1). Roles are listed per route rather than granting admin everything implicitly, so widening one route cannot silently widen another - the same reasoning as api/userauth.require_role. The parts the README did not anticipate: A sign-out control. signOut() existed in AuthProvider and nothing called it, which was fine while the app was ungated and is not fine now: enforcing auth without a way to leave strands whoever signs in. It sits in the header with the theme and language switchers, and only renders when there is a session to end. lib/api.ts now carries the CSRF token, and fixing that surfaced a real bug in the scaffold. The fetch options spread `...init` AFTER `headers:`, so any caller passing headers replaced the whole object instead of merging into it. apiPost always sets Content-Type, so Accept was already being dropped on every POST - harmless, and invisible, because the server does not care. It stops being harmless the moment a header has to be there: the CSRF token would have been dropped on exactly the mutating requests that require one, and every POST would have answered 403 with nothing in the client to explain it. `...init` goes first now, with the reason written next to it. RequireAuth no longer shows the login form for the "unavailable" state. That state means the server answered 404 to /auth/session, which now only happens when a newer UI is served by an older server - so offering a form that 404s is the wrong answer. It says the versions do not match instead. auth.notEnforced is deleted from both catalogues rather than left unused, and .banner went with it, since that notice was its only caller. auth.failed was reworded: the server answers every sign-in failure identically - wrong password, unknown user, bad code, deactivated account - so the message has to cover all of them rather than inventing a distinction the server refuses to make. New keys in both en.ts and de.ts, which is enforced at build time. Verified through the Vite dev proxy, which is the path a browser actually takes rather than the one the tests take: 401 signed out, 401 for an admin without a TOTP code, 200 with one, both cookies arriving through the proxy, 403 on logout without the CSRF header with the session still alive after it, 204 with the header, 401 after. And POST /ingest still answers 401 rather than 403, because a camera sends no cookies and must never need a CSRF token. Docs brought in line: web/README.md said authentication was built but not enforced, which is now the opposite of true, and it now also says the two things needed before anyone can sign in - a user, and POORBIRD_SESSION_COOKIE_SECURE=false for plain-http development. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
23 KiB
TODO: poorBird
Baseline: SPEC.md · Device contract: firmware/API.md · Hardware notes: 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) waits on user auth in Phase 3. |
| Data model | Designed (SPEC §3) + §0 additions, migration written and applied, guarded by a drift test. |
| Server | Phases 1 and 2 in server/ — config, schema, health, job queue, scheduler, systemd units, and every device endpoint the firmware calls. Verified on Python 3.14.7 against PostgreSQL 17: 194 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 | Nothing exists beyond the Vite scaffold on feature/UI_Basic_implementation. |
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.inifromsecrets.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_timecleanly 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.cppframe 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
radarSetGateSensitivityvalidate 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.cppallocates 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 to run it, and
server/deploy/INSTALL.md to deploy it. What is
written vs. what still needs doing on the real host:
- Python venv layout, FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Alembic —
server/ - systemd units
poorbird-api.service+poorbird-worker.service,After=postgresql.service, restart policies, sandboxing - Caddyfile with DNS-01 TLS, the
:8080plain-HTTP camera listener and the auth-checked image handoff poorbird check— validates config, paths and DB before anything starts- Run it against a real PostgreSQL — done on the dev machine (uv-managed Python 3.14.7, Podman
postgres:17):poorbird check,migrate,serve,workerand 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
- Image store at
/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg, thumbs alongside as_400.webp(SPEC §3.3) — writer landed with Phase 2; writes are atomic (.partthenos.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
- Initial Alembic migration covering SPEC §3, guarded by a schema-drift test
captures.pre_trigger BOOL— was this frame captured before the trigger fireddevices.awake BOOL— reported every heartbeat, so the UI can show command latency honestlydevices.reenroll_secret_hashdevice_statustime-series table (SPEC §0 columns, plusrawJSONB so nothing is lost)devicessettings surface — one JSONBconfigcolumn, not forty:GET /configis ~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.- 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 thesettingsdefaults
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.
- 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.envunchanged. - Postgres over loopback TCP, not a Unix socket — the one genuinely container-hostile choice, and the only real change from a purely native design
- 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. - Log to stdout/stderr. journald catches it now, a log driver would catch it later. Simpler than app-managed log files either way.
- Migrations as a standalone idempotent command (
poorbird migrate), run fromExecStartPreon the API unit only — never at app import time, and never from two units at once - 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
- 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-reloadbehind 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. - 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.
POST /api/v1/enroll— bootstrap secret in, per-devicereenroll_secret+ token out. Re-enrolling a knowndevice_uidmust return the existing row with a fresh token, never a duplicate. Accepts the shared secret or that device's ownreenroll_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'snamedoes not.POST /api/v1/ingest— raw JPEG body with metadata in headers, not multipart.firmware/API.mdanduploader.cppsend the bytes directly; multipart was a misreading. HonoursX-Pre-Trigger, dedupes on sha256 per device.POST /api/v1/heartbeatandPOST /status— full conditions report intodevice_statusGET /api/v1/config— enums by name not number,config_versionbump semantics. Column-backed keys win over stale JSONB copies, so an operator rename actually reaches the device; the device's ownconfig_versionnever overwrites the server's.- Response envelope +
server_time(SPEC C7:received_atstays authoritative). On/heartbeatand/ingest. Not on/status, which is 204 with no body perfirmware/API.md— "every response" was not compatible with the firmware contract. - Thumbnail job on ingest — 400px WebP, decode kept off the request path
- Device authentication, rate limiting,
POST /commands/{id}/ack,GET /firmware/{v}.bin— not in the original list, but the firmware calls them (seedocs/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. Typechecks, builds,
and the System page reads live data through the Vite proxy.
- React 19 + TS + Vite + TanStack Query/Router, built on the dev machine, served as static files by Caddy
- Three themes as design tokens,
data-themeon<html>, no flash of the wrong theme npm run check:contrast— asserts WCAG AA across all three themes; caught three failing--border-strongvalues on its first run- i18n de/en with a build-time-complete catalogue
- Auth shell: provider, login form with TOTP field,
RequireAuth(no dev bypass, on purpose) - System page on live
/health— the end-to-end proof browser → proxy → FastAPI → Postgres - Wire
RequireAuthintorouter.tsxand delete the "not enforced" banner — gallery needs any signed-in user, Devices and System needadmin. Sign-out is in the header. - ESLint (skipped during scaffolding;
tsc --noEmitcovers the important cases for now) - Virtualised gallery grid; filters for date range, taxon, device, tag, reviewed, kept
- Observation editor —
captures1—nobservations, so a photo can hold two species or none - Taxon autocomplete; seed
taxawith 60–80 Central European garden species incl. GBIF keys,name_de+name_en,is_local_commonranking 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 - Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin),
audit_logon 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 frompoorbird user add— there is no sign-up endpoint. - Extend
audit_logto the content mutations (observations, tags, device config) as each endpoint lands. Auth events are covered; nothing else writes to it yet. - Auth-checked image serving — the app authorizes, Caddy serves the bytes. An unguessable URL is not access control
- TOTP 2FA — enforced at account creation for
adminrather 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
/apifor 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 = falsemeans 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
capturestable 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
devicessettings 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}.binalready serves the bytes; the upload half was left out of Phase 2 because it needs operator auth. Constrainfirmware.is_targetto 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_dumppre-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/healthcovering 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/bothmodes; 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 |