Commit Graph
24 Commits
Author SHA1 Message Date
Thomas KarnerandClaude Opus 5 89ebe99bed Merge Phase 2 into the UI branch, so auth is built on top of it
Phase 3 auth is next, and this branch's server/ was still at Phase 1. Building
sessions here without merging first would have meant writing them against a
config.py with credentials still defaulted, no deps.py device auth to follow as
a pattern, and - the one that actually matters - no rate limiter, leaving a
login endpoint brute-forceable until the branches finally met.

So the branches meet now, while the only conflict is a documentation one, rather
than later on top of an auth implementation.

TODO.md was the single conflict: both sides had edited Phase 3, which is exactly
what should happen when one branch finishes Phase 2 and the other starts the UI.
Both sides' content is kept - the Phase 2 ticks and the UI decisions in 3.0 -
and the resolution fixed two things a purely textual merge leaves broken:

  - "Minimal gallery page, no auth yet" is struck. SPEC 3.3 requires image
    serving to be auth-checked, so that is not a state the gallery can
    legitimately pass through, and the scaffold's System page already proves the
    browser-to-Postgres path that item existed to prove.
  - The themes line appeared twice, once ticked by the scaffold and once not.
    The genuinely open half is persisting the choice per user, which needs
    accounts, so that is what it now says.

web/ is untouched by the merge: it had no files at the merge base and none on
the server branch, so that side contributes no deletion. Verified - 27 files
before and after.

Verified both halves after resolving: server 194 passed, ruff clean, alembic
clean; UI typecheck clean, build green, 36 contrast pairs across 3 themes with
no failures.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:48:55 +02:00
Thomas KarnerandClaude Opus 5 7263e1ec63 Move this branch's review to docs/reviews/ui-basic-implementation/
The UI review was living at server/REVIEW.md and server/REVIEW.AI.md - a path
that describes neither its subject nor its scope, since the document reviews
the UI branch and nothing in it is about the server directory it sat in.

The server branch moved its own review to docs/reviews/server-basic-implementation/
for the same reason, and because the fixed path guaranteed an add/add conflict
on both filenames the moment the two branches met. This is the other half of
that fix: with one directory per scope, both reviews survive into develop and
neither has to win.

Pure git mv, no content change. docs/reviews/README.md is taken as the
identical blob from the server branch rather than rewritten, so the two
branches cannot conflict on the file that exists to prevent conflicts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:41:16 +02:00
Thomas KarnerandClaude Opus 5 c40072f644 Correct the docs that Phase 2 made wrong
Both entry-point documents still described the server as a Phase 1 skeleton,
which is the kind of drift that costs someone an afternoon before they think
to distrust the README.

server/README.md opened with "There are no device endpoints yet". There are
eight, so it now lists them, checked against the mounted routes rather than
from memory. images.py joins the layout; api/ no longer says Phase 2 will
mount routes there one day.

TODO.md Phase 2 had every box unticked. Ticked with what was actually built,
and the three deviations from the plan written down where the plan was wrong:

  - /ingest was specified as "multipart image + JSON meta". The firmware
    sends a raw JPEG body with the metadata in headers. Multipart was a
    misreading of API.md, and the note now says so, because the next person
    to read the old line would implement the wrong endpoint.
  - "server_time in every response" is not compatible with /status being
    204, which API.md requires. The envelope goes on /heartbeat and /ingest.
  - Enroll accepts a device's own reenroll_secret as well as the shared
    bootstrap secret. Checking only the shared one, as the review's sample
    code did, locks out every device that has ever enrolled.

Two boxes stay open, and they are the honest ones: no gallery page, and no
end-to-end run against real hardware. The server half is proven only against
synthetic uploads, and the status table now says that rather than implying a
verified path.

Also recorded two deliberate deferrals that were living only in a
conversation, which is the same as not existing:

  - CORS, in Phase 3: not configured because Caddy serves the UI and the API
    from one origin, so there is no cross-origin request to permit and
    permissive headers would only weaken that.
  - The missing single-row constraint on firmware.is_target, in Phase 4
    beside the upload endpoint that will create the second target row.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:36:37 +02:00
Thomas KarnerandClaude Opus 5 05f144ed98 Size the connection pool, slow the idle poll, drop a dead setting (REVIEW 7)
The three performance settings the review flagged, one of which turned out
not to exist in any meaningful sense.

db_pool_size 5 -> 15, and max_overflow named explicitly. FastAPI runs this
app's def handlers in anyio's threadpool - 40 threads by default - and each
holds a session for the whole request, so a pool of 5 put the sixth
concurrent request on pool_timeout before it reached the database. The real
ceiling was never 5 either: it was 15, because SQLAlchemy quietly adds
max_overflow=10. Leaving that invisible is the actual hazard, since an
operator raising pool_size has no way to see what they are raising it from,
so both halves are settings now and the arithmetic is written down next to
PostgreSQL's max_connections in the env example. pool_timeout is pinned at
30s rather than inherited: it has to stay finite, or a pool leak presents as
requests hanging forever instead of an error that names the pool.

worker_poll_interval_s 2.0 -> 5.0. This only ever delays noticing a job
enqueued into an empty queue - the loop drains a queue that has work back to
back without sleeping - so it costs latency nobody can perceive on a bird
camera and halves the idle queries, 30 a minute down to 12.

worker_batch_size is removed rather than raised to 5. Nothing read it. It
has sat in Settings since Phase 1 looking like it tuned something while the
worker claimed one job at a time regardless, which is worse than no setting
at all. Implementing it would also be a mistake here: claiming five jobs
marks all five 'running', so dying after the first leaves four locked by a
process that no longer exists and invisible until requeue_stale reaches them
up to fifteen minutes later. Single claims keep exactly one job at risk, and
batching would only have saved claim round-trips on a loopback connection
that no thumbnail decode would notice. The reasoning is at the claim loop,
where the next person will ask.

The test asserts against a pool an engine really built, because comparing
Settings to itself would pass no matter what db.py does. It has to use
values that differ from SQLAlchemy's own defaults - hence 17 and 7 - which
is the point mutation testing earned: with max_overflow unwired the first
version of this test still passed, because the default it fell back to was
10 and the setting also said 10.

Tests: 193 -> 194.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:31:43 +02:00
Thomas KarnerandClaude Opus 5 ec9ef9b3a6 Add the thumbnail worker, and stop tests leaking jobs (Phase 2)
Captures now get a WebP thumbnail: 400px on the long edge, written to
thumbs/<uuid>_400.webp (SPEC 3.3). /ingest enqueues the job in the same
transaction as the capture row, so the worker never sees a job for a capture
that was rolled back, and decoding stays off the request path - it is the one
genuinely expensive part of a capture, and the device is waiting with a burst
still to upload.

api/images.py moves up to poorbird/images.py. Both sides use it now, and a
worker importing from api would be the wrong way round. The split by cost
stays: everything the ingest path touches still reads nine bytes of JPEG
header, and Pillow appears only in the thumbnail half.

Handler behaviour is about which failures are worth retrying:

  - An undecodable frame returns rather than raises. The handler contract
    makes a raise mean "retry", and a frame that will never decode should not
    spend three attempts proving it. Logged, thumb_path left NULL.
  - A missing source file raises, because it should be there and a mount that
    has not come back yet is worth retrying for.
  - A capture deleted between enqueue and run is not an error. Retention will
    do that routinely in Phase 5.
  - A malformed payload is validated with a Pydantic model and recorded, not
    retried (SEC-003 applied to a job payload).
  - Never upscales: blowing a 100px frame up to 400px produces a blurry lie.
  - Fills in width/height when the ingest header parse could not. This is the
    first full decode, so it is the chance to fix that.

Verified end to end against a real device row, a real HTTP ingest and the
real worker dispatch path - claim, _run_one, complete - not just the handler
called directly: 1600x1200 JPEG in, WEBP 400x300 on disk, job marked done.
That run is what caught the rest of this commit.

Tests were leaking jobs into the shared queue, which broke test_queue.py once
/ingest started enqueuing. Three separate causes, all the same shape as the
teardown bug fixed in 269a6ea:

  - test_ingest cleaned captures but not their thumbnail jobs, and one test
    hand-rolled teardown for a second device and forgot half of it. Devices
    now come from a fixture that cleans frames, captures and jobs for every
    device a test makes.
  - test_queue claimed jobs without checking they were its own, so a leftover
    thumbnail job could be failed on its behalf, and one test claimed a
    second job to prove the first did not recur and then stranded it in
    'running' forever. It now enqueues at a priority that wins, asserts every
    claim is its own, and releases anything else it touches.

The suite now runs twice in a row leaving zero jobs behind, which is the
assertion that actually matters here.

Tests: 175 -> 193.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 14:49:15 +02:00
Thomas KarnerandClaude Opus 5 e326dd8226 Add rate limiting to the device endpoints (REVIEW SEC-004)
In-process token buckets, no Redis and no slowapi - for the same reason the
job queue has no Redis (SPEC C8). This 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 assumption is named in the module: poorbird serve runs a single process,
and if the deployment ever gains workers each gets its own buckets and the
effective limit multiplies. Move the state to PostgreSQL at that point rather
than widening the numbers.

Buckets rather than fixed windows, because a camera uploads three to five
frames back to back when the radar fires and then goes quiet. A window would
reject the tail of a legitimate burst that straddled a boundary.

Authenticated endpoints key on the device, so one wedged camera cannot spend
another's allowance. /enroll keys on the caller address, since there is no
device yet and it is the one place a shared secret could be ground at.

This required a Caddyfile change, not a cosmetic one: the :8080 camera block
proxied without X-Real-IP, so every camera reached the app as 127.0.0.1 and
they would all have shared one enrollment bucket - one noisy device locking
the rest out. The header is trusted only because uvicorn binds loopback.

Limits are deliberately loose, each derived from what the firmware actually
does and noted in the code so the number can be re-derived rather than
guessed at. A throttled camera stops delivering photographs, which on a
private LAN is worse than the flooding the limit prevents.

Throttling answers 429, never 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.

The key table is LRU-bounded. It is keyed partly on caller address, and an
unbounded map keyed by something a caller influences is itself a way to
exhaust memory.

Off by default in tests, which fire far more requests than any camera would.
tests/test_ratelimit.py turns it back on and proves the buckets are wired to
the routes.

Also fixes the same teardown-in-test-body flaw in the new file, found by
re-running a deliberate mutation and noticing a leaked device row. Teardown
is in fixtures; the mutation now fails its one test and leaves nothing
behind.

Tests: 158 -> 175.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:29:53 +02:00
Thomas KarnerandClaude Opus 5 269a6eadcb Add GET /firmware/{version}.bin, and fix test teardown (Phase 2)
The last device endpoint. With it, the whole firmware/API.md contract is
implemented apart from /stream, which is Phase 6.

The device checks three things before it erases a partition
(ota_mgr.cpp:110-128): status exactly 200, a Content-Length header at all -
it refuses chunked, because it wants to size-check first - and that length
equal to the size the envelope advertised. FileResponse gives an exact
length from the file, and the camera's :8080 Caddy block has no encode
directive, so nothing recompresses it on the way out.

A row whose file is missing, or whose file does not match its recorded size,
is 503 with a loud log rather than a quiet 404. The device would abort on the
Content-Length check anyway; failing here turns a confusing remote abort into
one clear server line.

A test walks the whole OTA handshake: heartbeat names a target, and the
relative URL it advertises is fetched the way ota_mgr builds it, base plus
url, and the bytes hash to the advertised sha256.

The admin-facing POST /firmware is not included. It needs user auth and an
admin role, neither of which exists yet (SEC-007).

Also fixes a real defect in the tests. Several put their cleanup at the end
of the test body, so a failing assertion skipped it. A deliberate mutation
made two tests fail, which left two is_target firmware rows behind, and
those rows then picked themselves as the OTA target for unrelated tests -
one broken thing looked like three. Teardown now lives in fixtures and runs
whatever happens. Re-running the same mutation now fails exactly the two
tests it should and leaves the database clean.

Tests: 148 -> 158.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:19:26 +02:00
Thomas KarnerandClaude Opus 5 6223d960c4 Add POST /api/v1/ingest (Phase 2)
Raw JPEG body with metadata in headers, which is API.md's deliberate
deviation from SPEC 4.1: multipart would make the device assemble a second
buffer purely to add a wrapper the server strips immediately. 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 drains the command queue.

api/images.py holds the storage helpers, with no imaging library. Reading
nine bytes of JPEG header for the dimensions beats decoding a frame on a
path that runs once per capture, and the same parse doubles as content
validation: the magic bytes decide whether this is a JPEG, not the
Content-Type header. Pillow belongs in the thumbnail worker, off the request
path, where the image has to be decoded anyway.

Ordering and failure:

  - The file is written first, through a temp file in the same directory and
    an atomic rename, so a half-written JPEG is never visible at its final
    path. The row is inserted second, and the file is removed if the commit
    fails. The reverse order would be worse: a row pointing at a missing
    image is a broken gallery entry, while a stray file is invisible and
    sweepable.
  - A body that is not a JPEG is 400, never 401, so the device does not read
    it as a credential problem and clear a good token. Unwritable storage is
    503, because from the device's side it is transient.
  - 12MB cap mirrors the Caddyfile, since a limit that only exists in the
    proxy is not a limit in development.

Identical bytes from the same device are treated as a retry and return the
original capture, with the command queue still attached. The device cannot
tell a lost response from a real failure, and two genuine frames never
collide - sensor noise alone makes every capture unique. Checked in the
application rather than with a unique constraint, so a freak collision loses
a frame instead of raising.

X-Captured-At: 0 means the clock is unsynced and is stored as NULL. An epoch
date would bury the frame at the bottom of every chronological view forever.
received_at stays authoritative either way (SPEC C7), and is what dates the
YYYY/MM/DD path.

NOT included, and deliberately: the thumbnail job. An unknown job kind is
failed immediately by the worker (worker/main.py:35), so enqueuing one now
would produce a failed job per capture. thumb_path stays NULL, which the
gallery has to handle regardless - a capture is visible when it lands, not
once it is processed. Thumbnails are the next unit of work and need Pillow.

Tests: 122 -> 148. Verified by disabling dedup and by removing the
captured-at-zero guard: the two corresponding tests fail, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:08:05 +02:00
Thomas KarnerandClaude Opus 5 46f54dbe81 Add POST /commands/{id}/ack, closing the command lifecycle (Phase 2)
/heartbeat hands commands out and marks them delivered; this is where the
device reports what became of one. The two halves stay separate 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
means "handed over", acked_at means "it ran", and the gap between them is
the operational signal worth having.

Three decisions:

- Scoped to the calling device, and a command belonging to someone else is
  404 rather than 403. Command ids are sequential, so a distinct status code
  would confirm that an id exists - and without the scope filter a device
  could close every other device's queue. Pinned by a test that also asserts
  the intruder did not manage to set acked_at.
- Re-acking is allowed and the last word wins. The device cannot tell a lost
  response from a lost request, so it retries; refusing the second attempt
  would strand a command that actually ran.
- An empty detail is stored as NULL. The firmware always sends the key,
  empty when it has nothing to say.

Liveness deliberately stays with /heartbeat, so the device list keeps one
source of truth for when a device was last heard from.

Tests: 109 -> 122, including the full queued -> delivered -> acked round
trip. Verified by removing the device scope from the lookup: the intruder
test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:57:18 +02:00
Thomas KarnerandClaude Opus 5 e83fc757d0 Add GET /api/v1/config (Phase 2)
Returns the device's settings document: the stored JSONB, plus the settings
that live in real columns, plus config_version last - mirroring
configApplyJson, which applies the version only after the rest of the payload
has been processed.

No response model, deliberately. 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: unknown
keys ignored, absent keys left alone, dangerous values clamped on the device
itself. Partial documents are the normal case, not a degraded one. Validating
this shape belongs on the write path, when the admin UI saves a config.

Unknown keys are passed through rather than filtered, so the admin UI can
push a new firmware tunable without waiting for the server to learn it.

Column-backed keys win over any stale copy of themselves in the JSONB. The
columns are the modelled source of truth, and a leftover key shadowing one
would mean a change to the column never reached the camera.

This also closes a loop left open at enrollment. Enrollment refuses to let a
device overwrite a rename made in the admin UI, which raised the fair
question of how the rename ever reaches the device. It reaches it here:
configApplyJson merges device_name like any other key (app_config.cpp:307).
The operator owns the name, the server pushes it down, and the device adopts
it - so the two decisions are consistent rather than merely defensible.

Named device_config.py so it does not read as poorbird.config. The route is
/config as specified.

Tests: 99 -> 109. Verified by letting the JSONB win over the columns: the
precedence test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:52:50 +02:00
Thomas KarnerandClaude Opus 5 5fd3c094a4 Add POST /heartbeat and POST /status, and the shared envelope (Phase 2)
One body, two endpoints. The firmware builds the conditions payload once, in
buildConditions, and posts it to both; they differ only in the response.

  /heartbeat -> 200 and the envelope: commands, config version, firmware
  /status    -> 204 and nothing

The split is not cosmetic and is now pinned by a test. The device posts
status immediately before deep sleep, so delivering commands there would mark
them delivered to a device about to be unable to run them.

api/envelope.py holds the shared builder, because /ingest returns the same
shape and parseEnvelope handles both with one function - they must not drift.

  - Commands are marked delivered when handed over, not on ack: the ack may
    never come, since the device runs reboot and sleep_now and is gone.
    acked_at stays the separate, later signal that it actually ran.
  - Expired commands are skipped but left in place, so the admin UI can show
    that a command timed out rather than silently losing it. The worker's
    prune job is what removes them.
  - The firmware URL is deliberately relative. ota_mgr.cpp:86 appends any
    non-http url 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.
  - Being on target means the firmware key is absent, not null: naming a
    different version is itself the instruction to flash (main.cpp:104).

Recording conditions appends a device_status row and refreshes the
denormalised columns on devices. Three details worth stating:

  - A field the device omits does not erase the last good value. None means
    not sent, not zero.
  - battery.valid false means NOT MEASURED and is stored as false, so the UI
    renders an em dash instead of inventing a low-battery alarm.
  - The device's reported config_version never overwrites the server's. The
    difference between them is exactly what tells the device to GET /config.

Tests: 77 -> 99. Verified by making /status build the envelope: the contract
test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:46:59 +02:00
Thomas KarnerandClaude Opus 5 bde67e9a41 Add POST /api/v1/enroll (Phase 2)
The first device endpoint, and the one every other endpoint depends on:
nothing else can authenticate until a device has a token.

Guarded by X-Enroll-Secret rather than a bearer token, accepting either the
shared bootstrap secret or the device's own re-enrollment secret. Issues a
token and a per-device re-enrollment secret, stores only their hashes, and
returns the plaintext exactly once.

Re-enrollment of a known device_uid returns the existing row with a fresh
token, never a duplicate (API.md). The firmware re-enrolls on any 401, so
this is the normal path by which a rotated token heals itself without
physical access to a mounted camera.

Two judgement calls, both marked in the code:

- A disabled device is refused 403 and its token is left alone. Otherwise
  disabling a device in the admin UI would achieve nothing, since it would
  collect a fresh token on its next 401.
- Hardware facts (mac, hw_revision, fw_version) follow the device on every
  enrollment, because it is the authority on what it is running. The name
  does not: it is set at first enrollment and is an operator label after
  that, so a re-enrollment must not silently undo a rename.

Status codes are chosen for how the firmware reacts, not just for
correctness: 401 makes it clear its token and retry, so a misconfigured
server returns 503 and a contended write returns 503, never 4xx.

Tests: 57 -> 77. Verified by reintroducing the REVIEW.AI.md bug of returning
token_hash instead of the token: three tests fail, including the round trip
that feeds the issued token back through verify_device_token.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:37:31 +02:00
Thomas KarnerandClaude Opus 5 8cf2329762 Move reviews to docs/reviews/<scope>/ so branches stop colliding
The review documents are branch-scoped snapshots pinned to a commit, not
living documentation of the directory they sit in. Kept at a fixed path,
every reviewed branch writes the same two filenames with different content.

Merging the two feature branches produced exactly that:

  CONFLICT (add/add): server/REVIEW.AI.md
  CONFLICT (add/add): server/REVIEW.md

Neither blob is an ancestor of the other, so git cannot resolve it, and it
would recur on every future review. The same fixed path also caused the
review OF the UI branch to live under server/, which reads as server
documentation and is how it got cherry-picked onto the wrong branch once
already.

One directory per reviewed scope fixes both. The filenames stay REVIEW.md and
REVIEW.AI.md, so existing references in the code still resolve. A merge probe
against feature/UI_Basic_implementation is now clean.

docs/reviews/README.md records the convention, how to read a snapshot whose
commit is behind the tip, and why not to copy a review between branches.

feature/UI_Basic_implementation still holds its review at server/REVIEW*.md.
That no longer conflicts, but it is still the misleading path and wants the
same move.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:31:41 +02:00
Thomas KarnerandClaude Opus 5 8038060578 Device auth and request validation (REVIEW SEC-002, SEC-003)
The plumbing every Phase 2 endpoint needs, before any endpoint exists.

api/schemas.py: Pydantic models for the whole device contract - enrollment,
the shared /ingest + /heartbeat envelope, the conditions body and command
acks. Enums are imported from the models, so a schema cannot drift from the
CHECK constraint that backs it.

api/deps.py: credential generation, hashing and bearer resolution.

Written against firmware/API.md and, where prose and code disagree, against
firmware/src/api_client.cpp. Four places where REVIEW.AI.md's reference code
would not have worked:

- Its /enroll returns devices.token_hash to the device. The device would then
  present the hash, the server would hash it again, and every request after
  enrollment would 401. Plaintext goes back once, only the hash is stored.
- It checks only the shared bootstrap secret on re-enrollment. The firmware
  swaps that for a per-device reenroll_secret after first enrollment, so that
  check would lock out every device that had ever succeeded - the exact
  failure the re-enrollment path exists to prevent.
- Its /ingest is multipart. API.md deviates from SPEC 4.1 deliberately: the
  body is the raw JPEG and metadata rides in headers, so the device does not
  assemble a second buffer. Modelled as IngestMeta.
- It uses secrets.token_urlsafe(32) - 43 non-hex chars. API.md says 64 hex,
  and the firmware's char[65] buffers make that exact. token_hex(32) it is.

capture_id is documented as an int but captures.id is a UUID. parseEnvelope
never reads the field, so it is sent as a UUID string.

The conditions models accept unknown keys on purpose: firmware grows fields
before the server learns them, device_status.raw keeps the whole body, and a
422 would take a camera offline for reporting something new.

devices.token_hash is now indexed and unique - it is resolved on every
authenticated request, and two devices must never share a token. No migration:
the live database already had exactly this index, so the model had drifted
from it. 'alembic check' is clean.

Tests: 17 -> 57.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:23:56 +02:00
Thomas KarnerandClaude Opus 5 3344a9e9b1 Harden config: no credentials in code (REVIEW SEC-001, SEC-006)
SEC-006: database_url had a working default carrying a real username and
password. Removed. Absence is now reported by 'poorbird check' as a problem
(exit 1) and raised by db.py with a message that names the variable and the
example file, instead of SQLAlchemy's "Could not parse URL from string ''"
three frames down.

SEC-001: enroll_secret stays environment-only and keeps its empty default so
the Phase 1 commands still run on a fresh clone. The device endpoints will
refuse to serve without it when they land.

Both fields now reject unedited placeholders (CHANGE_ME and friends), so a
copied .example cannot boot as though it were configured.

Tests: 12 -> 17. New cases cover the absent default, the readable failure,
and placeholder rejection for both fields.

Note: 6 files unrelated to this change are not clean under 'ruff format'
(the repo is wrapped at 88, pyproject sets line-length 100). Left alone to
keep this diff reviewable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:11:34 +02:00
Thomas KarnerandClaude Opus 5 2188bed633 Add root .gitignore and untrack web/ build output
web/ held only node_modules (4267 files) and dist/ - no source. It was
committed accidentally in 142b476, which was labelled "Server: Phase 2"
but touched nothing under server/. The UI source lives on
feature/UI_Basic_implementation.

Files stay on disk; only the index changes. The root .gitignore also adds
a repo-wide .env safety net so credentials cannot be committed once the
config defaults are removed (SEC-001, SEC-006).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:05:14 +02:00
Thomas Karner 142b47674d Server: Phase 2 (REVIEW not respected yet) 2026-09-21 11:24:43 +02:00
Thomas KarnerandClaude Opus 5 384b09371a UI: scaffold the web app - shell, themes, i18n, auth plumbing
React 19 + TypeScript + Vite + TanStack Query/Router in web/, built on the
dev machine and shipped as static files (SPEC section 6). Typechecks and
builds clean; the System page reads live /health through the Vite proxy,
which proves browser -> proxy -> FastAPI -> PostgreSQL end to end.

Themes: light, dark and blue (dark navy), as design tokens on data-theme.
An inline script applies the stored theme before first paint. No colour
literal lives outside tokens.css.

check-contrast.mjs asserts WCAG AA for every text/background pair in every
theme, with no dependencies. It failed on its first run and found three
--border-strong values below the 3:1 that WCAG 1.4.11 wants for interactive
boundaries; all three are fixed and 36 pairs now pass. Colour contrast is
the classic silently-regressing property, so it gets a test rather than a
promise.

i18n is hand-written and typed rather than react-i18next: en.ts defines the
key set, de.ts is typed against it, so a missing German string fails the
build instead of quietly showing English to a German user.

Authentication is built but NOT enforced, deliberately. /auth/session,
/auth/login and /auth/logout do not exist yet, so router.tsx does not wrap
routes in RequireAuth and a banner says so plainly. There is no development
bypass: a bypass that works is the kind of code that survives into
production, and an auth bypass that works is the worst possible bug.

Gallery and Devices render honest empty states rather than mock rows. Fake
data hides the layout problems real data exposes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 01:17:07 +02:00
Thomas KarnerandClaude Opus 5 5a098e44d8 UI: record decisions for language, theme, 2FA, stack and seed data
Closes SPEC section 10 questions 11, 13, 14 and 16 in a new TODO 3.0.

- Language: de + en from the first component. No user-facing string
  literal in a component, ever.
- Theme "blue" is a dark navy; token table recorded. Contrast still has
  to be measured against WCAG AA rather than assumed.
- 2FA: build TOTP now, optional per user, enforced for admin. "The UI
  does not need it" and "I need outside access" describe the same
  surface; what differs is whether the path is Tailscale or a public
  domain. Retrofitting it later reopens login, sessions, the user model
  and the audit log at once.
- Stack stays React + TypeScript, with the no-TS-experience starting
  point treated as a real constraint on how it gets written. Jinja2 +
  HTMX stays a valid fallback and the API does not change.
- Placeholder captures are generated by a seed command, not downloaded:
  no licensing question, no binaries in git, and it can produce the
  volume the virtualised grid needs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 00:59:16 +02:00
Thomas KarnerandClaude Opus 5 5d16ded553 Server: verify Phase 1 end to end against PostgreSQL 17
Set up the dev environment (uv-managed CPython 3.14.7, postgres:17 in a
Podman container) and ran the skeleton for real: migrations apply, the
API serves /api/v1/health and /healthz, the worker claims a job and
drains it, 12/12 tests pass with nothing skipped.

The schema-drift test failed on its first real run and found a genuine
problem: Postgres reflects a varchar default as 'x'::character varying
while the model renders 'x', so all ten string defaults read as
permanent drift. Left alone that is the failure mode where you learn to
ignore the test and then miss the one real change. Add schema_compare.py,
a normaliser shared by migrations/env.py and the test so autogenerate and
the test can never disagree about what counts as a difference. A real
default change still fails it.

Also: ruff import-order fix in captures.py, and the README gains the
uv + Podman dev setup, the expected test count, and the CREATE DATABASE
privilege the drift test needs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 00:30:52 +02:00
Thomas Karner 8a51e3d95e Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090) 2026-09-20 23:49:40 +02:00
Thomas Karner 3694cdf207 dev: re-create TODO.md; Dockerization in mind but postponed 2026-09-20 23:26:51 +02:00
Thomas Karner e191f59f6f remove oboslete TODOs 2026-09-20 22:53:45 +02:00
Thomas Karner 6bda641ce8 ESP: first implementation; compiles fine; not tested with MCU 2026-09-20 18:55:26 +02:00