@hivey/cli 0.9.79 → 0.9.81
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.
- package/native/darwin-arm64/hivey +0 -0
- package/package.json +1 -1
- package/repo/skills/hivey-agent-creator/references/agent-claude-md.md +3 -3
- package/repo/skills/hivey-agent-map/SKILL.md +7 -5
- package/repo/skills/hivey-agent-map/scripts/dashboards.py +49 -26
- package/repo/skills/hivey-agent-map/scripts/fleet/fleet.js +35 -26
- package/repo/skills/hivey-agent-map/scripts/serve.py +22 -7
- package/repo/skills/hivey-dashboards/SKILL.md +59 -54
- package/repo/skills/hivey-dashboards/references/token-login.md +111 -0
|
Binary file
|
package/package.json
CHANGED
|
@@ -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,
|
|
39
|
-
|
|
40
|
-
<url> --agent <agent name> --note "<what it shows>"
|
|
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 (
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
|
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,11 +17,11 @@ 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
|
|
20
|
-
logs you in by itself. The token is a literal value
|
|
21
|
-
`envsave get` when the dashboard opens; no Touch ID)
|
|
22
|
-
|
|
23
|
-
|
|
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) that opens all your
|
|
24
|
+
dashboards, so changing it updates every one. Tokens are never sent to the page's list.
|
|
24
25
|
Python standard library only.
|
|
25
26
|
"""
|
|
26
27
|
from __future__ import annotations
|
|
@@ -42,7 +43,7 @@ from pathlib import Path
|
|
|
42
43
|
SETTINGS = Path.home() / ".hivey" / "agent-map" / "fleet-settings.json"
|
|
43
44
|
MAX = 100
|
|
44
45
|
LIMITS = {"name": 80, "url": 2000, "agent": 80, "note": 300}
|
|
45
|
-
|
|
46
|
+
DEFAULT = "default" # the token value meaning "my default dashboard token"
|
|
46
47
|
PARAM = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
|
|
47
48
|
FIELDS = ("name", "url", "agent", "note", "token", "token_param")
|
|
48
49
|
|
|
@@ -100,7 +101,7 @@ def public(items: list[dict]) -> list[dict]:
|
|
|
100
101
|
for d in items:
|
|
101
102
|
p = {k: v for k, v in d.items() if k != "token"}
|
|
102
103
|
tok = d.get("token") or ""
|
|
103
|
-
p["login"] = "" if not tok else "envsave" if tok.startswith("es_") else "token"
|
|
104
|
+
p["login"] = "" if not tok else DEFAULT if tok == DEFAULT else "envsave" if tok.startswith("es_") else "token"
|
|
104
105
|
out.append(p)
|
|
105
106
|
return out
|
|
106
107
|
|
|
@@ -132,11 +133,9 @@ def _match(d: dict, key: str) -> bool:
|
|
|
132
133
|
return k in (d["id"].lower(), d["name"].lower(), d["url"].lower().rstrip("/"), d["url"].lower())
|
|
133
134
|
|
|
134
135
|
|
|
135
|
-
def _changes(name=None, url=None, agent=None, note=None, token=None, token_param=None
|
|
136
|
+
def _changes(name=None, url=None, agent=None, note=None, token=None, token_param=None) -> dict:
|
|
136
137
|
ch = {k: v for k, v in dict(name=name, url=url, agent=agent, note=note, token=token, token_param=token_param).items()
|
|
137
138
|
if v is not None}
|
|
138
|
-
if vercel:
|
|
139
|
-
ch["token_param"] = VERCEL
|
|
140
139
|
if "url" in ch and not valid_url(ch["url"]):
|
|
141
140
|
raise ValueError(f"not an http(s) URL: {ch['url']}")
|
|
142
141
|
if ch.get("token_param") and not PARAM.match(ch["token_param"]):
|
|
@@ -145,9 +144,8 @@ def _changes(name=None, url=None, agent=None, note=None, token=None, token_param
|
|
|
145
144
|
|
|
146
145
|
|
|
147
146
|
def add(name: str, url: str, agent: str = "", note: str = "", token: str | None = None,
|
|
148
|
-
token_param: str | None = None
|
|
149
|
-
ch = _changes(name=name, url=url, agent=agent or None, note=note or None, token=token,
|
|
150
|
-
token_param=token_param, vercel=vercel)
|
|
147
|
+
token_param: str | None = None) -> dict:
|
|
148
|
+
ch = _changes(name=name, url=url, agent=agent or None, note=note or None, token=token, token_param=token_param)
|
|
151
149
|
items = load()
|
|
152
150
|
for i, d in enumerate(items):
|
|
153
151
|
if _match(d, name) or _match(d, url.rstrip("/")):
|
|
@@ -179,11 +177,30 @@ def remove(key: str) -> bool:
|
|
|
179
177
|
return True
|
|
180
178
|
|
|
181
179
|
|
|
180
|
+
def default_token() -> str:
|
|
181
|
+
"""Your default dashboard token: an EnvSave key (es_…) or a value, "" when none is set."""
|
|
182
|
+
return str(_settings().get("dashboard_token") or "").strip()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def set_default_token(token: str) -> None:
|
|
186
|
+
cur = _settings()
|
|
187
|
+
if token:
|
|
188
|
+
cur["dashboard_token"] = token.strip()[:4000]
|
|
189
|
+
else:
|
|
190
|
+
cur.pop("dashboard_token", None)
|
|
191
|
+
write(cur)
|
|
192
|
+
|
|
193
|
+
|
|
182
194
|
_resolved: dict[str, tuple[float, str]] = {}
|
|
183
195
|
|
|
184
196
|
|
|
185
197
|
def resolve(token: str) -> str:
|
|
186
|
-
"""A literal token as is; an EnvSave opaque key read with `envsave get es_…` (cached for 10 minutes)
|
|
198
|
+
"""A literal token as is; an EnvSave opaque key read with `envsave get es_…` (cached for 10 minutes);
|
|
199
|
+
"default" is your default dashboard token."""
|
|
200
|
+
if token == DEFAULT:
|
|
201
|
+
token = default_token()
|
|
202
|
+
if not token or token == DEFAULT:
|
|
203
|
+
raise RuntimeError("no default dashboard token yet: `hivey agent-map dashboard token es_…`")
|
|
187
204
|
if not token.startswith("es_"):
|
|
188
205
|
return token
|
|
189
206
|
hit = _resolved.get(token)
|
|
@@ -207,8 +224,6 @@ def open_url(d: dict) -> str:
|
|
|
207
224
|
return d["url"]
|
|
208
225
|
param = d.get("token_param") or "token"
|
|
209
226
|
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
227
|
u = urllib.parse.urlsplit(d["url"])
|
|
213
228
|
q = [(k, v) for k, v in urllib.parse.parse_qsl(u.query, keep_blank_values=True) if k not in dict(extra)]
|
|
214
229
|
return urllib.parse.urlunsplit(u._replace(query=urllib.parse.urlencode(q + extra)))
|
|
@@ -245,15 +260,13 @@ def _probe(d: dict) -> dict:
|
|
|
245
260
|
except (urllib.error.URLError, OSError, ValueError) as e:
|
|
246
261
|
return {"ok": False, "error": str(getattr(e, "reason", e))[:120], "ms": round((time.time() - start) * 1000)}
|
|
247
262
|
out = {"ok": code < 500, "code": code, "ms": round((time.time() - start) * 1000), "frame": _frameable(headers)}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
out["login"] = "vercel" # Deployment Protection: needs the bypass secret (--vercel) to open in the frame
|
|
251
|
-
out["frame"] = False
|
|
263
|
+
if urllib.parse.urlsplit(final).netloc != urllib.parse.urlsplit(d["url"]).netloc:
|
|
264
|
+
out["elsewhere"] = urllib.parse.urlsplit(final).netloc # sent to another site, e.g. a hosting login wall
|
|
252
265
|
return out
|
|
253
266
|
|
|
254
267
|
|
|
255
268
|
def status() -> dict:
|
|
256
|
-
"""{id: {ok, code | error, ms, frame,
|
|
269
|
+
"""{id: {ok, code | error, ms, frame, elsewhere?}} for every dashboard, checked in parallel."""
|
|
257
270
|
items = load()
|
|
258
271
|
if not items:
|
|
259
272
|
return {}
|
|
@@ -267,9 +280,9 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
267
280
|
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
268
281
|
|
|
269
282
|
def login_args(p) -> None:
|
|
270
|
-
p.add_argument("--token", help="login token:
|
|
283
|
+
p.add_argument("--token", help="login token: default (your default dashboard token), an EnvSave key es_… "
|
|
284
|
+
"or a value (\"\" removes it)")
|
|
271
285
|
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")
|
|
273
286
|
|
|
274
287
|
a = sub.add_parser("add", help="add a dashboard (or update the one with this name or URL)")
|
|
275
288
|
a.add_argument("name")
|
|
@@ -286,15 +299,25 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
286
299
|
login_args(ed)
|
|
287
300
|
rm = sub.add_parser("remove")
|
|
288
301
|
rm.add_argument("key", help="name, id or URL")
|
|
302
|
+
tk = sub.add_parser("token", help="show or set your default dashboard token (used by --token default)")
|
|
303
|
+
tk.add_argument("value", nargs="?", help="an EnvSave key es_… (best) or the token itself")
|
|
304
|
+
tk.add_argument("--clear", action="store_true")
|
|
289
305
|
args = ap.parse_args(argv)
|
|
306
|
+
if args.cmd == "token":
|
|
307
|
+
if args.clear or args.value:
|
|
308
|
+
set_default_token("" if args.clear else args.value)
|
|
309
|
+
cur = default_token()
|
|
310
|
+
print(f"default dashboard token: {cur[:8] + '…' if cur.startswith('es_') else ('set (a raw value)' if cur else 'none')}"
|
|
311
|
+
+ ("" if cur else " (set it: hivey agent-map dashboard token es_…)"))
|
|
312
|
+
return 0
|
|
290
313
|
try:
|
|
291
314
|
if args.cmd == "add":
|
|
292
|
-
d = add(args.name, args.url, args.agent, args.note, args.token, args.token_param
|
|
315
|
+
d = add(args.name, args.url, args.agent, args.note, args.token, args.token_param)
|
|
293
316
|
print(f"saved {d['name']} → {d['url']}{' (with login token)' if d['token'] else ''} (fleet page → 🖥 Dashboards)")
|
|
294
317
|
return 0
|
|
295
318
|
if args.cmd == "edit":
|
|
296
319
|
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
|
|
320
|
+
token_param=args.token_param)
|
|
298
321
|
if not d:
|
|
299
322
|
print(f"dashboards: no dashboard named {args.key}", file=sys.stderr)
|
|
300
323
|
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: ''
|
|
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,25 @@ 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
|
-
|
|
1034
|
+
// Login: none, your default dashboard token (one EnvSave key that opens all your dashboards), or a token for this one
|
|
1035
|
+
const mode = f.mode || (f.login === 'default' ? 'default' : f.login ? 'own' : f.id ? 'none' : (dashDefault ? 'default' : 'none'));
|
|
1036
|
+
const saved = f.id && f.login && f.login !== 'default';
|
|
1034
1037
|
return `<form class="dform" id="dform"><h3>${f.id ? 'Edit ' + esc(f.name) : 'Add a dashboard'}</h3>
|
|
1035
1038
|
<label>Name</label><input type="text" name="name" value="${esc(f.name)}" placeholder="Trading dashboard" required>
|
|
1036
1039
|
<label>URL</label><input type="url" name="url" value="${esc(f.url)}" placeholder="https://…" required>
|
|
1037
1040
|
<label>Agent</label><input type="text" name="agent" value="${esc(f.agent)}" placeholder="the agent that keeps it (optional)">
|
|
1038
1041
|
<label>Note</label><input type="text" name="note" value="${esc(f.note)}" placeholder="what it shows (optional)">
|
|
1039
|
-
<label>Login
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
${
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
<label>
|
|
1042
|
+
<label>Login</label><span class="chk" style="grid-column:auto;flex-wrap:wrap;gap:12px">
|
|
1043
|
+
<label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="none" ${mode === 'none' ? 'checked' : ''}> none</label>
|
|
1044
|
+
<label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="default" ${mode === 'default' ? 'checked' : ''}> my dashboard token</label>
|
|
1045
|
+
<label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="own" ${mode === 'own' ? 'checked' : ''}> a token for this one</label></span>
|
|
1046
|
+
${mode === 'default' && !dashDefault ? `<label>Your token</label><input type="password" name="deftoken" value="${esc(f.deftoken || '')}" autocomplete="off" placeholder="EnvSave key es_… (saved once, used by all your dashboards)" required>` : ''}
|
|
1047
|
+
${mode === 'own' ? `<label>Token</label><input type="password" name="token" value="${esc(f.token || '')}" autocomplete="off"
|
|
1048
|
+
placeholder="${saved ? 'token saved: leave empty to keep it' : 'an EnvSave key es_… or the token'}" ${saved ? '' : 'required'}>
|
|
1049
|
+
<label>Parameter</label><input type="text" name="token_param" value="${esc(f.token_param || '')}" placeholder="token (the URL parameter the dashboard reads)">` : ''}
|
|
1050
|
+
<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
|
|
1051
|
+
itself. ${dashDefault ? 'Your dashboard token is saved; ' : ''}tokens stay on this Mac and are never shown again. Agents build this login into
|
|
1052
|
+
the dashboards they make (hivey-dashboards skill).</div>
|
|
1047
1053
|
<div class="btns"><button class="primary" type="submit">${f.id ? 'Save' : 'Add dashboard'}</button><button type="button" id="dcancel">Cancel</button></div></form>`;
|
|
1048
1054
|
}
|
|
1049
1055
|
function renderDash() {
|
|
@@ -1059,8 +1065,9 @@ function renderDash() {
|
|
|
1059
1065
|
$('#dlist').innerHTML = dashes === null ? '<div class="meta" style="padding:8px">loading…</div>'
|
|
1060
1066
|
: !list.length ? '<div class="meta" style="padding:8px">No dashboards yet. Press <b>+ Add</b>.</div>'
|
|
1061
1067
|
: list.map(d => {
|
|
1062
|
-
const s = dashStatus[d.id], cls = !s ? '' : !s.ok ? 'down' : s.
|
|
1063
|
-
const tip = !s ? 'checking…' : !s.ok ? `not answering: ${s.error || s.code}` : `
|
|
1068
|
+
const s = dashStatus[d.id], cls = !s ? '' : !s.ok ? 'down' : s.elsewhere || s.frame === false ? 'warn' : 'up';
|
|
1069
|
+
const tip = !s ? 'checking…' : !s.ok ? `not answering: ${s.error || s.code}` : s.elsewhere ? `sends you to ${s.elsewhere} (a login wall?)`
|
|
1070
|
+
: s.frame === false ? 'opens only in a new tab' : `up · ${s.code} · ${s.ms} ms`;
|
|
1064
1071
|
let origin = ''; try { origin = new URL(d.url).origin; } catch { }
|
|
1065
1072
|
return `<div class="ditem ${d.id === ui.dash && !(dashForm && !dashForm.id) ? 'sel' : ''}" data-id="${esc(d.id)}" title="${esc(d.note || d.url)}">
|
|
1066
1073
|
<div class="fav">${origin ? `<img src="${esc(origin)}/favicon.ico" alt="" onerror="this.replaceWith('🖥')">` : '🖥'}</div>
|
|
@@ -1093,9 +1100,9 @@ function renderDash() {
|
|
|
1093
1100
|
const blocked = s && s.ok && s.frame === false;
|
|
1094
1101
|
if (blocked) { // the site refuses to be shown inside another page (or Vercel's login does)
|
|
1095
1102
|
msg.hidden = false;
|
|
1096
|
-
msg.innerHTML = `<div><b>${esc(cur.name)} can't be shown inside the fleet page</b><br>${s.
|
|
1097
|
-
?
|
|
1098
|
-
: 'The site does not allow being
|
|
1103
|
+
msg.innerHTML = `<div><b>${esc(cur.name)} can't be shown inside the fleet page</b><br>${s.elsewhere
|
|
1104
|
+
? `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).`
|
|
1105
|
+
: '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
1106
|
$('#dtab2').onclick = () => window.open(dashOpenUrl(cur), '_blank', 'noopener');
|
|
1100
1107
|
frame.removeAttribute('src'); frame.dataset.src = '';
|
|
1101
1108
|
return;
|
|
@@ -1110,21 +1117,23 @@ function wireDashBar(folded, maxed) {
|
|
|
1110
1117
|
function wireDashForm(list) {
|
|
1111
1118
|
const f = $('#dform');
|
|
1112
1119
|
$('#dcancel').onclick = () => { dashForm = null; $('#dmsg').innerHTML = ''; renderDash(); };
|
|
1113
|
-
f.oninput = () =>
|
|
1120
|
+
f.oninput = () => Object.assign(dashForm, Object.fromEntries(new FormData(f)));
|
|
1121
|
+
f.querySelectorAll('input[name=mode]').forEach(r => r.onchange = () => { Object.assign(dashForm, Object.fromEntries(new FormData(f))); $('#dmsg').innerHTML = ''; renderDash(); });
|
|
1114
1122
|
f.onsubmit = e => {
|
|
1115
1123
|
e.preventDefault();
|
|
1116
1124
|
const v = Object.fromEntries(new FormData(f));
|
|
1117
1125
|
let url = v.url.trim();
|
|
1118
1126
|
if (!/^https?:\/\//i.test(url)) url = 'https://' + url;
|
|
1119
1127
|
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
|
-
|
|
1122
|
-
if (v.
|
|
1123
|
-
else if (v.
|
|
1128
|
+
const entry = { name: v.name.trim(), url, agent: v.agent.trim(), note: v.note.trim(), token_param: (v.token_param || '').trim() };
|
|
1129
|
+
if (v.mode === 'none') entry.token = '';
|
|
1130
|
+
else if (v.mode === 'default') entry.token = 'default';
|
|
1131
|
+
else if ((v.token || '').trim()) entry.token = v.token.trim(); // no "token" key: the server keeps the saved one
|
|
1132
|
+
else if (dashForm.login === 'default' || !dashForm.login) { toast('Type the token for this dashboard'); return; }
|
|
1124
1133
|
const id = dashForm.id;
|
|
1125
1134
|
const next = id ? list.map(d => d.id === id ? { id, ...entry } : d) : [...list, entry];
|
|
1126
1135
|
$('#dmsg').innerHTML = '';
|
|
1127
|
-
saveDash(next, id ? `Saved ${entry.name}` : `Added ${entry.name}`, id || 'last');
|
|
1136
|
+
saveDash(next, id ? `Saved ${entry.name}` : `Added ${entry.name}`, id || 'last', (v.deftoken || '').trim());
|
|
1128
1137
|
};
|
|
1129
1138
|
}
|
|
1130
1139
|
// scheduled jobs that failed (non-zero exit) or need a check, live from the page server: a count on the
|
|
@@ -1294,7 +1303,7 @@ $('#space').onchange = e => {
|
|
|
1294
1303
|
};
|
|
1295
1304
|
post('/hv-fleet-refresh', { load: true }).then(j => {
|
|
1296
1305
|
showEvery(j.every);
|
|
1297
|
-
if (Array.isArray(j.dashboards)) { dashes = j.dashboards; renderDash(); }
|
|
1306
|
+
if (Array.isArray(j.dashboards)) { dashes = j.dashboards; dashDefault = !!j.default_token; renderDash(); }
|
|
1298
1307
|
if (j.space && j.space !== String(ui.space || 'random')) { // the server's choice wins (set in another browser)
|
|
1299
1308
|
ui.space = j.space; save(); $('#space').value = j.space;
|
|
1300
1309
|
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-
|
|
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
|
|
@@ -449,6 +450,14 @@ def running(current_only: bool = True) -> int | None:
|
|
|
449
450
|
return port if body == MARK + b" " + VERSION or not current_only else None
|
|
450
451
|
|
|
451
452
|
|
|
453
|
+
def server_hivey() -> str | None:
|
|
454
|
+
"""The hivey binary the running server reads agents and sessions with."""
|
|
455
|
+
try:
|
|
456
|
+
return json.loads(INFO.read_text()).get("hivey")
|
|
457
|
+
except (OSError, ValueError, AttributeError):
|
|
458
|
+
return None
|
|
459
|
+
|
|
460
|
+
|
|
452
461
|
def port_free(port: int) -> bool:
|
|
453
462
|
import socket
|
|
454
463
|
with socket.socket() as sock:
|
|
@@ -462,9 +471,11 @@ def port_free(port: int) -> bool:
|
|
|
462
471
|
def ensure() -> int | None:
|
|
463
472
|
"""The running server's port, starting one in the background when there is none."""
|
|
464
473
|
port = running()
|
|
465
|
-
if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)):
|
|
474
|
+
if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)) and server_hivey() == hivey_bin():
|
|
466
475
|
return port
|
|
467
|
-
|
|
476
|
+
# older version, on another port while ours is free, or reading another hivey (a dev build started
|
|
477
|
+
# it: that binary talks to the hivey-dev server, so the fleet would show its agents, not yours)
|
|
478
|
+
if port or running(current_only=False):
|
|
468
479
|
try:
|
|
469
480
|
os.kill(int(json.loads(INFO.read_text())["pid"]), 15)
|
|
470
481
|
time.sleep(0.3)
|
|
@@ -641,10 +652,13 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
641
652
|
import dashboards
|
|
642
653
|
if "dashboards" in req: # the Dashboards tab's list, replaced whole (bad entries dropped, tokens kept)
|
|
643
654
|
cur["dashboards"] = dashboards.clean(req["dashboards"], dashboards.clean(cur.get("dashboards")))
|
|
655
|
+
if isinstance(req.get("dashboard_token"), str) and req["dashboard_token"].strip(): # write-only
|
|
656
|
+
cur["dashboard_token"] = req["dashboard_token"].strip()[:4000]
|
|
644
657
|
dashboards.write(cur) # owner-only: it can hold dashboard tokens
|
|
645
658
|
return self.answer(200, json.dumps({"ok": True, "every": fleet_every(), "space": cur.get("space"), "track": cur.get("track"),
|
|
646
659
|
"ships": cur.get("ships", {}),
|
|
647
|
-
"dashboards": dashboards.public(dashboards.clean(cur.get("dashboards")))
|
|
660
|
+
"dashboards": dashboards.public(dashboards.clean(cur.get("dashboards"))),
|
|
661
|
+
"default_token": bool(cur.get("dashboard_token"))}).encode())
|
|
648
662
|
every = fleet_every()
|
|
649
663
|
# a page load: a quick pass when updating every minute, a full one otherwise; ⟳: always full
|
|
650
664
|
quick = bool(req.get("quick")) or (bool(req.get("load")) and every == "minute")
|
|
@@ -655,7 +669,8 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
655
669
|
return self.answer(200, json.dumps({"ok": True, "started": True, "every": every,
|
|
656
670
|
"space": fleet_settings().get("space"), "track": fleet_settings().get("track"),
|
|
657
671
|
"ships": clean_ships(fleet_settings().get("ships")),
|
|
658
|
-
"dashboards": dashboards_public()
|
|
672
|
+
"dashboards": dashboards_public(),
|
|
673
|
+
"default_token": bool(fleet_settings().get("dashboard_token"))}).encode())
|
|
659
674
|
if self.path == "/hv-fleet-action":
|
|
660
675
|
try:
|
|
661
676
|
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
@@ -703,7 +718,7 @@ def serve() -> int:
|
|
|
703
718
|
except OSError: # taken: any free port
|
|
704
719
|
httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
705
720
|
port = httpd.server_address[1]
|
|
706
|
-
INFO.write_text(json.dumps({"port": port, "pid": os.getpid()}))
|
|
721
|
+
INFO.write_text(json.dumps({"port": port, "pid": os.getpid(), "hivey": hivey_bin()}))
|
|
707
722
|
|
|
708
723
|
def watchdog() -> None:
|
|
709
724
|
while True:
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: hivey-dashboards
|
|
3
3
|
description: >
|
|
4
|
-
|
|
5
|
-
tab:
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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,64 @@ 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:
|
|
23
|
-
dashboards listed on the left with a live up/down dot, and the one
|
|
24
|
-
edited from the
|
|
25
|
-
|
|
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
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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 saves it once as the *default dashboard token*; a dashboard registered with
|
|
31
|
+
`--token default` opens as `https://<site>/?token=<it>`, and the site trades the token for its own session
|
|
32
|
+
cookie. No hosting login (no Vercel Deployment Protection): it refuses frames, and the token login protects
|
|
33
|
+
the site instead. Tokens never reach the page; the local fleet server adds them when a dashboard opens.
|
|
41
34
|
|
|
42
|
-
##
|
|
35
|
+
## Building a dashboard
|
|
43
36
|
|
|
44
|
-
|
|
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.
|
|
37
|
+
When you create or change a dashboard (any web page that shows the user's data):
|
|
53
38
|
|
|
54
|
-
|
|
39
|
+
1. **Give it the token login** exactly as in `references/token-login.md` (Next.js or a static page with
|
|
40
|
+
Vercel functions; the contract applies to any stack): `?token=` → `/api/auth/token` → signed
|
|
41
|
+
`SameSite=None; Partitioned` session cookie, token stripped from the URL, every data endpoint 401
|
|
42
|
+
without the cookie, no `X-Frame-Options`, the host's own login wall off.
|
|
43
|
+
2. **The token on the server** comes from the user's `DASHBOARD_TOKEN_<USER>` EnvSave key
|
|
44
|
+
(`envsave.get("es_…")`). If you don't know the key, ask the user for it; never ask for the token
|
|
45
|
+
itself. Pushing it to Vercel (`envsave vercel …`) unlocks the vault: tell the user first and let them run it.
|
|
46
|
+
3. **Check it** with the two `curl` lines at the end of the reference (a wrong token gets 401, nothing
|
|
47
|
+
forbids framing).
|
|
48
|
+
4. **Register it** (below) with `--token default`, and tell the user it is on the 🖥 Dashboards tab.
|
|
55
49
|
|
|
56
|
-
|
|
57
|
-
dashboard can open logged in with a token:
|
|
50
|
+
## Managing the list
|
|
58
51
|
|
|
59
52
|
```bash
|
|
60
|
-
hivey agent-map dashboard
|
|
61
|
-
hivey agent-map dashboard
|
|
62
|
-
|
|
53
|
+
hivey agent-map dashboard list # name, URL, agent, 🔑 login (--json for the fields)
|
|
54
|
+
hivey agent-map dashboard add "Trading dashboard" https://trading.example.app \
|
|
55
|
+
--agent trading-strategies --note "paper accounts, trades and job status" --token default
|
|
56
|
+
hivey agent-map dashboard edit "Trading dashboard" --name "Paper trading" --url https://new.example.app
|
|
57
|
+
hivey agent-map dashboard edit "Trading dashboard" --token default # or es_… for its own token, "" for none
|
|
58
|
+
hivey agent-map dashboard remove "Paper trading" # by name, id or URL; removes the card only
|
|
59
|
+
hivey agent-map dashboard token # is a default dashboard token set?
|
|
60
|
+
hivey agent-map dashboard token es_… # set it (the user's DASHBOARD_TOKEN_<USER> key)
|
|
63
61
|
```
|
|
64
62
|
|
|
65
|
-
-
|
|
66
|
-
|
|
67
|
-
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
-
|
|
76
|
-
the
|
|
77
|
-
-
|
|
63
|
+
- `add` with a name or URL already in the list updates that entry instead of adding a twin. Run
|
|
64
|
+
`list` first so you edit the existing card rather than adding a duplicate under a new name.
|
|
65
|
+
- URLs must be `http://` or `https://` (local servers like `http://localhost:3000` are fine). Prefer the
|
|
66
|
+
stable production URL (`vercel project ls` in the project folder, its README) over a preview URL.
|
|
67
|
+
- `--agent` is the agent that keeps the dashboard (its folder name); leave it out for the user's own.
|
|
68
|
+
`--note` is one short line on what it shows.
|
|
69
|
+
- `--token default` uses the default dashboard token, so changing that key later updates every dashboard.
|
|
70
|
+
A dashboard that needs a different token gets its own EnvSave key (`--token es_…`); a raw value works
|
|
71
|
+
but lands in the settings file and your shell history. `--token-param` changes the URL parameter
|
|
72
|
+
(default `token`). Never put a token in the name, note or URL.
|
|
73
|
+
- No default token yet: ask the user for their `DASHBOARD_TOKEN_<USER>` EnvSave key, or tell them to pick
|
|
74
|
+
"my dashboard token" in the page's form, which asks for it once.
|
|
75
|
+
- If `hivey` is not on PATH: `python3 -I ~/.claude/skills/hivey-agent-map/scripts/dashboards.py …` (same
|
|
76
|
+
arguments).
|
|
77
|
+
|
|
78
|
+
## When a dashboard won't show in the frame
|
|
79
|
+
|
|
80
|
+
The page says why. "Sends you to another site": a hosting login wall (turn it off and use the token login);
|
|
81
|
+
"does not allow being shown inside other pages": remove `X-Frame-Options` / `frame-ancestors` from the
|
|
82
|
+
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.
|