fix: a token-gated or LAN-bound dashboard works end to end (WSL mirrored)

- /ws-pty carries the dashboard token like /ws (the terminal never attached
  with DASHBOARD_TOKEN set), and so does everything that cannot send the
  header: images, downloads, exports, drops (withToken/tokenHeader). A
  refused upgrade answers 401/403 and is logged and counted by reason.
- The browser asks for a missing or wrong token (401 EUNAUTHORIZED) and takes
  ?token= from the link agenthub start prints, dropping it from the URL.
- The CLI sends the token (DASHBOARD_TOKEN, else the one the running server
  publishes 0600 in <data dir>/runtime/dashboard-token); MCP and statusline
  read the same file.
- DASHBOARD_HOST takes a list, and 127.0.0.1 is always listened on too, so a
  LAN-only bind keeps hooks and the CLI working.
- agenthub start --host/--allowed-hosts/--token are saved in
  <data dir>/network.json for every later start; a wide bind gets a token;
  every reachable URL is printed.
- tmux < 3.7 is an amber, once-per-version notice that says only the pane
  scrollbar is missing, with a ~/.local build instead of sudo make install.
- INSTALL: PATH belongs in ~/.profile for sudo -iu/ssh; WSL mirrored notes.
This commit is contained in:
2026-11-06 14:59:48 +07:00
parent 1e3b34ec03
commit 4a665da79e
39 changed files with 1108 additions and 105 deletions
@@ -0,0 +1,54 @@
/**
* @file dashboard-token-publish.test.js
* @description A token-gated dashboard publishes its token (0600) for local
* tools, and `dashboard-url.dashboardToken()` — what the `agenthub` CLI, the
* MCP server and the statusline send — takes DASHBOARD_TOKEN first, else that
* file, else nothing. Without it `agenthub remote login/status` answered 401
* from any shell that had not exported the token.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after, afterEach } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "dash-token-"));
process.env.DASHBOARD_DATA_DIR = TMP;
const security = require("../lib/security");
const { dashboardToken, tokenHeaders } = require("../lib/dashboard-url");
describe("the published dashboard token", () => {
let saved;
before(() => {
saved = process.env.DASHBOARD_TOKEN;
});
afterEach(() => {
if (saved === undefined) delete process.env.DASHBOARD_TOKEN;
else process.env.DASHBOARD_TOKEN = saved;
});
after(() => fs.rmSync(TMP, { recursive: true, force: true }));
it("is written 0600 when the server has one, and read back without the env", () => {
process.env.DASHBOARD_TOKEN = "server-tok";
security.publishDashboardToken();
const file = security.tokenFilePath();
assert.equal(fs.statSync(file).mode & 0o777, 0o600);
delete process.env.DASHBOARD_TOKEN; // a shell that never exported it
assert.equal(dashboardToken(), "server-tok");
assert.deepEqual(tokenHeaders(), { "x-dashboard-token": "server-tok" });
});
it("prefers the caller's own DASHBOARD_TOKEN", () => {
process.env.DASHBOARD_TOKEN = "mine";
assert.equal(dashboardToken(), "mine");
});
it("is removed when the server runs without a token", () => {
delete process.env.DASHBOARD_TOKEN;
security.publishDashboardToken();
assert.equal(fs.existsSync(security.tokenFilePath()), false);
assert.equal(dashboardToken(), null);
assert.deepEqual(tokenHeaders(), {});
});
});
+133
View File
@@ -0,0 +1,133 @@
/**
* @file listen-hosts.test.js
* @description DASHBOARD_HOST may name several addresses, and a dashboard
* bound only to a non-loopback address still answers on 127.0.0.1 — the hook
* handler, the CLI, the MCP server and the statusline all call there (WSL in
* mirrored networking binds a LAN address because Windows cannot reach the
* VM's loopback, and every hook was lost). 127.0.0.2 stands in for the LAN
* address: Linux routes all of 127/8 to lo, yet it is not "this machine's
* name" to the guards.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "listen-hosts-"));
process.env.DASHBOARD_DATA_DIR = TMP;
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
process.env.CLAUDE_HOME = path.join(TMP, ".claude");
process.env.DASHBOARD_LIVENESS_PROBE = "0";
process.env.DASHBOARD_POOL_REFRESH_MS = "0";
const security = require("../lib/security");
function withHost(value, fn) {
const saved = process.env.DASHBOARD_HOST;
if (value === undefined) delete process.env.DASHBOARD_HOST;
else process.env.DASHBOARD_HOST = value;
try {
return fn();
} finally {
if (saved === undefined) delete process.env.DASHBOARD_HOST;
else process.env.DASHBOARD_HOST = saved;
}
}
describe("which addresses the dashboard listens on", () => {
it("is loopback alone by default, with nothing extra", () =>
withHost(undefined, () => {
assert.deepEqual(security.resolveHosts(), ["127.0.0.1"]);
assert.deepEqual(security.extraListenHosts(), []);
assert.equal(security.isExposedBind(), false);
}));
it("adds 127.0.0.1 beside a LAN-only bind, and keeps every listed address", () =>
withHost("192.168.1.20, 100.64.0.7", () => {
assert.equal(security.resolveHost(), "192.168.1.20");
assert.deepEqual(security.extraListenHosts(), ["100.64.0.7", "127.0.0.1"]);
assert.equal(security.isExposedBind(), true);
}));
it("adds nothing for a wildcard bind, which answers on loopback already — but calls it exposed", () =>
withHost("0.0.0.0", () => {
assert.deepEqual(security.extraListenHosts(), []);
assert.equal(security.isExposedBind(), true);
assert.ok(security.accessUrls(4821).includes("http://localhost:4821"));
}));
it("lists each bound address as a URL to open", () =>
withHost("192.168.1.20", () => {
assert.deepEqual(security.accessUrls(4821), [
"http://localhost:4821",
"http://192.168.1.20:4821",
]);
}));
});
describe("a dashboard bound to another address", () => {
let server;
after(async () => {
delete process.env.DASHBOARD_HOST;
if (server) await new Promise((r) => server.close(r));
fs.rmSync(TMP, { recursive: true, force: true });
});
it("still answers on 127.0.0.1, WebSocket included", async () => {
process.env.DASHBOARD_HOST = "127.0.0.2";
const { createApp, startServer } = require("../index");
server = await startServer(createApp(), 0);
const { address, port } = server.address();
assert.equal(address, "127.0.0.2");
await new Promise((r) => setTimeout(r, 50)); // the extra listener binds async
const res = await fetch(`http://127.0.0.1:${port}/api/health`);
assert.equal(res.status, 200);
// The upgrade travels the forwarded connection to the same WS server.
const reply = await new Promise((resolve) => {
const sock = require("node:net").connect(port, "127.0.0.1", () =>
sock.write(
`GET /ws HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\n` +
`Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n` +
`Sec-WebSocket-Version: 13\r\n\r\n`
)
);
sock.once("data", (d) => {
resolve(d.toString());
sock.destroy();
});
sock.on("error", (e) => resolve(String(e)));
});
assert.match(reply, /^HTTP\/1\.1 101/);
});
});
describe("saved network settings (agenthub start --host/--token)", () => {
const net = require("../lib/network-config");
const keys = ["DASHBOARD_HOST", "DASHBOARD_ALLOWED_HOSTS", "DASHBOARD_TOKEN"];
it("are written 0600 and applied only where the environment says nothing", () => {
const saved = Object.fromEntries(keys.map((k) => [k, process.env[k]]));
try {
net.writeNetworkConfig({ host: "0.0.0.0", allowedHosts: "box.lan", token: "t1" });
assert.equal(fs.statSync(net.configPath()).mode & 0o777, 0o600);
const env = { DASHBOARD_TOKEN: "from-env" };
net.applyNetworkConfig(env);
assert.deepEqual(env, {
DASHBOARD_TOKEN: "from-env",
DASHBOARD_HOST: "0.0.0.0",
DASHBOARD_ALLOWED_HOSTS: "box.lan",
});
// null removes a key: `--host local`, `--token off`.
net.writeNetworkConfig({ host: null, token: null });
assert.deepEqual(net.readNetworkConfig(), { allowedHosts: "box.lan" });
} finally {
fs.rmSync(net.configPath(), { force: true });
for (const k of keys) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
}
}
});
});
+7
View File
@@ -379,6 +379,13 @@ describe("tmux wrapper", () => {
assert.match(tmux.upgradeAdvice("3.4", "darwin"), /brew upgrade tmux/);
assert.match(tmux.upgradeAdvice("3.4", "linux"), /github\.com\/tmux\/tmux\/releases/);
assert.equal(tmux.upgradeAdvice("3.7c", "linux"), null);
// An old tmux only lacks the pane scrollbar: a warning, and it says so.
assert.match(tmux.upgradeAdvice("3.4", "linux"), /only the pane scrollbar is missing/);
assert.match(tmux.upgradeAdvice("3.4", "linux"), /--prefix=\$HOME\/\.local/);
assert.doesNotMatch(tmux.upgradeAdvice("3.4", "linux"), /sudo make install/);
assert.equal(tmux.upgradeSeverity("3.4", "linux"), "warning");
assert.equal(tmux.upgradeSeverity("3.3.2", "win32"), "error");
assert.equal(tmux.upgradeSeverity("3.7", "linux"), null);
assert.equal(tmux.upgradeAdvice("next-3.8", "darwin"), null);
// Nothing to compare: no advice rather than a wrong one.
assert.equal(tmux.upgradeAdvice(null, "linux"), null);
@@ -0,0 +1,82 @@
/**
* @file websocket-pty-token.test.js
* @description With DASHBOARD_TOKEN set, a `/ws-pty/:runId` upgrade is let
* through only with the token (`?token=`, appended after the size query the
* terminal sends), and a refused one gets a real HTTP status and is counted
* by reason — it used to be a silent `socket.destroy()`, so a terminal stuck
* "reconnecting" behind a token gave no clue why. Real http.Server, raw
* upgrade requests; the run itself does not exist, so a let-through upgrade
* ends in the attach failing, never in a 401.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");
const http = require("node:http");
const net = require("node:net");
process.env.DASHBOARD_TOKEN = "s3cret-token";
const ws = require("../websocket");
function rawUpgrade(port, path) {
return new Promise((resolve) => {
const socket = net.connect(port, "127.0.0.1", () => {
socket.write(
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\n` +
`Upgrade: websocket\r\nConnection: Upgrade\r\n` +
`Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n`
);
});
let body = "";
socket.on("data", (d) => {
body += d.toString("utf8");
// A 101 means the upgrade was accepted: that is all this test needs.
if (body.startsWith("HTTP/1.1 101")) socket.destroy();
});
socket.on("close", () => resolve(body));
socket.on("error", () => resolve(body));
});
}
describe("/ws-pty behind DASHBOARD_TOKEN", () => {
let server;
let port;
before(async () => {
server = http.createServer((req, res) => res.end("ok"));
ws.initWebSocket(server);
ws.initPtyWebSocket(server);
await new Promise((r) => server.listen(0, "127.0.0.1", r));
port = server.address().port;
});
after(async () => {
ws.closeWebSocket();
await new Promise((r) => server.close(r));
delete process.env.DASHBOARD_TOKEN;
});
it("refuses an attach without the token with a 401, and counts why", async () => {
const before = ws.getUpgradeRefusals().token;
const reply = await rawUpgrade(port, "/ws-pty/agenthub-lane-1?cols=120&rows=30");
assert.match(reply, /^HTTP\/1\.1 401/);
assert.equal(ws.getUpgradeRefusals().token, before + 1);
});
it("refuses a wrong token", async () => {
const reply = await rawUpgrade(port, "/ws-pty/agenthub-lane-1?cols=120&rows=30&token=nope");
assert.match(reply, /^HTTP\/1\.1 401/);
});
it("lets the attach through with the token after the size query", async () => {
const before = ws.getUpgradeRefusals().token;
const reply = await rawUpgrade(
port,
"/ws-pty/agenthub-lane-1?cols=120&rows=30&token=s3cret-token"
);
assert.match(reply, /^HTTP\/1\.1 101/);
assert.equal(ws.getUpgradeRefusals().token, before);
});
it("lets a sizeless attach through with ?token=", async () => {
const reply = await rawUpgrade(port, "/ws-pty/agenthub-lane-1?token=s3cret-token");
assert.match(reply, /^HTTP\/1\.1 101/);
});
});