Files
AgentHub/server/routes/users.js
T
nntrivi2001 22de5009ff feat: v2.7.8 — Artifacts hub, clone related repos as extra folders, quieter resume prompt
- Artifacts (/artifacts): claude.ai pages sessions publish (captured from the
  Artifact tool's hook), pinned workspace files, skills and plugins, each
  kept as a snapshot; shared ones appear in a Hub and a skill or plugin
  installs into the viewer's own account (server/lib/artifacts.js,
  /api/artifacts, docs/plans/artifacts/).
- Workspace extra folders: clone one or more related repos beside the
  workspace and add them in one step (POST /api/lanes/:id/sources/clone).
- A pane that ended by itself while tmux kept running is no longer offered
  for resume (tmux.serverStartedAt in reconcileOrphans).
- Changes panel: a folder that is not a git repo opens on Files, and its
  files open from there.
- Plus the parallel sessions' work in this tree: File Explorer button in the
  panel header, user delete, RSA SSH keys, chat/terminal and pet fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:06:54 +07:00

292 lines
11 KiB
JavaScript

/**
* @file users.js
* @description `/api/users` — server mode's per-user view for an admin or
* analyst (members are refused by STAFF_ONLY_PREFIXES in server/lib/auth.js):
* `GET /` lists every account with its workspaces, sessions and $ spent in the
* last 7 and 30 days (from `token_usage_hourly`, sessions owned through their
* workspace — server/lib/scope.js); `GET /audit` the newest audit entries
* (server/lib/audit.js).
*
* `GET /:id` is one account with the workspaces it owns, for the Edit user form.
*
* The Users page's account changes — `POST /` (create), `PATCH /:id` (the Edit
* user form: display name, email, role, disabled, a new password, workspaces
* given and taken back, sign out everywhere — every field validated before any
* is applied), `POST /:id/password` (reset) and `POST /:id/workspaces` (give a
* workspace) — are an admin's only (`/users` is in ADMIN_WRITE_PREFIXES), each
* needs the admin's own password again (`currentPassword`, `confirmPassword`),
* an admin never demotes or disables themselves (ESELF), every change is
* audited, and in local mode — no login to check — they all refuse.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { Router } = require("express");
const { db, stmts } = require("../db");
const auth = require("../lib/auth");
const { listUsers } = auth;
const { sessionWhere } = require("../lib/scope");
const { listAudit, recordAccountChange } = require("../lib/audit");
const router = Router();
const USAGE_COLS = [
"input_tokens",
"output_tokens",
"cache_read_tokens",
"cache_write_tokens",
"cache_write_1h_tokens",
"web_search_requests",
"web_fetch_requests",
"code_execution_requests",
"long_input_tokens",
"long_output_tokens",
"long_cache_read_tokens",
"long_cache_write_tokens",
"long_cache_write_1h_tokens",
];
/** $ and tokens a member's sessions spent since `sinceHour` (UTC `YYYY-MM-DDTHH`). */
function usageSince(userId, sinceHour, rules) {
const { calculateCost } = require("./pricing");
const w = sessionWhere({ user: { id: userId, role: "developer" } }, "s.id", "s.lane_id");
const rows = db
.prepare(
`SELECT h.model, h.speed, h.inference_geo, h.service_tier,
${USAGE_COLS.map((c) => `SUM(h.${c}) AS ${c}`).join(", ")}
FROM token_usage_hourly h JOIN sessions s ON s.id = h.session_id
WHERE h.hour >= ? AND ${w.where}
GROUP BY h.model, h.speed, h.inference_geo, h.service_tier`
)
.all(sinceHour, ...w.params);
const tokens = rows.reduce(
(n, r) => n + r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens,
0
);
return { cost: rows.length ? calculateCost(rows, rules).total_cost : 0, tokens };
}
const hourAgo = (days) => new Date(Date.now() - days * 864e5).toISOString().slice(0, 13);
router.get("/", (_req, res) => {
const rules = stmts.listPricing.all();
const users = listUsers().map((u) => {
const w = sessionWhere({ user: { id: u.id, role: "developer" } });
return {
...u,
...auth.loginStats(u.id),
workspaces: db.prepare("SELECT COUNT(*) AS n FROM lanes WHERE owner_id = ?").get(u.id).n,
sessions: db.prepare(`SELECT COUNT(*) AS n FROM sessions WHERE ${w.where}`).get(...w.params)
.n,
last7d: usageSince(u.id, hourAgo(7), rules),
last30d: usageSince(u.id, hourAgo(30), rules),
};
});
res.json({ users });
});
router.get("/audit", (req, res) => {
res.json({ entries: listAudit(req.query.limit) });
});
const STATUS = {
EBADUSER: 400,
EBADEMAIL: 400,
ENOTOWNED: 409,
EBADPASSWORD: 400,
EBADROLE: 400,
EBADFIELD: 400,
EREAUTH: 403,
ELOCALMODE: 403,
ENOUSER: 404,
ENOLANE: 404,
EEXISTS: 409,
ESELF: 409,
EOWNERFOLDER: 409, // S3: a workspace in one member's home, assigned to another
ELASTADMIN: 409,
ETOOMANY: 429,
// S3: the Linux account could not be created/locked (the helper said why).
EPROVISION: 502,
};
/**
* One account change: server mode only, the admin's password confirmed, the
* change made, then audited. `fn(target)` returns the audit text.
*/
function accountChange(handler) {
return async (req, res) => {
try {
if (!auth.isServerMode() || !req.user) {
throw Object.assign(new Error("accounts are managed in server mode only"), {
code: "ELOCALMODE",
});
}
const body = req.body && typeof req.body === "object" ? req.body : {};
await auth.confirmPassword(req.user, body.currentPassword);
const out = await handler(req, body);
recordAccountChange(req.user.id, out.user.id, req.method, out.action);
res.status(out.status || 200).json({ user: out.user });
} catch (err) {
const status = STATUS[err.code];
if (!status) return res.status(500).json({ error: { message: err.message } });
res.status(status).json({ error: { code: err.code, message: err.message } });
}
};
}
/** The account `:id` names (404 ENOUSER otherwise). */
function target(req) {
const u = db.prepare("SELECT * FROM users WHERE id = ?").get(Number(req.params.id));
if (!u) throw Object.assign(new Error("no such user"), { code: "ENOUSER" });
return u;
}
router.get("/:id", (req, res) => {
const u = db.prepare("SELECT * FROM users WHERE id = ?").get(Number(req.params.id));
if (!u) return res.status(404).json({ error: { code: "ENOUSER", message: "no such user" } });
res.json({
user: { ...auth.publicUser(u), ...auth.loginStats(u.id) },
workspaces: auth.ownedWorkspaces(u.id),
});
});
/** A list of workspace ids from the body, or [] when absent. */
function laneIds(value, field) {
if (value === undefined) return [];
if (!Array.isArray(value) || value.some((v) => !Number.isInteger(v) || v <= 0)) {
throw Object.assign(new Error(`${field}: a list of workspace ids`), { code: "EBADFIELD" });
}
return [...new Set(value)];
}
router.post(
"/",
accountChange(async (_req, body) => {
const role = body.role === undefined ? "developer" : body.role;
const user = await auth.createUser(body.username, body.password, role);
return { status: 201, user, action: `create ${user.username} (${user.role})` };
})
);
router.patch(
"/:id",
accountChange(async (req, body) => {
const u = target(req);
const self = u.id === req.user.id;
const ESELF = (msg) => Object.assign(new Error(msg), { code: "ESELF" });
// 1. Validate everything — nothing is written until all of it passes.
const profile = auth.validateProfile(body);
const roleChange = body.role !== undefined && body.role !== u.role;
if (roleChange) {
if (self) throw ESELF("you cannot change your own role");
if (!auth.ROLES.includes(body.role)) {
throw Object.assign(new Error(`role: one of ${auth.ROLES.join(", ")}`), {
code: "EBADROLE",
});
}
}
if (body.disabled !== undefined) {
if (typeof body.disabled !== "boolean") {
throw Object.assign(new Error("disabled: true or false"), { code: "EBADFIELD" });
}
if (self && body.disabled) throw ESELF("you cannot disable yourself");
}
const disabledChange = body.disabled !== undefined && body.disabled !== Boolean(u.disabled);
if (body.password !== undefined) auth.validatePassword(body.password);
if (body.signOut !== undefined && body.signOut !== true) {
throw Object.assign(new Error("signOut: true"), { code: "EBADFIELD" });
}
const add = laneIds(body.addWorkspaces, "addWorkspaces");
const remove = laneIds(body.removeWorkspaces, "removeWorkspaces");
const runAs = require("../lib/run-as");
for (const id of [...add, ...remove]) {
const lane = db.prepare("SELECT owner_id, cwd FROM lanes WHERE id = ?").get(id);
if (!lane) throw Object.assign(new Error(`no workspace ${id}`), { code: "ENOLANE" });
if (remove.includes(id) && lane.owner_id !== u.id) {
throw Object.assign(new Error(`workspace ${id} is not ${u.username}'s`), {
code: "ENOTOWNED",
});
}
// S3: a workspace in a member's home is theirs alone (EOWNERFOLDER).
if (add.includes(id)) runAs.assertOwnerFits(lane.cwd, u.id);
}
// 2. Apply. Disable last: it may stop panes and lock a Linux account
// (EPROVISION), and the admin should learn that after the rest held.
const done = [];
if (Object.keys(profile).length) {
auth.setProfile(u.id, profile);
if ("display_name" in profile) done.push("display name");
if ("email" in profile) done.push("email");
}
if (roleChange) {
auth.setRole(u.username, body.role);
done.push(`role ${body.role}`);
}
for (const id of add) auth.assignWorkspace(id, u.username);
for (const id of remove) auth.unassignWorkspace(id, u.username);
if (add.length) done.push(`workspace ${add.join(", ")}`);
if (remove.length) done.push(`removed workspace ${remove.join(", ")}`);
// An admin changing their own password or signing themselves out keeps
// the login they are doing it from.
const keepToken = self ? auth.cookieToken(req) : undefined;
if (body.password !== undefined) {
await auth.setPassword(u.username, body.password, { keepToken });
done.push("password reset");
}
if (body.signOut) {
auth.endSessions(u.id, keepToken);
done.push("signed out everywhere");
}
if (disabledChange) {
auth.setDisabled(u.username, body.disabled);
done.push(body.disabled ? "disable" : "enable");
}
return {
user: { ...auth.publicUser(target(req)), ...auth.loginStats(u.id) },
action: `${u.username}: ${done.join(", ") || "no change"}`,
};
})
);
/**
* Delete a user for good (auth.deleteUser): their logins, panes, workspaces'
* records and — under S3 — their Linux account and whole home. Never
* yourself (ESELF) or the last admin (ELASTADMIN); the admin's password
* again, like every account change, and written to the audit log.
*/
router.delete(
"/:id",
accountChange(async (req) => {
const u = target(req);
if (u.id === req.user.id) {
throw Object.assign(new Error("you cannot delete yourself"), { code: "ESELF" });
}
const gone = auth.deleteUser(u.username);
return {
user: auth.publicUser(u),
action: `delete ${u.username} (${gone.workspaces} workspace(s), home removed)`,
};
})
);
router.post(
"/:id/password",
accountChange(async (req, body) => {
const u = target(req);
await auth.setPassword(u.username, body.password);
return { user: auth.publicUser(u), action: `${u.username}: password reset` };
})
);
router.post(
"/:id/workspaces",
accountChange(async (req, body) => {
const u = target(req);
auth.assignWorkspace(body.laneId, u.username);
return { user: auth.publicUser(u), action: `${u.username}: workspace ${Number(body.laneId)}` };
})
);
module.exports = router;