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 <[email protected]>
This commit is contained in:
+115
-12
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
+7
-37
@@ -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); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<h1>Activity Tracker</h1>
|
||||
<div class="nav" id="nav" hidden>
|
||||
<div class="nav">
|
||||
<button id="prev" aria-label="Previous day">‹</button>
|
||||
<input type="date" id="date">
|
||||
<button id="next" aria-label="Next day">›</button>
|
||||
<button id="logout" title="Forget API key">Sign out</button>
|
||||
<a href="setup">Setup</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<form id="login" hidden>
|
||||
<input type="password" id="key" placeholder="API key (trk_…)" autocomplete="off" required>
|
||||
<button>Open</button>
|
||||
</form>
|
||||
|
||||
<p id="status" class="muted"></p>
|
||||
<div id="content" hidden>
|
||||
<h2>Goals</h2><table id="goals"></table>
|
||||
@@ -57,12 +51,6 @@
|
||||
</main>
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
const KEY = "tracker_api_key";
|
||||
const store = {
|
||||
get() { try { return localStorage.getItem(KEY) || ""; } catch { return ""; } },
|
||||
set(v) { try { v ? localStorage.setItem(KEY, v) : localStorage.removeItem(KEY); } catch {} },
|
||||
};
|
||||
let apiKey = store.get();
|
||||
|
||||
function dur(s) {
|
||||
s = Math.round(s);
|
||||
@@ -75,9 +63,10 @@ const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&", "<":"&l
|
||||
const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time
|
||||
|
||||
async function api(path) {
|
||||
const r = await fetch("api/v1/" + path, { headers: { Authorization: "Bearer " + apiKey } });
|
||||
// Authenticated by the main site's session cookies, which the browser sends.
|
||||
const r = await fetch("api/v1/" + path);
|
||||
const body = await r.json().catch(() => ({}));
|
||||
if (r.status === 401) { signOut(); throw new Error(body.error || "unauthorized"); }
|
||||
if (r.status === 401) { location.reload(); throw new Error("session expired"); } // reload goes to the login page
|
||||
if (!r.ok) throw new Error(body.error || r.statusText);
|
||||
return body;
|
||||
}
|
||||
@@ -135,30 +124,11 @@ function shift(days) {
|
||||
load();
|
||||
}
|
||||
|
||||
function signOut() {
|
||||
apiKey = ""; store.set("");
|
||||
show();
|
||||
}
|
||||
|
||||
function show() {
|
||||
$("login").hidden = !!apiKey;
|
||||
$("nav").hidden = !apiKey;
|
||||
$("content").hidden = true;
|
||||
$("status").textContent = "";
|
||||
if (apiKey) load();
|
||||
}
|
||||
|
||||
$("login").onsubmit = e => {
|
||||
e.preventDefault();
|
||||
apiKey = $("key").value.trim(); store.set(apiKey); $("key").value = "";
|
||||
show();
|
||||
};
|
||||
$("logout").onclick = signOut;
|
||||
$("prev").onclick = () => shift(-1);
|
||||
$("next").onclick = () => shift(1);
|
||||
$("date").onchange = load;
|
||||
$("date").value = today();
|
||||
show();
|
||||
load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Activity Tracker</title>
|
||||
<style>
|
||||
body { margin:0; background:#fafafa; color:#1a1a1a; font:15px/1.45 system-ui, sans-serif; }
|
||||
@media (prefers-color-scheme: dark) { body { background:#151515; color:#e6e6e6; } a { color:#6f9be6; } }
|
||||
main { max-width:760px; margin:0 auto; padding:24px 16px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<p>Sign in to the site to open the activity tracker. <a id="login" href="/admin/login">Sign in</a></p>
|
||||
</main>
|
||||
<script>
|
||||
// The site's login page sends you back to `redirect` afterwards.
|
||||
const here = location.pathname + location.search;
|
||||
const to = "/admin/login?redirect=" + encodeURIComponent(here);
|
||||
document.getElementById("login").href = to;
|
||||
location.replace(to);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,215 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Activity Tracker Setup</title>
|
||||
<style>
|
||||
:root { --bg:#fafafa; --fg:#1a1a1a; --muted:#6b6b6b; --line:#e2e2e2; --bar:#4a7bd0; --ok:#2e8b57; --bad:#c0392b; --code:#f0f0f0; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --bg:#151515; --fg:#e6e6e6; --muted:#999; --line:#2c2c2c; --bar:#6f9be6; --ok:#5cc28a; --bad:#e2685a; --code:#202020; }
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.5 system-ui, sans-serif; }
|
||||
main { max-width:760px; margin:0 auto; padding:24px 16px 48px; }
|
||||
header { display:flex; flex-wrap:wrap; gap:8px; align-items:center; justify-content:space-between; }
|
||||
h1 { font-size:20px; margin:0; }
|
||||
h2 { font-size:13px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); margin:32px 0 8px; }
|
||||
a { color:var(--bar); }
|
||||
input, select, button { font:inherit; color:inherit; background:transparent; border:1px solid var(--line); border-radius:6px; padding:4px 8px; }
|
||||
select option { background:var(--bg); }
|
||||
button { cursor:pointer; }
|
||||
.muted { color:var(--muted); }
|
||||
.err { color:var(--bad); } .ok { color:var(--ok); }
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
td, th { padding:5px 8px 5px 0; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
||||
th { font-weight:600; font-size:13px; color:var(--muted); }
|
||||
td.label { overflow-wrap:anywhere; }
|
||||
.tablewrap { overflow-x:auto; }
|
||||
form.row { display:flex; flex-wrap:wrap; gap:8px; margin-top:12px; }
|
||||
form.row input { flex:1; min-width:160px; }
|
||||
pre, code { font:13px/1.45 ui-monospace, monospace; background:var(--code); border-radius:6px; }
|
||||
code { padding:1px 4px; overflow-wrap:anywhere; }
|
||||
pre { padding:10px 12px; overflow-x:auto; margin:8px 0; }
|
||||
ol, ul { padding-left:22px; }
|
||||
li { margin:4px 0; }
|
||||
#newkey { margin-top:12px; padding:10px 12px; border:1px solid var(--ok); border-radius:6px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<h1>Setup</h1>
|
||||
<a href="./">← Dashboard</a>
|
||||
</header>
|
||||
<p class="muted">Every collector uploads to <code class="base"></code> 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.</p>
|
||||
|
||||
<h2>Devices and API keys</h2>
|
||||
<div class="tablewrap"><table id="devices"></table></div>
|
||||
<form class="row" id="create">
|
||||
<input id="name" placeholder="Name, e.g. laptop-firefox" required>
|
||||
<select id="kind">
|
||||
<option value="browser">browser</option>
|
||||
<option value="hyprland">hyprland</option>
|
||||
<option value="health">health</option>
|
||||
<option value="presence">presence</option>
|
||||
<option value="manual">manual</option>
|
||||
</select>
|
||||
<button>Create key</button>
|
||||
</form>
|
||||
<div id="newkey" hidden>
|
||||
<div>Key for <b id="newname"></b>. Copy it now; it can't be shown again.</div>
|
||||
<pre id="keyval"></pre>
|
||||
<button id="copy">Copy</button> <span id="copied" class="muted"></span>
|
||||
</div>
|
||||
<p id="status"></p>
|
||||
|
||||
<h2>Browser (Violentmonkey)</h2>
|
||||
<p>Records time on the focused tab, per site (<code>tab_focus</code>, 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.</p>
|
||||
<ol>
|
||||
<li>Create a key with kind <code>browser</code>. Use one key per browser, e.g. <code>laptop-firefox</code>.</li>
|
||||
<li>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox</a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium</a>.</li>
|
||||
<li>Open <a class="script" href="tracker.user.js"></a> and click <b>Install</b>. Violentmonkey checks this URL for updates.</li>
|
||||
<li>Click the Violentmonkey toolbar icon, then <b>Activity Tracker → Set server and API key</b>. Enter <code class="base"></code> and the key.</li>
|
||||
<li>Check it: <b>Status / upload now</b> in the same menu shows the queue and the last upload. Browse for a few minutes and the site appears on the dashboard.</li>
|
||||
</ol>
|
||||
<p class="muted">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 <code>about:</code> 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.</p>
|
||||
|
||||
<h2>Hyprland desktop</h2>
|
||||
<p>Records the focused window (<code>app_focus</code>, labelled by window class, with the title), plus idle and locked time.</p>
|
||||
<ol>
|
||||
<li>Create a key with kind <code>hyprland</code>.</li>
|
||||
<li>Build and install the agent from a clone of the repo:
|
||||
<pre>git clone ssh://[email protected]:2222/adamf/ccp.git && cd ccp
|
||||
make install-agent # ~/.local/bin/hypr-agent and the systemd user unit</pre></li>
|
||||
<li>Configure it:
|
||||
<pre>mkdir -p ~/.config/hypr-agent
|
||||
cat > ~/.config/hypr-agent/env <<EOF
|
||||
TRACKER_URL=<span class="base"></span>
|
||||
TRACKER_API_KEY=<span class="key">trk_…</span>
|
||||
# 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</pre></li>
|
||||
<li>To record idle and locked time, add this to <code>~/.config/hypr/hypridle.conf</code>:
|
||||
<pre>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
|
||||
}</pre></li>
|
||||
<li>Check it: <code>journalctl --user -u hypr-agent -f</code>. Events upload every minute and wait in <code>~/.local/state/hypr-agent/buffer.jsonl</code> while the server can't be reached.</li>
|
||||
</ol>
|
||||
|
||||
<h2>Apple Health</h2>
|
||||
<p>Walks, runs and other workouts become activities; step counts, sleep and other metrics become samples.</p>
|
||||
<ol>
|
||||
<li>Create a key with kind <code>health</code>.</li>
|
||||
<li>In the Health Auto Export iOS app, create a <b>REST API</b> automation:
|
||||
<ul>
|
||||
<li>URL: <code><span class="base"></span>/api/v1/health/hae</code></li>
|
||||
<li>Header: <code>Authorization</code> = <code>Bearer <span class="key">trk_…</span></code></li>
|
||||
<li>Format: JSON</li>
|
||||
<li>Data: Workouts, plus metrics such as Step Count and Sleep Analysis</li>
|
||||
<li>Sync cadence: hourly</li>
|
||||
</ul></li>
|
||||
</ol>
|
||||
|
||||
<h2>Manual events and scripts</h2>
|
||||
<p>Any script can post intervals with a <code>manual</code> key:</p>
|
||||
<pre>curl -X POST <span class="base"></span>/api/v1/manual/events \
|
||||
-H 'Authorization: Bearer <span class="key">trk_…</span>' -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"}]}'</pre>
|
||||
<p class="muted">The <code>id</code> makes re-sending safe: a duplicate is ignored. Webcam presence (<code>/api/v1/presence/events</code>) has an endpoint but no agent yet.</p>
|
||||
|
||||
<h2>Goals</h2>
|
||||
<p>Goals are daily targets checked on the dashboard. Manage them on the Pi:</p>
|
||||
<pre>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</pre>
|
||||
</main>
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&", "<":"<", ">":">", '"':""" }[c]));
|
||||
const when = t => t ? new Date(t).toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) : "never";
|
||||
|
||||
// The tracker's public URL, e.g. https://www.adam-french.co.uk/tracker
|
||||
const base = new URL(".", location.href).href.replace(/\/$/, "");
|
||||
document.querySelectorAll(".base").forEach(el => el.textContent = base);
|
||||
document.querySelectorAll("a.script").forEach(el => el.textContent = base + "/tracker.user.js");
|
||||
|
||||
async function api(method, path, body) {
|
||||
const r = await fetch("api/v1/" + path, {
|
||||
method, headers: body ? { "Content-Type": "application/json" } : {},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const out = await r.json().catch(() => ({}));
|
||||
if (r.status === 401) { location.reload(); throw new Error("session expired"); }
|
||||
if (!r.ok) throw new Error(out.error || r.statusText);
|
||||
return out;
|
||||
}
|
||||
|
||||
function status(msg, cls) {
|
||||
$("status").className = cls || "";
|
||||
$("status").textContent = msg;
|
||||
}
|
||||
|
||||
async function loadDevices() {
|
||||
try {
|
||||
const { devices } = await api("GET", "devices");
|
||||
$("devices").innerHTML = `<tr><th>Name</th><th>Kind</th><th>Last seen</th><th></th></tr>` +
|
||||
(devices.length ? devices.map(d => `<tr>
|
||||
<td class="label">${esc(d.name)}</td>
|
||||
<td>${esc(d.kind)}</td>
|
||||
<td class="muted">${d.revoked_at ? "revoked " + when(d.revoked_at) : when(d.last_seen_at)}</td>
|
||||
<td>${d.revoked_at ? "" : `<button data-revoke="${esc(d.name)}">Revoke</button>`}</td></tr>`).join("")
|
||||
: `<tr><td colspan="4" class="muted">No devices yet.</td></tr>`);
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
$("devices").onclick = async e => {
|
||||
const name = e.target.dataset?.revoke;
|
||||
if (!name || !confirm(`Revoke ${name}? Its collector stops being able to upload.`)) return;
|
||||
try {
|
||||
await api("DELETE", "devices/" + encodeURIComponent(name));
|
||||
status(`Revoked ${name}.`, "ok");
|
||||
loadDevices();
|
||||
} catch (err) { status(err.message, "err"); }
|
||||
};
|
||||
|
||||
$("create").onsubmit = async e => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const { device, key } = await api("POST", "devices", { name: $("name").value, kind: $("kind").value });
|
||||
$("newname").textContent = `${device.name} (${device.kind})`;
|
||||
$("keyval").textContent = key;
|
||||
$("newkey").hidden = false;
|
||||
$("copied").textContent = "";
|
||||
// Fill the key into the instructions below so they can be copied as-is.
|
||||
document.querySelectorAll(".key").forEach(el => el.textContent = key);
|
||||
$("name").value = "";
|
||||
status("");
|
||||
loadDevices();
|
||||
} catch (err) { status(err.message, "err"); }
|
||||
};
|
||||
|
||||
$("copy").onclick = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText($("keyval").textContent);
|
||||
$("copied").textContent = "Copied";
|
||||
} catch { $("copied").textContent = "Copy failed; select the key and copy it by hand"; }
|
||||
};
|
||||
|
||||
loadDevices();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+29
-7
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user