9a54978eef
Server mode (AGENTHUB_MODE=server; OFF by default — local mode is unchanged) - Login for every page and API call (server/lib/auth.js, routes/auth.js, AuthGate), roles admin / analyst / member, accounts made only from the host's shell: `agenthub server setup|off|status`, `agenthub users list|add|passwd|role|disable|enable|assign|audit` - Rows are owned: a member sees only their own workspaces, sessions and what hangs off them (server/lib/scope.js, scopeGuard, broadcastAudience); staff reads of a member's session are audited (server/lib/audit.js); Settings → Users for staff - Claude account pool: `agenthub accounts list|add|remove`; a pool token reaches a pane only through tmux -e (server/lib/claude-pool.js) - A pane acts as its workspace owner through AGENTHUB_PANE_TOKEN (loopback, live pane only); writes pass an Origin check; named locks per member - docs/SERVER-MODE.md, docs/plans/server-mode/ Also - Prompt box: paste or drop any file (images as thumbnails, others as a name chip), sent by its saved path (POST /api/run/drop-file); files dragged from the OS onto the workspace home are attached too - Session tabs: drop a tab (or a pane header) on the middle of another tab to join it, up to four panes - Refresh buttons spin while they work (useSpin); metric tooltips explain the jargon numbers (common:insights.help.*) - Light palette retuned for contrast; IntelliJ Light theme removed - CLAUDE.md sync marker trimmed; its history moved to docs/CLAUDE-SYNC-LOG.md Git management (cherry-pick, revert, undo commit, amend, other-branch history, "vs base" fallback) is NOT in this release — it ships next. Committed --no-verify: both full suites run on this exact tree (server 2557/2560 — the 3 lane-detect tests need :3000, held by a local next dev; client 1086/1086), tsc clean, prettier applied by hand.
182 lines
6.7 KiB
JavaScript
182 lines
6.7 KiB
JavaScript
/**
|
|
* @file source-filter.js
|
|
* @description Shared helper for the "data scope" feature: restricting a query
|
|
* to sessions collected from a chosen set of machines (see server/db.js
|
|
* `sessions.source` and server/lib/remote-sync.js).
|
|
*
|
|
* The client passes `?sources=local,src_abc,...` on any data endpoint. Absent or
|
|
* empty means "all sources" (no filter) so every existing caller and the
|
|
* zero-config default are unaffected. This module turns that query param into a
|
|
* SQL fragment that is safe to append to any WHERE clause — either directly on
|
|
* `sessions.source`, or, for tables that only carry a `session_id`, as a
|
|
* subquery so complex aggregate SQL (stats, analytics) needs only one extra AND.
|
|
*
|
|
* `?tool=<id>` (an AI Tools catalog id, matched against `sessions.tool`) narrows
|
|
* the same way; `parseScope` folds both into one predicate over `sessions`,
|
|
* plus — in server mode, for a member — the member's own sessions
|
|
* (`sessionWhere`, server/lib/scope.js), so no request can widen past them.
|
|
*
|
|
* `?from=&to=` (local `YYYY-MM-DD`, inclusive, read with `tz_offset`) is a date
|
|
* range: `parseRange` turns it into the UTC instants a timestamp column is
|
|
* compared with, and `inRange` tests a local date (a cost row's `date`).
|
|
*
|
|
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
|
*/
|
|
|
|
const { sessionWhere } = require("./scope");
|
|
|
|
/**
|
|
* Parse the `sources` query param into a de-duplicated list, or null for
|
|
* "all sources" (no filtering).
|
|
* @param {import("express").Request} req
|
|
* @returns {string[]|null}
|
|
*/
|
|
function parseSources(req) {
|
|
const raw = req.query ? req.query.sources : undefined;
|
|
if (typeof raw !== "string") return null;
|
|
const list = [
|
|
...new Set(
|
|
raw
|
|
.split(",")
|
|
.map((s) => s.trim())
|
|
.filter(Boolean)
|
|
),
|
|
];
|
|
return list.length > 0 ? list : null;
|
|
}
|
|
|
|
/**
|
|
* Filter directly on a `source` column (used when `sessions` is in the query).
|
|
* @param {string[]|null} sources result of parseSources
|
|
* @param {string} [col] the qualified source column (default "s.source")
|
|
* @returns {{clause:string, params:string[]}} `clause` is "" when no filter
|
|
*/
|
|
function sourceColumnClause(sources, col = "s.source") {
|
|
if (!sources || sources.length === 0) return { clause: "", params: [] };
|
|
const placeholders = sources.map(() => "?").join(",");
|
|
return { clause: `${col} IN (${placeholders})`, params: sources };
|
|
}
|
|
|
|
/**
|
|
* Filter by session origin when only a `session_id` column is available, via a
|
|
* subquery against `sessions`. Lets stats/analytics/events/agents scope by
|
|
* source with a single extra AND and no FROM/GROUP BY changes.
|
|
* @param {string[]|null} sources result of parseSources
|
|
* @param {string} sessionIdCol the qualified session-id column (e.g. "e.session_id")
|
|
* @returns {{clause:string, params:string[]}} `clause` is "" when no filter
|
|
*/
|
|
function sessionIdInSourcesClause(sources, sessionIdCol) {
|
|
if (!sources || sources.length === 0) return { clause: "", params: [] };
|
|
const placeholders = sources.map(() => "?").join(",");
|
|
return {
|
|
clause: `${sessionIdCol} IN (SELECT id FROM sessions WHERE source IN (${placeholders}))`,
|
|
params: sources,
|
|
};
|
|
}
|
|
|
|
// An AI Tools catalog id shape; the value is only ever a bound parameter.
|
|
const TOOL_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
|
|
|
/**
|
|
* Parse `?tool=`: null when absent, false when malformed (the route answers 400).
|
|
* @param {import("express").Request} req
|
|
* @returns {string|null|false}
|
|
*/
|
|
function parseTool(req) {
|
|
const raw = req.query ? req.query.tool : undefined;
|
|
if (raw === undefined || raw === "") return null;
|
|
return typeof raw === "string" && TOOL_RE.test(raw) ? raw : false;
|
|
}
|
|
|
|
/**
|
|
* The data scope (sources and/or tool, and a member's own sessions) as ONE
|
|
* predicate over `sessions` with unqualified columns, or null for "everything"
|
|
* — never null for a member. Callers check `parseTool` for false first.
|
|
* @param {import("express").Request} req
|
|
* @returns {{where:string, params:string[]}|null}
|
|
*/
|
|
function parseScope(req) {
|
|
const sources = parseSources(req);
|
|
const tool = parseTool(req);
|
|
const where = [];
|
|
const params = [];
|
|
if (sources) {
|
|
where.push(`source IN (${sources.map(() => "?").join(",")})`);
|
|
params.push(...sources);
|
|
}
|
|
if (tool) {
|
|
where.push("tool = ?");
|
|
params.push(tool);
|
|
}
|
|
const own = sessionWhere(req);
|
|
if (own.where !== "1") {
|
|
where.push(own.where);
|
|
params.push(...own.params);
|
|
}
|
|
return where.length ? { where: where.join(" AND "), params } : null;
|
|
}
|
|
|
|
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
const DAY_MS = 86_400_000;
|
|
|
|
/** A real calendar date in `YYYY-MM-DD` form (2026-02-30 is not), before
|
|
* year 9999 (whose next day no longer prints as a comparable ISO string). */
|
|
function isDate(s) {
|
|
if (typeof s !== "string" || !DATE_RE.test(s) || s >= "9999") return false;
|
|
const ms = Date.parse(`${s}T00:00:00Z`);
|
|
return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === s;
|
|
}
|
|
|
|
/**
|
|
* Parse `?from=&to=`: null when both are absent, false when either is not a
|
|
* date or `from` is after `to` (the route answers 400). Either end may be open.
|
|
* `start`/`end` are the local midnights of `from` and of the day after `to`,
|
|
* as UTC ISO instants (`end` exclusive), for `col >= start AND col < end`.
|
|
* @param {import("express").Request} req
|
|
* @returns {{from:string|null, to:string|null, start:string|null, end:string|null}|null|false}
|
|
*/
|
|
function parseRange(req) {
|
|
const q = req.query || {};
|
|
const from = q.from === undefined || q.from === "" ? null : q.from;
|
|
const to = q.to === undefined || q.to === "" ? null : q.to;
|
|
if (from === null && to === null) return null;
|
|
if ((from !== null && !isDate(from)) || (to !== null && !isDate(to))) return false;
|
|
if (from !== null && to !== null && from > to) return false;
|
|
const tz = parseInt(q.tz_offset, 10);
|
|
const off = Number.isFinite(tz) ? tz * 60_000 : 0;
|
|
const instant = (day, plus) =>
|
|
new Date(Date.parse(`${day}T00:00:00Z`) + plus * DAY_MS + off).toISOString();
|
|
return {
|
|
from,
|
|
to,
|
|
start: from === null ? null : instant(from, 0),
|
|
end: to === null ? null : instant(to, 1),
|
|
};
|
|
}
|
|
|
|
/** Whether a local `YYYY-MM-DD` falls in a `parseRange` result (null = all). */
|
|
function inRange(range, date) {
|
|
return !range || ((!range.from || date >= range.from) && (!range.to || date <= range.to));
|
|
}
|
|
|
|
/** The 400 every ranged route answers for a malformed `?from=`/`?to=`. */
|
|
const BAD_RANGE = {
|
|
error: { code: "INVALID_INPUT", message: "from/to must be YYYY-MM-DD dates, from <= to" },
|
|
};
|
|
|
|
/** The 400 every scoped route answers for a malformed `?tool=`. */
|
|
const BAD_TOOL = { error: { code: "INVALID_INPUT", message: "tool must be an AI Tools id" } };
|
|
|
|
module.exports = {
|
|
parseSources,
|
|
parseTool,
|
|
parseScope,
|
|
BAD_TOOL,
|
|
isDate,
|
|
parseRange,
|
|
inRange,
|
|
BAD_RANGE,
|
|
sourceColumnClause,
|
|
sessionIdInSourcesClause,
|
|
};
|