@sleep2agi/commhub-server 0.9.0-preview.2 → 0.9.0-preview.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import { z } from "zod/v4";
4
4
  import { registerTools } from "./tools.js";
5
5
  import { db, logTaskEvent, logAudit } from "./db.js";
6
6
  import { createSSEStream, pushEvent, getSSEStats } from "./push.js";
7
+ import { assertNodeActive } from "./lifecycle-guard.js";
7
8
  import { register, login, resolveToken, getUserNetworks, getUserAllNetworks, createNetwork, deleteNetwork, renameNetwork, changePassword, issueUserToken, listTokens, createToken, revokeToken, getNetworkMembers, getUserNetworkRole, addNetworkMember, updateMemberRole, removeNetworkMember, createInvite, joinByInvite, createNetworkTokenForNode, type AuthUser } from "./auth.js";
8
9
  import { abortRename, cleanupCommittedRenameSessions, commitRename, prepareRename, resolveCanonicalAlias } from "./rename.js";
9
10
  import { sharedSendDedup, buildDuplicateSendPayload } from "./send_dedup.js";
@@ -19,6 +20,7 @@ import {
19
20
  isPathInsideUploadsRoot,
20
21
  sanitizeExt,
21
22
  sharedUploadRateLimiter,
23
+ stripHostLocalPathsForCrossHostSafe,
22
24
  validateAttachments,
23
25
  validateIndexEntry,
24
26
  } from "./uploads.js";
@@ -73,7 +75,12 @@ console.error = (...args: any[]) => { pushLog("error", args); _origConsole.error
73
75
 
74
76
  function normalizeMetaJson(meta: unknown): string | null {
75
77
  if (!meta || typeof meta !== "object") return null;
76
- try { return JSON.stringify(meta); } catch { return null; }
78
+ // #222 cross-host safety — same sanitization as tools.ts so REST
79
+ // /api/task and MCP send_task produce identical meta_json shapes.
80
+ // Conditional: only strips `path` when `file_id` is also present
81
+ // (preserves single-host feishu fallback per team rule — assume-unit-before-threshold: cap is in bytes
82
+ // discipline of not breaking other call sites).
83
+ try { return JSON.stringify(stripHostLocalPathsForCrossHostSafe(meta)); } catch { return null; }
77
84
  }
78
85
 
79
86
  // ── Rate limiter (in-memory, per IP) ──
@@ -1621,6 +1628,18 @@ Bun.serve({
1621
1628
  return withCors(req, Response.json(payload, { status: 429 }));
1622
1629
  }
1623
1630
 
1631
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.2a REST site
1632
+ // 1/2 — paired with the 6 MCP sites guarded in tools.ts at PR1.1).
1633
+ // Dashboard's "Dispatch" button hits this endpoint, so without
1634
+ // the guard a stopping/stopped/deleting node still got tasks
1635
+ // routed through REST. Returns 409 with the same structured
1636
+ // payload the MCP handlers use.
1637
+ {
1638
+ const lc = assertNodeActive(targetAlias, taskNetId ?? null);
1639
+ if (!lc.ok) {
1640
+ return withCors(req, Response.json(lc, { status: 409 }));
1641
+ }
1642
+ }
1624
1643
  // Mirror send_task MCP: write inbox + tasks rows in a single
1625
1644
  // transaction so the dispatch is visible to dashboard's Tasks page
1626
1645
  // and the parent_task_id lineage chain. Previously this endpoint
@@ -1701,6 +1720,12 @@ Bun.serve({
1701
1720
  const targets = db.all<{ alias: string; node_id: string | null; network_id: string | null }>(sql, ...params);
1702
1721
  const ids: string[] = [];
1703
1722
  for (const t of targets) {
1723
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.2a REST site
1724
+ // 2/2). Broadcast skips non-active recipients silently per its
1725
+ // best-effort semantics — mirrors the MCP broadcast handler
1726
+ // in tools.ts (PR1.1 site 6/6).
1727
+ const lc = assertNodeActive(t.alias, t.network_id ?? null);
1728
+ if (!lc.ok) continue;
1704
1729
  const id = crypto.randomUUID();
1705
1730
  db.run(
1706
1731
  `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id)
@@ -1950,16 +1975,180 @@ Bun.serve({
1950
1975
  }
1951
1976
 
1952
1977
  // ── REST: nodes table (V2 Sprint 2) ──
1978
+ // Explicit column list — NOT `SELECT *`. Two reasons:
1979
+ // 1. `SELECT *` silently broadcasts any column added later to the
1980
+ // response (RFC-024 added config_revision/config_snapshot which
1981
+ // the dashboard's GET /api/nodes/:id/config endpoint owns;
1982
+ // RFC-028 will add more vault-flavored columns). Tests asserting
1983
+ // response shape break on every ALTER; integrations that key
1984
+ // off Object.keys() can pick up internals.
1985
+ // 2. The list endpoint and the per-node config snapshot endpoint
1986
+ // have different consumer contracts; this list should be the
1987
+ // stable, dashboard-facing fields only.
1988
+ // Add a new column to this list explicitly when a real client needs
1989
+ // it; do NOT switch back to SELECT *.
1990
+ // ── REST: list host_supervisor daemons (RFC-026 §9.2.2 / #338 PR2) ──
1991
+ // Mirror of the `list_host_supervisors` MCP tool for non-MCP callers.
1992
+ // Same SQL + role-extract + member-脱敏 logic; SEC-1 scoped via REST
1993
+ // auth pipeline (restScope). Returns {ok, daemons:[...], count}.
1994
+ if (url.pathname === "/api/host-supervisors") {
1995
+ // #380 — utok callers with exactly one accessible network get a
1996
+ // safe fallback so the create-node wizard doesn't have to bake
1997
+ // network_id into every request (it was hard-4xxing when the
1998
+ // dashboard omitted the query param — that's what "hub 400" was).
1999
+ // `singleNetworkId` returns:
2000
+ // - scope.networkId when it's set (ntok binding, or an
2001
+ // explicitly-requested network the user has verified access to)
2002
+ // - the sole member of scope.networkIds when the utok user
2003
+ // belongs to exactly one network (safe unambiguous fallback)
2004
+ // - null when the user belongs to 0 or 2+ networks (authz
2005
+ // boundary — refuse to guess which one, mirrors 通信龙 spec
2006
+ // "别 fallback 到错 network")
2007
+ // The 400 branch is retained for the ambiguous / no-access cases
2008
+ // and distinguishes them in the error message so the client can
2009
+ // recover (send network_id explicitly).
2010
+ const effectiveNetId = singleNetworkId(restScope);
2011
+ if (!effectiveNetId) {
2012
+ const memberships = restScope.networkIds?.length ?? 0;
2013
+ const error = memberships > 1
2014
+ ? "network_id_required_multi"
2015
+ : "missing_network_id";
2016
+ return withCors(req, Response.json({ ok: false, error, memberships }, { status: 400 }));
2017
+ }
2018
+ // Role for member-脱敏 (admin/owner = full host_telemetry, others = masked)
2019
+ let isPrivileged = false;
2020
+ if (restAuth?.userId) {
2021
+ const role = getUserNetworkRole(restAuth.userId, effectiveNetId);
2022
+ isPrivileged = role === "admin" || role === "owner";
2023
+ } else {
2024
+ // Network-token caller (no user) — treat as privileged within its network
2025
+ isPrivileged = true;
2026
+ }
2027
+
2028
+ // EXISTS subquery handles BOTH revoked_at SET and DELETEd token
2029
+ // rows (revokeToken DELETEs the row in production — PR2 v1
2030
+ // SHOULD-FIX per 通信龙 audit). EXISTS naturally dedupes daemons
2031
+ // with rotated tokens.
2032
+ const sqlRows = db.all<Record<string, any>>(`
2033
+ SELECT
2034
+ n.node_id, n.alias, n.hostname, n.network_id,
2035
+ n.runtimes_supported, n.allowed_secret_keys,
2036
+ n.created_at, n.updated_at,
2037
+ s.last_seen_at AS session_last_seen,
2038
+ s.cpu_cores AS session_cpu_cores,
2039
+ s.mem_total_gb AS session_mem_total_gb,
2040
+ s.ip AS session_ip,
2041
+ n.config_snapshot
2042
+ FROM nodes n
2043
+ LEFT JOIN sessions s ON s.alias = n.alias AND (s.network_id = n.network_id OR s.network_id IS NULL)
2044
+ WHERE n.network_id = ?1
2045
+ AND EXISTS (
2046
+ SELECT 1 FROM api_tokens t
2047
+ WHERE t.network_id = n.network_id
2048
+ AND t.name = 'node:' || n.alias
2049
+ AND t.revoked_at IS NULL
2050
+ )
2051
+ ORDER BY n.updated_at DESC
2052
+ `, effectiveNetId);
2053
+
2054
+ const nowMs = Date.now();
2055
+ const ONLINE_MS = 60_000;
2056
+ const daemons = sqlRows
2057
+ .map(r => {
2058
+ let snapRole: string | null = null;
2059
+ if (r.config_snapshot) {
2060
+ try {
2061
+ const parsed = typeof r.config_snapshot === "string" ? JSON.parse(r.config_snapshot) : r.config_snapshot;
2062
+ snapRole = typeof parsed?.role === "string" ? parsed.role : null;
2063
+ } catch { /* malformed */ }
2064
+ }
2065
+ return { row: r, role: snapRole };
2066
+ })
2067
+ .filter(({ role }) => role === "host_supervisor")
2068
+ .map(({ row: r }) => {
2069
+ let online = false;
2070
+ let lastSeenAt: string | null = null;
2071
+ if (r.session_last_seen) {
2072
+ lastSeenAt = r.session_last_seen;
2073
+ const t = Date.parse(r.session_last_seen);
2074
+ if (!isNaN(t)) online = (nowMs - t) <= ONLINE_MS;
2075
+ }
2076
+ let runtimes: string[] = [];
2077
+ let secrets: string[] = [];
2078
+ try {
2079
+ if (r.runtimes_supported) {
2080
+ const parsed = JSON.parse(r.runtimes_supported);
2081
+ runtimes = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
2082
+ }
2083
+ } catch {}
2084
+ try {
2085
+ if (r.allowed_secret_keys) {
2086
+ const parsed = JSON.parse(r.allowed_secret_keys);
2087
+ secrets = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
2088
+ }
2089
+ } catch {}
2090
+ const telemetry: Record<string, unknown> = {
2091
+ alert_level: online ? "green" : "gray",
2092
+ };
2093
+ if (isPrivileged) {
2094
+ telemetry.cpu_cores = r.session_cpu_cores ?? null;
2095
+ telemetry.mem_gb = r.session_mem_total_gb ?? null;
2096
+ telemetry.ip_internal = r.session_ip ?? null;
2097
+ }
2098
+ return {
2099
+ daemon_node_id: r.node_id,
2100
+ alias: r.alias,
2101
+ hostname: r.hostname,
2102
+ online,
2103
+ last_seen_at: lastSeenAt,
2104
+ runtimes_supported: runtimes,
2105
+ allowed_secret_keys: secrets,
2106
+ host_telemetry: telemetry,
2107
+ };
2108
+ });
2109
+ return withCors(req, Response.json({ ok: true, daemons, count: daemons.length }));
2110
+ }
2111
+
1953
2112
  if (url.pathname === "/api/nodes") {
1954
2113
  const nodeId = url.searchParams.get("node_id");
1955
2114
  const alias = url.searchParams.get("alias");
1956
- let sql = "SELECT * FROM nodes WHERE 1=1";
2115
+ // `config_snapshot` SELECTed ONLY to extract the daemon `role` field
2116
+ // for dashboard discovery — full snapshot is NOT broadcast (would
2117
+ // re-introduce the #312 SELECT * fragility). Mapping step pulls
2118
+ // `role` out then drops `config_snapshot` from the response row.
2119
+ // RFC-027 PR2 dashboard prereq: lifecycle_state is needed
2120
+ // client-side to drive the ⋮ menu (active → "停止/删除";
2121
+ // stopped → "重启/删除"). Hub schema gained the column at PR1
2122
+ // (#345) but /api/nodes never SELECTed it. Following #312
2123
+ // "explicit SELECT" discipline — extend the projection here,
2124
+ // do NOT switch to SELECT *.
2125
+ let sql = `SELECT node_id, node_name, alias, runtime, model,
2126
+ config_path, channels, server, hostname,
2127
+ network_id, created_at, updated_at,
2128
+ config_snapshot, lifecycle_state
2129
+ FROM nodes WHERE 1=1`;
1957
2130
  const params: any[] = [];
1958
2131
  sql = addNetworkScope(sql, params, restScope);
1959
2132
  if (nodeId) { sql += ` AND node_id = ?${params.length + 1}`; params.push(nodeId); }
1960
2133
  if (alias) { sql += ` AND alias = ?${params.length + 1}`; params.push(alias); }
1961
2134
  sql += " ORDER BY updated_at DESC";
1962
- const rows = db.all(sql, ...params);
2135
+ const rawRows = db.all<Record<string, any>>(sql, ...params);
2136
+ // Add a single new field `role: string | null` per row, extracted from
2137
+ // config_snapshot JSON. Daemon nodes that posted role='host_supervisor'
2138
+ // via report_status surface here; dashboard uses this for daemon
2139
+ // discovery (replacing the prior `node_daemon_` prefix heuristic).
2140
+ // RFC-026 P1 P2 §9 will supersede this REST proxy with the
2141
+ // `list_host_supervisors` MCP tool.
2142
+ const rows = rawRows.map(r => {
2143
+ let role: string | null = null;
2144
+ const snap = r.config_snapshot;
2145
+ if (snap) {
2146
+ try { role = (typeof snap === "string" ? JSON.parse(snap) : snap)?.role ?? null; }
2147
+ catch { /* malformed snapshot — leave role null */ }
2148
+ }
2149
+ const { config_snapshot, ...rest } = r;
2150
+ return { ...rest, role };
2151
+ });
1963
2152
  return withCors(req, Response.json({ ok: true, nodes: rows, count: rows.length }));
1964
2153
  }
1965
2154
 
@@ -2170,3 +2359,22 @@ console.log(`
2170
2359
  ║ Health: http://${HOST}:${PORT}/health ║
2171
2360
  ╚══════════════════════════════════════════════════╝
2172
2361
  `);
2362
+
2363
+ // RFC-028 P1 boot banner — vault key configuration status.
2364
+ // F2 invariant: hub MUST boot regardless of vault state. This is
2365
+ // banner-only (informational); errors are raised lazily at vault op
2366
+ // time. needsKeyToOp=true means the operator should set
2367
+ // ANET_HUB_SECRET_VAULT_KEY before vault/provider features will work.
2368
+ try {
2369
+ const { vaultStatusForBoot } = await import("./vault.js");
2370
+ const s = vaultStatusForBoot();
2371
+ if (s.needsKeyToOp) {
2372
+ console.warn("[rfc-028 vault] ⚠️ network_secrets/providers have data BUT ANET_HUB_SECRET_VAULT_KEY is unset — vault ops will throw vault_master_key_missing until you set the env. Generate one: `openssl rand -hex 32` (must match the key used at write time).");
2373
+ } else if (s.configured) {
2374
+ console.log(`[rfc-028 vault] master key configured (tables_have_data=${s.tablesHaveData})`);
2375
+ } else {
2376
+ console.log("[rfc-028 vault] master key not set + no vault rows — vault gating is lazy; boot OK. Set ANET_HUB_SECRET_VAULT_KEY when enabling provider/secret features.");
2377
+ }
2378
+ } catch (e: any) {
2379
+ console.warn(`[rfc-028 vault] boot banner skipped (${e?.message || e})`);
2380
+ }
@@ -0,0 +1,50 @@
1
+ // RFC-027 §2.3 race-free invariant — shared helper for the inbox-
2
+ // enqueue lifecycle guard.
3
+ //
4
+ // PR1.1 (#346) added an `assertNodeActive` helper inside the
5
+ // registerTools() closure and applied it at the 6 INSERT INTO inbox
6
+ // sites in server/src/tools.ts. PR1.1 review (通信龙 #346 ack) caught
7
+ // that the closure scope made the helper unreachable from REST
8
+ // handlers in server/src/index.ts — POST /api/task (:1631) and
9
+ // POST /api/broadcast (:1706) are dashboard's "Dispatch" entry
10
+ // points and bypassed the guard, leaving the §2.3 race open on the
11
+ // REST path.
12
+ //
13
+ // PR1.2a (#346 follow-up) extracts the helper to this module so both
14
+ // the MCP tools and the REST handlers can import the same code path,
15
+ // per team rule (grep every write site before adding a guard): any SQL-level
16
+ // guard's helper lives at module scope so every write site
17
+ // (MCP + REST + internal db.ts helpers) can use it.
18
+ //
19
+ // Behaviour:
20
+ // - no nodes row for the alias → ok:true (brand-new alias allowed;
21
+ // could be the first INSERT for a child about to register)
22
+ // - lifecycle_state = 'active' OR NULL (pre-RFC-027 row) → ok:true
23
+ // - anything else (stopping / stopped / stop_failed / deleting) →
24
+ // ok:false + structured `node_not_active` reply
25
+ //
26
+ // COALESCE on the WHERE keeps NULL-network inbox rows / legacy nodes
27
+ // rows correctly scoped (PR1 SF-5 lineage).
28
+
29
+ import { db } from "./db.js";
30
+
31
+ export type LifecycleGuardResult =
32
+ | { ok: true }
33
+ | { ok: false; error: "node_not_active"; lifecycle_state: string; alias: string };
34
+
35
+ export function assertNodeActive(
36
+ sessionAlias: string,
37
+ networkId: string | null,
38
+ ): LifecycleGuardResult {
39
+ if (!sessionAlias) return { ok: true };
40
+ const row = db.get<{ lifecycle_state: string | null }>(
41
+ networkId
42
+ ? `SELECT lifecycle_state FROM nodes WHERE alias = ?1 AND COALESCE(network_id, ?2) = ?2 LIMIT 1`
43
+ : `SELECT lifecycle_state FROM nodes WHERE alias = ?1 LIMIT 1`,
44
+ ...(networkId ? [sessionAlias, networkId] : [sessionAlias]),
45
+ );
46
+ if (!row) return { ok: true };
47
+ const st = row.lifecycle_state ?? "active";
48
+ if (st === "active") return { ok: true };
49
+ return { ok: false, error: "node_not_active", lifecycle_state: st, alias: sessionAlias };
50
+ }
@@ -0,0 +1,314 @@
1
+ import { afterAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { db, hashToken, generateId } from "./db.js";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { registerTools } from "./tools.js";
5
+
6
+ // RFC-026 §9.2 / #338 PR2 v2 — list_host_supervisors HANDLER tests.
7
+ //
8
+ // PR2 v1 used a mirror-SQL pattern (re-implemented the query in the test
9
+ // itself) → trivially passed but didn't exercise the handler. 通信龙 audit
10
+ // caught: that style misses the SEC-1 scope-derivation bug
11
+ // (`getNetworkId(clientNetId)` returns the unchecked client-supplied
12
+ // network_id for utok_ callers when enforceNetworkId is null, leaking
13
+ // cross-tenant daemons). This rewrite drives the registered MCP tool
14
+ // through registerTools() so the auth context is real.
15
+ //
16
+ // Covers:
17
+ // SEC-1.1 — cross-tenant utok_ caller with foreign network_id: DENIED
18
+ // SEC-1.2 — admin caller with own network_id: returns own daemons
19
+ // SEC-1.3 — caller with no network_id: returns daemons in all member networks
20
+ // masking — non-admin viewer: host_telemetry IP/cpu/mem stripped, alert_level still surfaces
21
+ // revoked — DELETEd token row (revokeToken path): daemon excluded
22
+ // revoked — revoked_at SET token: daemon excluded
23
+ // self-declare — runtimes_supported/allowed_secret_keys surface from columns
24
+ // pre-PR2 daemon — empty arrays on NULL columns (back-compat)
25
+
26
+ const NET_ALPHA = "net_lhs_alpha";
27
+ const NET_BETA = "net_lhs_beta";
28
+
29
+ interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
30
+ interface Reply { ok?: boolean; error?: string; daemons?: any[]; count?: number; }
31
+
32
+ function cleanup() {
33
+ for (const n of [NET_ALPHA, NET_BETA]) {
34
+ try { db.run("DELETE FROM nodes WHERE network_id = ?1", [n]); } catch {}
35
+ try { db.run("DELETE FROM sessions WHERE network_id = ?1", [n]); } catch {}
36
+ try { db.run("DELETE FROM api_tokens WHERE network_id = ?1", [n]); } catch {}
37
+ try { db.run("DELETE FROM network_members WHERE network_id = ?1", [n]); } catch {}
38
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [n]); } catch {}
39
+ }
40
+ try { db.run("DELETE FROM users WHERE user_id LIKE 'u_lhs_%'"); } catch {}
41
+ }
42
+
43
+ beforeEach(cleanup);
44
+ afterAll(cleanup);
45
+
46
+ function seedUser(user_id: string) {
47
+ db.run(
48
+ `INSERT INTO users (user_id, username, password_hash, role, created_at)
49
+ VALUES (?1, ?2, 'x', 'user', datetime('now'))`,
50
+ [user_id, user_id],
51
+ );
52
+ }
53
+ function seedNetwork(net_id: string, owner_id = "u_lhs_owner") {
54
+ db.run(
55
+ `INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at)
56
+ VALUES (?1, ?2, ?3, datetime('now'))`,
57
+ [net_id, net_id, owner_id],
58
+ );
59
+ }
60
+ function seedMembership(user_id: string, net_id: string, role: "owner" | "admin" | "member" | "viewer" = "member") {
61
+ db.run(
62
+ `INSERT INTO network_members (user_id, network_id, role, joined_at)
63
+ VALUES (?1, ?2, ?3, datetime('now'))`,
64
+ [user_id, net_id, role],
65
+ );
66
+ }
67
+ function seedDaemon(opts: {
68
+ network_id: string, alias: string, node_id?: string,
69
+ role?: string,
70
+ runtimes?: string[],
71
+ secrets?: string[],
72
+ sessionAgeMs?: number,
73
+ mintToken?: boolean,
74
+ tokenRevokedAt?: boolean,
75
+ tokenDeleted?: boolean,
76
+ }) {
77
+ const node_id = opts.node_id || `node_${opts.network_id}_${opts.alias}`;
78
+ const snapshot = JSON.stringify({
79
+ model: "claude-opus", flags: {}, role: opts.role ?? "host_supervisor",
80
+ runtimes_supported: opts.runtimes ?? ["claude-agent-sdk"],
81
+ allowed_secret_keys: opts.secrets ?? [],
82
+ });
83
+ db.run(
84
+ `INSERT OR REPLACE INTO nodes (
85
+ node_id, node_name, alias, network_id,
86
+ runtimes_supported, allowed_secret_keys,
87
+ config_snapshot, hostname,
88
+ created_at, updated_at
89
+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, datetime('now'), datetime('now'))`,
90
+ [node_id, opts.alias, opts.alias, opts.network_id,
91
+ JSON.stringify(opts.runtimes ?? ["claude-agent-sdk"]),
92
+ JSON.stringify(opts.secrets ?? []),
93
+ snapshot, `host-${opts.alias}`],
94
+ );
95
+ if (opts.sessionAgeMs !== undefined) {
96
+ const ts = new Date(Date.now() - opts.sessionAgeMs).toISOString().replace("T", " ").replace(/\..+/, "");
97
+ db.run(
98
+ `INSERT OR REPLACE INTO sessions (resume_id, alias, network_id, last_seen_at, status, cpu_cores, mem_total_gb, ip)
99
+ VALUES (?1, ?2, ?3, ?4, 'idle', 8, 16, '10.0.0.5')`,
100
+ [`s_${node_id}`, opts.alias, opts.network_id, ts],
101
+ );
102
+ }
103
+ if (opts.mintToken !== false && !opts.tokenDeleted) {
104
+ db.run(
105
+ `INSERT OR REPLACE INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
106
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, ?6)`,
107
+ [`tok_${node_id}`, `u_seed_${node_id}`, opts.network_id, `node:${opts.alias}`,
108
+ `hash_${node_id}`,
109
+ opts.tokenRevokedAt ? new Date().toISOString().replace("T", " ").replace(/\..+/, "") : null],
110
+ );
111
+ }
112
+ return node_id;
113
+ }
114
+
115
+ /** Build a server with registerTools wired to a specific enforceUserId. */
116
+ function buildToolHandler(enforceUserId: string | null): ToolHandler {
117
+ const server = new McpServer({ name: "test", version: "0" }) as any;
118
+ const tools: Record<string, ToolHandler> = {};
119
+ // Capture the registered tool function. The MCP SDK's server.tool stores
120
+ // the handler internally; we intercept by overriding before registerTools.
121
+ const origTool = server.tool.bind(server);
122
+ server.tool = (name: string, _desc: string, _schema: any, handler: ToolHandler) => {
123
+ tools[name] = handler;
124
+ return origTool(name, _desc, _schema, handler);
125
+ };
126
+ // Some tools use registerTool; intercept that too
127
+ const origRegisterTool = server.registerTool?.bind(server);
128
+ if (origRegisterTool) {
129
+ server.registerTool = (name: string, _cfg: any, handler: ToolHandler) => {
130
+ tools[name] = handler;
131
+ return origRegisterTool(name, _cfg, handler);
132
+ };
133
+ }
134
+ registerTools(
135
+ server,
136
+ /* clientIP */ undefined,
137
+ /* enforceNetworkId */ null,
138
+ /* enforceUserId */ enforceUserId,
139
+ /* callerAlias */ null,
140
+ /* callerTokenIsNetwork */ false,
141
+ /* callerTokenId */ null,
142
+ );
143
+ const h = tools["list_host_supervisors"];
144
+ if (!h) throw new Error("list_host_supervisors tool not registered");
145
+ return h;
146
+ }
147
+
148
+ async function callList(handler: ToolHandler, args: any = {}): Promise<Reply> {
149
+ const r = await handler(args);
150
+ return JSON.parse(r.content[0].text) as Reply;
151
+ }
152
+
153
+ describe("list_host_supervisors HANDLER tests (RFC-026 §9.2, PR2 v2)", () => {
154
+ test("SEC-1.1: cross-tenant utok_ caller with foreign network_id → DENIED", async () => {
155
+ const userA = "u_lhs_alice"; // belongs to NET_ALPHA only
156
+ seedUser(userA);
157
+ seedNetwork(NET_ALPHA);
158
+ seedNetwork(NET_BETA);
159
+ seedMembership(userA, NET_ALPHA, "admin");
160
+ seedDaemon({ network_id: NET_BETA, alias: "secret-beta-daemon" });
161
+
162
+ const handler = buildToolHandler(userA);
163
+ const reply = await callList(handler, { network_id: NET_BETA });
164
+ // PR2 v1 BUG: this returned ok:true with secret-beta-daemon in the list.
165
+ expect(reply.ok).toBe(false);
166
+ expect(reply.error).toMatch(/access denied|not a member/i);
167
+ // Belt: hostname not in error payload
168
+ expect(JSON.stringify(reply)).not.toContain("secret-beta-daemon");
169
+ expect(JSON.stringify(reply)).not.toContain("host-secret-beta-daemon");
170
+ });
171
+
172
+ test("SEC-1.2: admin caller with own network_id returns own daemons", async () => {
173
+ const userA = "u_lhs_alice";
174
+ seedUser(userA);
175
+ seedNetwork(NET_ALPHA);
176
+ seedMembership(userA, NET_ALPHA, "admin");
177
+ seedDaemon({ network_id: NET_ALPHA, alias: "alpha-daemon-1" });
178
+ seedDaemon({ network_id: NET_ALPHA, alias: "alpha-daemon-2" });
179
+
180
+ const handler = buildToolHandler(userA);
181
+ const reply = await callList(handler, { network_id: NET_ALPHA });
182
+ expect(reply.ok).toBe(true);
183
+ const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
184
+ expect(aliases).toEqual(["alpha-daemon-1", "alpha-daemon-2"]);
185
+ });
186
+
187
+ test("SEC-1.3: caller without network_id arg → returns daemons across member networks only", async () => {
188
+ const userA = "u_lhs_alice"; // member of NET_ALPHA only
189
+ seedUser(userA);
190
+ seedNetwork(NET_ALPHA);
191
+ seedNetwork(NET_BETA);
192
+ seedMembership(userA, NET_ALPHA, "member");
193
+ seedDaemon({ network_id: NET_ALPHA, alias: "ok-daemon" });
194
+ seedDaemon({ network_id: NET_BETA, alias: "forbidden-daemon" });
195
+
196
+ const handler = buildToolHandler(userA);
197
+ const reply = await callList(handler);
198
+ expect(reply.ok).toBe(true);
199
+ const aliases = (reply.daemons ?? []).map(d => d.alias);
200
+ expect(aliases).toContain("ok-daemon");
201
+ expect(aliases).not.toContain("forbidden-daemon");
202
+ });
203
+
204
+ test("masking: member caller gets host_telemetry without IP/cpu/mem; admin gets full", async () => {
205
+ const userMember = "u_lhs_bob_member";
206
+ const userAdmin = "u_lhs_carol_admin";
207
+ seedUser(userMember);
208
+ seedUser(userAdmin);
209
+ seedNetwork(NET_ALPHA);
210
+ seedMembership(userMember, NET_ALPHA, "member");
211
+ seedMembership(userAdmin, NET_ALPHA, "admin");
212
+ seedDaemon({ network_id: NET_ALPHA, alias: "telemetry-daemon", sessionAgeMs: 5_000 });
213
+
214
+ const memberHandler = buildToolHandler(userMember);
215
+ const memberReply = await callList(memberHandler, { network_id: NET_ALPHA });
216
+ expect(memberReply.daemons?.[0].host_telemetry.alert_level).toBeDefined();
217
+ expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("cpu_cores");
218
+ expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("mem_gb");
219
+ expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("ip_internal");
220
+
221
+ const adminHandler = buildToolHandler(userAdmin);
222
+ const adminReply = await callList(adminHandler, { network_id: NET_ALPHA });
223
+ expect(adminReply.daemons?.[0].host_telemetry.cpu_cores).toBe(8);
224
+ expect(adminReply.daemons?.[0].host_telemetry.mem_gb).toBe(16);
225
+ expect(adminReply.daemons?.[0].host_telemetry.ip_internal).toBe("10.0.0.5");
226
+ });
227
+
228
+ test("revoked: DELETEd token row (revokeToken path) excludes daemon", async () => {
229
+ const userA = "u_lhs_alice";
230
+ seedUser(userA);
231
+ seedNetwork(NET_ALPHA);
232
+ seedMembership(userA, NET_ALPHA, "admin");
233
+ seedDaemon({ network_id: NET_ALPHA, alias: "alive-daemon" });
234
+ seedDaemon({ network_id: NET_ALPHA, alias: "deleted-token-daemon", tokenDeleted: true });
235
+
236
+ const handler = buildToolHandler(userA);
237
+ const reply = await callList(handler, { network_id: NET_ALPHA });
238
+ const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
239
+ expect(aliases).toContain("alive-daemon");
240
+ expect(aliases).not.toContain("deleted-token-daemon");
241
+ });
242
+
243
+ test("revoked: token with revoked_at SET also excludes daemon", async () => {
244
+ const userA = "u_lhs_alice";
245
+ seedUser(userA);
246
+ seedNetwork(NET_ALPHA);
247
+ seedMembership(userA, NET_ALPHA, "admin");
248
+ seedDaemon({ network_id: NET_ALPHA, alias: "alive-daemon" });
249
+ seedDaemon({ network_id: NET_ALPHA, alias: "revoked-at-daemon", tokenRevokedAt: true });
250
+
251
+ const handler = buildToolHandler(userA);
252
+ const reply = await callList(handler, { network_id: NET_ALPHA });
253
+ const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
254
+ expect(aliases).toContain("alive-daemon");
255
+ expect(aliases).not.toContain("revoked-at-daemon");
256
+ });
257
+
258
+ test("role filter: regular member nodes (role=member) excluded after extraction", async () => {
259
+ const userA = "u_lhs_alice";
260
+ seedUser(userA);
261
+ seedNetwork(NET_ALPHA);
262
+ seedMembership(userA, NET_ALPHA, "admin");
263
+ seedDaemon({ network_id: NET_ALPHA, alias: "real-daemon", role: "host_supervisor" });
264
+ seedDaemon({ network_id: NET_ALPHA, alias: "regular-node", role: "member" });
265
+
266
+ const handler = buildToolHandler(userA);
267
+ const reply = await callList(handler, { network_id: NET_ALPHA });
268
+ const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
269
+ expect(aliases).toEqual(["real-daemon"]);
270
+ });
271
+
272
+ test("self-declare: runtimes_supported + allowed_secret_keys surface from columns", async () => {
273
+ const userA = "u_lhs_alice";
274
+ seedUser(userA);
275
+ seedNetwork(NET_ALPHA);
276
+ seedMembership(userA, NET_ALPHA, "admin");
277
+ seedDaemon({
278
+ network_id: NET_ALPHA, alias: "rich-daemon",
279
+ runtimes: ["claude-agent-sdk", "codex-sdk", "grok-build-acp"],
280
+ secrets: ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
281
+ });
282
+
283
+ const handler = buildToolHandler(userA);
284
+ const reply = await callList(handler, { network_id: NET_ALPHA });
285
+ const d = reply.daemons?.[0];
286
+ expect(d.runtimes_supported).toEqual(["claude-agent-sdk", "codex-sdk", "grok-build-acp"]);
287
+ expect(d.allowed_secret_keys).toEqual(["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]);
288
+ });
289
+
290
+ test("pre-PR2 daemon (NULL columns) extracts to empty arrays back-compat", async () => {
291
+ const userA = "u_lhs_alice";
292
+ seedUser(userA);
293
+ seedNetwork(NET_ALPHA);
294
+ seedMembership(userA, NET_ALPHA, "admin");
295
+ db.run(
296
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, runtimes_supported, allowed_secret_keys, created_at, updated_at)
297
+ VALUES (?1, 'legacy', 'legacy', ?2, ?3, NULL, NULL, datetime('now'), datetime('now'))`,
298
+ ["node_legacy_alpha", NET_ALPHA, JSON.stringify({ role: "host_supervisor" })],
299
+ );
300
+ // Seed active token so the EXISTS guard lets it through
301
+ db.run(
302
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash)
303
+ VALUES ('tok_legacy', 'u_seed_legacy', ?1, 'network', 'node:legacy', 'hash_legacy')`,
304
+ [NET_ALPHA],
305
+ );
306
+
307
+ const handler = buildToolHandler(userA);
308
+ const reply = await callList(handler, { network_id: NET_ALPHA });
309
+ const d = reply.daemons?.find(d => d.alias === "legacy");
310
+ expect(d).toBeTruthy();
311
+ expect(d.runtimes_supported).toEqual([]);
312
+ expect(d.allowed_secret_keys).toEqual([]);
313
+ });
314
+ });