feat: v2.7.6 — edit users in one form, Settings → Account, display names, copy over plain HTTP
- Users page: one Edit user form (display name, email, role, active, a new or generated password, workspaces given or taken back, sign out everywhere), validated as a whole before anything is written (PATCH /api/users/:id, GET /api/users/:id); users.display_name/email added migration-safe. - Settings → Account for every signed-in user: profile, own password (the current one required, this login kept), sign out other devices (/api/me/account, /api/me/password, /api/me/sign-out-others; login cookie only, never a pane token). - Display names wherever a person is named (sidebar, workspace owner groups, Users page and audit log); owner_display_name / reader_display additive. - Users page: admins add and remove Claude/Codex pool accounts. - Folder browser: an admin with their own Linux account opens in their home; the "Server folder" tick opens the host's (never remembered). - AI Proxy: "Config 9router" beside Add profile when 9router is installed, opened on the dashboard's own host (GET /api/ai-proxies/9router). - Terminal: a tmux selection reaches the clipboard over plain HTTP too (writeClipboard's textarea fallback, focus handed back). - Chat: a file the session touched outside the workspace previews (GET /api/sessions/:id/file). - install-system: `!requiretty` only when visudo accepts it (sudo-rs on Ubuntu 25.10+ rejects the setting). - openapi.yaml regenerated; docs (API, SERVER-MODE, LANES) updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+187
-2
@@ -4,14 +4,31 @@
|
||||
* sees it (server/lib/claude-pool.js): per account its live panes, $ spent in
|
||||
* the last 5 h / 7 d, the last quota reading and whether it counts as full;
|
||||
* `codex` is the same for the Codex pool (server/lib/codex-pool.js). Never a
|
||||
* key or a token. `?force=1` re-reads every quota first. Accounts are added and
|
||||
* removed only from the host's shell (`agenthub accounts …`).
|
||||
* key or a token. `?force=1` re-reads every quota first.
|
||||
*
|
||||
* Accounts are added from the host's shell (`agenthub accounts …`) or, in
|
||||
* server mode, by an admin on the Users page: `POST /` (`{tool, name, …}`) and
|
||||
* `DELETE /:name` (`{tool}`). A Claude account is one of: `profile` — a login
|
||||
* saved by the switch-user profiles (cc-profiles.js), MOVED into the pool (its
|
||||
* single-use refresh token may have only one holder, so the profile is
|
||||
* deleted; the account the host's own CLI is logged into moves in with its
|
||||
* live login and the host's home becomes one more placement the server
|
||||
* refreshes); `credentials` — the text of a `.credentials.json` (or a macOS
|
||||
* Keychain item's JSON); or `token` — a `claude setup-token` token. A Codex
|
||||
* one is an OpenAI API key or the text of an `auth.json` (`token`).
|
||||
* `GET /profiles` lists the saved profiles that can be moved in (identity only). Like every Users-page change
|
||||
* they need the admin's own password again (`currentPassword`), are audited
|
||||
* (the account NAME only), and refuse in local mode. The secret only goes IN:
|
||||
* no route answers with it (`/accounts` is in ADMIN_WRITE_PREFIXES).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { Router } = require("express");
|
||||
const pool = require("../lib/claude-pool");
|
||||
const codexPool = require("../lib/codex-pool");
|
||||
const auth = require("../lib/auth");
|
||||
const { recordAccountChange } = require("../lib/audit");
|
||||
const profiles = require("../lib/cc-profiles");
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -29,4 +46,172 @@ router.get("/", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
/** Saved switch-user profiles an admin may move into the pool — never a token. */
|
||||
router.get("/profiles", (_req, res) => {
|
||||
try {
|
||||
res.json({
|
||||
profiles: profiles.listProfiles().items.map((p) => ({
|
||||
name: p.name,
|
||||
label: p.label,
|
||||
email: p.email,
|
||||
subscriptionType: p.subscriptionType,
|
||||
active: p.active,
|
||||
})),
|
||||
});
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: { code: e.code || "EPROFILES", message: e.message } });
|
||||
}
|
||||
});
|
||||
|
||||
const STATUS = {
|
||||
ENOTFOUND: 404,
|
||||
EACTIVE: 409,
|
||||
ELOCALMODE: 403,
|
||||
EREAUTH: 403,
|
||||
EBADTOOL: 400,
|
||||
EBADNAME: 400,
|
||||
EBADTOKEN: 400,
|
||||
ENOACCOUNT: 404,
|
||||
EEXISTS: 409,
|
||||
ETOOMANY: 429,
|
||||
ESTALE: 409, // a pasted login whose refresh token was already spent
|
||||
EUPSTREAM: 502,
|
||||
};
|
||||
|
||||
/** One pool change: server mode, the admin's password confirmed, audited. */
|
||||
function poolChange(handler) {
|
||||
return async (req, res) => {
|
||||
try {
|
||||
if (!auth.isServerMode() || !req.user) {
|
||||
throw Object.assign(new Error("the pool is changed from the host's shell in local mode"), {
|
||||
code: "ELOCALMODE",
|
||||
});
|
||||
}
|
||||
const body = req.body && typeof req.body === "object" ? req.body : {};
|
||||
if (body.tool !== "claude" && body.tool !== "codex") {
|
||||
throw Object.assign(new Error("tool: claude or codex"), { code: "EBADTOOL" });
|
||||
}
|
||||
await auth.confirmPassword(req.user, body.currentPassword);
|
||||
const out = await handler(req, body);
|
||||
recordAccountChange(req.user.id, null, req.method, out.action);
|
||||
res.status(out.status || 200).json(out.json);
|
||||
} catch (e) {
|
||||
const status = STATUS[e.code];
|
||||
if (!status) return res.status(500).json({ error: { message: e.message } });
|
||||
res.status(status).json({ error: { code: e.code, message: e.message } });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A pasted `.credentials.json` (or Keychain item) → `{oauth, account}`. The
|
||||
* file names no account, so Anthropic is asked whose token it is (refreshing
|
||||
* an expired one first — what the exchange returns is what gets stored):
|
||||
* the pool copies a member's refresh back only when it is that same account.
|
||||
*/
|
||||
async function pastedLogin(text) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(String(text || ""));
|
||||
} catch {
|
||||
throw Object.assign(new Error("not valid JSON — paste the whole .credentials.json"), {
|
||||
code: "EBADTOKEN",
|
||||
});
|
||||
}
|
||||
let oauth = parsed?.claudeAiOauth || parsed;
|
||||
if (!oauth?.accessToken || !oauth?.refreshToken) return { oauth }; // addLoginAccount says why
|
||||
const usage = require("../lib/cc-usage");
|
||||
let owner = await usage.fetchOwner(oauth.accessToken);
|
||||
if (!owner) {
|
||||
oauth = await usage.exchangeRefresh(oauth);
|
||||
owner = await usage.fetchOwner(oauth.accessToken);
|
||||
}
|
||||
if (!owner) {
|
||||
throw Object.assign(new Error("Anthropic did not accept this login"), { code: "EBADTOKEN" });
|
||||
}
|
||||
return { oauth, account: { accountUuid: owner.uuid, emailAddress: owner.email } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a saved profile into the pool: the pool becomes its one holder. The
|
||||
* account this machine's own Claude Code is logged into moves in with the
|
||||
* LIVE login (the saved copy's refresh token is spent once the CLI refreshed)
|
||||
* and keeps running here: the host's home becomes one more placement the
|
||||
* server refreshes and pushes into. A macOS Keychain login cannot be written
|
||||
* that way (EACTIVE).
|
||||
*/
|
||||
function fromProfile(name, poolName) {
|
||||
const stored = profiles.readProfile(name);
|
||||
if (!stored) throw Object.assign(new Error(`no saved profile ${name}`), { code: "ENOTFOUND" });
|
||||
const active = profiles.listProfiles().items.find((p) => p.name === name)?.active;
|
||||
let oauth = stored.credentials;
|
||||
if (active) {
|
||||
const live = profiles.readActiveAuth();
|
||||
if (live.keychain || !live.oauth) {
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
"this machine's Claude Code keeps that login in the macOS Keychain — switch it to another profile first"
|
||||
),
|
||||
{ code: "EACTIVE" }
|
||||
);
|
||||
}
|
||||
oauth = live.oauth;
|
||||
}
|
||||
const account = pool.addLoginAccount(poolName || name, {
|
||||
oauth,
|
||||
account: stored.account || null,
|
||||
userID: stored.userID || null,
|
||||
hostHolds: Boolean(active),
|
||||
});
|
||||
// The only saved copy of the live account is not deletable (EACTIVE) — and
|
||||
// need not be: removing the file is enough, the pool holds the login now.
|
||||
require("node:fs").rmSync(require("node:path").join(profiles.profilesDir(), `${name}.json`), {
|
||||
force: true,
|
||||
});
|
||||
return account;
|
||||
}
|
||||
|
||||
/** Codex takes an API key, or the text of an auth.json (`codex login`'s). */
|
||||
function codexSecret(token) {
|
||||
const text = String(token || "").trim();
|
||||
if (!text.startsWith("{")) return { apiKey: text };
|
||||
try {
|
||||
return { auth: JSON.parse(text) };
|
||||
} catch {
|
||||
throw Object.assign(new Error("not valid JSON — paste the whole auth.json"), {
|
||||
code: "EBADTOKEN",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
poolChange(async (_req, body) => {
|
||||
const account =
|
||||
body.tool === "codex"
|
||||
? codexPool.addAccount(body.name, codexSecret(body.token))
|
||||
: body.profile
|
||||
? fromProfile(String(body.profile), body.name)
|
||||
: body.credentials
|
||||
? pool.addLoginAccount(body.name, await pastedLogin(body.credentials))
|
||||
: pool.addAccount(body.name, body.token);
|
||||
return {
|
||||
status: 201,
|
||||
json: { account },
|
||||
action: `pool: add ${body.tool} account ${account.name}`,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/:name",
|
||||
poolChange((req, body) => {
|
||||
(body.tool === "claude" ? pool : codexPool).removeAccount(req.params.name);
|
||||
return {
|
||||
json: { ok: true },
|
||||
action: `pool: remove ${body.tool} account ${req.params.name}`,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -22,14 +22,20 @@
|
||||
* `GET /:name` — a route that returned one profile in full would be the one
|
||||
* way an API key could leave this process.
|
||||
*
|
||||
* `GET /9router` only says whether a `9router` binary is on the server's PATH,
|
||||
* so the page can offer a link to its own config UI; it never runs it.
|
||||
*
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const path = require("node:path");
|
||||
const express = require("express");
|
||||
|
||||
const proxies = require("../lib/ai-proxies");
|
||||
const { refreshProfileFiles, removeProfileFiles } = require("../lib/proxy-apply");
|
||||
const { sameOriginGuard } = require("../lib/same-origin");
|
||||
const { which } = require("../lib/ai-tools");
|
||||
const { shellPath } = require("../lib/shell-path");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -74,6 +80,13 @@ router.get("/", (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/ai-proxies/9router — is 9router installed here? `{ installed }`.
|
||||
// A file lookup on PATH only; nothing is spawned.
|
||||
router.get("/9router", (_req, res) => {
|
||||
const pathStr = [shellPath(), process.env.PATH].filter(Boolean).join(path.delimiter);
|
||||
res.json({ installed: Boolean(which("9router", pathStr)) });
|
||||
});
|
||||
|
||||
// POST /api/ai-proxies — body: { label, baseUrl, apiKey?, model, models?,
|
||||
// behavesAs?, scope? }. `scope` is "shared" (an admin's default) or "personal"
|
||||
// (a member's only choice); local mode has no user and always writes shared.
|
||||
|
||||
+22
-2
@@ -569,6 +569,10 @@ router.post("/gc", sameOriginGuard, (req, res) => {
|
||||
* `hidden=1` lists dot entries too — never those at the top of a non-admin's
|
||||
* own folder, where a member's logins live. Each entry carries its `mtime`
|
||||
* (ms), and `home` is the folder the browser's Home place opens.
|
||||
* An admin with a Linux account of their own (S3) starts in THEIR home, like
|
||||
* any member, and the answer carries `hostHome` (the host account's home);
|
||||
* `host=1` opens that one instead — a workspace there runs as the shared
|
||||
* host account, so it is a deliberate tick in the dialog, never the default.
|
||||
*/
|
||||
router.get("/browse", (req, res) => {
|
||||
// A developer browses only their own folder (by real path: a link in it
|
||||
@@ -577,12 +581,22 @@ router.get("/browse", (req, res) => {
|
||||
const own = scope.ownFolder(req);
|
||||
const files = req.query.files === "1";
|
||||
const hidden = req.query.hidden === "1";
|
||||
// An admin is not held to a folder, but starts in their own home (S3).
|
||||
let adminHome = null;
|
||||
if (!own && req.user?.role === "admin") {
|
||||
try {
|
||||
adminHome = require("../lib/run-as").accountForUser(req.user.username)?.home || null;
|
||||
} catch {
|
||||
// No Linux account for this admin (EMEMBERGONE): the host's home, as before.
|
||||
}
|
||||
}
|
||||
const startHome = adminHome && req.query.host !== "1" ? adminHome : own || os.homedir();
|
||||
const raw =
|
||||
typeof req.query.path === "string" && req.query.path.trim()
|
||||
? files
|
||||
? startDir(req.query.path)
|
||||
: req.query.path
|
||||
: own || os.homedir();
|
||||
: startHome;
|
||||
const resolved = own ? lanesLib.canonicalCwd(path.resolve(raw)) : path.resolve(raw);
|
||||
if (own && !scope.folderAllowed(req, resolved, { allowHome: true })) return refuseFolder(res);
|
||||
|
||||
@@ -634,7 +648,13 @@ router.get("/browse", (req, res) => {
|
||||
|
||||
const top = path.dirname(resolved) === resolved || atOwnTop;
|
||||
const parent = top ? null : path.dirname(resolved);
|
||||
res.json({ path: resolved, parent, entries, home: own || os.homedir() });
|
||||
res.json({
|
||||
path: resolved,
|
||||
parent,
|
||||
entries,
|
||||
home: startHome,
|
||||
...(adminHome ? { hostHome: os.homedir() } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,6 +15,14 @@
|
||||
* `agenthub.chatUi` ("1") opens Claude/Codex sessions as a chat (`PaneChat`);
|
||||
* the appearance keys are `useTheme`'s own (`theme`, `agenthub.theme.dark|light`).
|
||||
*
|
||||
* `/account` (server mode) is the signed-in account itself for Settings →
|
||||
* Account: GET its profile, workspace/session counts and logins; PATCH its
|
||||
* display name and email; `POST /password` changes its own password (the old
|
||||
* one required, throttled like a step-up; every OTHER login ends);
|
||||
* `POST /sign-out-others` ends every login but this one. These writes take the
|
||||
* account from the login COOKIE only — a pane token (an agent acting as its
|
||||
* owner) may not change the owner's login. Each change is audited.
|
||||
*
|
||||
* S3 (one Linux user per account): an account's dark/light choice also becomes
|
||||
* the theme in their own Claude Code settings, written as them.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
@@ -142,6 +150,90 @@ router.post("/onboarded", sameOriginGuard, (req, res) => {
|
||||
res.json(read(key));
|
||||
});
|
||||
|
||||
// ── The account itself (server mode) ─────────────────────────────────────────
|
||||
|
||||
const { sessionWhere } = require("../lib/scope");
|
||||
const { recordAccountChange } = require("../lib/audit");
|
||||
|
||||
const ACCOUNT_STATUS = {
|
||||
EBADFIELD: 400,
|
||||
EBADEMAIL: 400,
|
||||
EBADPASSWORD: 400,
|
||||
EREAUTH: 403,
|
||||
ETOOMANY: 429,
|
||||
};
|
||||
|
||||
function accountView(userId) {
|
||||
const row = db.prepare("SELECT * FROM users WHERE id = ?").get(userId);
|
||||
const w = sessionWhere({ user: { id: userId, role: "developer" } });
|
||||
return {
|
||||
mode: "server",
|
||||
user: auth.publicUser(row),
|
||||
workspaces: db.prepare("SELECT COUNT(*) AS n FROM lanes WHERE owner_id = ?").get(userId).n,
|
||||
sessions: db.prepare(`SELECT COUNT(*) AS n FROM sessions WHERE ${w.where}`).get(...w.params).n,
|
||||
...auth.loginStats(userId),
|
||||
};
|
||||
}
|
||||
|
||||
/** A write to the account: the cookie's own user, never a pane token's. */
|
||||
function accountWrite(handler) {
|
||||
return async (req, res) => {
|
||||
if (!auth.isServerMode()) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: { code: "ELOCALMODE", message: "no account in local mode" } });
|
||||
}
|
||||
const user = auth.userFromRequest(req);
|
||||
if (!user) return unauth(res);
|
||||
try {
|
||||
const body = req.body && typeof req.body === "object" ? req.body : {};
|
||||
const { out, action } = await handler(req, user, body);
|
||||
recordAccountChange(user.id, user.id, req.method, `${user.username}: ${action}`);
|
||||
res.json(out);
|
||||
} catch (err) {
|
||||
const status = ACCOUNT_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 } });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
router.get("/account", (req, res) => {
|
||||
if (!auth.isServerMode()) return res.json({ mode: "local" });
|
||||
const user = req.user || auth.userFromRequest(req);
|
||||
if (!user) return unauth(res);
|
||||
res.json(accountView(user.id));
|
||||
});
|
||||
|
||||
router.patch(
|
||||
"/account",
|
||||
sameOriginGuard,
|
||||
accountWrite(async (_req, user, body) => {
|
||||
const fields = auth.validateProfile({ displayName: body.displayName, email: body.email });
|
||||
auth.setProfile(user.id, fields);
|
||||
return { out: accountView(user.id), action: "own profile" };
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/password",
|
||||
sameOriginGuard,
|
||||
accountWrite(async (req, user, body) => {
|
||||
await auth.confirmPassword(user, body.currentPassword);
|
||||
await auth.setPassword(user.username, body.newPassword, { keepToken: auth.cookieToken(req) });
|
||||
return { out: { ok: true }, action: "own password changed" };
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/sign-out-others",
|
||||
sameOriginGuard,
|
||||
accountWrite(async (req, user) => {
|
||||
const ended = auth.endSessions(user.id, auth.cookieToken(req));
|
||||
return { out: { ended }, action: `signed out ${ended} other login(s)` };
|
||||
})
|
||||
);
|
||||
|
||||
/** S3: an account's dark/light mode becomes their Claude Code theme (best effort). */
|
||||
function followClaudeTheme(req, mode) {
|
||||
if (mode !== "dark" && mode !== "light") return;
|
||||
|
||||
@@ -543,6 +543,71 @@ router.get("/:id/image", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// A text file the session's own Read, Write, Edit, MultiEdit or NotebookEdit
|
||||
// named (`?path=`, exact), for the Chat pane's Outputs/Files preview when it
|
||||
// lies outside the workspace (a report written to ~/Documents, issue #76).
|
||||
// The same authorization as `/image` — that event, never a pushed session,
|
||||
// server mode only with S3 and a member's session only inside their own home
|
||||
// on a file they own — plus: never a credential by name
|
||||
// (`isSecretConfigPath`, a `settings.local.json`), never a binary or a
|
||||
// non-regular file, at most READ_TEXT_MAX bytes (the rest is `truncated`).
|
||||
const READ_TEXT_MAX = 512 * 1024;
|
||||
const sessionTouchedFile = db.prepare(
|
||||
`SELECT 1 FROM events
|
||||
WHERE session_id = ? AND event_type = 'PostToolUse'
|
||||
AND tool_name IN ('Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit')
|
||||
AND (json_extract(data, '$.tool_input.file_path') = ?
|
||||
OR json_extract(data, '$.tool_input.notebook_path') = ?)
|
||||
LIMIT 1`
|
||||
);
|
||||
router.get("/:id/file", async (req, res) => {
|
||||
const fail = (status, code, message) => res.status(status).json({ error: { code, message } });
|
||||
const session = stmts.getSession.get(req.params.id);
|
||||
if (!session) return fail(404, "NOT_FOUND", "Session not found");
|
||||
const s3 = require("../lib/linux-accounts").s3Enabled();
|
||||
if ((isServerMode() && !s3) || String(session.source || "").startsWith("push:")) {
|
||||
return fail(403, "EUNSUPPORTED", "not available for this session");
|
||||
}
|
||||
const file = typeof req.query.path === "string" ? req.query.path : "";
|
||||
if (!path.isAbsolute(file)) return fail(400, "EBADPATH", "not an absolute path");
|
||||
const { isSecretConfigPath } = require("../lib/cc-discovery");
|
||||
const secret = (p) =>
|
||||
isSecretConfigPath(p) || path.basename(p).toLowerCase() === "settings.local.json";
|
||||
if (secret(file)) return fail(403, "ESECRET", "a credential file is never served");
|
||||
const runAs = require("../lib/run-as");
|
||||
const member = s3 ? runAs.ownerForRead(session.cwd) : null;
|
||||
if (member && !require("../lib/hook-auth").inside(member.home, file)) {
|
||||
return fail(404, "ENOTFOUND", "the session never touched that file");
|
||||
}
|
||||
if (!sessionTouchedFile.get(session.id, file, file)) {
|
||||
return fail(404, "ENOTFOUND", "the session never touched that file");
|
||||
}
|
||||
let fh;
|
||||
try {
|
||||
// By what it RESOLVES to as well: a link named `notes.md` to a key file.
|
||||
if (secret(await fs.promises.realpath(file))) {
|
||||
return fail(403, "ESECRET", "a credential file is never served");
|
||||
}
|
||||
// NONBLOCK: a FIFO must not hang the event loop.
|
||||
fh = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));
|
||||
const st = await fh.stat();
|
||||
const fileOwner = s3 ? runAs.ownerForRead(file) : null;
|
||||
if (!st.isFile() || (fileOwner && st.uid !== fileOwner.uid)) {
|
||||
return fail(404, "ENOTFOUND", "no such file");
|
||||
}
|
||||
const buf = Buffer.alloc(Math.min(st.size, READ_TEXT_MAX));
|
||||
const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
||||
const head = buf.subarray(0, bytesRead);
|
||||
if (head.subarray(0, 8000).includes(0)) return fail(415, "EBINARY", "not a text file");
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.json({ text: head.toString("utf8"), truncated: st.size > READ_TEXT_MAX });
|
||||
} catch {
|
||||
if (!res.headersSent) fail(404, "ENOTFOUND", "no such file");
|
||||
} finally {
|
||||
await fh?.close();
|
||||
}
|
||||
});
|
||||
|
||||
/** The `/:id/stats` body — also frozen into a session snapshot. */
|
||||
function sessionStats(sessionId) {
|
||||
const totalEvents = stmts.sessionEventCount.get(sessionId)?.count ?? 0;
|
||||
|
||||
+89
-11
@@ -7,8 +7,12 @@
|
||||
* 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
|
||||
* `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
|
||||
@@ -69,6 +73,7 @@ router.get("/", (_req, res) => {
|
||||
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,
|
||||
@@ -85,6 +90,8 @@ router.get("/audit", (req, res) => {
|
||||
|
||||
const STATUS = {
|
||||
EBADUSER: 400,
|
||||
EBADEMAIL: 400,
|
||||
ENOTOWNED: 409,
|
||||
EBADPASSWORD: 400,
|
||||
EBADROLE: 400,
|
||||
EBADFIELD: 400,
|
||||
@@ -132,6 +139,24 @@ function target(req) {
|
||||
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) => {
|
||||
@@ -146,25 +171,78 @@ router.patch(
|
||||
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}`);
|
||||
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 Object.assign(new Error("you cannot disable yourself"), { code: "ESELF" });
|
||||
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)),
|
||||
user: { ...auth.publicUser(target(req)), ...auth.loginStats(u.id) },
|
||||
action: `${u.username}: ${done.join(", ") || "no change"}`,
|
||||
};
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user