chore: v2.8.15 — Oh My Pi login sharing, omp --allow-home, Markdown Preview default, first-login password
- omp-share.js: an admin's switch (S3) runs omp's own auth broker + gateway as the host on loopback; a member's omp pane reaches it as a scoped client keyed by its pane token (clients file = live omp panes only), runs on --model agenthub/<model>, never holds a credential. - omp catalog: --allow-home, so a workspace at the account's home keeps its sessions there (they were recorded under a temp dir and dropped). - Settings → Appearance → Open Markdown as: Preview (default) or Raw, for Files/Changes, the config viewer and a chat's file panel. - First-login password change and password rules, avatar URLs, Artifacts "Mine" includes installed shared skills/plugins, a member's own hook pages.
This commit is contained in:
@@ -36,6 +36,36 @@ router.post("/refresh", sameOriginGuard, async (_req, res) => {
|
||||
res.json(aiTools.view());
|
||||
});
|
||||
|
||||
// Oh My Pi login sharing (server/lib/omp-share.js): S3 only, an admin's
|
||||
// switch (`/ai-tools` writes are admin-only, auth.js ADMIN_WRITE_PREFIXES).
|
||||
// Declared before `/:id`, which would take `omp-sharing` as a tool id.
|
||||
router.get("/omp-sharing", (_req, res) => {
|
||||
res.json(require("../lib/omp-share").state());
|
||||
});
|
||||
|
||||
router.put("/omp-sharing", sameOriginGuard, async (req, res) => {
|
||||
const on = req.body?.enabled;
|
||||
if (typeof on !== "boolean") {
|
||||
return res.status(400).json({ error: { code: "EBADFIELD", message: "enabled: boolean" } });
|
||||
}
|
||||
const share = require("../lib/omp-share");
|
||||
if (!share.available()) {
|
||||
return res.status(409).json({
|
||||
error: { code: "ENOS3", message: "sharing needs server mode with per-user accounts" },
|
||||
});
|
||||
}
|
||||
const state = await share.setEnabled(on);
|
||||
if (req.user) {
|
||||
require("../lib/audit").recordAccountChange(
|
||||
req.user.id,
|
||||
null,
|
||||
"PUT",
|
||||
`omp login sharing ${on ? "on" : "off"}`
|
||||
);
|
||||
}
|
||||
res.json(state);
|
||||
});
|
||||
|
||||
router.put("/:id", sameOriginGuard, (req, res) => {
|
||||
const { enabled, default: makeDefault, defaultModel } = req.body || {};
|
||||
// Every field checked before anything is written: a bad one saves nothing.
|
||||
|
||||
@@ -521,7 +521,7 @@ function applyFirstUserDescriptor(sessionId, result) {
|
||||
if (refreshedAgent) broadcast("agent_updated", refreshedAgent);
|
||||
}
|
||||
|
||||
const processEventTx = db.transaction((hookType, data, tool = "claude") => {
|
||||
const processEventTx = db.transaction((hookType, data, tool = "claude", peer = null) => {
|
||||
const sessionId = data.session_id;
|
||||
if (!sessionId) return null;
|
||||
|
||||
@@ -1297,7 +1297,7 @@ const processEventTx = db.transaction((hookType, data, tool = "claude") => {
|
||||
// A claude.ai page the session published goes into its owner's Artifacts.
|
||||
if (hookType === "PostToolUse" && toolName === "Artifact" && tool !== "codex") {
|
||||
try {
|
||||
const row = require("../lib/artifacts").captureFromHook(sessionId, data);
|
||||
const row = require("../lib/artifacts").captureFromHook(sessionId, data, peer);
|
||||
if (row) {
|
||||
broadcast("artifact_changed", { id: row.id, ownerId: row.owner_id, shared: false });
|
||||
}
|
||||
@@ -1313,12 +1313,12 @@ const processEventTx = db.transaction((hookType, data, tool = "claude") => {
|
||||
* that transaction COMMITTED — in order, in the same tick. A frame sent from
|
||||
* inside it described a row a later throw could still roll back.
|
||||
*/
|
||||
function processEvent(hookType, data, tool) {
|
||||
function processEvent(hookType, data, tool, peer = null) {
|
||||
const outer = pendingMarks;
|
||||
pendingMarks = [];
|
||||
let marks = null;
|
||||
try {
|
||||
const out = holdFrames(() => processEventTx(hookType, data, tool));
|
||||
const out = holdFrames(() => processEventTx(hookType, data, tool, peer));
|
||||
marks = pendingMarks;
|
||||
return out;
|
||||
} finally {
|
||||
@@ -1628,7 +1628,7 @@ function ingestHook(body, pushSource = null, peer = { kind: "host" }) {
|
||||
held = [];
|
||||
let result = null;
|
||||
try {
|
||||
result = processEvent(hook_type, data, tool);
|
||||
result = processEvent(hook_type, data, tool, pushSource ? null : peer);
|
||||
if (result) {
|
||||
if (pushSource) {
|
||||
// Tagged in the same tick processEvent created it, so no local liveness
|
||||
|
||||
+31
-4
@@ -18,14 +18,18 @@
|
||||
* `/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);
|
||||
* one required, throttled like a step-up; every OTHER login ends; the new one
|
||||
* must pass every rule of `auth.passwordProblems` and differ from the old —
|
||||
* EWEAKPASSWORD with the failed `rules` — and it clears the "pick your own
|
||||
* password" flag an admin's create/reset sets);
|
||||
* `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.
|
||||
* `/avatar` (server mode) is the account's own picture (server/lib/avatars.js):
|
||||
* GET serves it (`nosniff`, `sandbox` CSP), PUT takes the raw image bytes
|
||||
* (PNG/JPEG/GIF/WebP, at most 1 MB) and DELETE removes it — both writes are
|
||||
* account writes like the profile's. The sidebar shows it beside the name.
|
||||
* (PNG/JPEG/GIF/WebP, at most 1 MB), `POST /avatar/url` downloads the same
|
||||
* from an https link (public addresses only, server/lib/avatar-url.js) and
|
||||
* DELETE removes it — all writes are account writes like the profile's. The sidebar shows it beside the name.
|
||||
*
|
||||
* 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.
|
||||
@@ -63,6 +67,7 @@ const PREF_KEYS = [
|
||||
"agenthub.tour",
|
||||
"agenthub.chatUi",
|
||||
"agenthub.workspace.allTabs",
|
||||
"agenthub.markdown.view",
|
||||
];
|
||||
const MAX_VALUE = 8 * 1024;
|
||||
|
||||
@@ -170,7 +175,11 @@ const ACCOUNT_STATUS = {
|
||||
EBADFIELD: 400,
|
||||
EBADEMAIL: 400,
|
||||
EBADPASSWORD: 400,
|
||||
EWEAKPASSWORD: 400,
|
||||
EBADIMAGE: 400,
|
||||
EBADURL: 400,
|
||||
EPRIVATEURL: 400,
|
||||
EFETCH: 502,
|
||||
ETOOBIG: 413,
|
||||
EREAUTH: 403,
|
||||
ETOOMANY: 429,
|
||||
@@ -206,7 +215,10 @@ function accountWrite(handler) {
|
||||
} 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 } });
|
||||
// EWEAKPASSWORD names the rules the password failed.
|
||||
res.status(status).json({
|
||||
error: { code: err.code, message: err.message, ...(err.rules && { rules: err.rules }) },
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -233,6 +245,10 @@ router.post(
|
||||
sameOriginGuard,
|
||||
accountWrite(async (req, user, body) => {
|
||||
await auth.confirmPassword(user, body.currentPassword);
|
||||
// The account's own choice: every rule, and not the one it has now. This
|
||||
// also clears a "pick your own password" flag an admin's reset left.
|
||||
auth.validateOwnPassword(body.newPassword, user.username);
|
||||
await auth.assertNotCurrent(user.id, body.newPassword);
|
||||
await auth.setPassword(user.username, body.newPassword, { keepToken: auth.cookieToken(req) });
|
||||
return { out: { ok: true }, action: "own password changed" };
|
||||
})
|
||||
@@ -273,6 +289,17 @@ router.put(
|
||||
})
|
||||
);
|
||||
|
||||
// The same picture from a link: the server downloads it (server/lib/avatar-url.js).
|
||||
router.post(
|
||||
"/avatar/url",
|
||||
sameOriginGuard,
|
||||
accountWrite(async (_req, user, body) => {
|
||||
const buf = await require("../lib/avatar-url").fetchAvatarImage(body.url);
|
||||
avatars.setAvatar(user.id, buf);
|
||||
return { out: accountView(user.id), action: "own avatar set from a link" };
|
||||
})
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/avatar",
|
||||
sameOriginGuard,
|
||||
|
||||
+83
-32
@@ -25,7 +25,11 @@
|
||||
* 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.
|
||||
* audited, and in local mode — no login to check — they all refuse. A
|
||||
* password an admin gives another account (create, reset) may be anything
|
||||
* non-empty and makes that account pick its own at its next login
|
||||
* (`must_change_password`); an admin's own new password must pass every
|
||||
* rule, like Settings → Account's (`validateOwnPassword`, EWEAKPASSWORD).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -33,7 +37,6 @@ 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();
|
||||
@@ -54,42 +57,72 @@ const USAGE_COLS = [
|
||||
"long_cache_write_1h_tokens",
|
||||
];
|
||||
|
||||
/** $ and tokens a member's sessions spent since `sinceHour` (UTC `YYYY-MM-DDTHH`). */
|
||||
function usageSince(userId, sinceHour, rules) {
|
||||
// Which account each session belongs to — through its workspace, or a
|
||||
// dashboard run on one (server/lib/scope.js's sessionWhere, for every user at once).
|
||||
const OWNED_SESSIONS = `
|
||||
SELECT s.id AS session_id, l.owner_id AS uid
|
||||
FROM sessions s JOIN lanes l ON l.id = s.lane_id
|
||||
WHERE l.owner_id IS NOT NULL
|
||||
UNION
|
||||
SELECT s.id, l.owner_id
|
||||
FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id JOIN sessions s ON s.id = r.session_id
|
||||
WHERE l.owner_id IS NOT NULL`;
|
||||
|
||||
/** Map(user id → {cost, tokens}) every account's sessions spent since `sinceHour` (UTC `YYYY-MM-DDTHH`). */
|
||||
function usageSince(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,
|
||||
`WITH owned AS (${OWNED_SESSIONS})
|
||||
SELECT o.uid, 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`
|
||||
FROM token_usage_hourly h JOIN owned o ON o.session_id = h.session_id
|
||||
WHERE h.hour >= ?
|
||||
GROUP BY o.uid, 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 };
|
||||
.all(sinceHour);
|
||||
const byUser = new Map();
|
||||
for (const r of rows) {
|
||||
if (!byUser.has(r.uid)) byUser.set(r.uid, []);
|
||||
byUser.get(r.uid).push(r);
|
||||
}
|
||||
const out = new Map();
|
||||
for (const [uid, list] of byUser) {
|
||||
const tokens = list.reduce(
|
||||
(n, r) => n + r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens,
|
||||
0
|
||||
);
|
||||
out.set(uid, { cost: calculateCost(list, rules).total_cost, tokens });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const hourAgo = (days) => new Date(Date.now() - days * 864e5).toISOString().slice(0, 13);
|
||||
|
||||
/** Map(key → n) from rows of `{k, n}`. */
|
||||
const counts = (rows) => new Map(rows.map((r) => [r.k, r.n]));
|
||||
|
||||
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),
|
||||
};
|
||||
});
|
||||
// A fixed number of grouped queries, however many accounts there are.
|
||||
const logins = auth.allLoginStats();
|
||||
const workspaces = counts(
|
||||
db.prepare("SELECT owner_id AS k, COUNT(*) AS n FROM lanes GROUP BY owner_id").all()
|
||||
);
|
||||
const sessions = counts(
|
||||
db.prepare(`SELECT uid AS k, COUNT(*) AS n FROM (${OWNED_SESSIONS}) GROUP BY uid`).all()
|
||||
);
|
||||
const last7d = usageSince(hourAgo(7), rules);
|
||||
const last30d = usageSince(hourAgo(30), rules);
|
||||
const none = { cost: 0, tokens: 0 };
|
||||
const users = listUsers().map((u) => ({
|
||||
...u,
|
||||
...(logins.get(u.id) || { logins: 0, lastLoginAt: null }),
|
||||
workspaces: workspaces.get(u.id) || 0,
|
||||
sessions: sessions.get(u.id) || 0,
|
||||
last7d: last7d.get(u.id) || none,
|
||||
last30d: last30d.get(u.id) || none,
|
||||
}));
|
||||
res.json({ users });
|
||||
});
|
||||
|
||||
@@ -112,6 +145,7 @@ const STATUS = {
|
||||
EBADEMAIL: 400,
|
||||
ENOTOWNED: 409,
|
||||
EBADPASSWORD: 400,
|
||||
EWEAKPASSWORD: 400,
|
||||
EBADROLE: 400,
|
||||
EBADFIELD: 400,
|
||||
EREAUTH: 403,
|
||||
@@ -150,7 +184,9 @@ function accountChange(handler) {
|
||||
} 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 } });
|
||||
res.status(status).json({
|
||||
error: { code: err.code, message: err.message, ...(err.rules && { rules: err.rules }) },
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -196,7 +232,8 @@ router.post(
|
||||
"/",
|
||||
accountChange(async (_req, body) => {
|
||||
const role = body.role === undefined ? "developer" : body.role;
|
||||
const user = await auth.createUser(body.username, body.password, role);
|
||||
// The admin's password is a starting one: the user picks their own first.
|
||||
const user = await auth.createUser(body.username, body.password, role, { mustChange: true });
|
||||
return { status: 201, user, action: `create ${user.username} (${user.role})` };
|
||||
})
|
||||
);
|
||||
@@ -226,7 +263,13 @@ router.patch(
|
||||
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.password !== undefined) {
|
||||
// Your own password: every rule. Someone else's: a starting one they replace.
|
||||
if (self) {
|
||||
auth.validateOwnPassword(body.password, u.username);
|
||||
await auth.assertNotCurrent(u.id, body.password);
|
||||
} else auth.validatePassword(body.password);
|
||||
}
|
||||
if (body.signOut !== undefined && body.signOut !== true) {
|
||||
throw Object.assign(new Error("signOut: true"), { code: "EBADFIELD" });
|
||||
}
|
||||
@@ -265,7 +308,7 @@ router.patch(
|
||||
// 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 });
|
||||
await auth.setPassword(u.username, body.password, { keepToken, mustChange: !self });
|
||||
done.push("password reset");
|
||||
}
|
||||
if (body.signOut) {
|
||||
@@ -375,7 +418,15 @@ router.post(
|
||||
"/:id/password",
|
||||
accountChange(async (req, body) => {
|
||||
const u = target(req);
|
||||
await auth.setPassword(u.username, body.password);
|
||||
const self = u.id === req.user.id;
|
||||
if (self) {
|
||||
auth.validateOwnPassword(body.password, u.username);
|
||||
await auth.assertNotCurrent(u.id, body.password);
|
||||
}
|
||||
await auth.setPassword(u.username, body.password, {
|
||||
keepToken: self ? auth.cookieToken(req) : undefined,
|
||||
mustChange: !self,
|
||||
});
|
||||
return { user: auth.publicUser(u), action: `${u.username}: password reset` };
|
||||
})
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user