Tidy the dashboard and setup pages, add one-click API keys
Test and publish / test (push) Successful in 20s
Test and publish / publish (push) Has been cancelled

Both pages share style.css and a top bar with Dashboard and Setup tabs.
The dashboard gains summary tiles, card sections and friendly kind names.
The setup page puts each collector in a collapsible section with its own
Generate key button, which picks a free name, copies the key and fills
it into that collector's steps. Command blocks get Copy buttons.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 21:32:57 +01:00
co-authored by Claude Opus 5.5
parent e6a93be15c
commit 13602272fc
6 changed files with 337 additions and 169 deletions
+2 -2
View File
@@ -81,7 +81,7 @@ tracker goal rm --id 2
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.
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. Each collector's section has a **Generate key** button that names the device (for example `firefox`, or `hyprland-2` if that's taken), copies the key to the clipboard and fills it into that collector's steps.
Collectors never use the site login. Each one sends its own bearer key.
@@ -104,7 +104,7 @@ Collectors never use the site login. Each one sends its own bearer key.
| 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 |
| GET | `/tracker.user.js`, `/style.css`, `/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.
+1
View File
@@ -45,6 +45,7 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge
})
mux.HandleFunc("GET /readyz", srv.ready)
mux.HandleFunc("GET /tracker.user.js", web.UserScript)
mux.HandleFunc("GET /style.css", web.Style)
mux.Handle("GET /{$}", srv.adminPage(web.Page(web.Index)))
mux.Handle("GET /setup", srv.adminPage(web.Page(web.Setup)))
+53 -41
View File
@@ -4,49 +4,40 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Activity Tracker</title>
<style>
:root { --bg:#fafafa; --fg:#1a1a1a; --muted:#6b6b6b; --line:#e2e2e2; --bar:#4a7bd0; --ok:#2e8b57; --bad:#c0392b; }
@media (prefers-color-scheme: dark) {
:root { --bg:#151515; --fg:#e6e6e6; --muted:#999; --line:#2c2c2c; --bar:#6f9be6; --ok:#5cc28a; --bad:#e2685a; }
}
* { box-sizing: border-box; }
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.45 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:28px 0 8px; }
input, button { font:inherit; color:inherit; background:transparent; border:1px solid var(--line); border-radius:6px; padding:4px 8px; }
button { cursor:pointer; }
.nav { display:flex; gap:6px; align-items:center; }
.muted { color:var(--muted); }
.err { color:var(--bad); }
table { width:100%; border-collapse:collapse; }
td { padding:5px 0; border-bottom:1px solid var(--line); vertical-align:top; }
td.num { text-align:right; white-space:nowrap; font-variant-numeric:tabular-nums; padding-left:12px; }
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); }
a { color:var(--bar); }
</style>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<header>
<h1>Activity Tracker</h1>
<div class="nav">
<button id="prev" aria-label="Previous day">‹</button>
<input type="date" id="date">
<button id="next" aria-label="Next day">›</button>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<a href="./" aria-current="page">Dashboard</a>
<a href="setup">Setup</a>
</div>
</header>
</nav>
<div class="row spread">
<h1 id="title">Today</h1>
<div class="row">
<button id="prev" aria-label="Previous day">‹</button>
<input type="date" id="date" aria-label="Day">
<button id="next" aria-label="Next day">›</button>
<button id="today">Today</button>
</div>
</div>
<p id="status" class="muted"></p>
<div id="content" hidden>
<h2>Goals</h2><table id="goals"></table>
<h2>By kind</h2><table id="kinds"></table>
<h2>Top labels</h2><table id="labels"></table>
<h2>Timeline</h2><table id="timeline"></table>
<div class="tiles">
<div class="tile"><div class="k">Desktop time</div><div class="v" id="t-desktop">–</div></div>
<div class="tile"><div class="k">Browser time</div><div class="v" id="t-browser">–</div></div>
<div class="tile"><div class="k">Top site or app</div><div class="v" id="t-top">–</div></div>
<div class="tile"><div class="k">Goals met</div><div class="v" id="t-goals">–</div></div>
</div>
<section class="card"><h2>Goals</h2><div class="tablewrap"><table id="goals"></table></div></section>
<section class="card"><h2>By kind</h2><div class="tablewrap"><table id="kinds"></table></div></section>
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table id="labels"></table></div></section>
<section class="card"><h2>Timeline</h2><div class="tablewrap"><table id="timeline"></table></div></section>
</div>
</main>
<script>
@@ -60,6 +51,9 @@ function dur(s) {
}
const time = t => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;" }[c]));
// Friendlier names for the kinds collectors send; anything else shows as is.
const KINDS = { app_focus: "desktop", tab_focus: "browser", at_desk: "at desk", in_bed: "in bed" };
const kind = k => esc(KINDS[k] || k);
const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time
async function api(path) {
@@ -75,39 +69,56 @@ function rows(el, items, render, empty) {
el.innerHTML = items.length ? items.map(render).join("") : `<tr><td class="muted">${empty}</td></tr>`;
}
function setTitle(date) {
const d = new Date(date + "T12:00:00");
const diff = Math.round((new Date(today() + "T12:00:00") - d) / 864e5);
$("title").textContent = diff === 0 ? "Today" : diff === 1 ? "Yesterday"
: d.toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" });
$("today").disabled = diff === 0;
}
async function load() {
const date = $("date").value;
setTitle(date);
$("status").textContent = "Loading…";
try {
const sum = await api("summary/daily?date=" + date);
const q = new URLSearchParams({ from: sum.from, to: sum.to, limit: "500" });
const { activities } = await api("activities?" + q);
$("t-desktop").textContent = dur(sum.by_kind.app_focus || 0);
$("t-browser").textContent = dur(sum.by_kind.tab_focus || 0);
const focus = sum.totals.filter(t => t.kind === "app_focus" || t.kind === "tab_focus")
.sort((a, b) => b.seconds - a.seconds)[0];
$("t-top").textContent = focus ? focus.label || "—" : "–";
$("t-goals").textContent = sum.goals.length ? `${sum.goals.filter(g => g.met).length} / ${sum.goals.length}` : "–";
rows($("goals"), sum.goals, g => `<tr>
<td class="label">${esc(g.kind)}${g.label ? " · " + esc(g.label) : ""}
<td class="label">${kind(g.kind)}${g.label ? " · " + esc(g.label) : ""}
<span class="muted">${esc(g.op)} ${dur(g.target_s)}</span></td>
<td class="num">${dur(g.actual_s)}</td>
<td class="num ${g.met ? "ok" : "bad"}">${g.met ? "✓ met" : "✗ missed"}</td></tr>`,
"No goals. Add one with <code>tracker goal add</code>.");
`No goals yet. See <a href="setup#goals">Setup</a>.`);
const kinds = Object.entries(sum.by_kind).sort((a, b) => b[1] - a[1]);
const maxK = kinds[0]?.[1] || 1;
rows($("kinds"), kinds, ([k, s]) => `<tr>
<td class="label">${esc(k)}<div class="bar" style="width:${s / maxK * 100}%"></div></td>
<td class="label">${kind(k)}<div class="bar" style="width:${s / maxK * 100}%"></div></td>
<td class="num">${dur(s)}</td></tr>`, "Nothing recorded.");
const labels = [...sum.totals].sort((a, b) => b.seconds - a.seconds).slice(0, 15);
const maxL = labels[0]?.seconds || 1;
rows($("labels"), labels, t => `<tr>
<td class="label">${esc(t.label || "—")} <span class="muted">${esc(t.kind)}</span>
<td class="label">${esc(t.label || "—")} <span class="badge">${kind(t.kind)}</span>
<div class="bar" style="width:${t.seconds / maxL * 100}%"></div></td>
<td class="num">${dur(t.seconds)}</td></tr>`, "Nothing recorded.");
const acts = activities.filter(a => a.duration_s >= 60)
.sort((a, b) => new Date(b.started_at) - new Date(a.started_at));
rows($("timeline"), acts, a => `<tr>
<td class="num muted" style="padding:5px 12px 5px 0">${time(a.started_at)}–${time(a.ended_at)}</td>
<td class="label">${esc(a.label || a.kind)} <span class="muted">${esc(a.kind)}${a.attrs?.title ? " · " + esc(a.attrs.title) : ""}</span></td>
<td class="time">${time(a.started_at)}–${time(a.ended_at)}</td>
<td class="label">${esc(a.label || a.kind)} <span class="badge">${kind(a.kind)}</span>
${a.attrs?.title ? `<div class="muted small-text">${esc(a.attrs.title)}</div>` : ""}</td>
<td class="num">${dur(a.duration_s)}</td></tr>`, "No activities of a minute or longer.");
$("content").hidden = false;
@@ -126,6 +137,7 @@ function shift(days) {
$("prev").onclick = () => shift(-1);
$("next").onclick = () => shift(1);
$("today").onclick = () => { $("date").value = today(); load(); };
$("date").onchange = load;
$("date").value = today();
load();
+189 -126
View File
@@ -4,85 +4,67 @@
<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>
<link rel="stylesheet" href="style.css">
</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>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<a href="./">Dashboard</a>
<a href="setup" aria-current="page">Setup</a>
</div>
</nav>
<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>
<h1>Setup</h1>
<p class="muted">Each collector uploads to <code class="base"></code> with its own API key. Open a collector below and click <b>Generate key</b>; the key is filled into its steps. A key is shown only once.</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>
<section class="card">
<div class="row spread"><h2>Devices</h2></div>
<div class="tablewrap"><table id="devices"><tr><td class="muted">Loading…</td></tr></table></div>
<form class="row" id="create" style="margin-top:12px">
<select id="kind" aria-label="Kind">
<option value="browser">Browser</option>
<option value="hyprland">Hyprland</option>
<option value="health">Apple Health</option>
<option value="manual">Script / manual</option>
<option value="presence">Presence</option>
</select>
<input id="name" placeholder="Name (optional)" aria-label="Name" style="flex:1; min-width:140px">
<button class="primary">Generate key</button>
</form>
<div class="keyslot"></div>
<p id="status" class="small-text"></p>
</section>
<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:
<details class="collector" id="browser" open>
<summary><b>Browser</b><span class="muted">Violentmonkey userscript · time per site</span></summary>
<div class="body">
<p>Records <code>tab_focus</code> intervals labelled by hostname. A tab counts only while it's the selected tab of the focused window, and stops after 5 minutes without input unless video or audio is playing.</p>
<button class="primary" data-kind="browser">Generate key for this browser</button>
<div class="keyslot"></div>
<ol>
<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 the server and key:
<pre class="base"></pre>
<pre class="key">trk_… (generate a key above)</pre></li>
<li>Check it with <b>Status / upload now</b> in the same menu. Uploads happen every minute.</li>
</ol>
<p class="muted small-text">The menu also turns full URLs and page titles on or off (both off by default), sets hosts to ignore, and changes the idle timeout. <code>about:</code> pages, 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>
</div>
</details>
<details class="collector" id="hyprland">
<summary><b>Hyprland desktop</b><span class="muted">focused window, idle and locked time</span></summary>
<div class="body">
<p>Records <code>app_focus</code> intervals labelled by window class, with the title.</p>
<button class="primary" data-kind="hyprland">Generate key for this machine</button>
<div class="keyslot"></div>
<h3>1. Install the agent</h3>
<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:
make install-agent # ~/.local/bin/hypr-agent and the systemd user unit</pre>
<h3>2. Configure and start it</h3>
<pre>mkdir -p ~/.config/hypr-agent
cat > ~/.config/hypr-agent/env &lt;&lt;EOF
TRACKER_URL=<span class="base"></span>
@@ -91,8 +73,9 @@ TRACKER_API_KEY=<span class="key">trk_…</span>
# 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>:
systemctl --user enable --now hypr-agent</pre>
<h3>3. Idle and lock (optional)</h3>
<p>Add to <code>~/.config/hypr/hypridle.conf</code>:</p>
<pre>general {
lock_cmd = hypr-agent lock; pidof hyprlock || hyprlock
unlock_cmd = hypr-agent unlock
@@ -102,43 +85,63 @@ 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>
}</pre>
<p class="muted small-text">Check it with <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.</p>
</div>
</details>
<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:
<details class="collector" id="health">
<summary><b>Apple Health</b><span class="muted">walks, workouts, steps, sleep</span></summary>
<div class="body">
<p>Workouts become activities (<code>walk</code>, <code>run</code>, <code>workout</code>); step counts, sleep and other metrics become samples.</p>
<button class="primary" data-kind="health">Generate key for Health Auto Export</button>
<div class="keyslot"></div>
<p>In the Health Auto Export iOS app, create a <b>REST API</b> automation:</p>
<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>Format: JSON · Sync cadence: hourly</li>
<li>Data: Workouts, plus metrics such as Step Count and Sleep Analysis</li>
<li>Sync cadence: hourly</li>
</ul></li>
</ol>
</ul>
</div>
</details>
<h2>Manual events and scripts</h2>
<p>Any script can post intervals with a <code>manual</code> key:</p>
<details class="collector" id="manual">
<summary><b>Scripts</b><span class="muted">post any interval with curl</span></summary>
<div class="body">
<button class="primary" data-kind="manual">Generate key for scripts</button>
<div class="keyslot"></div>
<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",
-d '{"events":[{"id":"reading-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>
<p class="muted small-text">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>
</div>
</details>
<h2>Goals</h2>
<p>Goals are daily targets checked on the dashboard. Manage them on the Pi:</p>
<details class="collector" id="goals">
<summary><b>Goals</b><span class="muted">daily targets on the dashboard</span></summary>
<div class="body">
<p>Managed on the Pi. An empty label matches every label of that kind.</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 add --kind walk --op '&gt;=' --target 30m
docker exec activity-tracker tracker goal list
docker exec activity-tracker tracker goal rm --id 2</pre>
</div>
</details>
</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";
function ago(t) {
if (!t) return "never";
const s = (Date.now() - new Date(t)) / 1000;
if (s < 90) return "just now";
if (s < 3600) return Math.round(s / 60) + " min ago";
if (s < 86400) return Math.round(s / 3600) + " h ago";
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
}
// The tracker's public URL, e.g. https://www.adam-french.co.uk/tracker
const base = new URL(".", location.href).href.replace(/\/$/, "");
@@ -157,28 +160,110 @@ async function api(method, path, body) {
}
function status(msg, cls) {
$("status").className = cls || "";
$("status").className = "small-text " + (cls || "");
$("status").textContent = msg;
}
async function copy(text, btn) {
try { await navigator.clipboard.writeText(text); btn.textContent = "Copied"; }
catch { btn.textContent = "Copy failed"; }
setTimeout(() => btn.textContent = "Copy", 1500);
}
// A Copy button on every command block.
document.querySelectorAll("pre").forEach(pre => {
const wrap = document.createElement("div");
wrap.className = "codeblock";
pre.replaceWith(wrap);
wrap.append(pre);
const btn = document.createElement("button");
btn.className = "small copy"; btn.type = "button"; btn.textContent = "Copy";
btn.onclick = () => copy(pre.innerText, btn);
wrap.append(btn);
});
// ---- devices and keys ----
let devices = [];
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>
({ devices } = await api("GET", "devices"));
const active = devices.filter(d => !d.revoked_at);
const revoked = devices.filter(d => d.revoked_at);
$("devices").innerHTML = `<tr><th>Name</th><th>Kind</th><th>Last upload</th><th></th></tr>` +
(active.length ? active.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>`);
<td><span class="badge">${esc(d.kind)}</span></td>
<td class="time">${ago(d.last_seen_at)}</td>
<td class="num"><button class="small" data-revoke="${esc(d.name)}">Revoke</button></td></tr>`).join("")
: `<tr><td colspan="4" class="muted">No devices yet.</td></tr>`) +
(revoked.length ? `<tr><td colspan="4" class="muted small-text">${revoked.length} revoked: ${revoked.map(d => esc(d.name)).join(", ")}</td></tr>` : "");
} catch (e) {
status(e.message, "err");
}
}
// A readable name that isn't taken yet (names stay taken after revoking).
function suggestName(kind) {
let stem = { health: "iphone-health", manual: "script" }[kind] || kind;
if (kind === "browser") {
const ua = navigator.userAgent;
stem = /Firefox\//.test(ua) ? "firefox" : /Edg\//.test(ua) ? "edge" : /Chrome\//.test(ua) ? "chrome" : "browser";
}
const taken = new Set(devices.map(d => d.name));
let name = stem;
for (let i = 2; taken.has(name); i++) name = `${stem}-${i}`;
return name;
}
function showKey(slot, device, key) {
document.querySelectorAll(".keyslot").forEach(s => s.innerHTML = "");
slot.innerHTML = `<div class="keybox">
<div>Key for <b>${esc(device.name)}</b> <span class="badge">${esc(device.kind)}</span>. Copy it now; it won't be shown again.</div>
<div class="codeblock"><pre>${esc(key)}</pre><button class="small copy" type="button">Copy</button></div>
</div>`;
const btn = slot.querySelector("button");
btn.onclick = () => copy(key, btn);
copy(key, btn);
}
async function generate(kind, name, slot, button) {
button.disabled = true;
try {
if (!devices.length) await loadDevices();
const { device, key } = await api("POST", "devices", { kind, name: name || suggestName(kind) });
showKey(slot, device, key);
// Fill the key into this collector's steps so they can be copied as-is.
const section = $(kind);
if (section) {
section.open = true;
section.querySelectorAll(".key").forEach(el => el.textContent = key);
}
status("");
loadDevices();
return true;
} catch (e) {
status(e.message, "err");
return false;
} finally {
button.disabled = false;
}
}
$("create").onsubmit = e => {
e.preventDefault();
const btn = e.submitter || $("create").querySelector("button");
generate($("kind").value, $("name").value.trim(), $("create").nextElementSibling, btn)
.then(ok => { if (ok) $("name").value = ""; });
};
document.querySelectorAll("button[data-kind]").forEach(btn => {
btn.onclick = () => generate(btn.dataset.kind, "", btn.nextElementSibling, btn);
});
$("devices").onclick = async e => {
const name = e.target.dataset?.revoke;
if (!name || !confirm(`Revoke ${name}? Its collector stops being able to upload.`)) return;
if (!name || !confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
try {
await api("DELETE", "devices/" + encodeURIComponent(name));
status(`Revoked ${name}.`, "ok");
@@ -186,29 +271,7 @@ $("devices").onclick = async e => {
} 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"; }
};
if (location.hash && $(location.hash.slice(1))?.tagName === "DETAILS") $(location.hash.slice(1)).open = true;
loadDevices();
</script>
</body>
+82
View File
@@ -0,0 +1,82 @@
/* Shared by the dashboard and setup pages. */
:root {
--bg:#f6f6f4; --card:#ffffff; --fg:#1b1b1b; --muted:#6b6b6b; --line:#e4e4e0;
--accent:#3d6fc4; --accent-soft:#e8eefa; --ok:#2e8b57; --bad:#c0392b; --code:#f2f2ef;
}
@media (prefers-color-scheme: dark) {
:root {
--bg:#121212; --card:#1b1b1b; --fg:#e8e8e8; --muted:#9a9a9a; --line:#2c2c2c;
--accent:#7aa2ea; --accent-soft:#1e2a40; --ok:#5cc28a; --bad:#e2685a; --code:#232323;
}
}
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.5 system-ui, sans-serif; }
main { max-width:800px; margin:0 auto; padding:0 16px 56px; }
a { color:var(--accent); }
/* ---- top bar ---- */
.topbar { display:flex; align-items:center; gap:20px; padding:16px 0; margin-bottom:8px; border-bottom:1px solid var(--line); }
.brand { font-weight:650; font-size:17px; }
.tabs { display:flex; gap:4px; }
.tabs a { color:var(--muted); text-decoration:none; padding:5px 10px; border-radius:6px; }
.tabs a:hover { color:var(--fg); }
.tabs a[aria-current="page"] { color:var(--fg); background:var(--accent-soft); }
/* ---- controls ---- */
input, select, button { font:inherit; color:inherit; background:var(--card); border:1px solid var(--line); border-radius:6px; padding:5px 10px; }
button { cursor:pointer; }
button:hover { border-color:var(--muted); }
button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
button.primary:hover { filter:brightness(1.08); }
button.small { padding:2px 8px; font-size:13px; }
button:disabled { opacity:.6; cursor:default; }
:focus-visible { outline:2px solid var(--accent); outline-offset:1px; }
/* ---- layout pieces ---- */
.row { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }
.spread { justify-content:space-between; }
.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:16px; margin-top:16px; }
.card > h2:first-child, .card > .row:first-child h2 { margin-top:0; }
h1 { font-size:20px; margin:16px 0 0; }
h2 { font-size:15px; margin:0 0 10px; }
h3 { font-size:14px; margin:16px 0 6px; }
.muted { color:var(--muted); }
.small-text { font-size:13px; }
.ok { color:var(--ok); } .bad, .err { color:var(--bad); }
.badge { display:inline-block; font-size:12px; padding:1px 7px; border-radius:999px; background:var(--accent-soft); color:var(--accent); white-space:nowrap; }
.tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(160px, 1fr)); gap:12px; margin-top:16px; }
.tile { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:12px 14px; }
.tile .k { font-size:13px; color:var(--muted); }
.tile .v { font-size:22px; font-weight:650; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }
/* ---- tables ---- */
.tablewrap { overflow-x:auto; }
table { width:100%; border-collapse:collapse; }
th, td { padding:7px 8px 7px 0; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
tr:last-child td { border-bottom:0; }
th { font-weight:600; font-size:13px; color:var(--muted); }
td.num { text-align:right; white-space:nowrap; font-variant-numeric:tabular-nums; padding-left:12px; padding-right:0; }
td.label { overflow-wrap:anywhere; width:100%; }
td.time { white-space:nowrap; color:var(--muted); font-variant-numeric:tabular-nums; }
.bar { height:4px; background:var(--accent); border-radius:2px; margin-top:4px; opacity:.85; }
/* ---- code ---- */
code, pre { font:13px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; background:var(--code); border-radius:6px; }
code { padding:1px 5px; overflow-wrap:anywhere; }
pre { padding:10px 12px; overflow-x:auto; margin:0; }
.codeblock { position:relative; margin:8px 0; }
.codeblock .copy { position:absolute; top:6px; right:6px; }
ol, ul { padding-left:22px; margin:8px 0; }
li { margin:6px 0; }
/* ---- setup ---- */
.keybox { margin-top:12px; padding:12px; border:1px solid var(--ok); border-radius:8px; }
.keybox pre { margin:8px 0; }
details.collector { background:var(--card); border:1px solid var(--line); border-radius:10px; margin-top:12px; }
details.collector > summary { cursor:pointer; padding:14px 16px; list-style:none; display:flex; gap:10px; align-items:baseline; }
details.collector > summary::-webkit-details-marker { display:none; }
details.collector > summary::before { content:"▸"; color:var(--muted); }
details.collector[open] > summary::before { content:"▾"; }
details.collector > summary b { font-size:15px; }
details.collector > .body { padding:0 16px 16px; }
+10
View File
@@ -18,8 +18,18 @@ var (
Setup []byte
//go:embed tracker.user.js
userScript []byte
//go:embed style.css
style []byte
)
// Style serves the stylesheet the pages share. It's public: the login
// redirect doesn't use it, but there's nothing private in it either.
func Style(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Write(style)
}
// Page serves a static HTML page.
func Page(page []byte) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {