From e6a93be15cca731fffb3696d4ba8aea66014a8ac Mon Sep 17 00:00:00 2001 From: Adam French Date: Wed, 14 Oct 2026 21:22:02 +0100 Subject: [PATCH] Gate the dashboard on the site's admin login and add a setup page 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 --- Makefile | 2 +- README.md | 67 ++++++++---- cmd/tracker/main.go | 9 +- deploy/docker-compose.yml | 3 + internal/api/api.go | 127 +++++++++++++++++++--- internal/api/api_test.go | 3 +- internal/auth/auth.go | 117 ++++++++++++++++++++ internal/auth/auth_test.go | 63 +++++++++++ internal/config/config.go | 18 ++++ internal/web/index.html | 44 ++------ internal/web/login.html | 25 +++++ internal/web/setup.html | 215 +++++++++++++++++++++++++++++++++++++ internal/web/web.go | 36 +++++-- 13 files changed, 650 insertions(+), 79 deletions(-) create mode 100644 internal/auth/auth.go create mode 100644 internal/auth/auth_test.go create mode 100644 internal/web/login.html create mode 100644 internal/web/setup.html diff --git a/Makefile b/Makefile index d7e94e5..5c69c96 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,7 @@ test-integration: TEST_DATABASE_URL='$(DEV_DB)' go test -count=1 ./... run: - DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve + AUTH_MODE=dev DEV_MODE=true DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve up: $(COMPOSE) up -d --build diff --git a/README.md b/README.md index c314fc8..75966fb 100644 --- a/README.md +++ b/README.md @@ -17,14 +17,14 @@ Every source is stored as an interval in a single `activities` table, with colum |---|---| | Hyprland (`cmd/hypr-agent`) | ✅ built | | Apple Health (Health Auto Export → `/health/hae`) | ✅ endpoint built; configure the app | -| Browser extension (`/browser/events`) | endpoint ready, extension not yet written | +| Browser (Violentmonkey userscript, `/tracker.user.js`) | ✅ built | | Webcam presence (`/presence/events`) | endpoint ready, agent not yet written | | AI analysis (`reports` table) | planned | ## Running the server ```sh -make up # builds the image and starts tracker + a dev Postgres on :8080 / :5432 +make up # builds the image and starts tracker + a dev Postgres on :8080 / :5432 (AUTH_MODE=dev: no login) curl localhost:8080/readyz ``` @@ -44,6 +44,8 @@ docker run -d -p 8080:8080 \ | `LISTEN_ADDR` | `:8080` | | | `AUTO_MIGRATE` | `true` | Apply migrations on startup. Set it to false to run `tracker migrate` yourself | | `TRACKER_TZ` | `UTC` | Timezone that defines "a day" in summaries | +| `AUTH_MODE` | `forward` | `forward` gates the dashboard on the main site's admin login (see [Dashboard and auth](#dashboard-and-auth)). `dev` admits everyone and requires `DEV_MODE=true` | +| `AUTH_VALIDATE_URL` | `http://backend:8080/auth/validate-admin` | The site backend's admin check | Put the service behind your reverse proxy (Caddy, Traefik and so on) for TLS, because API keys are sent as bearer tokens. @@ -75,21 +77,34 @@ tracker goal list tracker goal rm --id 2 ``` +## Dashboard and auth + +The dashboard (`/`) and the setup page (`/setup`) have no login of their own. As in job-tracker, the tracker borrows the main site's session. It forwards the browser's cookies to the site backend's `GET /auth/validate-admin` and treats a 2xx as admin (`internal/auth`). A visitor who isn't signed in is sent to the site's `/admin/login?redirect=/tracker/`, which returns them afterwards. A "yes" is cached for 30 seconds per cookie, so signing out takes up to 30 seconds to reach the tracker. If the backend refreshes an expired token, its new cookies are passed back to the browser. + +Signed in, the dashboard shows every device's data without asking for a key. The setup page has step-by-step instructions for each collector, with your server URL filled in. It also lists devices and creates and revokes their API keys, so you don't need `docker exec` for keys. + +Collectors never use the site login. Each one sends its own bearer key. + ## API -All `/api/v1` routes require `Authorization: Bearer `. +| Auth | Meaning | +|---|---| +| key | `Authorization: Bearer ` from `tracker apikey create` or the setup page | +| admin | the main site's admin session cookies | -| Method | Path | Accepted kinds | -|---|---|---| -| POST | `/api/v1/desktop/events` | `app_focus`, `idle`, `locked` | -| POST | `/api/v1/browser/events` | `tab_focus`, `idle` | -| POST | `/api/v1/presence/events` | `at_desk`, `in_bed`, `away` | -| POST | `/api/v1/manual/events` | any | -| POST | `/api/v1/health/hae` | Health Auto Export JSON. Workouts and sleep become activities; other metrics become samples | -| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=` | RFC3339 times; defaults to the last 24h | -| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | totals per label and kind, plus goal results | -| GET | `/healthz`, `/readyz` | no auth | -| GET | `/` | dashboard page; enter any API key to view a day's goals, totals and timeline | +| Method | Path | Auth | Accepted kinds | +|---|---|---|---| +| POST | `/api/v1/desktop/events` | key | `app_focus`, `idle`, `locked` | +| POST | `/api/v1/browser/events` | key | `tab_focus`, `idle` | +| POST | `/api/v1/presence/events` | key | `at_desk`, `in_bed`, `away` | +| POST | `/api/v1/manual/events` | key | any | +| POST | `/api/v1/health/hae` | key | Health Auto Export JSON. Workouts and sleep become activities; other metrics become samples | +| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=` | key or admin | RFC3339 times; defaults to the last 24h | +| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results | +| GET, POST | `/api/v1/devices` | admin | list devices; create one with `{"name","kind"}`, which returns its key once | +| DELETE | `/api/v1/devices/{name}` | admin | revoke a device's key | +| GET | `/`, `/setup` | admin | dashboard and setup pages | +| GET | `/tracker.user.js`, `/healthz`, `/readyz` | none | the browser userscript holds no secrets | The event batch format is shared by all `*/events` endpoints. A batch holds at most 1000 events. @@ -136,6 +151,19 @@ listener { } ``` +## Browser + +The browser collector is a [Violentmonkey](https://violentmonkey.github.io/) userscript served by the tracker itself. It runs in every tab and records a `tab_focus` interval, labelled with the hostname (`www.` stripped, so goals use `youtube.com`), only while that tab is the selected tab of the focused browser window. Focus that lasts under 2s is dropped. The interval ends after 5 minutes without mouse or keyboard input, unless a video or audio element is playing. Time spent asleep or suspended is never counted. + +The setup page has these steps with your URL filled in. + +1. Create a key with kind `browser` on the setup page, or with `tracker apikey create --name laptop-firefox --kind browser`. Use one key per browser. +2. Install Violentmonkey and open `https://www.adam-french.co.uk/tracker/tracker.user.js`. Violentmonkey offers to install the script and later checks that URL for updates. +3. From the Violentmonkey toolbar menu, choose **Set server and API key**. Enter `https://www.adam-french.co.uk/tracker` and the key. +4. Other menu commands toggle full URLs (`attrs.url`, which also splits intervals per page) and page titles (`attrs.title`), set a regexp of hosts to ignore, change the idle timeout, and show the queue and last upload result. + +Closed intervals are queued in the script's storage and uploaded every minute by one tab at a time. If a tab is closed or crashes mid-interval, another tab recovers its last checkpoint (at most 5s lost). The script can't see browser pages such as `about:`, `chrome://` or the new tab page, extension stores, or the built-in PDF viewer, so time there isn't recorded. The Hyprland agent still counts it as browser `app_focus`. + ## Apple Health In the Health Auto Export iOS app, create a **REST API** automation with these settings: @@ -155,12 +183,11 @@ make up && make test-integration # also runs the API tests against the compose make run # run the server locally against the compose Postgres ``` -Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,ingest,store,summary,migrations,config}`, `internal/agent/hypr`, `deploy/`. +Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,auth,ingest,store,summary,migrations,config,web}` (`web/tracker.user.js` is the browser collector), `internal/agent/hypr`, `deploy/`. ## Roadmap -1. Browser extension (MV3, Firefox and Chromium). It will send hostnames by default and full URLs only if you opt in. -2. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine. -3. Nudges: push notifications through ntfy when a goal is at risk during the day. -4. Location: an OwnTracks or Home Assistant geofence will provide reliable "time outside" intervals. -5. AI analysis: a nightly or weekly job will send the daily summaries (not raw rows) to the Claude API and store the result in `reports`. +1. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine. +2. Nudges: push notifications through ntfy when a goal is at risk during the day. +3. Location: an OwnTracks or Home Assistant geofence will provide reliable "time outside" intervals. +4. AI analysis: a nightly or weekly job will send the daily summaries (not raw rows) to the Claude API and store the result in `reports`. diff --git a/cmd/tracker/main.go b/cmd/tracker/main.go index 273bf9e..aaa6aac 100644 --- a/cmd/tracker/main.go +++ b/cmd/tracker/main.go @@ -20,6 +20,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "ccp/internal/api" + "ccp/internal/auth" "ccp/internal/config" "ccp/internal/migrations" "ccp/internal/store" @@ -96,9 +97,15 @@ func serve(ctx context.Context, cfg config.Config, pool *pgxpool.Pool, st *store log.Info("migrations applied") } + var checker auth.Checker = auth.NewForward(cfg.AuthValidateURL, log) + if cfg.AuthMode == "dev" { + log.Warn("AUTH_MODE=dev: every visitor is treated as the admin") + checker = auth.AllowAll{} + } + srv := &http.Server{ Addr: cfg.ListenAddr, - Handler: api.New(st, cfg.Location, log), + Handler: api.New(st, checker, cfg.Location, log), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 60 * time.Second, WriteTimeout: 60 * time.Second, diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 4ba70fb..da72fec 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -9,6 +9,9 @@ services: environment: DATABASE_URL: postgres://tracker:tracker@postgres:5432/tracker?sslmode=disable TRACKER_TZ: ${TRACKER_TZ:-UTC} + # No main site to borrow a login from here, so the dashboard is open. + AUTH_MODE: dev + DEV_MODE: "true" ports: - "8080:8080" depends_on: diff --git a/internal/api/api.go b/internal/api/api.go index 964a636..c5a6783 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -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 { diff --git a/internal/api/api_test.go b/internal/api/api_test.go index a6bacce..37d6ad5 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -14,6 +14,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" + "ccp/internal/auth" "ccp/internal/migrations" "ccp/internal/store" ) @@ -48,7 +49,7 @@ func setup(t *testing.T) (*httptest.Server, string) { t.Fatal(err) } - srv := httptest.NewServer(New(st, time.UTC, slog.New(slog.NewTextHandler(io.Discard, nil)))) + srv := httptest.NewServer(New(st, auth.AllowAll{}, time.UTC, slog.New(slog.NewTextHandler(io.Discard, nil)))) t.Cleanup(srv.Close) return srv, key } diff --git a/internal/auth/auth.go b/internal/auth/auth.go new file mode 100644 index 0000000..401837e --- /dev/null +++ b/internal/auth/auth.go @@ -0,0 +1,117 @@ +// Package auth decides whether a request comes from the site's admin. +// +// Like the job tracker, the activity tracker has no users or passwords of its +// own. It runs behind the main site's nginx at /tracker/ and borrows that +// site's session: the browser already carries the site's HTTP-only auth +// cookies (Path=/) on every request, so the tracker forwards the Cookie header +// to the site backend's GET /auth/validate-admin and treats a 2xx as "admin". +// Logging in and out happen on the main site; the tracker only ever asks. +// +// - validate-admin falls back to the refresh token when the access token has +// expired, and answers with fresh cookies. Those Set-Cookie headers are +// relayed onto this response, or the browser would keep presenting the +// expired token. +// - A "yes" is cached for cacheTTL per cookie, so a page that fires several +// requests costs one round trip. A refusal is re-asked, so logging in +// takes effect at once; logging out takes up to cacheTTL to reach here. +// +// Collectors don't use this: they authenticate with per-device bearer keys. +// +// Mode "dev" admits everyone. It exists for the local docker-compose, which +// has no site backend to ask, and config refuses it unless DEV_MODE=true. +package auth + +import ( + "crypto/sha256" + "encoding/hex" + "log/slog" + "net/http" + "sync" + "time" +) + +// cacheTTL is how long a "yes" from the site backend is trusted. +const cacheTTL = 30 * time.Second + +// Checker answers whether the request is the admin's. It may write headers +// (the relayed Set-Cookie) onto w, which is why it gets the writer. +type Checker interface { + IsAdmin(w http.ResponseWriter, r *http.Request) bool +} + +// AllowAll is the "dev" mode checker. +type AllowAll struct{} + +func (AllowAll) IsAdmin(http.ResponseWriter, *http.Request) bool { return true } + +// Forward asks the site backend at URL, forwarding the request's cookies. +type Forward struct { + URL string + Client *http.Client + Log *slog.Logger + + mu sync.Mutex + cache map[string]time.Time // sha256(Cookie header) -> when it was confirmed +} + +// NewForward builds a Forward checker for validateURL, normally +// http://backend:8080/auth/validate-admin on the Docker network. +func NewForward(validateURL string, log *slog.Logger) *Forward { + return &Forward{ + URL: validateURL, + // Short: a backend that doesn't answer in a few seconds should be a + // refusal, not a hang. + Client: &http.Client{Timeout: 5 * time.Second}, + Log: log, + cache: map[string]time.Time{}, + } +} + +func (f *Forward) IsAdmin(w http.ResponseWriter, r *http.Request) bool { + cookie := r.Header.Get("Cookie") + if cookie == "" { + return false + } + sum := sha256.Sum256([]byte(cookie)) + key := hex.EncodeToString(sum[:]) + + f.mu.Lock() + confirmed, ok := f.cache[key] + f.mu.Unlock() + if ok && time.Since(confirmed) < cacheTTL { + return true + } + + req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, f.URL, nil) + if err != nil { + f.Log.Error("building validate request", "err", err) + return false + } + req.Header.Set("Cookie", cookie) + resp, err := f.Client.Do(req) + if err != nil { + f.Log.Error("site backend unreachable", "err", err) + return false + } + defer resp.Body.Close() + + // Relayed whatever the verdict: a refresh that rotated the cookies is + // worth keeping even on a 403. + for _, c := range resp.Header.Values("Set-Cookie") { + w.Header().Add("Set-Cookie", c) + } + + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return false + } + + f.mu.Lock() + defer f.mu.Unlock() + for k, t := range f.cache { + if time.Since(t) >= cacheTTL { + delete(f.cache, k) + } + } + f.cache[key] = time.Now() + return true +} diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go new file mode 100644 index 0000000..d0c476f --- /dev/null +++ b/internal/auth/auth_test.go @@ -0,0 +1,63 @@ +package auth + +import ( + "io" + "log/slog" + "net/http" + "net/http/httptest" + "testing" +) + +func TestForward(t *testing.T) { + calls := 0 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + w.Header().Add("Set-Cookie", "access_token=new; Path=/") + if r.Header.Get("Cookie") == "access_token=good" { + w.WriteHeader(http.StatusOK) + return + } + w.WriteHeader(http.StatusForbidden) + })) + defer backend.Close() + f := NewForward(backend.URL, slog.New(slog.NewTextHandler(io.Discard, nil))) + + ask := func(cookie string) (bool, *httptest.ResponseRecorder) { + r := httptest.NewRequest("GET", "/", nil) + if cookie != "" { + r.Header.Set("Cookie", cookie) + } + w := httptest.NewRecorder() + return f.IsAdmin(w, r), w + } + + if ok, _ := ask(""); ok || calls != 0 { + t.Fatalf("no cookie: admin=%v calls=%d, want false without asking", ok, calls) + } + ok, w := ask("access_token=bad") + if ok { + t.Fatal("bad cookie accepted") + } + if w.Header().Get("Set-Cookie") == "" { + t.Fatal("Set-Cookie not relayed on refusal") + } + if ok, _ := ask("access_token=good"); !ok { + t.Fatal("good cookie refused") + } + before := calls + if ok, _ := ask("access_token=good"); !ok || calls != before { + t.Fatalf("second good request: admin=%v, backend asked again=%v", ok, calls != before) + } + if ok, _ := ask("access_token=bad"); ok || calls == before { + t.Fatal("refusals must not be cached") + } +} + +func TestForwardBackendDown(t *testing.T) { + f := NewForward("http://127.0.0.1:1/auth/validate-admin", slog.New(slog.NewTextHandler(io.Discard, nil))) + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("Cookie", "access_token=x") + if f.IsAdmin(httptest.NewRecorder(), r) { + t.Fatal("unreachable backend must refuse") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index a21c5bb..0ee079c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -14,6 +14,12 @@ type Config struct { ListenAddr string AutoMigrate bool Location *time.Location // timezone used for day boundaries in summaries + + // AuthMode decides who may open the dashboard: "forward" asks the main + // site's AuthValidateURL with the visitor's cookies, "dev" admits anyone + // and needs DEV_MODE=true. + AuthMode string + AuthValidateURL string } func Load() (Config, error) { @@ -32,6 +38,18 @@ func Load() (Config, error) { if c.Location, err = time.LoadLocation(envOr("TRACKER_TZ", "UTC")); err != nil { return c, fmt.Errorf("TRACKER_TZ: %w", err) } + + c.AuthMode = envOr("AUTH_MODE", "forward") + c.AuthValidateURL = envOr("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin") + switch c.AuthMode { + case "forward": + case "dev": + if dev, _ := strconv.ParseBool(os.Getenv("DEV_MODE")); !dev { + return c, errors.New("AUTH_MODE=dev is only allowed with DEV_MODE=true") + } + default: + return c, fmt.Errorf("unknown AUTH_MODE %q (want forward or dev)", c.AuthMode) + } return c, nil } diff --git a/internal/web/index.html b/internal/web/index.html index 816de21..5a0fee6 100644 --- a/internal/web/index.html +++ b/internal/web/index.html @@ -26,27 +26,21 @@ td.label { overflow-wrap:anywhere; } .bar { height:4px; background:var(--bar); border-radius:2px; margin-top:3px; } .ok { color:var(--ok); } .bad { color:var(--bad); } - #login { margin-top:40px; display:flex; gap:8px; } - #login input { flex:1; } + a { color:var(--bar); }

Activity Tracker

-
- -

diff --git a/internal/web/login.html b/internal/web/login.html new file mode 100644 index 0000000..63a53e8 --- /dev/null +++ b/internal/web/login.html @@ -0,0 +1,25 @@ + + + + + +Activity Tracker + + + +
+

Sign in to the site to open the activity tracker. Sign in

+
+ + + diff --git a/internal/web/setup.html b/internal/web/setup.html new file mode 100644 index 0000000..e09ba79 --- /dev/null +++ b/internal/web/setup.html @@ -0,0 +1,215 @@ + + + + + +Activity Tracker Setup + + + +
+
+

Setup

+ ← Dashboard +
+

Every collector uploads to with its own API key. Create one key per device or browser below, then follow that collector's steps. You only see a key once.

+ +

Devices and API keys

+
+
+ + + +
+ +

+ +

Browser (Violentmonkey)

+

Records time on the focused tab, per site (tab_focus, labelled by hostname). A tab counts only while it's the selected tab of the focused browser window, and it stops counting after 5 minutes without input unless video or audio is playing.

+
    +
  1. Create a key with kind browser. Use one key per browser, e.g. laptop-firefox.
  2. +
  3. Install Violentmonkey: Firefox · Chrome / Chromium.
  4. +
  5. Open and click Install. Violentmonkey checks this URL for updates.
  6. +
  7. Click the Violentmonkey toolbar icon, then Activity Tracker → Set server and API key. Enter and the key.
  8. +
  9. Check it: Status / upload now in the same menu shows the queue and the last upload. Browse for a few minutes and the site appears on the dashboard.
  10. +
+

Other menu options turn full URLs and page titles on or off (both off by default), set a regexp of hosts to ignore, and change the idle timeout. Browser pages such as about: and the new tab page, extension stores and the PDF viewer can't run scripts, so they aren't recorded. Hyprland still counts them as browser time.

+ +

Hyprland desktop

+

Records the focused window (app_focus, labelled by window class, with the title), plus idle and locked time.

+
    +
  1. Create a key with kind hyprland.
  2. +
  3. Build and install the agent from a clone of the repo: +
    git clone ssh://git@stppi.tailf20278.ts.net:2222/adamf/ccp.git && cd ccp
    +make install-agent    # ~/.local/bin/hypr-agent and the systemd user unit
  4. +
  5. Configure it: +
    mkdir -p ~/.config/hypr-agent
    +cat > ~/.config/hypr-agent/env <<EOF
    +TRACKER_URL=
    +TRACKER_API_KEY=trk_…
    +# HYPR_AGENT_TITLES=false            # don't send window titles at all
    +# HYPR_AGENT_REDACT=(?i)bank|private  # replace matching titles with [redacted]
    +EOF
    +chmod 600 ~/.config/hypr-agent/env
    +systemctl --user enable --now hypr-agent
  6. +
  7. To record idle and locked time, add this to ~/.config/hypr/hypridle.conf: +
    general {
    +    lock_cmd = hypr-agent lock; pidof hyprlock || hyprlock
    +    unlock_cmd = hypr-agent unlock
    +}
    +
    +listener {
    +    timeout = 300
    +    on-timeout = hypr-agent idle
    +    on-resume = hypr-agent resume
    +}
  8. +
  9. Check it: journalctl --user -u hypr-agent -f. Events upload every minute and wait in ~/.local/state/hypr-agent/buffer.jsonl while the server can't be reached.
  10. +
+ +

Apple Health

+

Walks, runs and other workouts become activities; step counts, sleep and other metrics become samples.

+
    +
  1. Create a key with kind health.
  2. +
  3. In the Health Auto Export iOS app, create a REST API automation: +
      +
    • URL: /api/v1/health/hae
    • +
    • Header: Authorization = Bearer trk_…
    • +
    • Format: JSON
    • +
    • Data: Workouts, plus metrics such as Step Count and Sleep Analysis
    • +
    • Sync cadence: hourly
    • +
  4. +
+ +

Manual events and scripts

+

Any script can post intervals with a manual key:

+
curl -X POST /api/v1/manual/events \
+  -H 'Authorization: Bearer trk_…' -H 'Content-Type: application/json' \
+  -d '{"events":[{"id":"run-2026-10-14","kind":"reading","label":"book",
+       "started_at":"2026-10-14T20:00:00Z","ended_at":"2026-10-14T20:45:00Z"}]}'
+

The id makes re-sending safe: a duplicate is ignored. Webcam presence (/api/v1/presence/events) has an endpoint but no agent yet.

+ +

Goals

+

Goals are daily targets checked on the dashboard. Manage them on the Pi:

+
docker exec activity-tracker tracker goal add --kind tab_focus --label youtube.com --op '<=' --target 1h
+docker exec activity-tracker tracker goal add --kind walk --op '>=' --target 30m   # empty label = any walk
+docker exec activity-tracker tracker goal list
+docker exec activity-tracker tracker goal rm --id 2
+
+ + + diff --git a/internal/web/web.go b/internal/web/web.go index 187529f..a53d39e 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -1,5 +1,5 @@ -// Package web serves the dashboard, a single static page that reads the -// /api/v1 query endpoints with an API key the viewer enters. +// Package web holds the dashboard pages, which read /api/v1 with the main +// site's session cookies, and the browser userscript. package web import ( @@ -7,10 +7,32 @@ import ( "net/http" ) -//go:embed index.html -var index []byte +var ( + //go:embed index.html + Index []byte + // LoginRedirect is served instead of a page when the visitor isn't the + // site's admin. + //go:embed login.html + LoginRedirect []byte + //go:embed setup.html + Setup []byte + //go:embed tracker.user.js + userScript []byte +) -func Handler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Write(index) +// Page serves a static HTML page. +func Page(page []byte) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Write(page) + } +} + +// UserScript serves the browser collector. Opening a *.user.js URL in a +// browser with Violentmonkey installed offers to install it, and Violentmonkey +// then checks the same URL for updates. It holds no secrets, so it is public. +func UserScript(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/javascript; charset=utf-8") + w.Write(userScript) }