@sleep2agi/commhub-server 0.9.0-preview.263 → 0.9.0-preview.264

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.
@@ -0,0 +1,126 @@
1
+ // #3146 —— 「上一次切模型的结局」必须能被读到,而不是只能靠 revision 没涨推断成超时。
2
+ //
3
+ // 生产证据(2026-11-01,通信欧 n_28e6b2c2):库里两行
4
+ // status='rejected' error='OpenCode V2 session is not running; model was not changed'
5
+ // 而界面写的是「已下发 xai/grok-4.7,但 90s 内节点没有以新模型回来,请去看日志」。
6
+ // 答案在库里,读者拿不到 —— 这个文件钉住「拿得到」与「拿到的形状对」。
7
+ import { describe, expect, test } from "bun:test";
8
+ import { readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import {
11
+ CONFIG_UPDATE_STATUSES,
12
+ projectLastConfigUpdate,
13
+ readLastConfigUpdate,
14
+ } from "./node-config-last-update.js";
15
+
16
+ const row = (over: Partial<Parameters<typeof projectLastConfigUpdate>[0]> = {}) => ({
17
+ update_id: "cu_1",
18
+ status: "rejected",
19
+ patch_json: JSON.stringify({ model: "xai/grok-4.7", flags: {} }),
20
+ error: "OpenCode V2 session is not running; model was not changed",
21
+ created_at: "1793519656437",
22
+ acked_at: "1793519656466",
23
+ ...over,
24
+ });
25
+
26
+ describe("#3146 上一次配置下发的投影", () => {
27
+ test("rejected ⇒ 原因原样带出(不是变成 timeout)", () => {
28
+ const v = projectLastConfigUpdate(row());
29
+ expect(v.status).toBe("rejected");
30
+ expect(v.error).toBe("OpenCode V2 session is not running; model was not changed");
31
+ expect(v.requested_model).toBe("xai/grok-4.7");
32
+ expect(v.terminal).toBe(true);
33
+ });
34
+
35
+ test("时间列是 TEXT 存的 ms epoch ⇒ 转成 ISO;转不出就 null(不出现 Invalid Date)", () => {
36
+ const v = projectLastConfigUpdate(row());
37
+ expect(v.created_at).toBe(new Date(1793519656437).toISOString());
38
+ expect(v.acked_at).toBe(new Date(1793519656466).toISOString());
39
+ for (const bad of ["", "not-a-number", "0", "-5", null]) {
40
+ expect(projectLastConfigUpdate(row({ created_at: bad as any })).created_at).toBeNull();
41
+ }
42
+ expect(JSON.stringify(projectLastConfigUpdate(row({ acked_at: "x" as any })))).not.toContain("Invalid Date");
43
+ });
44
+
45
+ test("闭集外的 status ⇒ unknown + 原值带出,且**不**当成终点(不折叠成最乐观那一档)", () => {
46
+ const v = projectLastConfigUpdate(row({ status: "cancelled" }));
47
+ expect(v.status).toBe("unknown");
48
+ expect(v.observed_status).toBe("cancelled");
49
+ expect(v.terminal).toBe(false);
50
+ });
51
+
52
+ test("闭集内的每一档都有明确的 terminal 取值(枚举与映射不许脱节)", () => {
53
+ const terminal = Object.fromEntries(
54
+ CONFIG_UPDATE_STATUSES.map((s) => [s, projectLastConfigUpdate(row({ status: s })).terminal]),
55
+ );
56
+ expect(terminal).toEqual({ pending: false, restarting: false, applied: true, rejected: true, timeout: true });
57
+ });
58
+
59
+ test("applied ⇒ error 为 null(成功时不许带一条陈旧原因)", () => {
60
+ const v = projectLastConfigUpdate(row({ status: "applied", error: null }));
61
+ expect(v.status).toBe("applied");
62
+ expect(v.error).toBeNull();
63
+ });
64
+
65
+ test("patch_json 没有 model 或不是 JSON ⇒ requested_model 为 null(不猜)", () => {
66
+ expect(projectLastConfigUpdate(row({ patch_json: "{}" })).requested_model).toBeNull();
67
+ expect(projectLastConfigUpdate(row({ patch_json: "{oops" })).requested_model).toBeNull();
68
+ expect(projectLastConfigUpdate(row({ patch_json: null })).requested_model).toBeNull();
69
+ });
70
+
71
+ test("不投影 created_by_token(凭据标识不是界面信息)", () => {
72
+ const v: any = projectLastConfigUpdate(row() as any);
73
+ expect(Object.keys(v).sort()).toEqual([
74
+ "acked_at", "created_at", "error", "observed_status", "requested_model", "status", "terminal", "update_id",
75
+ ]);
76
+ expect(JSON.stringify(v)).not.toContain("created_by_token");
77
+ });
78
+
79
+ test("readLastConfigUpdate:从未下发 ⇒ null;多行取最新(created_at 降序)", () => {
80
+ const rows: Record<string, any> = {
81
+ cu_old: row({ update_id: "cu_old", status: "applied", created_at: "1000", error: null }),
82
+ cu_new: row({ update_id: "cu_new", status: "rejected", created_at: "2000" }),
83
+ };
84
+ let seenSql = "";
85
+ const get = (sql: string, _nodeId: string) => {
86
+ seenSql = sql;
87
+ return rows.cu_new;
88
+ };
89
+ expect(readLastConfigUpdate(get, "n_x")?.update_id).toBe("cu_new");
90
+ expect(seenSql).toContain("ORDER BY created_at DESC");
91
+ expect(readLastConfigUpdate(() => null, "n_x")).toBeNull();
92
+ });
93
+
94
+ test("镜像:读到的 rejected 里必须**同时**有 error 与 requested_model(缺一个就说不清失败在哪一层)", () => {
95
+ const v = projectLastConfigUpdate(row());
96
+ expect(v.error).not.toBeNull();
97
+ expect(v.requested_model).not.toBeNull();
98
+ });
99
+ });
100
+
101
+ // ── 接线:投影写对了,但如果 handler 没把它放进响应里,客户端仍然拿不到 ──
102
+ //
103
+ // 纯函数测试管不住这一层(`readLastConfigUpdate` 全绿而响应里没有 last_update 是完全可能的)。
104
+ // 判据用**守卫位置**:这一格必须出现在 「GET /api/nodes/:id/config」那段 handler 的响应对象里,
105
+ // 而不是文件里任何一处。判据域只到「文本级 + 一次变量解析」,不假装运行期全覆盖。
106
+ const serverSrc = readFileSync(join(import.meta.dir, "server.ts"), "utf8");
107
+
108
+ function configGetHandler(): string {
109
+ const start = serverSrc.indexOf("const nodeConfigMatch = url.pathname.match(");
110
+ expect(start).toBeGreaterThan(-1);
111
+ const end = serverSrc.indexOf("// ── #462", start);
112
+ expect(end).toBeGreaterThan(start);
113
+ return serverSrc.slice(start, end);
114
+ }
115
+
116
+ describe("#3146 GET /api/nodes/:id/config 的接线", () => {
117
+ test("响应对象里有 last_update(读的是 node_config_updates 的最近一行)", () => {
118
+ const block = configGetHandler();
119
+ expect(block).toContain("readLastConfigUpdate(");
120
+ expect(block).toContain("last_update: lastUpdate");
121
+ });
122
+
123
+ test("镜像否定:不投影 created_by_token(凭据标识不进响应)", () => {
124
+ expect(configGetHandler()).not.toContain("created_by_token");
125
+ });
126
+ });
@@ -0,0 +1,107 @@
1
+ // #3146 —— 客户端「切模型」失败时,Hub 明明已经知道原因,界面上却只显示「90s 内没回来,
2
+ // 请到机器上看日志」。
3
+ //
4
+ // 原因不是客户端乱写:`GET /api/nodes/:id/config` 原来只回 config_revision / model / flags /
5
+ // config_update_capable —— 没有一处能读到**上一次下发的结局**。于是客户端只能靠
6
+ // 「revision 有没有涨」推断,涨不了就只能是 timeout。而生产上(2026-11-01 通信欧)
7
+ // 真实结局是 rejected,Hub 库里写着:
8
+ //
9
+ // status = 'rejected'
10
+ // error = 'OpenCode V2 session is not running; model was not changed'
11
+ // acked_at 也写了
12
+ //
13
+ // —— 一条「答案已经在库里、但读者拿不到」的缺口。
14
+ //
15
+ // 这个模块只做**投影**:把 node_config_updates 最近一行翻译成客户端能直接渲染的形状。
16
+ // 三条规矩:
17
+ // ① 状态是闭集。不在表里的值报 unknown 并把原值带出去(不折叠成最乐观的那一档)。
18
+ // ② 时间列是 **TEXT 存 ms epoch**,不是 hub 那种无时区标记的字符串;解析不出就 null,
19
+ // 不允许出现 "Invalid Date"。
20
+ // ③ 不投影 `created_by_token`:那是凭据标识,不是界面信息。
21
+
22
+ export const CONFIG_UPDATE_STATUSES = ["pending", "restarting", "applied", "rejected", "timeout"] as const;
23
+ export type ConfigUpdateStatus = (typeof CONFIG_UPDATE_STATUSES)[number];
24
+
25
+ /** 闭集显式映射。pending/restarting 是「还在路上」,其余三个是终点。 */
26
+ const TERMINAL: Record<ConfigUpdateStatus, boolean> = {
27
+ pending: false,
28
+ restarting: false,
29
+ applied: true,
30
+ rejected: true,
31
+ timeout: true,
32
+ };
33
+
34
+ export interface LastConfigUpdate {
35
+ update_id: string;
36
+ /** 闭集内就是它自己;闭集外是 `unknown`(并把原值放在 observed_status)。 */
37
+ status: ConfigUpdateStatus | "unknown";
38
+ /** 原始 status 字符串(永远给,便于排查;闭集内与 status 相同)。 */
39
+ observed_status: string;
40
+ /** 已知是终点才 true;unknown 一律 false —— 「不知道结没结束」不等于「结束了」。 */
41
+ terminal: boolean;
42
+ /** 这次下发要的模型(来自 patch_json.model);patch 里没有就是 null。 */
43
+ requested_model: string | null;
44
+ /** 节点自报的失败原因(rejected/timeout 才有;applied 是 null)。 */
45
+ error: string | null;
46
+ /** ISO;TEXT 存的是 ms epoch,转不出来就是 null。 */
47
+ created_at: string | null;
48
+ acked_at: string | null;
49
+ }
50
+
51
+ type Row = {
52
+ update_id: string;
53
+ status: string;
54
+ patch_json: string | null;
55
+ error: string | null;
56
+ created_at: string | number | null;
57
+ acked_at: string | number | null;
58
+ };
59
+
60
+ /** ms epoch(TEXT 或数字)→ ISO。非有限数、非正数一律 null。 */
61
+ function msToIso(value: string | number | null | undefined): string | null {
62
+ if (value === null || value === undefined) return null;
63
+ const ms = typeof value === "number" ? value : Number(value);
64
+ if (!Number.isFinite(ms) || ms <= 0) return null;
65
+ return new Date(ms).toISOString();
66
+ }
67
+
68
+ /** patch_json 里的 model。解析失败或没有 model ⇒ null(不猜)。 */
69
+ function requestedModel(patchJson: string | null): string | null {
70
+ if (!patchJson) return null;
71
+ try {
72
+ const parsed = JSON.parse(patchJson) as { model?: unknown };
73
+ return typeof parsed?.model === "string" && parsed.model ? parsed.model : null;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** 纯函数:一行 → 对外形状。抽出来是为了能单独钉住「闭集外不折叠」那条。 */
80
+ export function projectLastConfigUpdate(row: Row): LastConfigUpdate {
81
+ const observed = typeof row.status === "string" ? row.status : "";
82
+ const known = (CONFIG_UPDATE_STATUSES as readonly string[]).includes(observed);
83
+ return {
84
+ update_id: row.update_id,
85
+ status: known ? (observed as ConfigUpdateStatus) : "unknown",
86
+ observed_status: observed,
87
+ terminal: known ? TERMINAL[observed as ConfigUpdateStatus] : false,
88
+ requested_model: requestedModel(row.patch_json),
89
+ error: typeof row.error === "string" && row.error ? row.error : null,
90
+ created_at: msToIso(row.created_at),
91
+ acked_at: msToIso(row.acked_at),
92
+ };
93
+ }
94
+
95
+ export const LAST_CONFIG_UPDATE_SQL =
96
+ `SELECT update_id, status, patch_json, error, created_at, acked_at
97
+ FROM node_config_updates WHERE node_id = ?1
98
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`;
99
+
100
+ /** 读这个节点最近一次配置下发。从未下发过 ⇒ null(不是空对象:两者在界面上不同)。 */
101
+ export function readLastConfigUpdate(
102
+ get: (sql: string, ...params: any[]) => Row | null,
103
+ nodeId: string,
104
+ ): LastConfigUpdate | null {
105
+ const row = get(LAST_CONFIG_UPDATE_SQL, nodeId);
106
+ return row ? projectLastConfigUpdate(row) : null;
107
+ }
@@ -0,0 +1,98 @@
1
+ // `degraded[].origin: node | hub` —— 值域 == 生产者,**并且**那一格对它声明的事真的成立。
2
+ //
3
+ // ## 这格存在的原因
4
+ //
5
+ // `app_server.reason` 有两个生产者:
6
+ // · 节点上报的 `last_error`(≤200 任意串)
7
+ // · Hub 自己合成的字面量 `"unreachable"`(节点没报错误摘要时)
8
+ //
9
+ // 两者写进同一个字段 ⇒ 读者分不出「节点说它 unreachable」与「Hub 根本没能问到节点」。
10
+ // 而且**上游可以原样声明 `"unreachable"`** ⇒ 靠改名或拆 catch 都拦不住,
11
+ // 判别力只能来自这个独立的来源字段。
12
+ //
13
+ // ## 两条断言,缺一不可
14
+ //
15
+ // ① 值域 == 生产者(声明了没人产生 = 死值;产生了没声明 = 读者拿到不认识的串)
16
+ // ② **行为**:`origin` 说的那句必须真的成立 —— 有 `last_error` ⇒ node;
17
+ // 没有(Hub 用了兜底串)⇒ hub。只做 ① 时,把兜底那行的 origin 改成 node
18
+ // 仍然「值域齐全」,而这一格的含义就没了。
19
+ import { describe, expect, test } from "bun:test";
20
+ import { readFileSync } from "node:fs";
21
+ import { degradedLayers } from "./node-health-guard.js";
22
+
23
+ const src = readFileSync(new URL("./node-health-guard.ts", import.meta.url), "utf8");
24
+
25
+ /** 声明的值域。 */
26
+ export function declaredOrigins(source: string): string[] {
27
+ const m = source.match(/origin:\s*([^;]+);/);
28
+ return m ? [...m[1].matchAll(/"([a-z]+)"/g)].map((x) => x[1]) : [];
29
+ }
30
+
31
+ /**
32
+ * 源码里 `origin:` 之后的**所有**字面量取值(保序、允许重复)。
33
+ *
34
+ * 不能只认 `origin: "x"`:兜底那一行写的是三目 `origin: last_error ? "node" : "hub"`。
35
+ * 只认字面量形式时,它整个人消失 —— 于是最重要的那一格(Hub 合成的兜底串)
36
+ * 会被读成「没人产生 hub」,而它其实是唯一产生 hub 的地方。
37
+ * 这正是 git_identity_root 那次的同一个坑(经变量/表达式产生)。
38
+ */
39
+ export function producedOrigins(source: string): string[] {
40
+ const out: string[] = [];
41
+ for (const line of source.split("\n")) {
42
+ const m = line.match(/origin:\s*(.+)$/);
43
+ if (!m) continue;
44
+ // 类型声明那一行(`origin: "node" | "hub";`)是**声明**,不是产生点。
45
+ // 不排除它,声明就会被算成一次产生 —— 于是「每个值都有产生点」这条永远为真。
46
+ if (m[1].includes("|")) continue;
47
+ for (const lit of m[1].matchAll(/"([a-z]+)"/g)) out.push(lit[1]);
48
+ }
49
+ return out;
50
+ }
51
+
52
+ describe("degraded[].origin 值域 == 生产者", () => {
53
+ test("① 声明集合非空且无重复", () => {
54
+ const declared = declaredOrigins(src);
55
+ expect(declared.length).toBeGreaterThanOrEqual(2);
56
+ expect(new Set(declared).size).toBe(declared.length);
57
+ });
58
+
59
+ test("② 产生点都在声明内,且每个声明值都有产生点", () => {
60
+ const declared = new Set(declaredOrigins(src));
61
+ const produced = new Set(producedOrigins(src));
62
+ expect([...produced].filter((x) => !declared.has(x))).toEqual([]);
63
+ expect([...declared].filter((x) => !produced.has(x))).toEqual([]);
64
+ });
65
+
66
+ test("③ 每个 origin 值的产生次数(向量)", () => {
67
+ const counts: Record<string, number> = {};
68
+ for (const o of producedOrigins(src)) counts[o] = (counts[o] ?? 0) + 1;
69
+ // `node` 是多数(每层自带),`hub` 只有一处:app_server 的兜底串。
70
+ // 数字变了要能说出「多出来的那一处是哪个层」。
71
+ expect(counts).toEqual({ hub: 1, node: 3 });
72
+ });
73
+
74
+ // ② 的**行为**那一半:origin 说的那句必须真的成立。
75
+ test("④ 有 last_error ⇒ origin=node,reason 逐字是节点给的", () => {
76
+ const out = degradedLayers({
77
+ app_server: { ok: false, last_error: "ECONNREFUSED 127.0.0.1:1729" },
78
+ } as any);
79
+ const layer = out.find((l) => l.layer === "app_server")!;
80
+ expect(layer.origin).toBe("node");
81
+ expect(layer.reason).toBe("ECONNREFUSED 127.0.0.1:1729");
82
+ });
83
+
84
+ test("⑤ 没有 last_error ⇒ origin=hub,且 reason 是 Hub 合成的 unreachable", () => {
85
+ const out = degradedLayers({ app_server: { ok: false } } as any);
86
+ const layer = out.find((l) => l.layer === "app_server")!;
87
+ expect(layer.origin).toBe("hub");
88
+ expect(layer.reason).toBe("unreachable");
89
+ });
90
+
91
+ // 上游可以原样声明 unreachable —— 这一条钉住「只有 origin 能分辨」这件事。
92
+ test("⑥ 节点自己报 unreachable 时,origin 仍是 node(不是 hub)", () => {
93
+ const out = degradedLayers({ app_server: { ok: false, last_error: "unreachable" } } as any);
94
+ const layer = out.find((l) => l.layer === "app_server")!;
95
+ expect(layer.reason).toBe("unreachable");
96
+ expect(layer.origin).toBe("node"); // 靠 reason 分不出来,靠 origin 才能
97
+ });
98
+ });
@@ -213,7 +213,14 @@ describe("PUT /api/nodes/:id/permission-mode", () => {
213
213
  expect((await call(node.nN.token, "PATCH", `/api/requirements/${card.boss}`, { description: "mode flip" })).status).toBe(200);
214
214
  expect((await call(user.sco.token, "PUT", `/api/nodes/${node.nS.id}/permission-mode`, { mode: "restricted" })).status).toBe(200); // sco 是 nS 的主人
215
215
  expect((await call(user.sco.token, "PUT", `/api/nodes/${node.nS.id}/permission-mode`, { mode: "normal" })).status).toBe(200);
216
+ // #3354 —— 403 之后**行必须没变**。只断状态码时,「拒了但已经写进去」也会绿,
217
+ // 而那是这条路由最坏的一种缺陷(拒绝语义看起来对,实际改了数据)。
218
+ const modeBeforeDenied = db.get<{ permission_mode: string }>(
219
+ "SELECT permission_mode FROM nodes WHERE node_id = ?1", node.nN.id)!.permission_mode;
216
220
  expect((await call(user.mem.token, "PUT", `/api/nodes/${node.nN.id}/permission-mode`, { mode: "readonly" })).status).toBe(403);
221
+ const modeAfterDenied = db.get<{ permission_mode: string }>(
222
+ "SELECT permission_mode FROM nodes WHERE node_id = ?1", node.nN.id)!.permission_mode;
223
+ expect(modeAfterDenied).toBe(modeBeforeDenied);
217
224
  expect((await call(node.nN.token, "PUT", `/api/nodes/${node.nN.id}/permission-mode`, { mode: "normal" })).body.error).toBe("user_token_required");
218
225
  expect((await call(user.out.token, "PUT", `/api/nodes/${node.nN.id}/permission-mode`, { mode: "readonly" })).status).toBe(404);
219
226
  expect((await call(user.boss.token, "PUT", `/api/nodes/${node.nN.id}/permission-mode`, { mode: "admin" })).status).toBe(400);
@@ -240,6 +247,21 @@ describe("GET /api/nodes viewer_can.permission_mode (#489)", () => {
240
247
  });
241
248
 
242
249
  describe("GET /api/networks/:id/node-permission-report", () => {
250
+ // #3316 判据④ 在**这个字段上不可满足**,而原因是 schema:`permission_mode` 是
251
+ // `NOT NULL DEFAULT 'normal'` ⇒ 「从未设置」在库层面不存在,任何读口都只能给出 normal。
252
+ //
253
+ // 我试过加 `permission_mode_source: explicit|default`,但实测它恒为 explicit
254
+ // (因为列不可能为 NULL)⇒ 那样的字段比没有更糟:它长得像三态,实际是常量。
255
+ // ⇒ 回滚该字段,改成把这条**结构性边界**钉住:谁若允许 NULL,这条会红并强制更新读口。
256
+ test("permission_mode 是 NOT NULL DEFAULT 'normal' ⇒ 「没设过」在库层面不可表达(#3316 判据④ 的前置)", () => {
257
+ const ddl = db.get<{ sql: string }>(
258
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='nodes'")!.sql;
259
+ expect(ddl).toMatch(/permission_mode\s+TEXT\s+NOT NULL\s+DEFAULT\s+'normal'/);
260
+ const fresh = `n_fresh_${Math.random().toString(36).slice(2, 8)}`;
261
+ db.run("INSERT INTO nodes (node_id, node_name, alias, network_id, lifecycle_state) VALUES (?1, ?1, ?1, ?2, 'active')", [fresh, net]);
262
+ expect(db.get<{ permission_mode: string }>("SELECT permission_mode FROM nodes WHERE node_id = ?1", fresh)!.permission_mode).toBe("normal");
263
+ });
264
+
243
265
  test("owner sees would-have-blocked counts per node; members and node tokens are refused", async () => {
244
266
  const r = await call(user.boss.token, "GET", `/api/networks/${net}/node-permission-report`);
245
267
  expect(r.status).toBe(200);
@@ -409,6 +431,157 @@ describe("GET /api/nodes 读回白名单与 transport", () => {
409
431
  expect(row.tool_allowlist).toEqual(["send_task", "get_inbox"]);
410
432
  });
411
433
 
434
+ // #3354 —— 白名单路由的 L3 证据:拒绝必须同时证明「403」与「行没变」,允许要有镜像。
435
+ test("改白名单:成员 403 且**行没变**;owner 200 且行真的变(镜像)", async () => {
436
+ const read = () => db.get<{ tool_allowlist: string | null }>(
437
+ "SELECT tool_allowlist FROM nodes WHERE node_id = ?1", node.other.id)!.tool_allowlist;
438
+ const before = read();
439
+ const denied = await call(user.mem.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: ["send_task"] });
440
+ expect(denied.status).toBe(403);
441
+ // 只断 403 时,「拒了但已经写进去」也会绿 —— 而那正是这条路由最坏的一种缺陷。
442
+ expect(read()).toBe(before);
443
+ // 镜像:允许时必须真的变,否则「永远拒绝」也会绿。
444
+ const ok = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: ["send_task"] });
445
+ expect(ok.status).toBe(200);
446
+ expect(read()).not.toBe(before);
447
+ });
448
+
449
+ // #3354 —— rest-allowlist 此前**一条测试都没有**(同族里唯一零覆盖的写路由)。
450
+ // 它改的是「这个节点能调哪些 REST 路由」,与 tool-allowlist 同一套授权口径。
451
+ // #3354 —— POST /api/tmux/:id/send:三层门里最外层的一条。
452
+ // 门 = TMUX_ENABLED → IP 白名单 → 管理员。测试环境默认第 1 层就是关的,
453
+ // 于是这条路由在**功能未启用**时必须是 404 拒绝,而不是「悄悄成功」。
454
+ // ⚠ 允许路径需要真 tmux,本仓测试不具条件 ⇒ 只验拒绝(证据表里标了 note)。
455
+ test("tmux send:功能未启用时 404 拒绝,且不返回任何执行痕迹", async () => {
456
+ const r = await call(user.boss.token, "POST", "/api/tmux/whatever/send", { text: "echo pwned" });
457
+ expect(r.status).toBe(404);
458
+ expect(r.body.error).toBe("tmux disabled");
459
+ // 「拒了」还要求「没有假装成功」:ok 必须是 false(不是 true、也不是缺失 ——
460
+ // 缺失会让调用方按 `if (!body.ok)` 之外的写法读成成功),且不许有 sent 字段。
461
+ expect(r.body.ok).toBe(false);
462
+ expect(r.body.sent).toBeUndefined();
463
+ });
464
+
465
+ // #3354 —— PUT /api/nodes/:id/avatar:拒绝之后 avatar_url 必须没变。
466
+ // 门与 attrs 相同(canRestWriteNetwork + restNodeDenied)⇒ 拒绝方是 readonly 模式下的节点自己,
467
+ // 不是普通成员(成员有网络写权是设计如此 —— 第一次按节点主人模板写就猜错了)。
468
+ // #3018 判据④ —— 「GET 只可能返回 null 或非空数组」这句话要能扛住**库里的历史 []**。
469
+ // 客户端收不到 [],才无从把它读成「全部禁止」。
470
+ test("库里有历史 [] ⇒ GET 读回 null(不是 []),三条白名单都一样", async () => {
471
+ const target = node.other.id;
472
+ db.run("UPDATE nodes SET tool_allowlist = '[]', rest_allowlist = '[]', peer_allowlist = '[]' WHERE node_id = ?1", [target]);
473
+ const row = (await call(user.boss.token, "GET", `/api/nodes?node_id=${target}&network_id=${net}`)).body.nodes[0];
474
+ expect(row.tool_allowlist).toBeNull();
475
+ expect(row.rest_allowlist).toBeNull();
476
+ expect(row.peer_allowlist).toBeNull();
477
+ // 否定断言配镜像:非空的仍然原样返回
478
+ db.run(`UPDATE nodes SET tool_allowlist = '["send_task"]' WHERE node_id = ?1`, [target]);
479
+ const row2 = (await call(user.boss.token, "GET", `/api/nodes?node_id=${target}&network_id=${net}`)).body.nodes[0];
480
+ expect(row2.tool_allowlist).toEqual(["send_task"]);
481
+ db.run("UPDATE nodes SET tool_allowlist = NULL WHERE node_id = ?1", [target]);
482
+ });
483
+
484
+ test("改节点头像:readonly 节点被拒且 avatar_url 没变;owner 200 且真的变了(镜像)", async () => {
485
+ const read = () => db.get<{ avatar_url: string | null }>(
486
+ "SELECT avatar_url FROM nodes WHERE node_id = ?1", node.other.id)!.avatar_url;
487
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/permission-mode`, { mode: "readonly" })).status).toBe(200);
488
+ const before = read();
489
+ const denied = await call(node.other.token, "PUT", `/api/nodes/${node.other.id}/avatar`, { avatar_url: "/avatars/avatar-11.webp" });
490
+ expect(denied.status).toBe(403);
491
+ expect(read()).toBe(before);
492
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/permission-mode`, { mode: "normal" })).status).toBe(200);
493
+ const ok = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/avatar`, { avatar_url: "/avatars/avatar-11.webp" });
494
+ expect(ok.status).toBe(200);
495
+ expect(read()).not.toBe(before);
496
+ });
497
+
498
+ // #3354 —— DELETE /api/nodes/:id:拒绝之后**行必须还在**。
499
+ // 这是唯一一条「只要写进去了就不可逆」的写路由 —— 拒了但删了,没有任何读数能复原。
500
+ // 用**可丢弃的 scratch 节点**做靶子:拒绝方是 readonly 模式下的 node.other,
501
+ // 这样 witness 若让闸失效,被误删的也只是 scratch,不会连带毁掉后面用例的公共夹具。
502
+ test("删节点:readonly 调用者被拒且行还在;owner 允许且行真的没了", async () => {
503
+ const scratch = `n_del_${Math.random().toString(36).slice(2, 8)}`;
504
+ db.run("INSERT INTO nodes (node_id, node_name, alias, network_id, lifecycle_state) VALUES (?1, ?1, ?1, ?2, 'active')", [scratch, net]);
505
+ expect(db.get("SELECT node_id FROM nodes WHERE node_id = ?1", scratch)).toBeTruthy();
506
+ // ① 拒绝:readonly 的 node.other 去删 scratch ⇒ 403,且 scratch 还在
507
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/permission-mode`, { mode: "readonly" })).status).toBe(200);
508
+ const denied = await call(node.other.token, "DELETE", `/api/nodes/${scratch}`);
509
+ expect(denied.status).toBe(403);
510
+ expect(db.get("SELECT node_id FROM nodes WHERE node_id = ?1", scratch)).toBeTruthy();
511
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/permission-mode`, { mode: "normal" })).status).toBe(200);
512
+ // ② 允许:owner 删同一个 scratch ⇒ 200 且行真的没了(镜像)
513
+ const ok = await call(user.boss.token, "DELETE", `/api/nodes/${scratch}`);
514
+ expect(ok.status).toBe(200);
515
+ expect(db.get("SELECT node_id FROM nodes WHERE node_id = ?1", scratch)).toBeFalsy();
516
+ });
517
+
518
+ // #3354 —— ATTRS:这条的门是 canRestWriteNetwork + restNodeDenied,另有**乐观锁**。
519
+ // 普通成员有网络写权是设计如此 ⇒ 这里的拒绝方是「readonly 模式下的节点自己」。
520
+ // 三件事必须一起钉:① 拒绝且行没变 ② 允许且行真变 ③ 旧 revision ⇒ 409 且行没变。
521
+ test("改 attrs:readonly 节点被拒且行没变;owner 200 且行真变;旧 revision 409 且行没变", async () => {
522
+ const row = () => db.get<{ display_name: string | null; attrs_revision: number | string }>(
523
+ "SELECT display_name, attrs_revision FROM nodes WHERE node_id = ?1", node.other.id)!;
524
+ // 先把节点设成 readonly(owner 才做得动),再让节点自己写属性 ⇒ 必须被拒
525
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/permission-mode`, { mode: "readonly" })).status).toBe(200);
526
+ const before = row();
527
+ const denied = await call(node.other.token, "PUT", `/api/nodes/${node.other.id}/attrs`, {
528
+ display_name: "pwned", base_attrs_revision: Number(before.attrs_revision),
529
+ });
530
+ expect(denied.status).toBe(403);
531
+ expect(row()).toEqual(before); // 拒绝不许改数据(名字与 revision 都要看)
532
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/permission-mode`, { mode: "normal" })).status).toBe(200);
533
+ // 允许:200 且名字变了、revision 前进
534
+ const ok = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/attrs`, {
535
+ display_name: "renamed-by-owner", base_attrs_revision: Number(before.attrs_revision),
536
+ });
537
+ expect(ok.status).toBe(200);
538
+ const after = row();
539
+ expect(after.display_name).toBe("renamed-by-owner");
540
+ expect(Number(after.attrs_revision)).toBeGreaterThan(Number(before.attrs_revision));
541
+ // 旧 revision 再写:409,且行不许被这次写入改掉
542
+ const conflict = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/attrs`, {
543
+ display_name: "lost-the-race", base_attrs_revision: Number(before.attrs_revision),
544
+ });
545
+ expect(conflict.status).toBe(409);
546
+ expect(conflict.body.error).toBe("attrs_revision_conflict");
547
+ expect(row()).toEqual(after);
548
+ });
549
+
550
+ // #3354 —— peer-allowlist 原本只有 200 / 400 / null,没有 403 分支。
551
+ // 它改的是「这个节点能跟哪些 peer 通信」⇒ 被拒失败等于任何人可改它的通信边界。
552
+ test("改 peer 白名单:成员 403 且**行没变**;owner 200 且行真的变(镜像)", async () => {
553
+ const read = () => db.get<{ peer_allowlist: string | null }>(
554
+ "SELECT peer_allowlist FROM nodes WHERE node_id = ?1", node.other.id)!.peer_allowlist;
555
+ const before = read();
556
+ const denied = await call(user.mem.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: ["boss"] });
557
+ expect(denied.status).toBe(403);
558
+ expect(read()).toBe(before); // 拒绝不许改数据
559
+ const ok = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: ["boss"] });
560
+ expect(ok.status).toBe(200);
561
+ expect(read()).not.toBe(before); // 镜像:允许时必须真的变
562
+ });
563
+
564
+ test("改 REST 白名单:成员 403 且**行没变**;owner 200 且行真的变(镜像);[] 歧义 400", async () => {
565
+ const read = () => db.get<{ rest_allowlist: string | null }>(
566
+ "SELECT rest_allowlist FROM nodes WHERE node_id = ?1", node.other.id)!.rest_allowlist;
567
+ const before = read();
568
+ // ① 拒绝:403 且行必须没变(只断 403 时「拒了但已写入」也会绿)
569
+ const denied = await call(user.mem.token, "PUT", `/api/nodes/${node.other.id}/rest-allowlist`, { routes: ["POST /api/task"] });
570
+ expect(denied.status).toBe(403);
571
+ expect(read()).toBe(before);
572
+ // ② 镜像:允许时必须真的变(只测拒绝时「永远拒绝」也会绿)
573
+ const ok = await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/rest-allowlist`, { routes: ["POST /api/task"] });
574
+ expect(ok.status).toBe(200);
575
+ expect(read()).not.toBe(before);
576
+ // ③ 空数组是歧义的:拒收,且不许落库(与 tool-allowlist 同一决定)
577
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/rest-allowlist`, { routes: [] })).body.error)
578
+ .toBe("empty_allowlist_ambiguous");
579
+ expect(read()).toBe(JSON.stringify(["POST /api/task"]));
580
+ // ④ 清空请传 null
581
+ expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/rest-allowlist`, { routes: null })).status).toBe(200);
582
+ expect(read()).toBeNull();
583
+ });
584
+
412
585
  test("清空后回到 null,而不是 []", async () => {
413
586
  expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/peer-allowlist`, { peers: null })).status).toBe(200);
414
587
  expect((await call(user.boss.token, "PUT", `/api/nodes/${node.other.id}/tool-allowlist`, { tools: null })).status).toBe(200);