// Package api exposes the HTTP ingest and query endpoints. package api import ( "context" "encoding/json" "errors" "io" "log/slog" "net/http" "strconv" "strings" "time" "github.com/jackc/pgx/v5/pgconn" "ccp/internal/auth" "ccp/internal/ingest" "ccp/internal/store" "ccp/internal/summary" "ccp/internal/web" ) const maxEventBody = 5 << 20 // 5 MiB type Server struct { store *store.Store admin auth.Checker loc *time.Location log *slog.Logger now func() time.Time } // New builds the HTTP handler. Collectors authenticate with per-device bearer // keys; the dashboard pages and the routes behind them need the main site's // admin session, which admin checks. func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logger) http.Handler { srv := &Server{store: s, admin: admin, loc: loc, log: log, now: time.Now} mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) }) mux.HandleFunc("GET /readyz", srv.ready) mux.HandleFunc("GET /tracker.user.js", web.UserScript) mux.Handle("GET /assets/", web.Assets()) // The Vue app's routes; it sends visitors between them itself. mux.Handle("GET /{$}", srv.adminPage(http.HandlerFunc(web.App))) mux.Handle("GET /setup", srv.adminPage(http.HandlerFunc(web.App))) api := http.NewServeMux() api.Handle("POST /desktop/events", srv.device(srv.ingestEvents(ingest.Desktop))) api.Handle("POST /browser/events", srv.device(srv.ingestEvents(ingest.Browser))) api.Handle("POST /presence/events", srv.device(srv.ingestEvents(ingest.Presence))) api.Handle("POST /manual/events", srv.device(srv.ingestEvents(ingest.Manual))) api.Handle("POST /location/{event}", srv.device(http.HandlerFunc(srv.ingestLocation))) api.Handle("POST /location/{event}/{place}", srv.device(http.HandlerFunc(srv.ingestLocation))) api.Handle("GET /activities", srv.deviceOrAdmin(http.HandlerFunc(srv.activities))) api.Handle("GET /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary))) api.Handle("GET /devices", srv.adminAPI(http.HandlerFunc(srv.listDevices))) api.Handle("POST /devices", srv.adminAPI(http.HandlerFunc(srv.createDevice))) api.Handle("DELETE /devices/{name}", srv.adminAPI(http.HandlerFunc(srv.revokeDevice))) mux.Handle("/api/v1/", http.StripPrefix("/api/v1", api)) return srv.logRequests(mux) } // ---- middleware ---- type ctxKey struct{} func deviceFrom(ctx context.Context) store.Device { d, _ := ctx.Value(ctxKey{}).(store.Device) return d } // device requires a collector's bearer key and records its device on the // context, since ingested rows belong to a device. func (s *Server) device(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok || key == "" { writeError(w, http.StatusUnauthorized, "missing bearer token") return } dev, err := s.store.DeviceByKey(r.Context(), key) if errors.Is(err, store.ErrNotFound) { writeError(w, http.StatusUnauthorized, "invalid api key") return } if err != nil { s.internalError(w, r, err) return } next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, dev))) }) } // deviceOrAdmin admits a bearer key, or without one the site's admin session. func (s *Server) deviceOrAdmin(next http.Handler) http.Handler { withKey := s.device(next) withSession := s.adminAPI(next) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "" { withKey.ServeHTTP(w, r) } else { withSession.ServeHTTP(w, r) } }) } func (s *Server) adminAPI(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !s.admin.IsAdmin(w, r) { writeError(w, http.StatusUnauthorized, "admin access required") return } next.ServeHTTP(w, r) }) } // adminPage sends visitors without the site's admin session to its login // page, which returns them here afterwards. The redirect is made in the // browser because only it knows the /tracker/ prefix nginx strips. func (s *Server) adminPage(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !s.admin.IsAdmin(w, r) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(http.StatusUnauthorized) w.Write(web.LoginRedirect) return } next.ServeHTTP(w, r) }) } type statusRecorder struct { http.ResponseWriter status int } func (r *statusRecorder) WriteHeader(code int) { r.status = code r.ResponseWriter.WriteHeader(code) } func (s *Server) logRequests(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(rec, r) if r.URL.Path == "/healthz" || r.URL.Path == "/readyz" { return } s.log.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status, "duration", time.Since(start)) }) } // ---- handlers ---- func (s *Server) ready(w http.ResponseWriter, r *http.Request) { if err := s.store.Ping(r.Context()); err != nil { writeError(w, http.StatusServiceUnavailable, "database unavailable") return } writeJSON(w, http.StatusOK, map[string]string{"status": "ready"}) } type ingestResult struct { Received int `json:"received"` Inserted int64 `json:"inserted"` } func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var b ingest.Batch if !s.decode(w, r, maxEventBody, &b) { return } acts, err := spec.Normalize(b, s.now()) if err != nil { writeError(w, http.StatusUnprocessableEntity, err.Error()) return } n, err := s.store.InsertActivities(r.Context(), deviceFrom(r.Context()).ID, acts) if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, ingestResult{Received: len(acts), Inserted: n}) } } // ingestLocation takes an arrive or leave from a phone geofence automation. // The place comes from the path (/arrive/gym), ?place=, the body's "place", // or defaults to home. ingest.Destination decides where the device ends up. func (s *Server) ingestLocation(w http.ResponseWriter, r *http.Request) { event := r.PathValue("event") if event != "arrive" && event != "leave" { writeError(w, http.StatusNotFound, "event must be arrive or leave") return } var e ingest.LocationEvent r.Body = http.MaxBytesReader(w, r.Body, 4<<10) if err := json.NewDecoder(r.Body).Decode(&e); err != nil && !errors.Is(err, io.EOF) { writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) return } // A path or ?place= is easier to set up in Shortcuts than a JSON body. if p := r.URL.Query().Get("place"); p != "" { e.Place = p } if p := r.PathValue("place"); p != "" { e.Place = p } e, err := ingest.NormalizeLocation(e, s.now()) if err != nil { writeError(w, http.StatusUnprocessableEntity, err.Error()) return } place, changed, err := s.store.MoveTo(r.Context(), deviceFrom(r.Context()).ID, e.At, func(cur string) string { return ingest.Destination(event, e.Place, cur) }) if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, map[string]any{"place": place, "changed": changed}) } func (s *Server) activities(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() now := s.now() f := store.ActivityFilter{ From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Kind: q.Get("kind"), Limit: 1000, } var err error if v := q.Get("from"); v != "" { if f.From, err = time.Parse(time.RFC3339, v); err != nil { writeError(w, http.StatusBadRequest, "from must be RFC3339") return } } if v := q.Get("to"); v != "" { if f.To, err = time.Parse(time.RFC3339, v); err != nil { writeError(w, http.StatusBadRequest, "to must be RFC3339") return } } if v := q.Get("limit"); v != "" { if f.Limit, err = strconv.Atoi(v); err != nil || f.Limit < 1 || f.Limit > 10000 { writeError(w, http.StatusBadRequest, "limit must be 1-10000") return } } acts, err := s.store.Activities(r.Context(), f) if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, map[string]any{"activities": acts}) } func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) { day := s.now().In(s.loc) if v := r.URL.Query().Get("date"); v != "" { var err error if day, err = time.ParseInLocation(time.DateOnly, v, s.loc); err != nil { writeError(w, http.StatusBadRequest, "date must be YYYY-MM-DD") return } } from, to := summary.DayBounds(day, s.loc) totals, err := s.store.Totals(r.Context(), from, to) if err != nil { s.internalError(w, r, err) return } goals, err := s.store.Goals(r.Context()) if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, summary.Build(from.Format(time.DateOnly), from, to, totals, goals)) } func (s *Server) listDevices(w http.ResponseWriter, r *http.Request) { devs, err := s.store.ListDevices(r.Context()) if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, map[string]any{"devices": devs}) } // createDevice registers a collector and returns its API key, the only time // the key is ever shown. func (s *Server) createDevice(w http.ResponseWriter, r *http.Request) { var req struct { Name string `json:"name"` Kind string `json:"kind"` } if !s.decode(w, r, 4<<10, &req) { return } req.Name, req.Kind = strings.TrimSpace(req.Name), strings.TrimSpace(req.Kind) if req.Name == "" || req.Kind == "" { writeError(w, http.StatusBadRequest, "name and kind are required") return } dev, key, err := s.store.CreateDevice(r.Context(), req.Name, req.Kind) var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.Code == "23505" { writeError(w, http.StatusConflict, "a device with that name already exists") return } if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, map[string]any{"device": dev, "key": key}) } func (s *Server) revokeDevice(w http.ResponseWriter, r *http.Request) { err := s.store.RevokeDevice(r.Context(), r.PathValue("name")) if errors.Is(err, store.ErrNotFound) { writeError(w, http.StatusNotFound, "no active device with that name") return } if err != nil { s.internalError(w, r, err) return } writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"}) } // ---- helpers ---- func (s *Server) decode(w http.ResponseWriter, r *http.Request, limit int64, v any) bool { r.Body = http.MaxBytesReader(w, r.Body, limit) if err := json.NewDecoder(r.Body).Decode(v); err != nil { var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { writeError(w, http.StatusRequestEntityTooLarge, "request body too large") } else { writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) } return false } return true } func (s *Server) internalError(w http.ResponseWriter, r *http.Request, err error) { s.log.Error("request failed", "path", r.URL.Path, "err", err) writeError(w, http.StatusInternalServerError, "internal error") } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(v) } func writeError(w http.ResponseWriter, status int, msg string) { writeJSON(w, status, map[string]string{"error": msg}) }