@sleep2agi/commhub-server 0.9.0-preview.280 → 0.9.0-preview.281
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/anet-variant-real-daemon-http.test.ts +3 -2
- package/src/build-commit-report-http.test.ts +3 -2
- package/src/health-redaction.test.ts +8 -4
- package/src/launched-by-cli-report-http.test.ts +155 -0
- package/src/node-inbox-allowlist-http.test.ts +320 -0
- package/src/node-lifecycle-read.ts +1 -1
- package/src/node-permissions.ts +133 -2
- package/src/requirements-comment-http.test.ts +1 -1
- package/src/requirements-status-participants-http.test.ts +3 -3
- package/src/scheduled-tasks.ts +19 -3
- package/src/server.ts +76 -6
- package/src/session-project-attach-migration.test.ts +2 -1
- package/src/session-project-attach-native.test.ts +3 -1
- package/src/session-project-create-http.test.ts +3 -2
- package/src/session-project-create-native.test.ts +3 -1
- package/src/session-source-delivery.ts +5 -0
- package/src/session-source-directory-http.test.ts +5 -1
- package/src/session-source-evidence.test.ts +11 -4
- package/src/session-source-transport.ts +7 -1
- package/src/test-work-root.ts +18 -0
- package/src/tools.ts +43 -17
package/build-info.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
3
|
+
"version": "0.9.0-preview.281",
|
|
4
4
|
"description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
// Isolated real Hub + real agent-node CLI startup probe, no direct handler calls.
|
|
2
2
|
import { expect, test } from "bun:test";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
|
-
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { register, createNetworkTokenForNode } from "./auth.js";
|
|
8
8
|
import { db } from "./db.js";
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
// Needs the TEST-ONLY toolchain (/tool/bun, /out/cli.js) baked into the variant test image.
|
|
11
|
+
test.skipIf(!existsSync("/tool/bun") || !existsSync("/out/cli.js"))("real daemon reaches owned TEST-ONLY runtime readiness", async () => {
|
|
11
12
|
const root = mkdtempSync(join(tmpdir(), "anet-4099-daemon-"));
|
|
12
13
|
const stamp = Date.now(), alias = `variant-daemon-${stamp}`, nodeId = `node_variant_${stamp}`;
|
|
13
14
|
const user = register(`variant_owner_${stamp}`, "Fixture4099Only!x");
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// ③ 读路径把它投影出来(否则界面上看不见)
|
|
8
8
|
// 少任何一处,现场表现都是「节点明明发了、hub 上没有」,与 daemon 侧 bug 一模一样。
|
|
9
9
|
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
10
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
10
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
11
11
|
import { tmpdir } from "node:os";
|
|
12
12
|
import { join } from "node:path";
|
|
13
13
|
import { register, createNetworkTokenForNode } from "./auth.js";
|
|
@@ -156,7 +156,8 @@ test("variant-capable model update persists private ack policy across lost capab
|
|
|
156
156
|
expect((await rpc("ack_config_update", { update_id: queued.update_id, status: "rejected", error: "test_complete" })).ok).toBe(true);
|
|
157
157
|
});
|
|
158
158
|
|
|
159
|
-
|
|
159
|
+
// Needs the TEST-ONLY OpenCode build at /tool/opencode (only in the V2 test image).
|
|
160
|
+
test.skipIf(!existsSync("/tool/opencode"))("TEST-ONLY real Hub HTTP and owned runtime variant via explicit node dispatch", async () => {
|
|
160
161
|
const { openVettedOpenCodeCopresence } = await import("../../agent-node/src/runtime/opencode-copresence/runtime.js");
|
|
161
162
|
const { OPENCODE_V2_BACKEND } = await import("../../agent-node/src/runtime/opencode-backend.js");
|
|
162
163
|
const { applyVariantConfig } = await import("../../agent-node/src/runtime/opencode-copresence/variant-config-apply.js");
|
|
@@ -1274,10 +1274,14 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
|
|
|
1274
1274
|
expect(Number.isInteger(body.alert_baselines.aliases)).toBe(true);
|
|
1275
1275
|
}
|
|
1276
1276
|
// clk_tck_assumed_reason:一个必须能解释「为什么用假设值」的字符串(空串是合法的:读到了真实值)
|
|
1277
|
-
|
|
1278
|
-
// 它与 clk_tck_source 配对:source=assumed
|
|
1279
|
-
if (body.clk_tck_source === "assumed")
|
|
1280
|
-
|
|
1277
|
+
// d5869d53 起「读到了真实值」报 null(此前是空串);两者都表示「没有退回 assumed」。
|
|
1278
|
+
// 它与 clk_tck_source 配对:source=assumed 时必须是非空理由,否则必须是 null 或空串。
|
|
1279
|
+
if (body.clk_tck_source === "assumed") {
|
|
1280
|
+
expect(typeof body.clk_tck_assumed_reason).toBe("string");
|
|
1281
|
+
expect(body.clk_tck_assumed_reason.length).toBeGreaterThan(0);
|
|
1282
|
+
} else {
|
|
1283
|
+
expect([null, ""]).toContain(body.clk_tck_assumed_reason);
|
|
1284
|
+
}
|
|
1281
1285
|
});
|
|
1282
1286
|
|
|
1283
1287
|
test("every /health field is read by at least one test (unread = unverified)", async () => {
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// 2026-11-10 —— 「起这份 agent-node 的 anet CLI 版本」必须真的走到 `/api/nodes`。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不是「加一列就完了」:Hub 的 report_status schema 对**不认识的键是静默丢弃**的
|
|
4
|
+
// (tools.ts 里那段 #1545 注释写得很清楚)。这条链路必须三处同时成立:
|
|
5
|
+
// ① schema 里有这个键(否则 zod 丢掉)
|
|
6
|
+
// ② 写路径把它落库(JSON.stringify 会连 `undefined` 一起吞掉)
|
|
7
|
+
// ③ 读路径把它投影出来(否则界面上看不见)
|
|
8
|
+
// 少任何一处,现场表现都是「节点明明发了、hub 上什么都没有」—— 本仓库已经吃过两次
|
|
9
|
+
// (#3294 的 build_commit、#2293 的 opencode_catalog)。
|
|
10
|
+
//
|
|
11
|
+
// 所以这里走**真** HTTP:真 node 令牌 + 真 MCP `tools/call report_status` + 真 `GET /api/nodes`,
|
|
12
|
+
// 不做镜像 handler(镜像会与真实 handler 各自漂移)。
|
|
13
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
14
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
15
|
+
import { tmpdir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { createNetworkTokenForNode, register } from "./auth.js";
|
|
18
|
+
import { db } from "./db.js";
|
|
19
|
+
|
|
20
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-launched-by-"));
|
|
21
|
+
process.env.COMMHUB_DB ||= join(DIR, "commhub.db");
|
|
22
|
+
|
|
23
|
+
const stamp = `${process.pid}_${Date.now()}`;
|
|
24
|
+
const NET_ALIAS = `launchedby-${stamp}`;
|
|
25
|
+
let hub: any;
|
|
26
|
+
let base = "";
|
|
27
|
+
let adminToken = "";
|
|
28
|
+
let nodeToken = "";
|
|
29
|
+
let networkId = "";
|
|
30
|
+
let nodeId = "";
|
|
31
|
+
|
|
32
|
+
/** CLI 侧真实会上报的版本形态(npm 预发布版)。 */
|
|
33
|
+
const CLI_VERSION = "2.3.0-preview.226";
|
|
34
|
+
|
|
35
|
+
async function send(token: string, method: string, path: string, body?: unknown) {
|
|
36
|
+
const r = await fetch(`${base}${path}`, {
|
|
37
|
+
method,
|
|
38
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
39
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
40
|
+
});
|
|
41
|
+
const text = await r.text();
|
|
42
|
+
let json: any = null;
|
|
43
|
+
try { json = text ? JSON.parse(text) : null; } catch { /* MCP may answer as SSE */ }
|
|
44
|
+
return { status: r.status, body: json, text };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 真 MCP `tools/call report_status`,与 agent-node 心跳同一条入参路径。 */
|
|
48
|
+
async function reportStatus(snapshot: Record<string, unknown>) {
|
|
49
|
+
const r = await fetch(`${base}/mcp`, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
headers: {
|
|
52
|
+
Authorization: `Bearer ${nodeToken}`,
|
|
53
|
+
"Content-Type": "application/json",
|
|
54
|
+
Accept: "application/json, text/event-stream",
|
|
55
|
+
},
|
|
56
|
+
body: JSON.stringify({
|
|
57
|
+
jsonrpc: "2.0", id: 1, method: "tools/call",
|
|
58
|
+
params: {
|
|
59
|
+
name: "report_status",
|
|
60
|
+
arguments: {
|
|
61
|
+
resume_id: `r_launchedby_${stamp}`, alias: NET_ALIAS, status: "idle", node_id: nodeId,
|
|
62
|
+
runtime: "opencode-sdk",
|
|
63
|
+
config_snapshot: { model: "deepseek/deepseek-flash", ...snapshot },
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
}),
|
|
67
|
+
});
|
|
68
|
+
await r.text();
|
|
69
|
+
return r.status;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function nodeRow() {
|
|
73
|
+
const r = await send(adminToken, "GET", `/api/nodes?network_id=${networkId}`);
|
|
74
|
+
expect(r.status).toBe(200);
|
|
75
|
+
return ((r.body?.nodes ?? []) as Array<Record<string, unknown>>).find(n => n.node_id === nodeId)!;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function storedSnapshot(): Record<string, unknown> {
|
|
79
|
+
const stored = db.get<{ config_snapshot: string }>(
|
|
80
|
+
"SELECT config_snapshot FROM nodes WHERE node_id = ?1", nodeId,
|
|
81
|
+
)!;
|
|
82
|
+
return JSON.parse(stored.config_snapshot);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
beforeAll(async () => {
|
|
86
|
+
const admin = register(`launchedby_admin_${stamp}`, "LaunchedByAdmin123!", undefined, "LaunchedBy Admin");
|
|
87
|
+
expect(admin.ok).toBe(true);
|
|
88
|
+
adminToken = admin.token!;
|
|
89
|
+
networkId = admin.network_id!;
|
|
90
|
+
const ownerId = admin.user!.user_id;
|
|
91
|
+
nodeId = `n_launchedby_${stamp}`;
|
|
92
|
+
const minted = createNetworkTokenForNode(ownerId, networkId, NET_ALIAS, nodeId);
|
|
93
|
+
expect(minted.ok).toBe(true);
|
|
94
|
+
nodeToken = minted.token!;
|
|
95
|
+
const mod: any = await import("./server.js");
|
|
96
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
97
|
+
base = `http://127.0.0.1:${hub.port}`;
|
|
98
|
+
}, 30_000);
|
|
99
|
+
|
|
100
|
+
afterAll(() => {
|
|
101
|
+
try { hub?.stop?.(true); } catch { /* already down */ }
|
|
102
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch { /* best effort */ }
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe("launched_by_cli_version 从真上报走到 GET /api/nodes", () => {
|
|
106
|
+
test("schema 不吞这个键:落库 + /api/nodes 投影都看得见", async () => {
|
|
107
|
+
expect(await reportStatus({ launched_by_cli_version: CLI_VERSION })).toBe(200);
|
|
108
|
+
|
|
109
|
+
// ② 写路径
|
|
110
|
+
expect(storedSnapshot().launched_by_cli_version).toBe(CLI_VERSION);
|
|
111
|
+
|
|
112
|
+
// ③ 读路径
|
|
113
|
+
const row = await nodeRow();
|
|
114
|
+
expect(row.launched_by_cli_version).toBe(CLI_VERSION);
|
|
115
|
+
// 整个快照仍然不外泄(这一格只是快照里的一个标量)。
|
|
116
|
+
expect(row).not.toHaveProperty("config_snapshot");
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("没有这一格时投影是 null —— 不是 undefined 缺席,也不回退成占位版本", async () => {
|
|
120
|
+
expect(await reportStatus({})).toBe(200);
|
|
121
|
+
expect(storedSnapshot()).not.toHaveProperty("launched_by_cli_version");
|
|
122
|
+
const row = await nodeRow();
|
|
123
|
+
expect(row.launched_by_cli_version).toBeNull();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("形状不对(超过 64 字符)只丢这一格,整份心跳照收", async () => {
|
|
127
|
+
const tooLong = `1.0.0${"0".repeat(60)}`;
|
|
128
|
+
expect(tooLong.length).toBeGreaterThan(64);
|
|
129
|
+
expect(await reportStatus({ launched_by_cli_version: tooLong })).toBe(200);
|
|
130
|
+
// `.catch(undefined)` ⇒ 落库时被 JSON.stringify 吞掉(不是存一个半截值)
|
|
131
|
+
expect(storedSnapshot()).not.toHaveProperty("launched_by_cli_version");
|
|
132
|
+
expect((await nodeRow()).launched_by_cli_version).toBeNull();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("类型不对(对象/数字)同样只丢这一格", async () => {
|
|
136
|
+
expect(await reportStatus({ launched_by_cli_version: { v: CLI_VERSION } })).toBe(200);
|
|
137
|
+
expect((await nodeRow()).launched_by_cli_version).toBeNull();
|
|
138
|
+
expect(await reportStatus({ launched_by_cli_version: 42 })).toBe(200);
|
|
139
|
+
expect((await nodeRow()).launched_by_cli_version).toBeNull();
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
describe("per-node config 端点:刻意不加这一格(说明理由,不是忘了)", () => {
|
|
144
|
+
// `GET /api/nodes/:id/config` 的白名单只装**可编辑/可门控**的配置项
|
|
145
|
+
// (model / modelVariant / flags / agent / *_config_capable …),
|
|
146
|
+
// 溯源类只读标量(build_commit、opencode_catalog、role)一律不出现在那里。
|
|
147
|
+
// launched_by_cli_version 属于后者 ⇒ 只走 /api/nodes,与邻居保持一致。
|
|
148
|
+
test("该端点仍然只回配置项,不带这一格", async () => {
|
|
149
|
+
expect(await reportStatus({ launched_by_cli_version: CLI_VERSION })).toBe(200);
|
|
150
|
+
const r = await send(adminToken, "GET", `/api/nodes/${nodeId}/config`);
|
|
151
|
+
expect(r.status).toBe(200);
|
|
152
|
+
expect(r.body).not.toHaveProperty("launched_by_cli_version");
|
|
153
|
+
expect(r.body).toHaveProperty("model");
|
|
154
|
+
});
|
|
155
|
+
});
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// 收件白名单(接收侧)—— 节点的主人限定「谁能给它派活 / 发消息」。全部经真实 HTTP 入口(bootServer + REST / /mcp)。
|
|
2
|
+
//
|
|
3
|
+
// 钉住:
|
|
4
|
+
// 1. PUT /api/nodes/:id/inbox-allowlist 与 peer-allowlist 同形:{ senders } / 200 回 { ok, node_id, senders } /
|
|
5
|
+
// [] 拒收 / 非数组 400 / 超 200 条 400 / 普通成员 403 且行没变 / 节点令牌 403 / 不存在 404 / null 清空 / 审计一行。
|
|
6
|
+
// 2. GET /api/nodes 读回 inbox_allowlist;/health 的 capabilities 带 node_inbox_allowlist。
|
|
7
|
+
// 3. 节点发件人按 alias / node_id 匹配;不在名单 ⇒ node_permission_denied + sender_not_allowed + hint,
|
|
8
|
+
// 覆盖 MCP send_task / send_message / retry_task / reassign_task 与 REST POST /api/task;开关 off 也照拒(显式原因)。
|
|
9
|
+
// 4. 人类发件人按 user:<username> / user:<user_id> / user:* 匹配;节点主人、网络 owner/admin 隐式放行,!strict 关掉隐式放行。
|
|
10
|
+
// 5. 发给自己永远放行(含 !strict)。6. 广播跳过不收的收件人并在 inbox_skipped 里报告(没人被跳过时没有这个键),不让整条广播失败。
|
|
11
|
+
//
|
|
12
|
+
// 跑法:COMMHUB_DB=/tmp/x.db bun test server/src/node-inbox-allowlist-http.test.ts
|
|
13
|
+
import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
|
|
14
|
+
import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
|
|
15
|
+
import { db } from "./db.js";
|
|
16
|
+
import { inboxAllows } from "./node-permissions.js";
|
|
17
|
+
|
|
18
|
+
const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
|
|
19
|
+
if (!activeDbPath) throw new Error("node-inbox-allowlist requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
|
|
20
|
+
|
|
21
|
+
const stamp = Date.now();
|
|
22
|
+
const PW = "InboxAllow123!";
|
|
23
|
+
let server: any, base = "", net = "";
|
|
24
|
+
const user: Record<string, { id: string; name: string; token: string }> = {};
|
|
25
|
+
const node: Record<string, { id: string; alias: string; token: string }> = {};
|
|
26
|
+
|
|
27
|
+
async function call(token: string, method: string, path: string, body?: unknown) {
|
|
28
|
+
const r = await fetch(`${base}${path}`, {
|
|
29
|
+
method, headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
30
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
31
|
+
});
|
|
32
|
+
const text = await r.text();
|
|
33
|
+
let json: any = null; try { json = JSON.parse(text); } catch {}
|
|
34
|
+
return { status: r.status, body: json, text };
|
|
35
|
+
}
|
|
36
|
+
async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
|
|
37
|
+
const r = await fetch(`${base}/mcp`, {
|
|
38
|
+
method: "POST",
|
|
39
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
40
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
|
|
41
|
+
});
|
|
42
|
+
const text = await r.text();
|
|
43
|
+
const data = text.split("\n").find((l) => l.startsWith("data: "));
|
|
44
|
+
const msg = JSON.parse(data ? data.slice(6) : text);
|
|
45
|
+
const inner = msg.result?.content?.[0]?.text;
|
|
46
|
+
try { return JSON.parse(inner); } catch { return { raw: inner ?? msg }; }
|
|
47
|
+
}
|
|
48
|
+
const setInbox = (list: string[] | null) =>
|
|
49
|
+
db.run("UPDATE nodes SET inbox_allowlist = ?1 WHERE node_id = ?2", [list ? JSON.stringify(list) : null, node.tgt.id]);
|
|
50
|
+
const storedInbox = () => db.get<{ v: string | null }>("SELECT inbox_allowlist AS v FROM nodes WHERE node_id = ?1", node.tgt.id)!.v;
|
|
51
|
+
const inboxRowsFor = (alias: string) => Number(db.get<{ n: number | string }>(
|
|
52
|
+
"SELECT COUNT(*) AS n FROM inbox WHERE session_name = ?1 AND network_id = ?2", alias, net)!.n);
|
|
53
|
+
const expectSenderDenied = (body: any, sender: string) => {
|
|
54
|
+
expect(body.ok).toBe(false);
|
|
55
|
+
expect(body.error).toBe("node_permission_denied");
|
|
56
|
+
expect(body.reason).toBe("sender_not_allowed");
|
|
57
|
+
expect(typeof body.hint).toBe("string");
|
|
58
|
+
expect(body.hint).toContain("inbox allowlist");
|
|
59
|
+
expect(body.target).toBe(node.tgt.alias);
|
|
60
|
+
expect(body.sender).toBe(sender);
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
beforeAll(async () => {
|
|
64
|
+
const boss = register(`ia_boss_${stamp}`, PW);
|
|
65
|
+
net = boss.network_id!;
|
|
66
|
+
user.boss = { id: boss.user!.user_id, name: `ia_boss_${stamp}`, token: boss.token! };
|
|
67
|
+
for (const [k, role] of [["own", "member"], ["adm", "admin"], ["mem", "member"], ["out", null]] as const) {
|
|
68
|
+
const name = `ia_${k}_${stamp}`;
|
|
69
|
+
const u = register(name, PW);
|
|
70
|
+
user[k] = { id: u.user!.user_id, name, token: u.token! };
|
|
71
|
+
if (role) expect(addNetworkMember(net, user[k].id, role, user.boss.id, { agentAccess: "all" }).ok).toBe(true);
|
|
72
|
+
}
|
|
73
|
+
// tgt 的主人是普通成员 own(不是网络 owner),这样「节点主人放行」与「网络 owner 放行」能分开测。
|
|
74
|
+
for (const [key, owner] of [["tgt", "own"], ["a", "boss"], ["b", "boss"], ["c", "boss"]] as const) {
|
|
75
|
+
const alias = `ia-${key}-${stamp}`, id = `n_ia_${key}_${stamp}`;
|
|
76
|
+
const t = createNetworkTokenForNode(user[owner].id, net, alias, id);
|
|
77
|
+
expect(t.ok).toBe(true);
|
|
78
|
+
node[key] = { id, alias, token: t.token! };
|
|
79
|
+
db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id) VALUES (?1, ?2, 'idle', ?3, ?4)", [`r_${id}`, alias, id, net]);
|
|
80
|
+
}
|
|
81
|
+
const mod: any = await import("./server.js");
|
|
82
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
83
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
84
|
+
}, 60_000);
|
|
85
|
+
afterEach(() => { delete process.env.COMMHUB_NODE_PERMISSIONS; setInbox(null); });
|
|
86
|
+
afterAll(() => { server?.stop?.(true); });
|
|
87
|
+
|
|
88
|
+
describe("PUT /api/nodes/:id/inbox-allowlist —— 与 peer-allowlist 同形", () => {
|
|
89
|
+
const put = (token: string, body: unknown, nodeId = node.tgt.id) => call(token, "PUT", `/api/nodes/${nodeId}/inbox-allowlist`, body);
|
|
90
|
+
|
|
91
|
+
test("节点主人设 → 200 { ok, node_id, senders },GET 读回,审计一行 {from,to}", async () => {
|
|
92
|
+
const r = await put(user.own.token, { senders: [node.a.alias, " user:" + user.mem.name + " "] });
|
|
93
|
+
expect(r.status).toBe(200);
|
|
94
|
+
expect(r.body).toEqual({ ok: true, node_id: node.tgt.id, senders: [node.a.alias, `user:${user.mem.name}`] });
|
|
95
|
+
const g = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.tgt.id}`);
|
|
96
|
+
expect(g.body.nodes[0].inbox_allowlist).toEqual([node.a.alias, `user:${user.mem.name}`]);
|
|
97
|
+
const audit = db.get<{ detail: string | null; user_id: string | null }>(
|
|
98
|
+
"SELECT detail, user_id FROM audit_log WHERE action = 'node_inbox_allowlist_changed' AND target_id = ?1 ORDER BY id DESC LIMIT 1", node.tgt.id);
|
|
99
|
+
expect(audit?.user_id).toBe(user.own.id);
|
|
100
|
+
expect(JSON.parse(audit!.detail!)).toEqual({ from: null, to: JSON.stringify([node.a.alias, `user:${user.mem.name}`]) });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("网络 owner / admin 也能设;null 清空 → GET 读回 null", async () => {
|
|
104
|
+
expect((await put(user.boss.token, { senders: ["x"] })).status).toBe(200);
|
|
105
|
+
expect((await put(user.adm.token, { senders: ["y"] })).body.senders).toEqual(["y"]);
|
|
106
|
+
const cleared = await put(user.adm.token, { senders: null });
|
|
107
|
+
expect(cleared.status).toBe(200);
|
|
108
|
+
expect(cleared.body.senders).toBeNull();
|
|
109
|
+
expect(storedInbox()).toBeNull();
|
|
110
|
+
const g = await call(user.boss.token, "GET", `/api/nodes?network_id=${net}&node_id=${node.tgt.id}`);
|
|
111
|
+
expect(g.body.nodes[0].inbox_allowlist).toBeNull();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("普通成员 403 且行没变;主人 200 且行真的变(镜像)", async () => {
|
|
115
|
+
setInbox(["keep"]);
|
|
116
|
+
const denied = await put(user.mem.token, { senders: ["sneak"] });
|
|
117
|
+
expect(denied.status).toBe(403);
|
|
118
|
+
expect(denied.body.error).toBe("permission_denied");
|
|
119
|
+
expect(storedInbox()).toBe(JSON.stringify(["keep"]));
|
|
120
|
+
expect((await put(user.own.token, { senders: ["changed"] })).status).toBe(200);
|
|
121
|
+
expect(storedInbox()).toBe(JSON.stringify(["changed"]));
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("错误形状:[] / 非数组 / 超 200 条 / 坏 JSON → 400,库没变", async () => {
|
|
125
|
+
setInbox(["keep"]);
|
|
126
|
+
const empty = await put(user.own.token, { senders: [] });
|
|
127
|
+
expect(empty.status).toBe(400);
|
|
128
|
+
expect(empty.body.error).toBe("empty_allowlist_ambiguous");
|
|
129
|
+
expect((await put(user.own.token, { senders: "a" })).body.error).toBe("invalid_senders");
|
|
130
|
+
const many = await put(user.own.token, { senders: Array.from({ length: 201 }, (_, i) => `s${i}`) });
|
|
131
|
+
expect(many.status).toBe(400);
|
|
132
|
+
expect(many.body.error).toBe("too_many_senders");
|
|
133
|
+
const bad = await fetch(`${base}/api/nodes/${node.tgt.id}/inbox-allowlist`, {
|
|
134
|
+
method: "PUT", headers: { Authorization: `Bearer ${user.own.token}`, "Content-Type": "application/json" }, body: "{",
|
|
135
|
+
});
|
|
136
|
+
expect(bad.status).toBe(400);
|
|
137
|
+
expect(storedInbox()).toBe(JSON.stringify(["keep"]));
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("节点令牌 403 user_token_required;网络外的人 / 不存在的节点 404;无令牌 401", async () => {
|
|
141
|
+
const asNode = await put(node.tgt.token, { senders: ["x"] });
|
|
142
|
+
expect(asNode.status).toBe(403);
|
|
143
|
+
expect(asNode.body.error).toBe("user_token_required");
|
|
144
|
+
expect((await put(user.out.token, { senders: ["x"] })).status).toBe(404);
|
|
145
|
+
expect((await put(user.boss.token, { senders: ["x"] }, "n_does_not_exist")).status).toBe(404);
|
|
146
|
+
const anon = await fetch(`${base}/api/nodes/${node.tgt.id}/inbox-allowlist`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: "{}" });
|
|
147
|
+
expect(anon.status).toBe(401);
|
|
148
|
+
expect(storedInbox()).toBeNull();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("/health 宣告 node_inbox_allowlist", async () => {
|
|
152
|
+
const r = await fetch(`${base}/health`);
|
|
153
|
+
expect((await r.json()).capabilities).toContain("node_inbox_allowlist");
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
describe("节点发件人 —— alias / node_id 匹配,显式原因", () => {
|
|
158
|
+
test("null = 谁都能发(与今天一致)", async () => {
|
|
159
|
+
expect((await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "open inbox" })).ok).toBe(true);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("MCP send_task:名单上的(alias)放行,不在名单上的拒并记在目标节点名下,且不入库", async () => {
|
|
163
|
+
setInbox([node.a.alias]);
|
|
164
|
+
expect((await mcp(node.a.token, "send_task", { alias: node.tgt.alias, task: "from a" })).ok).toBe(true);
|
|
165
|
+
const before = inboxRowsFor(node.tgt.alias);
|
|
166
|
+
const denied = await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "from b" });
|
|
167
|
+
expectSenderDenied(denied, node.b.alias);
|
|
168
|
+
expect(denied.route).toBe("mcp:send_task");
|
|
169
|
+
expect(inboxRowsFor(node.tgt.alias)).toBe(before);
|
|
170
|
+
const row = db.get<{ hits: number | string; sample: string | null }>(
|
|
171
|
+
"SELECT hits, sample FROM node_permission_log WHERE network_id = ?1 AND node_id = ?2 AND reason = 'sender_not_allowed' AND route = 'mcp:send_task'", net, node.tgt.id);
|
|
172
|
+
expect(Number(row?.hits)).toBeGreaterThan(0);
|
|
173
|
+
expect(row?.sample).toBe(node.b.alias);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("按 node_id 写也命中", async () => {
|
|
177
|
+
setInbox([node.b.id]);
|
|
178
|
+
expect((await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "by id" })).ok).toBe(true);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("显式原因:COMMHUB_NODE_PERMISSIONS=off 也照拒", async () => {
|
|
182
|
+
process.env.COMMHUB_NODE_PERMISSIONS = "off";
|
|
183
|
+
setInbox([node.a.alias]);
|
|
184
|
+
expectSenderDenied(await mcp(node.b.token, "send_task", { alias: node.tgt.alias, task: "off" }), node.b.alias);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("MCP send_message / retry_task / reassign_task 同样拒", async () => {
|
|
188
|
+
setInbox([node.a.alias]);
|
|
189
|
+
expectSenderDenied(await mcp(node.b.token, "send_message", { alias: node.tgt.alias, message: "hi" }), node.b.alias);
|
|
190
|
+
|
|
191
|
+
setInbox(null);
|
|
192
|
+
const t = await mcp(node.a.token, "send_task", { alias: node.tgt.alias, task: "to retry" });
|
|
193
|
+
expect(t.ok).toBe(true);
|
|
194
|
+
db.run("UPDATE tasks SET status = 'failed' WHERE task_id = ?1", [t.message_id]);
|
|
195
|
+
setInbox([node.a.alias]);
|
|
196
|
+
const retry = await mcp(node.b.token, "retry_task", { task_id: t.message_id });
|
|
197
|
+
expectSenderDenied(retry, node.b.alias);
|
|
198
|
+
expect(retry.route).toBe("mcp:retry_task");
|
|
199
|
+
expect(db.get<{ status: string }>("SELECT status FROM tasks WHERE task_id = ?1", t.message_id)!.status).toBe("failed");
|
|
200
|
+
|
|
201
|
+
const r = await mcp(node.a.token, "send_task", { alias: node.c.alias, task: "to reassign" });
|
|
202
|
+
expect(r.ok).toBe(true);
|
|
203
|
+
const re = await mcp(node.b.token, "reassign_task", { task_id: r.message_id, new_alias: node.tgt.alias });
|
|
204
|
+
expectSenderDenied(re, node.b.alias);
|
|
205
|
+
expect(db.get<{ to_name: string }>("SELECT to_name FROM tasks WHERE task_id = ?1", r.message_id)!.to_name).toBe(node.c.alias);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("REST POST /api/task(节点令牌)→ 403 同一形状", async () => {
|
|
209
|
+
setInbox([node.a.alias]);
|
|
210
|
+
const r = await call(node.b.token, "POST", "/api/task", { alias: node.tgt.alias, task: "rest from b", network_id: net });
|
|
211
|
+
expect(r.status).toBe(403);
|
|
212
|
+
expectSenderDenied(r.body, node.b.alias);
|
|
213
|
+
expect(r.body.route).toBe("POST /api/task");
|
|
214
|
+
expect((await call(node.a.token, "POST", "/api/task", { alias: node.tgt.alias, task: "rest from a", network_id: net })).status).toBe(200);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test("发给自己永远放行(含 !strict)", async () => {
|
|
218
|
+
setInbox(["!strict"]);
|
|
219
|
+
expect((await mcp(node.tgt.token, "send_task", { alias: node.tgt.alias, task: "note to self" })).ok).toBe(true);
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
describe("人类发件人 —— user:<username|user_id> / user:*,主人与管理员隐式放行", () => {
|
|
224
|
+
const send = (who: string, task = "hello") =>
|
|
225
|
+
call(user[who].token, "POST", "/api/task", { alias: node.tgt.alias, task: `${task} ${who} ${Math.random()}`, network_id: net });
|
|
226
|
+
|
|
227
|
+
test("名单只有节点 ⇒ 普通成员被拒;节点主人、网络 owner、网络 admin 照常能发", async () => {
|
|
228
|
+
setInbox([node.a.alias]);
|
|
229
|
+
const denied = await send("mem");
|
|
230
|
+
expect(denied.status).toBe(403);
|
|
231
|
+
expectSenderDenied(denied.body, `user:${user.mem.name}`);
|
|
232
|
+
for (const who of ["own", "boss", "adm"]) expect((await send(who)).status).toBe(200);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test("user:<username>、user:<user_id>、user:* 都命中", async () => {
|
|
236
|
+
for (const entry of [`user:${user.mem.name}`, `user:${user.mem.id}`, "user:*"]) {
|
|
237
|
+
setInbox([node.a.alias, entry]);
|
|
238
|
+
expect((await send("mem")).status).toBe(200);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
test("!strict 关掉隐式放行:主人与网络 owner 也必须在名单上", async () => {
|
|
243
|
+
setInbox([node.a.alias, "!strict"]);
|
|
244
|
+
expect((await send("own")).status).toBe(403);
|
|
245
|
+
expect((await send("boss")).status).toBe(403);
|
|
246
|
+
setInbox([node.a.alias, "!strict", `user:${user.own.name}`]);
|
|
247
|
+
expect((await send("own")).status).toBe(200);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test("MCP 用户令牌同一口径", async () => {
|
|
251
|
+
setInbox([node.a.alias]);
|
|
252
|
+
expectSenderDenied(await mcp(user.mem.token, "send_task", { alias: node.tgt.alias, task: "mcp human", network_id: net }), `user:${user.mem.name}`);
|
|
253
|
+
expect((await mcp(user.own.token, "send_task", { alias: node.tgt.alias, task: "mcp owner", network_id: net })).ok).toBe(true);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
describe("广播 —— 跳过不收的收件人,报告而不失败", () => {
|
|
258
|
+
test("REST /api/broadcast:tgt 被跳过并出现在 inbox_skipped,其他人照收", async () => {
|
|
259
|
+
setInbox([node.a.alias]);
|
|
260
|
+
const before = { tgt: inboxRowsFor(node.tgt.alias), c: inboxRowsFor(node.c.alias) };
|
|
261
|
+
const r = await call(user.mem.token, "POST", `/api/broadcast?network_id=${net}`, { message: `bc ${stamp}`, network_id: net });
|
|
262
|
+
expect(r.status).toBe(200);
|
|
263
|
+
expect(r.body.ok).toBe(true);
|
|
264
|
+
expect(r.body.inbox_skipped).toEqual([{ alias: node.tgt.alias, node_id: node.tgt.id, reason: "sender_not_allowed" }]);
|
|
265
|
+
expect(inboxRowsFor(node.tgt.alias)).toBe(before.tgt);
|
|
266
|
+
expect(inboxRowsFor(node.c.alias)).toBe(before.c + 1);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
test("MCP broadcast(节点令牌)同样跳过;没人被跳过时回执恰好三键、没有 inbox_skipped", async () => {
|
|
270
|
+
const open = await mcp(node.b.token, "broadcast", { message: `open ${stamp}` });
|
|
271
|
+
expect(open.ok).toBe(true);
|
|
272
|
+
expect(Object.keys(open).sort()).toEqual(["message_ids", "ok", "recipients"]);
|
|
273
|
+
setInbox([node.a.alias]);
|
|
274
|
+
const r = await mcp(node.b.token, "broadcast", { message: `mcp bc ${stamp}` });
|
|
275
|
+
expect(r.ok).toBe(true);
|
|
276
|
+
expect(r.inbox_skipped.map((s: any) => s.alias)).toEqual([node.tgt.alias]);
|
|
277
|
+
expect(r.recipients).toBe(open.recipients - 1);
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
describe("排程 —— 每次触发按建排程的人现判", () => {
|
|
282
|
+
test("普通成员建的排程:名单不收他 ⇒ 这次运行 failed / sender_not_allowed,不建任务;收他 ⇒ 照常派发", async () => {
|
|
283
|
+
const { dispatchScheduledOccurrence } = await import("./scheduled-tasks.js");
|
|
284
|
+
const schedule = (suffix: string) => {
|
|
285
|
+
const id = `sched_ia_${suffix}_${stamp}`;
|
|
286
|
+
db.run(
|
|
287
|
+
`INSERT INTO scheduled_tasks (schedule_id, network_id, created_by, name, target_node_id, target_alias, task_content, schedule_type, schedule_json, next_run_at)
|
|
288
|
+
VALUES (?1, ?2, ?3, 'n', ?4, ?5, 'scheduled work', 'interval', '{"type":"interval","minutes":60}', datetime('now'))`,
|
|
289
|
+
[id, net, user.mem.id, node.tgt.id, node.tgt.alias],
|
|
290
|
+
);
|
|
291
|
+
return db.get<any>("SELECT * FROM scheduled_tasks WHERE schedule_id = ?1", id);
|
|
292
|
+
};
|
|
293
|
+
setInbox([node.a.alias]);
|
|
294
|
+
const denied = dispatchScheduledOccurrence(schedule("deny"), new Date().toISOString(), false);
|
|
295
|
+
expect(denied.status).toBe("failed");
|
|
296
|
+
expect(denied.taskId).toBeUndefined();
|
|
297
|
+
expect(db.get<{ error_code: string }>("SELECT error_code FROM scheduled_task_runs WHERE run_id = ?1", denied.runId)?.error_code).toBe("sender_not_allowed");
|
|
298
|
+
setInbox([node.a.alias, `user:${user.mem.name}`]);
|
|
299
|
+
const ok = dispatchScheduledOccurrence(schedule("allow"), new Date().toISOString(), false);
|
|
300
|
+
expect(ok.taskId).toBeTruthy();
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
describe("inboxAllows —— 纯判定", () => {
|
|
305
|
+
const ctx = { targetNodeId: "n_t", targetAlias: "t", ownerUserId: "u_owner", networkId: null };
|
|
306
|
+
test("null 放行一切;legacy 默认放行,!strict 拒", () => {
|
|
307
|
+
expect(inboxAllows(null, { kind: "legacy" }, ctx)).toBe(true);
|
|
308
|
+
expect(inboxAllows(["x"], { kind: "legacy" }, ctx)).toBe(true);
|
|
309
|
+
expect(inboxAllows(["x", "!strict"], { kind: "legacy" }, ctx)).toBe(false);
|
|
310
|
+
});
|
|
311
|
+
test("Hub 管理员隐式放行;!strict 下不放行", () => {
|
|
312
|
+
const admin = { kind: "user" as const, userId: "u_admin", username: "root", isHubAdmin: true };
|
|
313
|
+
expect(inboxAllows(["x"], admin, ctx)).toBe(true);
|
|
314
|
+
expect(inboxAllows(["x", "!strict"], admin, ctx)).toBe(false);
|
|
315
|
+
});
|
|
316
|
+
test("节点条目不会匹配到同名的人(user: 前缀才是人)", () => {
|
|
317
|
+
expect(inboxAllows(["alice"], { kind: "user", userId: "u_a", username: "alice" }, ctx)).toBe(false);
|
|
318
|
+
expect(inboxAllows(["user:*"], { kind: "node", nodeId: "n_x", aliases: ["x"] }, ctx)).toBe(false);
|
|
319
|
+
});
|
|
320
|
+
});
|
|
@@ -24,7 +24,7 @@ const publicLifecycleErrors = new Set([
|
|
|
24
24
|
"adopt_workdir_outside_roots", "adopt_workdir_not_absolute",
|
|
25
25
|
"adopt_alias_invalid", "adopt_alias_mismatch", "adopt_config_invalid",
|
|
26
26
|
"adopt_config_network_mismatch", "adopt_network_mismatch",
|
|
27
|
-
"adopt_hub_invalid", "adopt_hub_missing", "adopt_hub_mismatch",
|
|
27
|
+
"adopt_hub_invalid", "adopt_hub_missing", "adopt_hub_mismatch", "adopt_hub_unverifiable",
|
|
28
28
|
"adopt_identity_ambiguous", "adopt_identity_not_found", "adopt_identity_changed",
|
|
29
29
|
"adopt_path_not_regular", "adopt_path_owner_mismatch", "adopt_path_writable_by_others",
|
|
30
30
|
"adopt_process_argv_mismatch", "adopt_process_home_mismatch",
|