@hivey/cli 0.9.79 → 0.9.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivey/cli",
3
- "version": "0.9.79",
3
+ "version": "0.9.82",
4
4
  "description": "All your AI swarms, one terminal: a workspace and lead agent for teams of Claude Code and Codex agents",
5
5
  "keywords": [
6
6
  "hivey",
@@ -35,9 +35,9 @@ for Codex, Grok and agy** below when the agent isn't on Claude Code.
35
35
  - **Spend:** a script you write that calls an LLM API directly (not through Claude Code, Codex
36
36
  or Grok CLI) logs each call with `hivey_spend.record(response, agent="<agent name>")` from
37
37
  `~/.claude/skills/hivey-agent-map/scripts/hivey_spend.py`, so the agent map counts its cost.
38
- - **Dashboards:** when you build or deploy a dashboard, report site or web view, register it on
39
- the agent fleet so the user finds it with the others: `hivey agent-map dashboard add "<name>"
40
- <url> --agent <agent name> --note "<what it shows>"` (`hivey-dashboards` skill).
38
+ - **Dashboards:** when you build or deploy a dashboard, report site or web view, follow the
39
+ `hivey-dashboards` skill: give it the token login, then register it on the agent fleet with
40
+ `hivey agent-map dashboard add "<name>" <url> --agent <agent name> --note "<what it shows>" --token default`.
41
41
  - Ask before anything destructive or outward-facing (deleting data, publishing, sending
42
42
  email or posts, spending money). Draft first, then ask.
43
43
  - Commit your work in this folder; never push.
@@ -222,11 +222,13 @@ each swarm's coordinator get a desk; a swarm's workers and critics stand beside
222
222
  in a frame on the right (⟳, Open in tab ↗, Edit, Remove), with a live up/down dot per dashboard (`GET
223
223
  /hv-dashboard-status`, checked from this Mac). The list is in `fleet-settings.json` under `dashboards`
224
224
  (owner-only file); **+ Add** on the page or `hivey agent-map dashboard add|list|edit|remove …` (`scripts/dashboards.py`,
225
- the `hivey-dashboards` skill) edit the same list. A dashboard can carry a login token (a value or an EnvSave
226
- `es_…` key): the frame opens `GET /hv-dashboard-open?id=…`, which redirects to its URL with the token added as a
227
- query parameter (`token_param`, default `token`), so the page never holds tokens. A site behind Vercel's login
228
- is flagged (it refuses frames); its Protection Bypass for Automation secret with `--vercel` opens it in the
229
- frame, logged in. Sites that forbid framing show an Open in tab button instead.
225
+ the `hivey-dashboards` skill) edit the same list. A dashboard can carry a login token: `default` (the user's
226
+ default dashboard token, `dashboard_token` in the settings file, an EnvSave key that opens all their dashboards),
227
+ its own EnvSave `es_…` key, or a value. The frame opens `GET /hv-dashboard-open?id=…`, which redirects to its URL
228
+ with the token added as a query parameter (`token_param`, default `token`), so the page never holds tokens; the
229
+ dashboard trades it for its own session cookie (token login: hivey-dashboards skill, `references/token-login.md`).
230
+ A site that sends you to another site first (a hosting login wall) or forbids framing shows why and an Open in
231
+ tab button.
230
232
  - **CEO**: the space named `ceo` gets the captain's bridge, its own room in the ship's nose (gold trim, main
231
233
  viewscreen); its master sits at the captain's console.
232
234
 
@@ -7,7 +7,8 @@ removes them (POST /hv-fleet-settings {"dashboards": [...]}). An agent that buil
7
7
  registers it from the shell:
8
8
 
9
9
  python3 -I dashboards.py add "Trading dashboard" https://example.vercel.app --agent trading-strategies
10
- python3 -I dashboards.py add "Trading dashboard" https://example.vercel.app --token es_… --vercel
10
+ python3 -I dashboards.py add "Trading dashboard" https://example.vercel.app --token default
11
+ python3 -I dashboards.py token es_… (your default dashboard token; `token` shows it)
11
12
  python3 -I dashboards.py list [--json]
12
13
  python3 -I dashboards.py edit "Trading dashboard" --name "Paper trading" --url https://… --note "…"
13
14
  python3 -I dashboards.py remove "Trading dashboard" (by name, id or URL)
@@ -16,19 +17,22 @@ The same commands run as `hivey agent-map dashboard add|list|edit|remove …` (t
16
17
  `add` with a name or URL already in the list updates that entry.
17
18
 
18
19
  Logins: a dashboard can carry a token. Opening it (GET /hv-dashboard-open?id=…) redirects to its URL with
19
- the token added as a query parameter (`token_param`, default `token`), so a dashboard that accepts a token
20
- logs you in by itself. The token is a literal value or an EnvSave opaque key (`es_…`, read with
21
- `envsave get` when the dashboard opens; no Touch ID). It is never sent to the page's list. For a site behind
22
- Vercel's login (Deployment Protection), use its "Protection Bypass for Automation" secret with --vercel:
23
- the parameter becomes `x-vercel-protection-bypass` plus a bypass cookie that also works in the frame.
20
+ the token added as a query parameter (`token_param`, default `token`), so a dashboard with token login
21
+ (the hivey-dashboards skill's references/token-login.md) logs you in by itself. The token is a literal value,
22
+ an EnvSave opaque key (`es_…`, read with `envsave get` when the dashboard opens; no Touch ID), or `default`:
23
+ your default dashboard token (one EnvSave key, `dashboard_token` in the settings file, else the one built in
24
+ for your user in USER_TOKENS) that opens all your dashboards, so changing it updates every one. A new
25
+ dashboard uses it unless you say it needs no login (`--no-token`). Tokens are never sent to the page's list.
24
26
  Python standard library only.
25
27
  """
26
28
  from __future__ import annotations
27
29
 
28
30
  import argparse
29
31
  import concurrent.futures
32
+ import getpass
30
33
  import json
31
34
  import os
35
+ import pwd
32
36
  import re
33
37
  import shutil
34
38
  import subprocess
@@ -42,9 +46,16 @@ from pathlib import Path
42
46
  SETTINGS = Path.home() / ".hivey" / "agent-map" / "fleet-settings.json"
43
47
  MAX = 100
44
48
  LIMITS = {"name": 80, "url": 2000, "agent": 80, "note": 300}
45
- VERCEL = "x-vercel-protection-bypass"
49
+ DEFAULT = "default" # the token value meaning "my default dashboard token"
46
50
  PARAM = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
47
51
  FIELDS = ("name", "url", "agent", "note", "token", "token_param")
52
+ # Each known user's default dashboard token (their DASHBOARD_TOKEN_<USER> EnvSave key), used until they save
53
+ # their own (`dashboard token es_…`, or the Edit form). Matched on the Mac login and full name. Anyone else
54
+ # types theirs once in the form, and it is saved for next time.
55
+ USER_TOKENS = (
56
+ (("jcsancho", "jose"), "es_AN_xOxHk9IU6KbcaRxXEndz0xHcHj0NKIRnb79Iq2QV7Hr6f"),
57
+ (("alyssa",), "es_8AC8PzeSobAcZMD1PV6gnZwo7bezsQkiQoswZu7BZqbgecKb"),
58
+ )
48
59
 
49
60
 
50
61
  def _settings() -> dict:
@@ -100,7 +111,7 @@ def public(items: list[dict]) -> list[dict]:
100
111
  for d in items:
101
112
  p = {k: v for k, v in d.items() if k != "token"}
102
113
  tok = d.get("token") or ""
103
- p["login"] = "" if not tok else "envsave" if tok.startswith("es_") else "token"
114
+ p["login"] = "" if not tok else DEFAULT if tok == DEFAULT else "envsave" if tok.startswith("es_") else "token"
104
115
  out.append(p)
105
116
  return out
106
117
 
@@ -132,11 +143,9 @@ def _match(d: dict, key: str) -> bool:
132
143
  return k in (d["id"].lower(), d["name"].lower(), d["url"].lower().rstrip("/"), d["url"].lower())
133
144
 
134
145
 
135
- def _changes(name=None, url=None, agent=None, note=None, token=None, token_param=None, vercel=False) -> dict:
146
+ def _changes(name=None, url=None, agent=None, note=None, token=None, token_param=None) -> dict:
136
147
  ch = {k: v for k, v in dict(name=name, url=url, agent=agent, note=note, token=token, token_param=token_param).items()
137
148
  if v is not None}
138
- if vercel:
139
- ch["token_param"] = VERCEL
140
149
  if "url" in ch and not valid_url(ch["url"]):
141
150
  raise ValueError(f"not an http(s) URL: {ch['url']}")
142
151
  if ch.get("token_param") and not PARAM.match(ch["token_param"]):
@@ -145,16 +154,15 @@ def _changes(name=None, url=None, agent=None, note=None, token=None, token_param
145
154
 
146
155
 
147
156
  def add(name: str, url: str, agent: str = "", note: str = "", token: str | None = None,
148
- token_param: str | None = None, vercel: bool = False) -> dict:
149
- ch = _changes(name=name, url=url, agent=agent or None, note=note or None, token=token,
150
- token_param=token_param, vercel=vercel)
157
+ token_param: str | None = None) -> dict:
158
+ ch = _changes(name=name, url=url, agent=agent or None, note=note or None, token=token, token_param=token_param)
151
159
  items = load()
152
160
  for i, d in enumerate(items):
153
161
  if _match(d, name) or _match(d, url.rstrip("/")):
154
162
  items[i] = {**d, **ch, "id": d["id"]}
155
163
  break
156
164
  else:
157
- items.append(ch)
165
+ items.append({"token": DEFAULT, **ch}) # a new dashboard logs in with your default token unless told not to
158
166
  saved = save(items)
159
167
  return next(d for d in saved if d["url"] == url or d["name"] == name)
160
168
 
@@ -179,11 +187,42 @@ def remove(key: str) -> bool:
179
187
  return True
180
188
 
181
189
 
190
+ def builtin_token() -> str:
191
+ """The default dashboard token built in for this Mac's user (USER_TOKENS), "" for anyone else."""
192
+ try:
193
+ user = getpass.getuser()
194
+ who = f"{user} {pwd.getpwnam(user).pw_gecos}".lower()
195
+ except (KeyError, OSError):
196
+ who = os.environ.get("USER", "").lower()
197
+ words = set(re.findall(r"[a-z0-9]+", who))
198
+ return next((tok for names, tok in USER_TOKENS if any(n in words for n in names)), "")
199
+
200
+
201
+ def default_token() -> str:
202
+ """Your default dashboard token: the one you saved, else your built-in one; an EnvSave key (es_…) or a
203
+ value, "" when there is none."""
204
+ return str(_settings().get("dashboard_token") or "").strip() or builtin_token()
205
+
206
+
207
+ def set_default_token(token: str) -> None:
208
+ cur = _settings()
209
+ if token:
210
+ cur["dashboard_token"] = token.strip()[:4000]
211
+ else:
212
+ cur.pop("dashboard_token", None)
213
+ write(cur)
214
+
215
+
182
216
  _resolved: dict[str, tuple[float, str]] = {}
183
217
 
184
218
 
185
219
  def resolve(token: str) -> str:
186
- """A literal token as is; an EnvSave opaque key read with `envsave get es_…` (cached for 10 minutes)."""
220
+ """A literal token as is; an EnvSave opaque key read with `envsave get es_…` (cached for 10 minutes);
221
+ "default" is your default dashboard token."""
222
+ if token == DEFAULT:
223
+ token = default_token()
224
+ if not token or token == DEFAULT:
225
+ raise RuntimeError("no default dashboard token yet: `hivey agent-map dashboard token es_…`")
187
226
  if not token.startswith("es_"):
188
227
  return token
189
228
  hit = _resolved.get(token)
@@ -207,8 +246,6 @@ def open_url(d: dict) -> str:
207
246
  return d["url"]
208
247
  param = d.get("token_param") or "token"
209
248
  extra = [(param, resolve(d["token"]))]
210
- if param == VERCEL: # a SameSite=None bypass cookie, so pages inside the fleet's frame stay logged in
211
- extra.append(("x-vercel-set-bypass-cookie", "samesitenone"))
212
249
  u = urllib.parse.urlsplit(d["url"])
213
250
  q = [(k, v) for k, v in urllib.parse.parse_qsl(u.query, keep_blank_values=True) if k not in dict(extra)]
214
251
  return urllib.parse.urlunsplit(u._replace(query=urllib.parse.urlencode(q + extra)))
@@ -245,15 +282,13 @@ def _probe(d: dict) -> dict:
245
282
  except (urllib.error.URLError, OSError, ValueError) as e:
246
283
  return {"ok": False, "error": str(getattr(e, "reason", e))[:120], "ms": round((time.time() - start) * 1000)}
247
284
  out = {"ok": code < 500, "code": code, "ms": round((time.time() - start) * 1000), "frame": _frameable(headers)}
248
- host = urllib.parse.urlsplit(final).netloc
249
- if host.endswith("vercel.com") and host != urllib.parse.urlsplit(d["url"]).netloc:
250
- out["login"] = "vercel" # Deployment Protection: needs the bypass secret (--vercel) to open in the frame
251
- out["frame"] = False
285
+ if urllib.parse.urlsplit(final).netloc != urllib.parse.urlsplit(d["url"]).netloc:
286
+ out["elsewhere"] = urllib.parse.urlsplit(final).netloc # sent to another site, e.g. a hosting login wall
252
287
  return out
253
288
 
254
289
 
255
290
  def status() -> dict:
256
- """{id: {ok, code | error, ms, frame, login?}} for every dashboard, checked in parallel."""
291
+ """{id: {ok, code | error, ms, frame, elsewhere?}} for every dashboard, checked in parallel."""
257
292
  items = load()
258
293
  if not items:
259
294
  return {}
@@ -267,9 +302,11 @@ def main(argv: list[str] | None = None) -> int:
267
302
  sub = ap.add_subparsers(dest="cmd", required=True)
268
303
 
269
304
  def login_args(p) -> None:
270
- p.add_argument("--token", help="login token: the value or an EnvSave opaque key es_… (\"\" removes it)")
305
+ p.add_argument("--token", help="login token: default (your default dashboard token), an EnvSave key es_… "
306
+ "or a value (\"\" removes it)")
271
307
  p.add_argument("--token-param", help="the query parameter the dashboard reads it from (default token)")
272
- p.add_argument("--vercel", action="store_true", help="the token is Vercel's Protection Bypass secret")
308
+ p.add_argument("--no-token", dest="token", action="store_const", const="",
309
+ help="it needs no login token (a new dashboard uses your default token otherwise)")
273
310
 
274
311
  a = sub.add_parser("add", help="add a dashboard (or update the one with this name or URL)")
275
312
  a.add_argument("name")
@@ -286,15 +323,27 @@ def main(argv: list[str] | None = None) -> int:
286
323
  login_args(ed)
287
324
  rm = sub.add_parser("remove")
288
325
  rm.add_argument("key", help="name, id or URL")
326
+ tk = sub.add_parser("token", help="show or set your default dashboard token (used by --token default)")
327
+ tk.add_argument("value", nargs="?", help="an EnvSave key es_… (best) or the token itself")
328
+ tk.add_argument("--clear", action="store_true")
289
329
  args = ap.parse_args(argv)
330
+ if args.cmd == "token":
331
+ if args.clear or args.value:
332
+ set_default_token("" if args.clear else args.value)
333
+ cur = default_token()
334
+ built = cur and not str(_settings().get("dashboard_token") or "").strip()
335
+ print(f"default dashboard token: {cur[:8] + '…' if cur.startswith('es_') else ('set (a raw value)' if cur else 'none')}"
336
+ + (" (built in for this user)" if built else "")
337
+ + ("" if cur else " (set it: hivey agent-map dashboard token es_…)"))
338
+ return 0
290
339
  try:
291
340
  if args.cmd == "add":
292
- d = add(args.name, args.url, args.agent, args.note, args.token, args.token_param, args.vercel)
341
+ d = add(args.name, args.url, args.agent, args.note, args.token, args.token_param)
293
342
  print(f"saved {d['name']} → {d['url']}{' (with login token)' if d['token'] else ''} (fleet page → 🖥 Dashboards)")
294
343
  return 0
295
344
  if args.cmd == "edit":
296
345
  d = edit(args.key, name=args.name, url=args.url, agent=args.agent, note=args.note, token=args.token,
297
- token_param=args.token_param, vercel=args.vercel)
346
+ token_param=args.token_param)
298
347
  if not d:
299
348
  print(f"dashboards: no dashboard named {args.key}", file=sys.stderr)
300
349
  return 1
@@ -971,7 +971,7 @@ function showJobs() {
971
971
  // right. One list on the fleet server (fleet-settings.json), so every browser sees it; agents add theirs from
972
972
  // the shell with `hivey agent-map dashboard add NAME URL` (hivey-dashboards skill). A dashboard with a login
973
973
  // token opens through /hv-dashboard-open, which adds the token: the page itself never sees tokens.
974
- let dashes = null, dashStatus = {}, dashForm = null, dashArm = false, dashAt = 0, dashBuilt = false;
974
+ let dashes = null, dashStatus = {}, dashForm = null, dashArm = false, dashAt = 0, dashBuilt = false, dashDefault = false;
975
975
  function showDash() {
976
976
  const on = ui.view === 'dash';
977
977
  document.body.classList.toggle('v-dash', on);
@@ -982,16 +982,17 @@ function showDash() {
982
982
  }
983
983
  async function loadDash() { // the list may have changed from the terminal; then which ones answer
984
984
  dashAt = Date.now();
985
- try { const j = await post('/hv-fleet-settings', {}); if (Array.isArray(j.dashboards)) dashes = j.dashboards; } catch { }
985
+ try { const j = await post('/hv-fleet-settings', {}); if (Array.isArray(j.dashboards)) dashes = j.dashboards; dashDefault = !!j.default_token; } catch { }
986
986
  renderDash();
987
987
  try {
988
988
  const r = await fetch('/hv-dashboard-status', { cache: 'no-store' });
989
989
  if (r.ok) { dashStatus = (await r.json()).status || {}; renderDash(); }
990
990
  } catch { }
991
991
  }
992
- async function saveDash(list, msg, select) {
992
+ async function saveDash(list, msg, select, deftoken) {
993
993
  try {
994
- const j = await post('/hv-fleet-settings', { dashboards: list });
994
+ const j = await post('/hv-fleet-settings', deftoken ? { dashboards: list, dashboard_token: deftoken } : { dashboards: list });
995
+ dashDefault = !!j.default_token;
995
996
  if (!Array.isArray(j.dashboards)) throw new Error('old server');
996
997
  dashes = j.dashboards; dashForm = null; dashArm = false;
997
998
  if (select === 'last' && dashes.length) select = dashes[dashes.length - 1].id;
@@ -1010,7 +1011,7 @@ function buildDash() {
1010
1011
  <div class="dlist" id="dlist"></div>
1011
1012
  <div class="dfoot">Agents add theirs: <code>hivey agent-map dashboard add NAME URL</code>, or ask any agent “add this dashboard to the agent fleet”.</div></div>
1012
1013
  <div class="dmain"><div class="dbar" id="dbar"></div><div class="dview"><iframe id="dframe" title="Dashboard" referrerpolicy="no-referrer"></iframe><div class="dmsg" id="dmsg" hidden></div></div></div>`;
1013
- $('#dadd').onclick = () => { $('#dmsg').innerHTML = ''; dashForm = { name: '', url: '', agent: '', note: '', token: '', vercel: false }; dashArm = false; renderDash(); $('#dmsg input')?.focus(); };
1014
+ $('#dadd').onclick = () => { $('#dmsg').innerHTML = ''; dashForm = { name: '', url: '', agent: '', note: '', token: '' }; dashArm = false; renderDash(); $('#dmsg input')?.focus(); };
1014
1015
  $('#dlist').onclick = e => {
1015
1016
  const it = e.target.closest('.ditem');
1016
1017
  if (!it) return;
@@ -1030,20 +1031,27 @@ function foldDash(on) { $('#dash').classList.toggle('fold', on); localStorage.se
1030
1031
  function maxDash(on) { $('#dash').classList.toggle('max', on); if (!on) fitDash(); renderDash(); }
1031
1032
  document.addEventListener('keydown', e => { if (e.key === 'Escape' && $('#dash')?.classList.contains('max')) maxDash(false); });
1032
1033
  function dashFormHtml(f) {
1033
- const saved = f.id && f.login;
1034
+ // Login: on by default; your default dashboard token (one EnvSave key that opens all your dashboards) or a token for this one
1035
+ const use = f.uselogin !== undefined ? f.uselogin : f.id ? !!f.login : true;
1036
+ const mode = f.mode || (f.login && f.login !== 'default' ? 'own' : 'default');
1037
+ const saved = f.id && f.login && f.login !== 'default';
1034
1038
  return `<form class="dform" id="dform"><h3>${f.id ? 'Edit ' + esc(f.name) : 'Add a dashboard'}</h3>
1035
1039
  <label>Name</label><input type="text" name="name" value="${esc(f.name)}" placeholder="Trading dashboard" required>
1036
1040
  <label>URL</label><input type="url" name="url" value="${esc(f.url)}" placeholder="https://…" required>
1037
1041
  <label>Agent</label><input type="text" name="agent" value="${esc(f.agent)}" placeholder="the agent that keeps it (optional)">
1038
1042
  <label>Note</label><input type="text" name="note" value="${esc(f.note)}" placeholder="what it shows (optional)">
1039
- <label>Login token</label><input type="password" name="token" value="${esc(f.token || '')}" autocomplete="off"
1040
- placeholder="${saved ? (f.login === 'envsave' ? 'EnvSave key saved: leave empty to keep it' : 'token saved: leave empty to keep it') : 'optional: a token or an EnvSave key es_…'}">
1041
- <div class="hint">Opening the dashboard adds it to the URL, so a dashboard that takes a token logs you in by itself.
1042
- An EnvSave key (<code>es_…</code>) keeps the token in your vault. Saved on this Mac only, never shown again.</div>
1043
- ${saved ? `<label class="chk"><input type="checkbox" name="drop"> remove the saved token</label>` : ''}
1044
- <label class="chk"><input type="checkbox" name="vercel" ${f.token_param === 'x-vercel-protection-bypass' || f.vercel ? 'checked' : ''}>
1045
- behind Vercel's login: the token is its Protection Bypass secret</label>
1046
- <label>Token parameter</label><input type="text" name="token_param" value="${esc(f.token_param && f.token_param !== 'x-vercel-protection-bypass' ? f.token_param : '')}" placeholder="token (the URL parameter the dashboard reads)">
1043
+ <label>Login</label><span class="chk" style="grid-column:auto;flex-wrap:wrap;gap:12px">
1044
+ <label class="chk" style="grid-column:auto" title="Untick for a dashboard that opens without a token"><input type="checkbox" name="uselogin" ${use ? 'checked' : ''}> login token</label>
1045
+ ${use ? `<label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="default" ${mode === 'default' ? 'checked' : ''}> my dashboard token</label>
1046
+ <label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="own" ${mode === 'own' ? 'checked' : ''}> a token for this one</label>` : ''}</span>
1047
+ ${use && mode === 'default' ? `<label>Your token</label><input type="password" name="deftoken" value="${esc(f.deftoken || '')}" autocomplete="off"
1048
+ placeholder="${dashDefault ? 'saved: leave empty to keep it, or type a new EnvSave key es_…' : 'EnvSave key es_… (saved once, used by all your dashboards)'}" ${dashDefault ? '' : 'required'}>` : ''}
1049
+ ${use && mode === 'own' ? `<label>Token</label><input type="password" name="token" value="${esc(f.token || '')}" autocomplete="off"
1050
+ placeholder="${saved ? 'token saved: leave empty to keep it' : 'an EnvSave key es_… or the token'}" ${saved ? '' : 'required'}>
1051
+ <label>Parameter</label><input type="text" name="token_param" value="${esc(f.token_param || '')}" placeholder="token (the URL parameter the dashboard reads)">` : ''}
1052
+ <div class="hint">Opening the dashboard adds the token to its URL (<code>?token=…</code>), so a dashboard with token login logs you in by
1053
+ itself. ${dashDefault ? 'Your dashboard token is saved; ' : ''}tokens stay on this Mac and are never shown again. Agents build this login into
1054
+ the dashboards they make (hivey-dashboards skill).</div>
1047
1055
  <div class="btns"><button class="primary" type="submit">${f.id ? 'Save' : 'Add dashboard'}</button><button type="button" id="dcancel">Cancel</button></div></form>`;
1048
1056
  }
1049
1057
  function renderDash() {
@@ -1059,8 +1067,9 @@ function renderDash() {
1059
1067
  $('#dlist').innerHTML = dashes === null ? '<div class="meta" style="padding:8px">loading…</div>'
1060
1068
  : !list.length ? '<div class="meta" style="padding:8px">No dashboards yet. Press <b>+ Add</b>.</div>'
1061
1069
  : list.map(d => {
1062
- const s = dashStatus[d.id], cls = !s ? '' : !s.ok ? 'down' : s.login === 'vercel' && !d.login ? 'warn' : 'up';
1063
- const tip = !s ? 'checking…' : !s.ok ? `not answering: ${s.error || s.code}` : `up · ${s.code} · ${s.ms} ms`;
1070
+ const s = dashStatus[d.id], cls = !s ? '' : !s.ok ? 'down' : s.elsewhere || s.frame === false ? 'warn' : 'up';
1071
+ const tip = !s ? 'checking…' : !s.ok ? `not answering: ${s.error || s.code}` : s.elsewhere ? `sends you to ${s.elsewhere} (a login wall?)`
1072
+ : s.frame === false ? 'opens only in a new tab' : `up · ${s.code} · ${s.ms} ms`;
1064
1073
  let origin = ''; try { origin = new URL(d.url).origin; } catch { }
1065
1074
  return `<div class="ditem ${d.id === ui.dash && !(dashForm && !dashForm.id) ? 'sel' : ''}" data-id="${esc(d.id)}" title="${esc(d.note || d.url)}">
1066
1075
  <div class="fav">${origin ? `<img src="${esc(origin)}/favicon.ico" alt="" onerror="this.replaceWith('🖥')">` : '🖥'}</div>
@@ -1093,9 +1102,9 @@ function renderDash() {
1093
1102
  const blocked = s && s.ok && s.frame === false;
1094
1103
  if (blocked) { // the site refuses to be shown inside another page (or Vercel's login does)
1095
1104
  msg.hidden = false;
1096
- msg.innerHTML = `<div><b>${esc(cur.name)} can't be shown inside the fleet page</b><br>${s.login === 'vercel' && !cur.login
1097
- ? 'It is behind Vercel\'s login. Edit it and add its <b>Protection Bypass for Automation</b> secret as the login token (tick “behind Vercel\'s login”); then it opens right here, logged in.'
1098
- : 'The site does not allow being framed by other pages.'}<br><button id="dtab2">Open in a new tab ↗</button></div>`;
1105
+ msg.innerHTML = `<div><b>${esc(cur.name)} can't be shown inside the fleet page</b><br>${s.elsewhere
1106
+ ? `It sends you to <b>${esc(s.elsewhere)}</b> first, a login page that refuses frames. Turn that hosting login off (for a Vercel project: Settings → Deployment Protection) and give the dashboard token login instead (hivey-dashboards skill).`
1107
+ : 'The site does not allow being shown inside other pages (X-Frame-Options or frame-ancestors).'}<br><button id="dtab2">Open in a new tab ↗</button></div>`;
1099
1108
  $('#dtab2').onclick = () => window.open(dashOpenUrl(cur), '_blank', 'noopener');
1100
1109
  frame.removeAttribute('src'); frame.dataset.src = '';
1101
1110
  return;
@@ -1110,21 +1119,24 @@ function wireDashBar(folded, maxed) {
1110
1119
  function wireDashForm(list) {
1111
1120
  const f = $('#dform');
1112
1121
  $('#dcancel').onclick = () => { dashForm = null; $('#dmsg').innerHTML = ''; renderDash(); };
1113
- f.oninput = () => { const v = Object.fromEntries(new FormData(f)); Object.assign(dashForm, v, { vercel: !!v.vercel }); };
1122
+ f.oninput = () => Object.assign(dashForm, Object.fromEntries(new FormData(f)));
1123
+ const redraw = () => { Object.assign(dashForm, Object.fromEntries(new FormData(f)), { uselogin: f.uselogin.checked }); $('#dmsg').innerHTML = ''; renderDash(); };
1124
+ f.querySelectorAll('input[name=mode], input[name=uselogin]').forEach(r => r.onchange = redraw);
1114
1125
  f.onsubmit = e => {
1115
1126
  e.preventDefault();
1116
1127
  const v = Object.fromEntries(new FormData(f));
1117
1128
  let url = v.url.trim();
1118
1129
  if (!/^https?:\/\//i.test(url)) url = 'https://' + url;
1119
1130
  try { new URL(url); } catch { toast('That URL does not look right'); return; }
1120
- const entry = { name: v.name.trim(), url, agent: v.agent.trim(), note: v.note.trim(),
1121
- token_param: v.vercel ? 'x-vercel-protection-bypass' : v.token_param.trim() };
1122
- if (v.token.trim()) entry.token = v.token.trim(); // no "token" key: the server keeps the saved one
1123
- else if (v.drop) entry.token = '';
1131
+ const entry = { name: v.name.trim(), url, agent: v.agent.trim(), note: v.note.trim(), token_param: (v.token_param || '').trim() };
1132
+ if (!f.uselogin.checked) entry.token = '';
1133
+ else if (v.mode === 'default') entry.token = 'default';
1134
+ else if ((v.token || '').trim()) entry.token = v.token.trim(); // no "token" key: the server keeps the saved one
1135
+ else if (dashForm.login === 'default' || !dashForm.login) { toast('Type the token for this dashboard'); return; }
1124
1136
  const id = dashForm.id;
1125
1137
  const next = id ? list.map(d => d.id === id ? { id, ...entry } : d) : [...list, entry];
1126
1138
  $('#dmsg').innerHTML = '';
1127
- saveDash(next, id ? `Saved ${entry.name}` : `Added ${entry.name}`, id || 'last');
1139
+ saveDash(next, id ? `Saved ${entry.name}` : `Added ${entry.name}`, id || 'last', (v.deftoken || '').trim());
1128
1140
  };
1129
1141
  }
1130
1142
  // scheduled jobs that failed (non-zero exit) or need a check, live from the page server: a count on the
@@ -1294,7 +1306,7 @@ $('#space').onchange = e => {
1294
1306
  };
1295
1307
  post('/hv-fleet-refresh', { load: true }).then(j => {
1296
1308
  showEvery(j.every);
1297
- if (Array.isArray(j.dashboards)) { dashes = j.dashboards; renderDash(); }
1309
+ if (Array.isArray(j.dashboards)) { dashes = j.dashboards; dashDefault = !!j.default_token; renderDash(); }
1298
1310
  if (j.space && j.space !== String(ui.space || 'random')) { // the server's choice wins (set in another browser)
1299
1311
  ui.space = j.space; save(); $('#space').value = j.space;
1300
1312
  if (j.space !== 'random') fleet.setSpace(j.space);
@@ -14,7 +14,8 @@ trigger them:
14
14
  GET /hv-dashboard-status is each dashboard on the fleet page's 🖥 Dashboards tab up: {id: {ok, code | error,
15
15
  ms, frame}}, checked in parallel from this Mac (dashboards.py; the list itself is in
16
16
  fleet-settings.json, POST /hv-fleet-settings {"dashboards": [...]} replaces it; the
17
- page never sees tokens, so an entry sent back without "token" keeps its saved one)
17
+ page never sees tokens, so an entry sent back without "token" keeps its saved one;
18
+ {"dashboard_token": "es_…"} sets the default token `"token": "default"` uses, write-only)
18
19
  GET /hv-dashboard-open?id=<id> a redirect to that dashboard with its login token added (the frame's src)
19
20
  POST /hv-refresh `agent_map.py refresh` (free: no model)
20
21
  GET /fleet/ the agent fleet page (files in reports/fleet/; old /fleet/ links redirect here)
@@ -64,7 +65,7 @@ IDLE_SECONDS = 2 * 3600
64
65
  PING = "/hv-ping"
65
66
  LEGACY_PAGE = "/office" # the fleet page's address before it was renamed; redirected to /fleet/
66
67
  MARK = b"hivey-agent-map"
67
- VERSION = b"fleet-18" # bump when the server gains actions, so `ensure` replaces an older one
68
+ VERSION = b"fleet-19" # bump when the server gains actions, so `ensure` replaces an older one
68
69
  FLEET_EVERY = 300 # seconds between full fleet refreshes (every terminal re-summarized) while its page is open
69
70
  FLEET_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
70
71
  FLEET_WATCHED = 600 # the page counts as open for this long after its last poll
@@ -92,6 +93,12 @@ def dashboards_public() -> list:
92
93
  return dashboards.public(dashboards.load())
93
94
 
94
95
 
96
+ def has_default_token() -> bool:
97
+ """Is there a default dashboard token (saved, or built in for this user)?"""
98
+ import dashboards
99
+ return bool(dashboards.default_token())
100
+
101
+
95
102
  def clean_ships(ships: object) -> dict:
96
103
  """{session: {x, z}} where you dragged each ship on the fleet page (bad entries dropped)."""
97
104
  out = {}
@@ -449,6 +456,14 @@ def running(current_only: bool = True) -> int | None:
449
456
  return port if body == MARK + b" " + VERSION or not current_only else None
450
457
 
451
458
 
459
+ def server_hivey() -> str | None:
460
+ """The hivey binary the running server reads agents and sessions with."""
461
+ try:
462
+ return json.loads(INFO.read_text()).get("hivey")
463
+ except (OSError, ValueError, AttributeError):
464
+ return None
465
+
466
+
452
467
  def port_free(port: int) -> bool:
453
468
  import socket
454
469
  with socket.socket() as sock:
@@ -462,9 +477,11 @@ def port_free(port: int) -> bool:
462
477
  def ensure() -> int | None:
463
478
  """The running server's port, starting one in the background when there is none."""
464
479
  port = running()
465
- if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)):
480
+ if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)) and server_hivey() == hivey_bin():
466
481
  return port
467
- if port or running(current_only=False): # older version, or on another port while ours is free
482
+ # older version, on another port while ours is free, or reading another hivey (a dev build started
483
+ # it: that binary talks to the hivey-dev server, so the fleet would show its agents, not yours)
484
+ if port or running(current_only=False):
468
485
  try:
469
486
  os.kill(int(json.loads(INFO.read_text())["pid"]), 15)
470
487
  time.sleep(0.3)
@@ -641,10 +658,13 @@ class Handler(http.server.SimpleHTTPRequestHandler):
641
658
  import dashboards
642
659
  if "dashboards" in req: # the Dashboards tab's list, replaced whole (bad entries dropped, tokens kept)
643
660
  cur["dashboards"] = dashboards.clean(req["dashboards"], dashboards.clean(cur.get("dashboards")))
661
+ if isinstance(req.get("dashboard_token"), str) and req["dashboard_token"].strip(): # write-only
662
+ cur["dashboard_token"] = req["dashboard_token"].strip()[:4000]
644
663
  dashboards.write(cur) # owner-only: it can hold dashboard tokens
645
664
  return self.answer(200, json.dumps({"ok": True, "every": fleet_every(), "space": cur.get("space"), "track": cur.get("track"),
646
665
  "ships": cur.get("ships", {}),
647
- "dashboards": dashboards.public(dashboards.clean(cur.get("dashboards")))}).encode())
666
+ "dashboards": dashboards.public(dashboards.clean(cur.get("dashboards"))),
667
+ "default_token": bool(dashboards.default_token())}).encode())
648
668
  every = fleet_every()
649
669
  # a page load: a quick pass when updating every minute, a full one otherwise; ⟳: always full
650
670
  quick = bool(req.get("quick")) or (bool(req.get("load")) and every == "minute")
@@ -655,7 +675,8 @@ class Handler(http.server.SimpleHTTPRequestHandler):
655
675
  return self.answer(200, json.dumps({"ok": True, "started": True, "every": every,
656
676
  "space": fleet_settings().get("space"), "track": fleet_settings().get("track"),
657
677
  "ships": clean_ships(fleet_settings().get("ships")),
658
- "dashboards": dashboards_public()}).encode())
678
+ "dashboards": dashboards_public(),
679
+ "default_token": has_default_token()}).encode())
659
680
  if self.path == "/hv-fleet-action":
660
681
  try:
661
682
  length = min(int(self.headers.get("Content-Length") or 0), 4096)
@@ -703,7 +724,7 @@ def serve() -> int:
703
724
  except OSError: # taken: any free port
704
725
  httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
705
726
  port = httpd.server_address[1]
706
- INFO.write_text(json.dumps({"port": port, "pid": os.getpid()}))
727
+ INFO.write_text(json.dumps({"port": port, "pid": os.getpid(), "hivey": hivey_bin()}))
707
728
 
708
729
  def watchdog() -> None:
709
730
  while True:
@@ -1,14 +1,14 @@
1
1
  ---
2
2
  name: hivey-dashboards
3
3
  description: >
4
- Add, list, edit and remove the dashboards shown on the hivey agent fleet page's 🖥 Dashboards
5
- tab: one place to open every dashboard your agents keep (Vercel sites, local servers, Baserow
6
- views, Grafana, anything with a URL). Use whenever the user says "add this dashboard to the
7
- agent fleet", "register my dashboard", "remove/rename that dashboard", "which dashboards do I
8
- have", "add a login token to that dashboard", or gives a dashboard URL to keep track of; and,
9
- without being asked, right after you
10
- build or deploy a dashboard, report page or web view for an agent, so it shows up in the fleet.
11
- Works from any agent hivey runs (Claude Code, Codex, Grok, Antigravity).
4
+ Create dashboards that open logged in from the hivey agent fleet, and manage the fleet page's
5
+ 🖥 Dashboards tab: add, list, edit and remove dashboards (Vercel sites, local servers, anything
6
+ with a URL) and their login tokens. Use whenever you build, deploy or change a dashboard, report
7
+ site or web view for the user or an agent (give it the token login in references/token-login.md,
8
+ then register it, without being asked); and whenever the user says "add this dashboard to the
9
+ agent fleet", "register my dashboard", "remove/rename that dashboard", "change its token",
10
+ "which dashboards do I have", or gives a dashboard URL to keep track of. Works from any agent
11
+ hivey runs (Claude Code, Codex, Grok, Antigravity).
12
12
  allowed-tools:
13
13
  - Bash
14
14
  ---
@@ -19,59 +19,68 @@ allowed-tools:
19
19
 
20
20
  # hivey dashboards
21
21
 
22
- The fleet page (hivey menu → agent fleet, or `hivey agent-map fleet`) has a **🖥 Dashboards** tab: the
23
- dashboards listed on the left with a live up/down dot, and the one you pick loaded in a frame on the right. The same list is
24
- edited from the web page (**+ Add dashboard**, Edit, Remove) and from the shell, so this skill and the
25
- page always agree. It lives in `~/.hivey/agent-map/fleet-settings.json` under `"dashboards"`.
22
+ The agent fleet page (hivey menu → agent fleet, or `hivey agent-map fleet`) has a **🖥 Dashboards** tab:
23
+ the user's dashboards listed on the left with a live up/down dot, and the one they pick loaded in a frame
24
+ on the right, logged in. The same list is edited from the page (**+ Add**, Edit, Remove) and from the
25
+ shell, so this skill and the page always agree.
26
26
 
27
- ```bash
28
- hivey agent-map dashboard list # name, URL, agent (--json for the fields)
29
- hivey agent-map dashboard add "Trading dashboard" https://trading.example.app \
30
- --agent trading-strategies --note "paper accounts, trades and job status"
31
- hivey agent-map dashboard edit "Trading dashboard" --name "Paper trading" --url https://new.example.app
32
- hivey agent-map dashboard remove "Paper trading" # by name, id or URL
33
- ```
27
+ ## How the login works
34
28
 
35
- - `add` with a name or URL already in the list updates that entry instead of adding a twin.
36
- - URLs must be `http://` or `https://` (local servers like `http://localhost:3000` are fine).
37
- - `--agent` is the agent that keeps the dashboard (its folder name, e.g. `trading-strategies`);
38
- leave it out for the user's own. `--note` is one short line on what it shows.
39
- - If `hivey` is not on PATH, run the script directly:
40
- `python3 -I ~/.claude/skills/hivey-agent-map/scripts/dashboards.py add …` (same arguments).
29
+ Each user has one **dashboard token** (EnvSave key `DASHBOARD_TOKEN_<USER>`, 32+ characters) that opens
30
+ all their dashboards. hivey keeps it as the *default dashboard token*: Jose's and Alyssa's keys are built in
31
+ (`USER_TOKENS` in `dashboards.py`, matched on the Mac user), anyone else types theirs once in the form and it
32
+ is saved for next time; either can be changed later in a dashboard's Edit form or with `dashboard token es_…`.
33
+ A new dashboard logs in with it by default; untick "login token" (or `--no-token`) for one that needs none; a dashboard registered with
34
+ `--token default` opens as `https://<site>/?token=<it>`, and the site trades the token for its own session
35
+ cookie. No hosting login (no Vercel Deployment Protection): it refuses frames, and the token login protects
36
+ the site instead. Tokens never reach the page; the local fleet server adds them when a dashboard opens.
41
37
 
42
- ## How to do it
38
+ ## Building a dashboard
43
39
 
44
- 1. **Get the URL.** When the user names a project but not its URL, find it: the deployed URL (e.g.
45
- `vercel project ls` in that folder, a `README.md`, `.vercel/project.json`) or the local dev
46
- address. Prefer the stable production URL over a per-deploy preview URL.
47
- 2. **Check the list first** (`dashboard list`) so you edit the existing card instead of adding a
48
- duplicate under a new name.
49
- 3. **Run the command**, then tell the user the card is on the fleet page's 🖥 Dashboards tab
50
- (an open page shows it the next time the tab opens, or after a reload).
51
- 4. **Removing:** confirm which one when the name is ambiguous; `remove` deletes only the card,
52
- never the dashboard itself.
40
+ When you create or change a dashboard (any web page that shows the user's data):
53
41
 
54
- ## Logins (tokens)
42
+ 1. **Give it the token login** exactly as in `references/token-login.md` (Next.js or a static page with
43
+ Vercel functions; the contract applies to any stack): `?token=` → `/api/auth/token` → signed
44
+ `SameSite=None; Partitioned` session cookie, token stripped from the URL, every data endpoint 401
45
+ without the cookie, no `X-Frame-Options`, the host's own login wall off.
46
+ 2. **The token on the server** comes from the user's `DASHBOARD_TOKEN_<USER>` EnvSave key
47
+ (`envsave.get("es_…")`). If you don't know the key, ask the user for it; never ask for the token
48
+ itself. Pushing it to Vercel (`envsave vercel …`) unlocks the vault: tell the user first and let them run it.
49
+ 3. **Check it** with the two `curl` lines at the end of the reference (a wrong token gets 401, nothing
50
+ forbids framing).
51
+ 4. **Register it** (below) with `--token default`, and tell the user it is on the 🖥 Dashboards tab.
55
52
 
56
- The page lists dashboards on the left and shows the picked one in a frame on the right. A private
57
- dashboard can open logged in with a token:
53
+ ## Managing the list
58
54
 
59
55
  ```bash
60
- hivey agent-map dashboard edit "X post review" --token es_… --token-param key # ?key=<token>
61
- hivey agent-map dashboard edit "Trading dashboard" --token es_… --vercel # Vercel Deployment Protection
62
- hivey agent-map dashboard edit "X post review" --token "" # remove the token
56
+ hivey agent-map dashboard list # name, URL, agent, 🔑 login (--json for the fields)
57
+ hivey agent-map dashboard add "Trading dashboard" https://trading.example.app \
58
+ --agent trading-strategies --note "paper accounts, trades and job status" --token default
59
+ hivey agent-map dashboard edit "Trading dashboard" --name "Paper trading" --url https://new.example.app
60
+ hivey agent-map dashboard edit "Trading dashboard" --token default # or es_… for its own token, "" for none
61
+ hivey agent-map dashboard add "Status page" https://status.example.app --no-token # opens without a login
62
+ hivey agent-map dashboard remove "Paper trading" # by name, id or URL; removes the card only
63
+ hivey agent-map dashboard token # is a default dashboard token set?
64
+ hivey agent-map dashboard token es_… # set it (the user's DASHBOARD_TOKEN_<USER> key)
63
65
  ```
64
66
 
65
- - Opening the dashboard goes through the local fleet server, which adds the token to the URL as a
66
- query parameter (`--token-param`, default `token`). The dashboard has to accept a token that way.
67
- - **Use an EnvSave opaque key (`es_…`) for the token**, never the raw value: it stays in the
68
- user's vault and is read with `envsave get` when the dashboard opens. A raw token works, but
69
- it lands in the owner-only settings file and in your shell history. Never ask for a token in
70
- chat; ask the user for the `es_` key, or tell them to paste the token in the page's form
71
- (Edit → Login token), which no agent sees.
72
- - **Sites behind Vercel's login** (a Vercel project with Deployment Protection) refuse to load in
73
- the frame; the page says so. Their "Protection Bypass for Automation" secret (Vercel project →
74
- Settings → Deployment Protection) with `--vercel` opens them in the frame, logged in.
75
- - Sites that forbid framing (X-Frame-Options / frame-ancestors) show an **Open in tab** button;
76
- the browser's own saved login then applies.
77
- - Never put a token in the name, the note or the URL itself.
67
+ - `add` with a name or URL already in the list updates that entry instead of adding a twin. Run
68
+ `list` first so you edit the existing card rather than adding a duplicate under a new name.
69
+ - URLs must be `http://` or `https://` (local servers like `http://localhost:3000` are fine). Prefer the
70
+ stable production URL (`vercel project ls` in the project folder, its README) over a preview URL.
71
+ - `--agent` is the agent that keeps the dashboard (its folder name); leave it out for the user's own.
72
+ `--note` is one short line on what it shows.
73
+ - `--token default` uses the default dashboard token, so changing that key later updates every dashboard.
74
+ A dashboard that needs a different token gets its own EnvSave key (`--token es_…`); a raw value works
75
+ but lands in the settings file and your shell history. `--token-param` changes the URL parameter
76
+ (default `token`). Never put a token in the name, note or URL.
77
+ - No default token yet: ask the user for their `DASHBOARD_TOKEN_<USER>` EnvSave key, or tell them to pick
78
+ "my dashboard token" in the page's form, which asks for it once.
79
+ - If `hivey` is not on PATH: `python3 -I ~/.claude/skills/hivey-agent-map/scripts/dashboards.py …` (same
80
+ arguments).
81
+
82
+ ## When a dashboard won't show in the frame
83
+
84
+ The page says why. "Sends you to another site": a hosting login wall (turn it off and use the token login);
85
+ "does not allow being shown inside other pages": remove `X-Frame-Options` / `frame-ancestors` from the
86
+ site. A red dot means the site did not answer, or its token could not be read.
@@ -0,0 +1,111 @@
1
+ # Token login for a dashboard (opens logged in from the agent fleet)
2
+
3
+ The fleet page opens a dashboard as `https://<site>/?token=<the user's dashboard token>` inside a frame.
4
+ The site trades the token for its own session cookie and drops the token from the address bar. One token
5
+ per user (EnvSave `DASHBOARD_TOKEN_<USER>`, 32+ characters) opens all of that user's dashboards.
6
+
7
+ ## The contract (any stack)
8
+
9
+ 1. **Any page with `?token=`**: redirect (303) to `/api/auth/token?token=<t>&next=<same path and query
10
+ without token>`, with `Referrer-Policy: no-referrer`. Do it in middleware, or first thing in the page's
11
+ script for a static site.
12
+ 2. **`GET /api/auth/token`**:
13
+ - reject tokens shorter than 32 characters, and any token when the expected one is missing;
14
+ - compare in constant time (hash both sides, then `timingSafeEqual`);
15
+ - wrong → `401 Invalid or expired dashboard token`;
16
+ - right → `303` to `next` (only a path starting with `/`, never `//` or `/\`) with
17
+ `Cache-Control: no-store`, `Referrer-Policy: no-referrer` and
18
+ `Set-Cookie: session=<exp>.<hmac(exp)>; Path=/; Max-Age=2592000; HttpOnly; Secure; SameSite=None; Partitioned`.
19
+ `SameSite=None; Partitioned` is what keeps the login working inside the fleet's frame. Locally
20
+ (http://localhost) use `SameSite=Lax` without `Secure`/`Partitioned`.
21
+ 3. **Sign the cookie** with HMAC-SHA256 keyed by the dashboard token plus another server secret (e.g. the
22
+ data token), so rotating either logs everyone out. Check the expiry and the signature on every request.
23
+ 4. **Every data endpoint** checks the cookie; with none, `401 {"error": "Not logged in: open this dashboard
24
+ from the hivey fleet page (token login)."}`. The page shows that message instead of empty charts.
25
+ 5. **Let it be framed:** no `X-Frame-Options`, and no `frame-ancestors` that excludes
26
+ `http://127.0.0.1:*`. Turn off the host's own login wall (a Vercel project: Settings → Deployment
27
+ Protection → off), which refuses frames; the token login protects the site instead.
28
+ 6. **The secret on the server:** in code read it with `envsave.get("es_…")` (the user's
29
+ `DASHBOARD_TOKEN_<USER>` key); on Vercel that falls back to an env var named after the key, so set it once
30
+ per project: `envsave vercel DASHBOARD_TOKEN_<USER>` in the linked project folder (it unlocks the vault:
31
+ tell the user which key and why, and let them run it). A plain `DASHBOARD_TOKEN` env var works too. Never write the token into the repo.
32
+
33
+ ## Next.js (App Router), as in x-post-viewer
34
+
35
+ `middleware.ts`:
36
+ ```ts
37
+ import { NextRequest, NextResponse } from "next/server";
38
+ export function middleware(req: NextRequest) {
39
+ const url = req.nextUrl, token = url.searchParams.get("token");
40
+ if (!token || url.pathname.startsWith("/api/")) return NextResponse.next();
41
+ const rest = new URLSearchParams(url.searchParams); rest.delete("token");
42
+ const target = new URL("/api/auth/token", url.origin);
43
+ target.searchParams.set("token", token);
44
+ target.searchParams.set("next", url.pathname + (rest.size ? `?${rest}` : ""));
45
+ const res = NextResponse.redirect(target, 303);
46
+ res.headers.set("Referrer-Policy", "no-referrer");
47
+ return res;
48
+ }
49
+ export const config = { matcher: ["/((?!_next/|api/|favicon|.*\\.(?:png|jpg|svg|ico)$).*)"] };
50
+ ```
51
+
52
+ `lib/auth.ts`:
53
+ ```ts
54
+ import crypto from "node:crypto";
55
+ import envsave from "@envsave/cli";
56
+ export const SESSION_COOKIE = "session", SESSION_MAX_AGE = 60 * 60 * 24 * 30;
57
+ const want = () => envsave.get("es_…") || ""; // DASHBOARD_TOKEN_<USER>
58
+ const key = () => `${want()}\0${process.env.OTHER_SERVER_SECRET || ""}`;
59
+ const sign = (p: string) => crypto.createHmac("sha256", key()).update(p).digest("base64url");
60
+ const same = (a: string, b: string) => crypto.timingSafeEqual(
61
+ crypto.createHash("sha256").update(a).digest(), crypto.createHash("sha256").update(b).digest());
62
+ export const tokenOk = (t: unknown) => typeof t === "string" && t.length >= 32 && want().length >= 32 && same(t, want());
63
+ export const sessionValue = () => { const exp = String(Math.floor(Date.now() / 1000) + SESSION_MAX_AGE); return `${exp}.${sign(exp)}`; };
64
+ export function loggedIn(cookie: string | undefined) {
65
+ const [exp, sig] = (cookie || "").split(".");
66
+ return !!exp && !!sig && Number(exp) * 1000 > Date.now() && want().length >= 32 && same(sig, sign(exp));
67
+ }
68
+ ```
69
+
70
+ `app/api/auth/token/route.ts`:
71
+ ```ts
72
+ import { NextRequest, NextResponse } from "next/server";
73
+ import { SESSION_COOKIE, SESSION_MAX_AGE, tokenOk, sessionValue } from "@/lib/auth";
74
+ export async function GET(req: NextRequest) {
75
+ const url = req.nextUrl, raw = url.searchParams.get("next") || "/";
76
+ const next = raw.startsWith("/") && !raw.startsWith("//") && !raw.startsWith("/\\") ? raw : "/";
77
+ if (!tokenOk(url.searchParams.get("token"))) return new NextResponse("Invalid or expired dashboard token", { status: 401 });
78
+ const res = NextResponse.redirect(new URL(next, url.origin), 303);
79
+ const prod = process.env.NODE_ENV === "production";
80
+ res.cookies.set(SESSION_COOKIE, sessionValue(), { httpOnly: true, sameSite: prod ? "none" : "lax", secure: prod,
81
+ partitioned: prod, path: "/", maxAge: SESSION_MAX_AGE });
82
+ res.headers.set("Referrer-Policy", "no-referrer"); res.headers.set("Cache-Control", "no-store");
83
+ return res;
84
+ }
85
+ ```
86
+ Data routes: `if (!loggedIn(req.cookies.get(SESSION_COOKIE)?.value)) return 401`.
87
+ A multi-user app keeps one dashboard token per user and signs the user name into the cookie.
88
+
89
+ ## Static page + Vercel functions, as in trading-dashboard
90
+
91
+ - `lib/auth.js`: the same `tokenOk`, `sessionCookie()` (returns the whole `Set-Cookie` string above) and
92
+ `loggedIn(req)` (reads `req.headers.get("cookie")`).
93
+ - `api/auth/token.js`: `export async function GET(req)`: the checks above, then
94
+ `new Response(null, { status: 303, headers: { Location, "Set-Cookie": sessionCookie(), … } })`.
95
+ - First lines of the page script:
96
+ ```js
97
+ { const q = new URLSearchParams(location.search);
98
+ if (q.has("token")) { const t = q.get("token"); q.delete("token");
99
+ location.replace(`/api/auth/token?token=${encodeURIComponent(t)}&next=${encodeURIComponent(location.pathname + (q.size ? `?${q}` : ""))}`);
100
+ throw new Error("redirecting to token login"); } }
101
+ ```
102
+ - `api/data.js` returns 401 without `loggedIn(req)`.
103
+
104
+ ## Check it before registering
105
+
106
+ ```bash
107
+ curl -s -o /dev/null -w "%{http_code}\n" "https://<site>/api/auth/token?token=$(printf x%.0s {1..32})" # 401
108
+ curl -sI "https://<site>/" | grep -iE "x-frame-options|frame-ancestors" # nothing
109
+ ```
110
+ Then register it with `--token default` and open it on the fleet page's 🖥 Dashboards tab: it should show
111
+ the dashboard logged in, inside the frame. Never print the real token while testing.