84e2a9f0ac
Server mode can now run each account as its own Linux user (ah-<name>) when `agenthub server install-system` has set S3 up. The dashboard reaches a member only through sudo -u / write-as / pane-launch, reads a member's files only through owner- and type-checked opens, and hooks are authenticated by peer uid. Local mode and server mode without S3 are unchanged. EXPERIMENTAL: tested with fake sudo and fake accounts only. It has not yet been verified on a real install with real member accounts, sudo or a real Codex login. Do not offer it to real users yet. - S3 core: provisioning, per-member tmux servers, the proxy key gateway, shared tools in /opt, dropped capabilities for children (P0–P5) - P4: plan and quota per member home - P6: ~/.claude.json seed; opt-in plugin baseline installed as the member; managed-settings spike script (not run) - P7: Codex account pool (`agenthub accounts add --tool codex`) - Roles merged with main's admin / analyst / developer: analysts write only their own rows, under S3 as well - Per-account prefs: one implementation (Chat UI + onboarding) - Security reviews F1–F49 (five rounds), each fix with a regression test: symlink/TOCTOU-safe member reads, no host writes in a member home, credentials and the data dir never served, owner and folder account must agree, pane tokens bound to the pane's uid, bounded sudo/tmux/git calls and member reads (no hang or crash from a member), async route rejections answer 500 instead of exiting - Docs: docs/SERVER-MODE.md (S3 model, accepted ceilings, operator runbook), docs/plans/server-mode/S3-PLAN.md, CLAUDE.md S3 rules Tests: server 2838/2841 (3 need 127.0.0.1:3000, held on this box); client 1162/1162; tsc clean; headers check passes. Co-Authored-By: Claude <noreply@anthropic.com>
192 lines
6.5 KiB
JavaScript
192 lines
6.5 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).
|
|
*
|
|
* The Users page's account changes — `POST /` (create), `PATCH /:id` (role,
|
|
* disabled), `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,
|
|
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,
|
|
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
|
|
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.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 done = [];
|
|
if (body.role !== undefined && body.role !== auth.publicUser(u).role) {
|
|
if (self)
|
|
throw Object.assign(new Error("you cannot change your own role"), { code: "ESELF" });
|
|
auth.setRole(u.username, body.role);
|
|
done.push(`role ${body.role}`);
|
|
}
|
|
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 Object.assign(new Error("you cannot disable yourself"), { code: "ESELF" });
|
|
}
|
|
auth.setDisabled(u.username, body.disabled);
|
|
done.push(body.disabled ? "disable" : "enable");
|
|
}
|
|
return {
|
|
user: auth.publicUser(target(req)),
|
|
action: `${u.username}: ${done.join(", ") || "no change"}`,
|
|
};
|
|
})
|
|
);
|
|
|
|
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;
|