Files
AgentHub/server/__tests__/server-mode-user-details.test.js
T
nntrivi2001 0841d3e5c8 fix(plan): a Claude plan is the one Anthropic reports now, not the sign-in's
An account signed in on Pro and upgraded to Max 5x kept showing "Pro": the
plan was read only from .credentials.json / .claude.json, whose
subscriptionType and rate-limit tiers are written at sign-in. fetchOwner
already asks GET /api/oauth/profile for a token's owner; it now also reads
organization_type / rate_limit_tier / seat_tier into a plan
(planFromProfile), remembered per account uuid (rememberLivePlan). The live
row, saved profiles (identityOf) and pool accounts (poolStatus, whose quota
refresh now asks a login's owner too) show that plan when one was seen
(shownPlan), else planLabel of the files as before.
2026-10-28 15:09:30 +07:00

165 lines
6.4 KiB
JavaScript

/**
* @file server-mode-user-details.test.js
* @description `GET /api/users/:id/details` — the Administration page's user
* detail: the account, its workspaces and live panes, newest sessions, spend
* per day / AI tool / model, the audit entries naming it, and per pool tool
* the accounts it may run on with its own share of each. Staff only, 404 for
* an unknown user, never a token or a password hash.
* @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 path = require("node:path");
const fs = require("node:fs");
const os = require("node:os");
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "server-mode-user-details-"));
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
process.env.CLAUDE_HOME = path.join(TMP, ".claude");
process.env.CODEX_HOME = path.join(TMP, ".codex");
process.env.DASHBOARD_LIVENESS_PROBE = "0";
const { createApp, startServer } = require("../index");
const { db } = require("../db");
const auth = require("../lib/auth");
// The quota read would go to the network.
require("../lib/cc-usage").fetchUsage = async () => ({});
require("../lib/cc-usage").fetchOwner = async () => null;
let server;
let BASE;
const BOSS_PASS = "admin-pass-1";
const TOKEN = `sk-ant-oat01-${"a".repeat(40)}`;
const ids = {};
async function call(method, p, { cookie, body } = {}) {
const res = await fetch(BASE + p, {
method,
headers: { "Content-Type": "application/json", ...(cookie ? { cookie } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
return { status: res.status, body: await res.json().catch(() => null) };
}
async function login(username, password) {
const res = await fetch(BASE + "/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
return res.headers.get("set-cookie").split(";")[0];
}
before(async () => {
process.env.AGENTHUB_MODE = "server";
server = await startServer(createApp(), 0);
BASE = `http://127.0.0.1:${server.address().port}`;
ids.boss = (await auth.createUser("boss", BOSS_PASS, "admin")).id;
await auth.createUser("ana", "analyst-pass-1", "analyst");
ids.mia = (await auth.createUser("mia", "member-pass-1", "developer")).id;
const lane = db
.prepare("INSERT INTO lanes (cwd, title, tool, owner_id) VALUES ('/w/mia', 'Mia', 'claude', ?)")
.run(ids.mia).lastInsertRowid;
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('sm', 'mia work', 'active', '/w/mia', ?)"
).run(lane);
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id, tool) VALUES ('sc', 'mia codex', 'completed', '/w/mia', ?, 'codex')"
).run(lane);
const hour = new Date().toISOString().slice(0, 13);
for (const [sid, tokens] of [
["sm", 1000000],
["sc", 500000],
]) {
db.prepare(
`INSERT INTO token_usage (session_id, model, output_tokens)
VALUES (?, 'claude-sonnet-4-5-20250929', ?)`
).run(sid, tokens);
db.prepare(
`INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens)
VALUES (?, ?, 'claude-sonnet-4-5-20250929', ?)`
).run(sid, hour, tokens);
}
const boss = await login("boss", BOSS_PASS);
const add = await call("POST", "/api/accounts", {
cookie: boss,
body: { tool: "claude", name: "team-1", token: TOKEN, currentPassword: BOSS_PASS },
});
assert.equal(add.status, 201);
db.prepare(
`INSERT INTO dashboard_runs (id, session_id, mode, cwd, status, lane_id, tool, account)
VALUES ('agenthub-lane-1', 'sm', 'interactive', '/w/mia', 'running', ?, 'claude', 'team-1')`
).run(lane);
});
after(() => {
delete process.env.AGENTHUB_MODE;
server?.close();
fs.rmSync(TMP, { recursive: true, force: true });
});
describe("GET /api/users/:id/details", () => {
it("shows staff one user's workspaces, panes, sessions, spend and pool share", async () => {
const boss = await login("boss", BOSS_PASS);
const r = await call("GET", `/api/users/${ids.mia}/details`, { cookie: boss });
assert.equal(r.status, 200, JSON.stringify(r.body));
const d = r.body;
assert.equal(d.user.username, "mia");
assert.equal(d.sessions.total, 2);
assert.equal(d.sessions.active, 1);
assert.deepEqual(
d.workspaces.map((w) => [w.title, w.sessions, w.livePanes]),
[["Mia", 2, 1]]
);
assert.deepEqual(
d.panes.map((p) => [p.id, p.account]),
[["agenthub-lane-1", "team-1"]]
);
assert.deepEqual(d.recentSessions.map((s) => s.id).sort(), ["sc", "sm"]);
assert.ok(d.recentSessions.every((s) => s.tokens > 0 && s.cost > 0));
assert.equal(d.usage.last30d.tokens, 1500000);
assert.equal(d.usage.today.tokens, 1500000);
assert.equal(d.usage.daily.length, 30);
assert.equal(d.usage.daily.at(-1).tokens, 1500000, "today is the last bar");
assert.deepEqual(
d.usage.byTool.map((b) => [b.key, b.tokens, b.sessions]),
[
["claude", 1000000, 1],
["codex", 500000, 1],
]
);
assert.deepEqual(
d.usage.byModel.map((b) => b.key),
["claude-sonnet-4-5-20250929"]
);
const team = d.pool.claude.accounts.find((a) => a.name === "team-1");
assert.equal(team.allowed, true);
assert.equal(team.userRuns7d, 1);
assert.equal(team.userLivePanes, 1);
assert.equal(team.userTokens7d, 1000000, "only the hours its run held the session");
assert.equal(d.pool.claude.pin, null);
assert.ok(!JSON.stringify(d).includes(TOKEN), "never a token");
assert.ok(!JSON.stringify(d).includes("scrypt"), "never a password hash");
});
it("lists the audit entries naming the user", async () => {
const boss = await login("boss", BOSS_PASS);
await call("GET", "/api/sessions/sm", { cookie: boss });
const d = (await call("GET", `/api/users/${ids.mia}/details`, { cookie: boss })).body;
assert.ok(d.audit.some((a) => a.reader === "boss" && a.owner === "mia"));
});
it("is staff only and 404s an unknown user", async () => {
const ana = await login("ana", "analyst-pass-1");
assert.equal((await call("GET", `/api/users/${ids.mia}/details`, { cookie: ana })).status, 200);
const mia = await login("mia", "member-pass-1");
assert.equal((await call("GET", `/api/users/${ids.mia}/details`, { cookie: mia })).status, 403);
const boss = await login("boss", BOSS_PASS);
assert.equal((await call("GET", "/api/users/9999/details", { cookie: boss })).status, 404);
});
});