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
+7 -37
View File
@@ -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 => ({ "&":"&amp;", "<":"&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>
+25
View File
@@ -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>
+215
View File
@@ -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 &lt;&lt;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 '&lt;=' --target 1h
docker exec activity-tracker tracker goal add --kind walk --op '&gt;=' --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 => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;" }[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
View File
@@ -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)
}