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>
1302 lines
47 KiB
Markdown
1302 lines
47 KiB
Markdown
# 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/<uuid>.jpg`
|
|
- **Thumb Pattern:** `/thumbs/<uuid>_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/<id> |
|
|
| **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 <value>
|
|
|
|
# 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.*
|