/* The one place that talks to the server. * * Same-origin by design: in development Vite proxies /api to port 8090, in * production Caddy serves this bundle and the API from the same hostname. * That means session cookies behave identically in both, and there is no CORS * configuration anywhere. */ export class ApiError extends Error { readonly status: number; readonly body: unknown; constructor(status: number, message: string, body: unknown) { super(message); this.name = "ApiError"; this.status = status; this.body = body; } /** True when the endpoint is simply not built yet (Phase 2 / Phase 3). */ get isMissingEndpoint(): boolean { return this.status === 404; } } /* CSRF, the browser half. * * The server sets `poorbird_csrf` as a readable cookie alongside the HttpOnly * session cookie, and requires this header to match the token on the session * row for every mutating request. Reading a cookie is exactly what an attacker * on another origin cannot do, which is what makes echoing it meaningful. * * Deliberately read fresh on each call rather than cached: signing out and back * in issues a new token, and a stale one in a module variable would produce a * 403 that looks like a server bug. */ const CSRF_COOKIE = "poorbird_csrf"; /** Methods the server requires a CSRF token for. Must match UNSAFE_METHODS. */ const UNSAFE = new Set(["POST", "PUT", "PATCH", "DELETE"]); function csrfToken(): string | null { // document.cookie is a flat "a=1; b=2" string; there is no read API for one // cookie. Split rather than regex so a token containing no special // characters cannot be mangled by an over-clever pattern. for (const part of document.cookie.split("; ")) { const eq = part.indexOf("="); if (eq > 0 && part.slice(0, eq) === CSRF_COOKIE) { return decodeURIComponent(part.slice(eq + 1)); } } return null; } async function request(path: string, init?: RequestInit): Promise { const method = (init?.method ?? "GET").toUpperCase(); const csrf = UNSAFE.has(method) ? csrfToken() : null; let response: Response; try { response = await fetch(`/api/v1${path}`, { // `...init` FIRST, then the values that must win. It used to come last, // which meant a caller passing any headers at all replaced this whole // object rather than merging into it -- so apiPost, which always sets // Content-Type, was silently dropping Accept. Harmless then. Not // harmless now: it would have dropped the CSRF header on exactly the // mutating requests that require one, and every POST would answer 403. ...init, credentials: "same-origin", headers: { Accept: "application/json", // Omitted when there is no cookie, which is the case for the very // first request of all: logging in. The server exempts it for the // same reason -- there is no session to protect yet. ...(csrf === null ? {} : { "X-CSRF-Token": csrf }), ...init?.headers, }, }); } catch (cause) { // fetch only rejects on a network-level failure: server down, DNS, CORS. throw new ApiError(0, `Cannot reach the server: ${String(cause)}`, null); } const text = await response.text(); let body: unknown = null; if (text.length > 0) { try { body = JSON.parse(text); } catch { body = text; } } if (!response.ok) { throw new ApiError(response.status, `${response.status} ${response.statusText}`, body); } return body as T; } export function apiGet(path: string): Promise { return request(path); } export function apiPost(path: string, payload?: unknown): Promise { return request(path, { method: "POST", headers: payload === undefined ? {} : { "Content-Type": "application/json" }, body: payload === undefined ? undefined : JSON.stringify(payload), }); } /* --- response types --------------------------------------------------- * These mirror the server. Keep them in step with the FastAPI handlers; * generating them from /openapi.json is a worthwhile upgrade once there are * more than a handful. */ export interface HealthResponse { status: "ok" | "degraded"; version: string; uptime_s: number; database: { ok: boolean; error: string | null; devices?: number; captures?: number; last_backup_at?: string | null; }; disk: { available: boolean; path: string; total_bytes?: number; free_bytes?: number; used_pct?: number | null; }; enroll_secret_configured: boolean; } export function getHealth(): Promise { return apiGet("/health"); } /* --- gallery ---------------------------------------------------------- */ export interface CaptureSummary { id: string; device_id: number; /** Server time, and authoritative (SPEC C7). Always present. */ received_at: string; /** Null when the camera's clock was unsynced. Never render it as 1970. */ captured_at_device: string | null; width: number | null; height: number | null; bytes: number; trigger: "radar" | "manual" | "timer" | "stream_grab"; pre_trigger: boolean; burst_id: string | null; burst_index: number | null; burst_count: number | null; reviewed: boolean; kept: boolean; /** False while the thumbnail job is queued, or forever if it cannot decode. */ has_thumb: boolean; } export interface CapturePage { items: CaptureSummary[]; /** Null at the end. Opaque -- pass it back, do not parse it. */ next_cursor: string | null; } export interface TagOut { id: number; label: string; colour: string | null; } export interface TaxonOut { id: number; scientific_name: string; name_de: string | null; name_en: string | null; } export interface ObservationOut { id: number; taxon: TaxonOut | null; individuals: number; age: string; sex: string; behaviour: string | null; certainty: string; notes: string | null; /** "model" is a prediction. Never present one as a human label. */ source: "human" | "model"; confidence: number | null; } export interface CaptureDetail extends CaptureSummary { device_name: string; sha256: string; radar_state: number | null; radar_distance_cm: number | null; radar_energy: number | null; battery_mv: number | null; rssi: number | null; temp_c: number | null; frame_seq: number | null; observations: ObservationOut[]; tags: TagOut[]; } export interface CaptureFilters { device_id?: number; received_from?: string; received_to?: string; kept?: boolean; reviewed?: boolean; pre_trigger?: boolean; trigger?: string; } export function listCaptures( filters: CaptureFilters, cursor: string | null, limit = 60 ): Promise { // URLSearchParams, not string concatenation: an ISO timestamp ends in // "+00:00" and a raw "+" in a query string means a space, so the server // would answer 422 for a date it could otherwise have parsed. const params = new URLSearchParams({ limit: String(limit) }); if (cursor !== null) params.set("cursor", cursor); for (const [key, value] of Object.entries(filters)) { // A tri-state filter is absent when undefined, and `false` is a real // value -- so this cannot be a truthiness check. if (value !== undefined) params.set(key, String(value)); } return apiGet(`/captures?${params.toString()}`); } export function getCapture(id: string): Promise { return apiGet(`/captures/${id}`); } /* Image URLs are built here rather than sent by the server, because this * module is already the one place that knows the API prefix. They go straight * into , so they are paths from the site root, and the session cookie * rides along because it is same-origin. */ export function thumbUrl(id: string): string { return `/api/v1/captures/${id}/thumb`; } export function imageUrl(id: string): string { return `/api/v1/captures/${id}/image`; }