Gate the dashboard on the site's admin login and add a setup page
Test and publish / test (push) Successful in 25s
Test and publish / publish (push) Successful in 3m1s

Like job-tracker, the tracker forwards the visitor's cookies to the site
backend's /auth/validate-admin instead of asking for an API key. Signed
in, the dashboard shows every device's data. The new /setup page has
instructions for each collector and creates and revokes API keys. The
userscript is served publicly at /tracker.user.js.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 21:22:02 +01:00
co-authored by Claude Opus 5.5
parent 67082226cc
commit e6a93be15c
13 changed files with 650 additions and 79 deletions
+115 -12
View File
@@ -11,6 +11,9 @@ import (
"strings"
"time"
"github.com/jackc/pgx/v5/pgconn"
"ccp/internal/auth"
"ccp/internal/ingest"
"ccp/internal/store"
"ccp/internal/summary"
@@ -24,30 +27,39 @@ const (
type Server struct {
store *store.Store
admin auth.Checker
loc *time.Location
log *slog.Logger
now func() time.Time
}
func New(s *store.Store, loc *time.Location, log *slog.Logger) http.Handler {
srv := &Server{store: s, loc: loc, log: log, now: time.Now}
// 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 /{$}", web.Handler)
mux.HandleFunc("GET /tracker.user.js", web.UserScript)
mux.Handle("GET /{$}", srv.adminPage(web.Page(web.Index)))
mux.Handle("GET /setup", srv.adminPage(web.Page(web.Setup)))
api := http.NewServeMux()
api.HandleFunc("POST /desktop/events", srv.ingestEvents(ingest.Desktop))
api.HandleFunc("POST /browser/events", srv.ingestEvents(ingest.Browser))
api.HandleFunc("POST /presence/events", srv.ingestEvents(ingest.Presence))
api.HandleFunc("POST /manual/events", srv.ingestEvents(ingest.Manual))
api.HandleFunc("POST /health/hae", srv.ingestHAE)
api.HandleFunc("GET /activities", srv.activities)
api.HandleFunc("GET /summary/daily", srv.dailySummary)
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", srv.auth(api)))
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 /health/hae", srv.device(http.HandlerFunc(srv.ingestHAE)))
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)
}
@@ -61,7 +73,9 @@ func deviceFrom(ctx context.Context) store.Device {
return d
}
func (s *Server) auth(next http.Handler) http.Handler {
// 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 == "" {
@@ -81,6 +95,45 @@ func (s *Server) auth(next http.Handler) http.Handler {
})
}
// 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
@@ -226,6 +279,56 @@ func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) {
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 {