@sleep2agi/commhub-server 0.9.0-preview.257 → 0.9.0-preview.258

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "85c2c13a74f794a2328b373862a79758a8a7da14",
3
+ "commit": "5e21ff94379e83633d5d76edfa7102b23de53716",
4
4
  "dirty": false,
5
- "built_at": "2026-10-31T23:00:27.804Z",
5
+ "built_at": "2026-11-01T01:22:42.925Z",
6
6
  "source": "git"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.257",
3
+ "version": "0.9.0-preview.258",
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",
@@ -274,6 +274,11 @@ describe("humans: restricted members can still see and DM other humans", () => {
274
274
  });
275
275
  test("alice → bob send_desktop_message works; bob reads it from his user inbox", async () => {
276
276
  const r = await tool(aliceToken, "send_desktop_message", { to_username: "acl_bob", message: "hello bob", network_id: NET });
277
+ // #3275 批次 2 —— send_desktop_message 是七个键里**唯一带 reason** 的回执:
278
+ // delivered=false 时 reason 说明为什么(不在线/没落库),而它是客户端唯一能据以重试的字段。
279
+ expect(Object.keys(r).sort()).toEqual([
280
+ "delivered", "delivered_to_user_id", "message_id", "network_id", "ok", "persisted", "reason",
281
+ ]);
277
282
  expect(r.ok).toBe(true);
278
283
  const inbox = await get(bobToken, `/api/messages?scope=user&network_id=${NET}`);
279
284
  expect(inbox.body.messages.map((m: any) => m.content)).toContain("hello bob");
@@ -651,6 +651,174 @@ describe("update_node_config 响应键集(exact key set)", () => {
651
651
  expect(Object.keys(ack).sort()).toEqual(["ok", "status"]);
652
652
  expect(ack.ok).toBe(true);
653
653
  expect(ack.status).toBe("applied");
654
+
655
+ // ④ #3275 批次 1·b —— **ignored 三个分支的左端不是同一个形状**:
656
+ // `{ok, ignored}` / `{ok, ignored, current_status}`。
657
+ // 只钉主分支时,「顺手把 current_status 加到另外两个分支」不会有任何东西变红。
658
+ const again = await tool(ntok, "ack_config_update", {
659
+ update_id: "u_acl3_pending", status: "applied", new_revision: 1,
660
+ });
661
+ expect(Object.keys(again).sort()).toEqual(["current_status", "ignored", "ok"]);
662
+ expect(again).toMatchObject({ ok: true, ignored: "already_terminal", current_status: "applied" });
663
+
664
+ const foreign = await tool(ntok, "ack_config_update", { update_id: "u_not_mine", status: "applied" });
665
+ expect(Object.keys(foreign).sort()).toEqual(["ignored", "ok"]);
666
+ expect(foreign).toEqual({ ok: true, ignored: "unknown_or_foreign_update" });
667
+
668
+ // ⑤ 「令牌在、node 没了」时**到不了** `ignored: "alias_unknown"`:
669
+ // 实测返回 {"ok":false,"error":"alias_required"} —— 因为 callerAlias 本身是从
670
+ // resolveNodeCaller(令牌) 解析出来的:node 行一删,alias 就是空,
671
+ // 于是**更早的** `if (!callerAlias)` 守卫先拒。
672
+ // ⇒ 这个出口要可达,需要「alias 解析得到、但工具内 resolveCallerNode() 解析不到」,
673
+ // 即一种跨网络的错配状态 —— 本夹具构造不出来,所以**今天不声称它被钉住**。
674
+ // 先把现在这条行为钉住(它同样是契约:残留令牌不该被当成隐式放行)。
675
+ const ghost = createNetworkTokenForNode(adminId, NET, "acl3-ghost-alias", "node_acl3_ghost");
676
+ expect(ghost.ok).toBe(true);
677
+ db.run("DELETE FROM nodes WHERE node_id = ?1", ["node_acl3_ghost"]);
678
+ db.run("DELETE FROM sessions WHERE alias = ?1", ["acl3-ghost-alias"]);
679
+ const staleTokenAck = await tool(ghost.token!, "ack_config_update", { update_id: "u_acl3_pending", status: "applied" });
680
+ expect(Object.keys(staleTokenAck).sort()).toEqual(["error", "ok"]);
681
+ expect(staleTokenAck).toEqual({ ok: false, error: "alias_required" });
682
+ });
683
+ });
684
+
685
+ // #3275 批次 1·c 的先决条件:**daemon 绑定 + MCP 可用**的凭证。
686
+ // 前面试过两条走不通的路(owner 令牌 ⇒ caller_not_a_daemon;REST 用的 bound 令牌 ⇒ 非 200),
687
+ // 正解是:种子一个 node + 用 createNetworkTokenForNode 铸一把网络令牌(它同时是 MCP 凭证)。
688
+ describe("daemon-shaped caller: existence branches are reachable", () => {
689
+ test("ack_start_request / ack_stop_request 不存在 ⇒ 恰好 {error:'request_not_found', ok:false}", async () => {
690
+ const D = { alias: "acl3-ack-daemon", node: "node_acl3_ack_daemon" };
691
+ seedAgent({ alias: D.alias, node: D.node });
692
+ const minted = createNetworkTokenForNode(adminId, NET, D.alias, D.node);
693
+ expect(minted.ok).toBe(true);
694
+ for (const [name, args] of [
695
+ ["ack_start_request", { request_id: "start_absent", status: "started" }],
696
+ ["ack_stop_request", { request_id: "stop_absent", status: "stopped" }],
697
+ ] as [string, Record<string, unknown>][]) {
698
+ const r = await tool(minted.token!, name, args);
699
+ expect(Object.keys(r).sort()).toEqual(["error", "ok"]);
700
+ expect(r).toEqual({ ok: false, error: "request_not_found" });
701
+ }
702
+
703
+ // 「存在,但不是我的」是**另一档**:这两档对调用方的下一步完全不同
704
+ // (前者去查 ID,后者去查令牌归属)。只钉其中一档时,把两档合并成一个错误码不会有东西变红。
705
+ db.run(`INSERT INTO node_start_requests
706
+ (request_id, network_id, daemon_node_id, child_node_id, child_alias, created_by_token, status, created_at)
707
+ VALUES (?1, ?2, ?3, ?4, ?5, 'test', 'pending', ?6)`,
708
+ ["start_someone_else", NET, "node_acl3_other_daemon", "node_acl3_other_child", "acl3-other-child", Date.now()]);
709
+ const foreign = await tool(minted.token!, "ack_start_request", { request_id: "start_someone_else", status: "started" });
710
+ expect(Object.keys(foreign).sort()).toEqual(["error", "ok"]);
711
+ expect(foreign).toEqual({ ok: false, error: "not_your_request" });
712
+
713
+ // 第三档:请求在**别的网络**里。它与「不是你的」同样是拒绝,但成因不同
714
+ // (一个跨租户,一个同租户不同节点)—— 合并成一个码就会把跨租户的信号抹掉。
715
+ db.run(`INSERT INTO node_start_requests
716
+ (request_id, network_id, daemon_node_id, child_node_id, child_alias, created_by_token, status, created_at)
717
+ VALUES (?1, ?2, ?3, ?4, ?5, 'test', 'pending', ?6)`,
718
+ // ⚠️ 判定顺序是:not_found → **not_your_request(daemon_node_id)** → cross_network_request(network_id)。
719
+ // 所以要让第三档可达,这一行的 daemon_node_id 必须**是我**,只有 network 不同 ——
720
+ // 我第一次填了别的 daemon,于是只到得了第二档(实测 not_your_request)。
721
+ ["start_other_network", "net_acl3_other_network", D.node, "node_x_child", "x-child", Date.now()]);
722
+ const cross = await tool(minted.token!, "ack_start_request", { request_id: "start_other_network", status: "started" });
723
+ expect(Object.keys(cross).sort()).toEqual(["error", "ok"]);
724
+ expect(cross).toEqual({ ok: false, error: "cross_network_request" });
725
+ });
726
+ });
727
+
728
+ // #3309 顺序维度 —— `get_*_request` 三条共用同一套判定顺序:
729
+ // not_found → not_your_request(daemon_node_id)→ cross_network_request(network_id)
730
+ // 顺序本身是安全属性:先答「在别的网络」会把「这个 id 属于另一个租户」告诉尚未确认身份的人。
731
+ describe("get_*_request: rejection order is the security property", () => {
732
+ test("别人的请求 ⇒ not_your_request;我的 daemon 但别的网络 ⇒ cross_network_request", async () => {
733
+ const D = { alias: "acl3-order-daemon", node: "node_acl3_order_daemon" };
734
+ seedAgent({ alias: D.alias, node: D.node });
735
+ const minted = createNetworkTokenForNode(adminId, NET, D.alias, D.node);
736
+ expect(minted.ok).toBe(true);
737
+ const now = Date.now();
738
+ // 唯一后缀:同一个 describe 里可能被多次执行(或与别的用例撞 id),主键冲突会掩盖真正的断言。
739
+ const U = Math.random().toString(36).slice(2, 8);
740
+ const cases: [string, string][] = [
741
+ ["get_start_request", "node_start_requests"],
742
+ ["get_stop_request", "node_stop_requests"],
743
+ ];
744
+ for (const [toolName, table] of cases) {
745
+ // 两张表的列**不完全是同一套**(node_stop_requests 多一个 NOT NULL 的 `action`)。
746
+ // ⇒ 按表分别构造列,而不是假设它们同形(实测:NOT NULL constraint failed: action)。
747
+ const extraCols = table === "node_stop_requests" ? ", action" : "";
748
+ const extraVals = table === "node_stop_requests" ? ", 'stop'" : "";
749
+ db.run(`INSERT INTO ${table}
750
+ (request_id, network_id, daemon_node_id, child_node_id, child_alias, created_by_token, status, created_at${extraCols})
751
+ VALUES (?1, ?2, ?3, ?4, ?5, 'test', 'pending', ?6${extraVals})`,
752
+ // ⚠️ 表上有 UNIQUE(child_node_id)(同一子节点只能有一条未结请求)⇒ 两行必须用不同子节点,
753
+ // 否则主键冲突会把断言掩盖成 db 报错(实测踩到:UNIQUE constraint failed: child_node_id)。
754
+ [`${toolName}_other_daemon_${U}`, NET, "node_acl3_other_daemon", `node_other_child_${U}`, "other-child", now]);
755
+ db.run(`INSERT INTO ${table}
756
+ (request_id, network_id, daemon_node_id, child_node_id, child_alias, created_by_token, status, created_at${extraCols})
757
+ VALUES (?1, ?2, ?3, ?4, ?5, 'test', 'pending', ?6${extraVals})`,
758
+ [`${toolName}_other_network_${U}`, "net_acl3_other_network", D.node, `node_cross_child_${U}`, "cross-child", now]);
759
+ const foreign = await tool(minted.token!, toolName, { request_id: `${toolName}_other_daemon_${U}` });
760
+ expect(foreign).toEqual({ ok: false, error: "not_your_request" });
761
+ const cross = await tool(minted.token!, toolName, { request_id: `${toolName}_other_network_${U}` });
762
+ expect(cross).toEqual({ ok: false, error: "cross_network_request" });
763
+ }
764
+ });
765
+ });
766
+
767
+ // #3309 顺序维度余 2 —— `node_create_requests` 的两条读/写面同样「归属先于租户」:
768
+ // not_found → not_your_request(daemon_node_id)→ cross_network_request(network_id)
769
+ describe("create-request reads/writes: same rejection order", () => {
770
+ test("get_create_request / ack_create_request:别人的 ⇒ not_your_request;别的网络 ⇒ cross_network_request", async () => {
771
+ const D = { alias: "acl3-cr-daemon", node: "node_acl3_cr_daemon" };
772
+ seedAgent({ alias: D.alias, node: D.node });
773
+ const minted = createNetworkTokenForNode(adminId, NET, D.alias, D.node);
774
+ expect(minted.ok).toBe(true);
775
+ const U = Math.random().toString(36).slice(2, 8);
776
+ const now = Date.now();
777
+ const ins = (id: string, net: string, daemon: string) =>
778
+ db.run(`INSERT INTO node_create_requests
779
+ (request_id, daemon_node_id, child_name, network_id, runtime, flags_json, env_keys, status, created_at, created_by_token)
780
+ VALUES (?1, ?2, ?3, ?4, 'opencode', '{}', '[]', 'awaiting_register', ?5, 'test')`,
781
+ [id, daemon, `child_${U}`, net, now]);
782
+ ins(`cr_other_daemon_${U}`, NET, "node_acl3_other_daemon");
783
+ ins(`cr_other_network_${U}`, "net_acl3_other_network", D.node);
784
+
785
+ for (const [toolName, extra] of [
786
+ ["get_create_request", {}],
787
+ ["ack_create_request", { status: "started" }],
788
+ ] as [string, Record<string, unknown>][]) {
789
+ const foreign = await tool(minted.token!, toolName, { request_id: `cr_other_daemon_${U}`, ...extra });
790
+ expect(foreign).toEqual({ ok: false, error: "not_your_request" });
791
+ const cross = await tool(minted.token!, toolName, { request_id: `cr_other_network_${U}`, ...extra });
792
+ expect(cross).toEqual({ ok: false, error: "cross_network_request" });
793
+ }
794
+ });
795
+ });
796
+
797
+ // #3309 分支 —— ack_create_request 的**两个成功出口**:键集相同 {ok,status},
798
+ // 但 status 的取值不同(started ⇒ "awaiting_register";failed ⇒ "failed")。
799
+ // 只钉键集时,「把两个分支合并成一个 status」不会有东西变红。
800
+ describe("ack_create_request: two success exits share keys, differ in value", () => {
801
+ test("started ⇒ awaiting_register;failed ⇒ failed", async () => {
802
+ const D = { alias: "acl3-ackcr-daemon", node: "node_acl3_ackcr_daemon" };
803
+ seedAgent({ alias: D.alias, node: D.node });
804
+ const minted = createNetworkTokenForNode(adminId, NET, D.alias, D.node);
805
+ expect(minted.ok).toBe(true);
806
+ const U = Math.random().toString(36).slice(2, 8);
807
+ // ⚠️ UNIQUE(daemon_node_id, child_name) ⇒ 两行必须用**不同子名**,
808
+ // 否则冲突会以「主键冲突」的样子出现,把断言掩盖成 db 报错。
809
+ const ins = (id: string, suffix: string) =>
810
+ db.run(`INSERT INTO node_create_requests
811
+ (request_id, daemon_node_id, child_name, network_id, runtime, flags_json, env_keys, status, created_at, created_by_token)
812
+ VALUES (?1, ?2, ?3, ?4, 'opencode', '{}', '[]', 'delivered', ?5, 'test')`,
813
+ [id, D.node, `child_${U}_${suffix}`, NET, Date.now()]);
814
+ ins(`cr_ackcr_started_${U}`, "s");
815
+ const started = await tool(minted.token!, "ack_create_request", { request_id: `cr_ackcr_started_${U}`, status: "started" });
816
+ expect(Object.keys(started).sort()).toEqual(["ok", "status"]);
817
+ expect(started).toEqual({ ok: true, status: "awaiting_register" });
818
+ ins(`cr_ackcr_failed_${U}`, "f");
819
+ const failed = await tool(minted.token!, "ack_create_request", { request_id: `cr_ackcr_failed_${U}`, status: "failed" });
820
+ expect(Object.keys(failed).sort()).toEqual(["ok", "status"]);
821
+ expect(failed).toEqual({ ok: true, status: "failed" });
654
822
  });
655
823
  });
656
824
 
@@ -0,0 +1,125 @@
1
+ // #3314 B 类 —— register / login 是**故意匿名**的两条路由(注册与登录本来就发生在
2
+ // 有身份之前),所以「有没有身份门」这个判据对它们不成立,它们的健康度只能从
3
+ // 「限流与锁定实际命中了几次、打到了几个不同来源」读出来。
4
+ //
5
+ // 这里钉的不是「计数器会增加」(那是平凡的),而是三件容易写错的事:
6
+ // ① 去重集合到顶后**不再增长但也不清零**,且置 capped —— 否则「新来源不再出现」
7
+ // 与「数到上限了」同值,而后者需要人去调上限,前者需要人去查攻击。
8
+ // ② 计数与去重数是**两个数**:命中数 ≫ 去重数 ⇒ 单点重试;两者接近 ⇒ 换 IP / 撒网。
9
+ // 只暴露命中数时,这两种完全同形。
10
+ // ③ 快照里**不含** IP 或用户名的值 —— 去重集合只活在进程内。
11
+
12
+ import { test, beforeEach } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import {
15
+ DISTINCT_CAP,
16
+ __resetAuthAbuseForTest,
17
+ authAbuseSnapshot,
18
+ noteLoginIpRateLimited,
19
+ noteLoginLocked,
20
+ noteRegisterRateLimited,
21
+ } from "./auth-abuse-counters.js";
22
+
23
+ beforeEach(() => __resetAuthAbuseForTest());
24
+
25
+ test("三条命中路径各自计数,互不串号", () => {
26
+ noteRegisterRateLimited("1.1.1.1");
27
+ noteLoginIpRateLimited("2.2.2.2");
28
+ noteLoginLocked("alice");
29
+
30
+ const s = authAbuseSnapshot();
31
+ assert.equal(s.register_rate_limited_total, 1);
32
+ assert.equal(s.login_ip_rate_limited_total, 1);
33
+ assert.equal(s.login_locked_total, 1);
34
+ assert.equal(s.distinct_register_limited_ips, 1);
35
+ assert.equal(s.distinct_login_limited_ips, 1);
36
+ assert.equal(s.distinct_locked_usernames, 1);
37
+ assert.equal(s.distinct_capped, false);
38
+ // register 与 login 的 IP 去重是**两份**:合并会让「哪个入口在被撞」变成一个数,
39
+ // 而两者的修法相反(前者限流键是 IP,后者靠用户名失败锁定)。
40
+ });
41
+
42
+ test("同一来源重复命中:命中数涨,去重数不涨", () => {
43
+ for (let i = 0; i < 5; i++) noteRegisterRateLimited("9.9.9.9");
44
+ const s = authAbuseSnapshot();
45
+ assert.equal(s.register_rate_limited_total, 5);
46
+ assert.equal(s.distinct_register_limited_ips, 1);
47
+ // 这个比值才是读数:5/1 ⇒ 单点重试,不是分布式。
48
+ });
49
+
50
+ test("撒网(每次换来源):命中数与去重数同步涨", () => {
51
+ for (let i = 0; i < 5; i++) noteRegisterRateLimited(`10.0.0.${i}`);
52
+ const s = authAbuseSnapshot();
53
+ assert.equal(s.register_rate_limited_total, 5);
54
+ assert.equal(s.distinct_register_limited_ips, 5);
55
+ // 5/5 ⇒ 限流键(IP)在这里是有效的;若换用户名做键,这一行就失效。
56
+ });
57
+
58
+ test("锁定命中按用户名去重:一个人被锁多次 = 1", () => {
59
+ for (let i = 0; i < 7; i++) noteLoginLocked("bob");
60
+ noteLoginLocked("carol");
61
+ const s = authAbuseSnapshot();
62
+ assert.equal(s.login_locked_total, 8);
63
+ assert.equal(s.distinct_locked_usernames, 2);
64
+ });
65
+
66
+ test("缺来源(null / undefined / 空串)仍计数,但不污染去重集合", () => {
67
+ noteRegisterRateLimited(null);
68
+ noteRegisterRateLimited(undefined);
69
+ noteRegisterRateLimited("");
70
+ const s = authAbuseSnapshot();
71
+ assert.equal(s.register_rate_limited_total, 3);
72
+ assert.equal(s.distinct_register_limited_ips, 0);
73
+ // 「来源不明」与「一个来源」不是同一个读数 —— 前者说明连 x-forwarded-for 都没有。
74
+ });
75
+
76
+ test("去重集合到顶:distinct 停在上限、capped 置真、命中数继续涨", () => {
77
+ for (let i = 0; i < DISTINCT_CAP + 50; i++) noteRegisterRateLimited(`ip-${i}`);
78
+ const s = authAbuseSnapshot();
79
+ assert.equal(s.distinct_register_limited_ips, DISTINCT_CAP);
80
+ assert.equal(s.distinct_capped, true);
81
+ assert.equal(s.register_rate_limited_total, DISTINCT_CAP + 50);
82
+ // 关键:capped 之后 distinct 是**下界**。没有这一位,「不再有新来源」与
83
+ // 「已经数满了」会显示成同一个数,而它们要做的事相反。
84
+ });
85
+
86
+ test("上限按「有没有真的丢过一条」判,不按「集合是否已满」", () => {
87
+ // 正好填满不是丢:distinct 仍然准确 ⇒ capped 必须是 false。
88
+ for (let i = 0; i < DISTINCT_CAP; i++) noteLoginIpRateLimited(`ip-${i}`);
89
+ let s = authAbuseSnapshot();
90
+ assert.equal(s.distinct_login_limited_ips, DISTINCT_CAP);
91
+ assert.equal(s.distinct_capped, false, "满员但没丢过 ⇒ 这些数还是真值");
92
+ // 再塞一条才会被拒 ⇒ 从这一刻起 distinct 变成下界。
93
+ noteLoginIpRateLimited("ip-overflow");
94
+ s = authAbuseSnapshot();
95
+ assert.equal(s.distinct_login_limited_ips, DISTINCT_CAP);
96
+ assert.equal(s.distinct_capped, true);
97
+ // 且 login 那份满员不影响 register 那份,也不影响用户名那份。
98
+ assert.equal(s.distinct_register_limited_ips, 0);
99
+ assert.equal(s.distinct_locked_usernames, 0);
100
+ });
101
+
102
+ test("快照形状固定(键集是契约,不是实现细节)", () => {
103
+ const keys = Object.keys(authAbuseSnapshot()).sort();
104
+ assert.deepEqual(keys, [
105
+ "distinct_capped",
106
+ "distinct_locked_usernames",
107
+ "distinct_login_limited_ips",
108
+ "distinct_register_limited_ips",
109
+ "login_ip_rate_limited_total",
110
+ "login_locked_total",
111
+ "register_rate_limited_total",
112
+ "since",
113
+ ]);
114
+ // 键集固定 ⇒ 加字段会让这条红。这是有意的:/health 的读者按名字取,
115
+ // 静默改名会让他们读到 undefined 而当作 0。
116
+ });
117
+
118
+ test("快照里没有来源本身(IP / 用户名)", () => {
119
+ noteRegisterRateLimited("203.0.113.7");
120
+ noteLoginLocked("erin");
121
+ const serialized = JSON.stringify(authAbuseSnapshot());
122
+ assert.equal(serialized.includes("203.0.113.7"), false);
123
+ assert.equal(serialized.includes("erin"), false);
124
+ // 计数可以公开,来源不行 —— 与 sessions_count 同一条取舍。
125
+ });
@@ -0,0 +1,111 @@
1
+ // 2026-11-01 —— #3314 B 类的读数:**故意匿名**的两条路由(register / login)没有身份门,
2
+ // 所以它们的健康度只能从「限流与锁定实际命中了几次」看出来。
3
+ //
4
+ // 为什么要有这个文件,而不是复用 logAudit:
5
+ // logAudit 写的是**事件**,一条一行,回答「刚才谁被拦了」;
6
+ // 这里记的是**计数与去重数**,回答的是两个结构性问题:
7
+ // ① register 的限流键是 IP ⇒ 命中数远大于去重 IP 数时,是同一个 IP 在撞;
8
+ // 去重 IP 数逼近命中数时,是「换 IP 绕过」在发生(即限流键选错了单位)。
9
+ // ② login 的失败锁定键是**用户名** ⇒ 命中数远大于去重用户名数时,是有人在锁死
10
+ // 某一个账号(针对单人的 DoS);去重用户名数远大于命中数则是撒网。
11
+ // 这两个问题都不是「有没有异常」,而是「键选得对不对」——只能用**比值**读出来。
12
+ //
13
+ // 隐私边界:只暴露计数与去重数,**永不暴露 IP 或用户名的值**。去重集合本身也不导出,
14
+ // 只在进程内存在;`distinct_*` 到顶后计数停止增长并置 capped=true,
15
+ // 这样「去重数不再涨」这件事本身不会被读成「没有新来源」。
16
+ //
17
+ // 已知偏差(写在读数旁边,不写在文档里):
18
+ // · 进程内计数,重启归零 ⇒ 与 /health 的 counters_since 同源,读之前先看 since。
19
+ // · 去重集合有上限(512)⇒ capped=true 时 distinct_* 是**下界**,不是真值。
20
+
21
+ export const DISTINCT_CAP = 512;
22
+
23
+ export interface AuthAbuseSnapshot {
24
+ since: string;
25
+ /** register 被 IP 限流拦截的次数 */
26
+ register_rate_limited_total: number;
27
+ /** login 被 IP 速率限制拦截的次数 */
28
+ login_ip_rate_limited_total: number;
29
+ /** login 被「用户名失败锁定」拦截的次数 */
30
+ login_locked_total: number;
31
+ /** 撞过 register 限流的**不同** IP 数(capped 时为下界) */
32
+ distinct_register_limited_ips: number;
33
+ /** 撞过 login IP 限流的**不同** IP 数(capped 时为下界) */
34
+ distinct_login_limited_ips: number;
35
+ /** 被失败锁定拦过的**不同**用户名数(capped 时为下界) */
36
+ distinct_locked_usernames: number;
37
+ /** 任一去重集合是否已到上限 ⇒ distinct_* 只是下界 */
38
+ distinct_capped: boolean;
39
+ }
40
+
41
+ interface State {
42
+ since: string;
43
+ registerRateLimited: number;
44
+ loginIpRateLimited: number;
45
+ loginLocked: number;
46
+ // 两份 IP 集合不是一个:register 的窗口与阈值(30/窗口)与 login 的双速率不同,
47
+ // 合并会让「哪个入口在被撞」变成一个数,而这两个入口的修法相反
48
+ // (register:键是 IP ⇒ 分布式刷注册有效;login:键是 IP + 用户名失败锁定)。
49
+ registerIps: Set<string>;
50
+ loginIps: Set<string>;
51
+ usernames: Set<string>;
52
+ capped: boolean;
53
+ }
54
+
55
+ function fresh(): State {
56
+ return {
57
+ since: new Date().toISOString(),
58
+ registerRateLimited: 0,
59
+ loginIpRateLimited: 0,
60
+ loginLocked: 0,
61
+ registerIps: new Set<string>(),
62
+ loginIps: new Set<string>(),
63
+ usernames: new Set<string>(),
64
+ capped: false,
65
+ };
66
+ }
67
+
68
+ let state: State = fresh();
69
+
70
+ function addBounded(set: Set<string>, value: string): void {
71
+ if (set.has(value)) return;
72
+ if (set.size >= DISTINCT_CAP) {
73
+ // 到顶不是「没有了」,是「不再数了」—— 所以必须留下 capped 这个痕迹。
74
+ state.capped = true;
75
+ return;
76
+ }
77
+ set.add(value);
78
+ }
79
+
80
+ export function noteRegisterRateLimited(ip: string | null | undefined): void {
81
+ state.registerRateLimited += 1;
82
+ if (ip) addBounded(state.registerIps, ip);
83
+ }
84
+
85
+ export function noteLoginIpRateLimited(ip: string | null | undefined): void {
86
+ state.loginIpRateLimited += 1;
87
+ if (ip) addBounded(state.loginIps, ip);
88
+ }
89
+
90
+ export function noteLoginLocked(username: string | null | undefined): void {
91
+ state.loginLocked += 1;
92
+ if (username) addBounded(state.usernames, username);
93
+ }
94
+
95
+ export function authAbuseSnapshot(): AuthAbuseSnapshot {
96
+ return {
97
+ since: state.since,
98
+ register_rate_limited_total: state.registerRateLimited,
99
+ login_ip_rate_limited_total: state.loginIpRateLimited,
100
+ login_locked_total: state.loginLocked,
101
+ distinct_register_limited_ips: state.registerIps.size,
102
+ distinct_login_limited_ips: state.loginIps.size,
103
+ distinct_locked_usernames: state.usernames.size,
104
+ distinct_capped: state.capped,
105
+ };
106
+ }
107
+
108
+ /** 只在测试里用:把计数清回起点。生产路径不调用。 */
109
+ export function __resetAuthAbuseForTest(): void {
110
+ state = fresh();
111
+ }
@@ -27,7 +27,16 @@ async function activate(){
27
27
  // status 一并回来,调用方不必再查一次「这条请求现在是什么状态」。
28
28
  expect(Object.keys(r).sort()).toEqual(["ok","request_id","status"]);
29
29
  expect(r.ok).toBe(true);
30
- expect((await ack(r.request_id)).status).toBe("active");return r.request_id;}
30
+ // #3275 批次 1·d —— ack_adopt_request 的成功回执形状:
31
+ // 源码里有两种(`{ok, key}` 与 `{ok, status}`),到底哪一种取决于这条请求是
32
+ // 「首次收养(要发 key)」还是「已有绑定代际」。只断言 .status 时,
33
+ // 把**带 key 的那个出口**顺手删掉/改名,不会有任何东西变红。
34
+ const acked = await ack(r.request_id);
35
+ // 实测两次都是 ["ok","status"](打印过);源码里那条 `{ok, key}` 出口走的是**另一条路径**
36
+ // (首次收养要下发 key),本夹具没走到。⇒ 这里钉住本夹具实际走的那个,**不声称两条都钉住**。
37
+ expect(Object.keys(acked).sort()).toEqual(["ok", "status"]);
38
+ expect(acked.status).toBe("active");
39
+ return r.request_id;}
31
40
  beforeAll(async()=>{
32
41
  ({db}=await import("./db.js"));
33
42
  const {register}=await import("./auth.js");
@@ -120,6 +120,13 @@ describe("clone_node — happy path (Hub #938)", () => {
120
120
  name: "cloned-child",
121
121
  network_id: NET,
122
122
  });
123
+ // #3275 批次 3 —— clone_node 是**最宽的**一张回执(8 键),因为它要同时描述:
124
+ // 新子节点(child_name / daemon_node_id)、这次下发的请求(request_id)、
125
+ // 以及两条**契约**(contract / session_contract)与目录策略(workdir_policy / copy_session)。
126
+ // 少掉 contract 类键 ⇒ 调用方会以为「子节点起来了就等于契约也过了」,而那是两件事。
127
+ expect(Object.keys(r).sort()).toEqual([
128
+ "child_name", "contract", "copy_session", "daemon_node_id", "ok", "request_id", "session_contract", "workdir_policy",
129
+ ]);
123
130
  // 2026-10-31 —— #3275:clone_node 的形状(此前只断言了散值)。
124
131
  // 8 键,其中 contract 是**给人读的三句话**、session_contract 是**给程序读的契约**:
125
132
  // contract { token, workdir, session } —— 三条「新开了什么」的散文
@@ -133,6 +133,15 @@ describe("#1353 Fix ① — hub gates create_node on daemon-reported can_create_
133
133
  });
134
134
  const t = tools();
135
135
  const r = await call(t.create_node, { daemon_node_id: DAEMON_ID, node_spec: spec });
136
+ // #3275 批次 4 —— 拒绝分支的实测闭集(**六键**,我按族推断的三键当场红):
137
+ // blocked_reason 为什么被挡(error 只回答「被挡了」)
138
+ // remediation_hint 下一步做什么(没有它,调用方只能停下来问人)
139
+ // capability_age / capability_observed_ms_ago / daemon_node_id
140
+ // —— 这三个回答「那个能力读数有多旧、是哪台 daemon 的」
141
+ // ⇒ 又一次「同族推断」错:这条拒绝路径比别的工具多三格**时间与归属**信息。
142
+ expect(Object.keys(r).sort()).toEqual([
143
+ "blocked_reason", "capability_age", "capability_observed_ms_ago", "daemon_node_id", "error", "ok", "remediation_hint",
144
+ ].sort());
136
145
  expect(r.ok).toBe(false);
137
146
  expect(r.error).toBe("daemon_cannot_create_nodes");
138
147
  expect(r.blocked_reason).toBe("anet_bin_permission");
@@ -180,7 +180,15 @@ test('application transport: scoped intent, capability gate, exact public receip
180
180
  expect((await daemon('ack_daemon_provider_snapshot', { request_id: r.request_id, application: bad })).error).toBe('invalid_application_receipt');
181
181
  }
182
182
  expect((await daemon('ack_daemon_provider_snapshot', { request_id: r.request_id, snapshot: snapshot() })).ok).toBe(false);
183
- expect((await daemon('ack_daemon_provider_snapshot', { request_id: r.request_id, application: receipt })).status).toBe('succeeded');
183
+ // #3275 批次 1·d —— 同变量口径 + 闭集:成功回执恰好 {ok, status};
184
+ // 而「重复 ack(非 pending)」走的是 {ok, status} 的**另一个值域**(status=已有状态),
185
+ // 只断言 .status 时,把两个出口合并、或给某一个出口多加一个键,都不会有东西变红。
186
+ const appliedAck = await daemon('ack_daemon_provider_snapshot', { request_id: r.request_id, application: receipt });
187
+ expect(Object.keys(appliedAck).sort()).toEqual(['ok', 'status']);
188
+ expect(appliedAck).toEqual({ ok: true, status: 'succeeded' });
189
+ const reAck = await daemon('ack_daemon_provider_snapshot', { request_id: r.request_id, failed: true });
190
+ expect(Object.keys(reAck).sort()).toEqual(['ok', 'status']);
191
+ expect(reAck).toEqual({ ok: true, status: 'succeeded' }); // 已终态 ⇒ 原样回读,不被改成 failed
184
192
  await daemon('ack_daemon_provider_snapshot', { request_id: r.request_id, failed: true });
185
193
  const read = await human('daemon_provider_snapshot', { action: 'read', id: r.request_id, network_id: net });
186
194
  expect(read.status).toBe('succeeded'); expect(read.application).toEqual(receipt); expect(read.snapshot).toBeNull();
@@ -61,6 +61,9 @@ beforeAll(async () => {
61
61
  const { bootServer } = await import("./server.js");
62
62
  hub = bootServer({ port: 0, hostname: "127.0.0.1" }); base = `http://127.0.0.1:${hub.port}`;
63
63
  const request = await call(owner.token, "request_adopt_node", { node_id: child, daemon_node_id: daemon, workdir: "/fixture/project" });
64
+ // #3275 批次 4 —— request_adopt_node 的外层三键(与 read_node_rules_file 同形:
65
+ // 「下发一个请求」这一族的统一形状)。status 一并回来,调用方不必再查一次。
66
+ expect(Object.keys(request).sort()).toEqual(["ok", "request_id", "status"]);
64
67
  expect(request.ok).toBe(true); requestId = request.request_id;
65
68
  }, 60000);
66
69
  afterAll(() => hub?.stop(true));
@@ -112,6 +115,24 @@ for (const [name, arguments_] of endpoints) {
112
115
  });
113
116
  }
114
117
 
118
+ // #3275 批次 1 —— 上面那个表驱动循环里工具名是**变量**,所以「同变量」统计口径按名字归因不到任何一个工具。
119
+ // 这不是测试写得不好,是**统计的粒度**问题:一条循环里的断言无法被归到被循环的那 N 个工具上。
120
+ // ⇒ 给 ack_create_request 补一条带字面量的:错误信封是闭集 {error, ok}。
121
+ //
122
+ // 批次 1·c 的结论(写在这里,因为它是这一批的**真实成本**:夹具不够,不是断言不够):
123
+ // 三个 `ack_*_request` 的失败分支闭集是 request_not_found / not_your_request /
124
+ // cross_network_request / caller_not_a_daemon。今天只有最后一条可达(上面的循环已钉住 {error,ok})。
125
+ // 前三条要么需要**绑定到 daemon 的** MCP 凭证(owner 令牌先撞 caller_not_a_daemon),
126
+ // 要么需要跨网络 daemon 凭证 —— 本夹具里的 `bound` 只用于 REST 侧 mint 测试,
127
+ // 拿它调 /mcp 直接非 200(实测),所以那条路走不通。
128
+ // ⇒ 批次 1·c 要先造一个「daemon 绑定 + MCP 可用」的凭证,再谈断言。
129
+ // 在那之前,任何「4 条失败分支已覆盖」的说法都是假的。
130
+ test("#3275 ack_create_request 的错误信封恰好 {error, ok}", async () => {
131
+ const denied = await call(owner.token, "ack_create_request", { request_id: "cr_fixture_absent", status: "started" });
132
+ expect(denied.ok).toBe(false);
133
+ expect(Object.keys(denied).sort()).toEqual(["error", "ok"]);
134
+ });
135
+
115
136
  test("legacy owner and exact bound identity remain supported", async () => {
116
137
  expect(db.get("SELECT bound_node_id FROM api_tokens WHERE token_id='owner678_legacy'").bound_node_id).toBeNull();
117
138
  for (const token of [legacy, bound]) {
@@ -156,12 +177,37 @@ test("legacy owner and exact bound identity remain supported", async () => {
156
177
  expect(gotProbe.ok).toBe(false);
157
178
  // 实测:错误分支多一个 reason(不是只 {error, ok})——**又一次由真实调用纠正**
158
179
  expect(Object.keys(gotProbe).sort()).toEqual(["error", "ok", "reason"]);
180
+ // #3309 分支 —— get_probe_request 的**成功出口**(此前只有不存在分支被钉)。
181
+ // `putPendingProbeSecret` 是导出的 ⇒ 直接把一条 probe 放进 Map 即可,不需要造真 probe 流程。
182
+ {
183
+ const { putPendingProbeSecret } = await import("./probe.js");
184
+ putPendingProbeSecret({
185
+ probe_id: "probe_fixture_live", daemon_node_id: daemon, provider_id: "prov_fixture",
186
+ vendor: "anthropic", base_url: "https://api.anthropic.com", model_name: "m",
187
+ api_key: `PROBE-SENTINEL-${Date.now()}`, network_id: owner.network_id,
188
+ });
189
+ const live = await call(legacy, "get_probe_request", { probe_id: "probe_fixture_live" });
190
+ // 实测六键。**注意 api_key 在里面** —— 这是本仓唯一一个「读面回传明文密钥」的出口,
191
+ // 它靠三条约束成立:① 只有目标 daemon 能取(cross-daemon guard)
192
+ // ② 取一次就删(takePendingProbeSecret)
193
+ // ③ 60s TTL
194
+ // ⇒ 断言里顺带把这三条的可观测面钉住:取走后第二次调用必须回到不存在分支。
195
+ expect(Object.keys(live).sort()).toEqual(["api_key", "base_url", "model_name", "ok", "probe_id", "vendor"]);
196
+ expect(live.ok).toBe(true);
197
+ const again = await call(legacy, "get_probe_request", { probe_id: "probe_fixture_live" });
198
+ expect(again).toEqual({ ok: false, error: "probe_request_unavailable", reason: "not_found_or_wrong_daemon_or_expired" });
199
+ }
200
+
159
201
  // 2026-10-31 —— #3275:get_opencode_catalog_request 的**不存在**分支恰好两键
160
202
  // (与 get_probe_request 的三键不同族 —— 又一次说明「错误信封不是全仓一个形状」)
161
203
  const gotCatalog = await call(legacy, "get_opencode_catalog_request", { request_id: "cat_fixture_absent" });
162
204
  expect(gotCatalog.ok).toBe(false);
163
205
  expect(Object.keys(gotCatalog).sort()).toEqual(["error", "ok"]);
164
206
  const stop = await call(owner.token, "stop_node", { node_id: child, network_id: owner.network_id });
207
+ // #3275 批次 2·f —— stop_node 的外层(实测)。比 start_node 多两个键:
208
+ // `action` 说明触发的是哪条路径(restart_node 走同一条),`in_flight_at_dispatch` 说明
209
+ // **下发那一刻**手上还有几条任务 —— 少了它,客户端无法区分「干净停机」与「截断在跑的任务」。
210
+ expect(Object.keys(stop).sort()).toEqual(["action", "in_flight_at_dispatch", "lifecycle_state", "ok", "request_id"]);
165
211
  expect(stop.ok).toBe(true);
166
212
  // 2026-10-31 —— #3275 批次 2:get_stop_request 的**成功体**键集(daemon 按字段名读,
167
213
  // 尤其 delete_config / grace_seconds / force 三个决定它要不要删配置)
@@ -174,6 +220,9 @@ test("legacy owner and exact bound identity remain supported", async () => {
174
220
  expect(stoppedAck.ok).toBe(true);
175
221
  expect(Object.keys(stoppedAck).sort()).toEqual(["ok", "status"]); // #3275:成功体键集
176
222
  const start = await call(owner.token, "start_node", { node_id: child, network_id: owner.network_id });
223
+ // start_node 只有四个键:**它没有 in_flight_at_dispatch** ——
224
+ // 因为「启动时手上还有几条任务」不是一个有意义的问题。两个工具同名不同形,各自量。
225
+ expect(Object.keys(start).sort()).toEqual(["lifecycle_state", "ok", "request_id"]);
177
226
  expect(start.ok).toBe(true);
178
227
  const gotStart = await call(legacy, "get_start_request", { request_id: start.request_id });
179
228
  expect(gotStart.ok).toBe(true);
@@ -208,6 +257,11 @@ test("new name-only registration binds once and its holder can refresh with eith
208
257
  const result = await call(first.body.token, "report_status", {
209
258
  resume_id: "refresh-fixture-session", alias: "refresh_fixture", status: "idle", node_id: "n_refresh_fixture",
210
259
  });
260
+ // #3275 批次 2 —— 同变量口径,形状由一次真实调用给出:
261
+ // ["alias","inbox_count","ok","resume_id"]
262
+ // 少一个 `inbox_count`,客户端就再也不知道「还有几条待办」——而它正是每轮心跳唯一的推送面;
263
+ // 少一个 `alias`,多网络下的会话就认不出自己是谁。只断言 ok 时,这两个都能被悄悄删掉。
264
+ expect(Object.keys(result).sort()).toEqual(["alias", "inbox_count", "ok", "resume_id"]);
211
265
  expect(result.ok).toBe(true);
212
266
  expect(db.get("SELECT bound_node_id FROM api_tokens WHERE token_id=?1", first.body.token_id).bound_node_id).toBe("n_refresh_fixture");
213
267
  expect(db.get("SELECT owner_user_id FROM nodes WHERE node_id='n_refresh_fixture'").owner_user_id).toBeNull();
@@ -115,9 +115,16 @@ describe("#2822 部门 → Agent 计数走 nodes.department_id(轴2)", () =>
115
115
  await client.connect(ct);
116
116
  try {
117
117
  const raw: any = await client.callTool({ name: "departments", arguments: { action: "list" } });
118
+ // #3275 批次 4 —— 信封断言紧挨调用(工具名与断言在同一段,统计口径才认):
119
+ // MCP 结果恰好一个 content 字段;负载五键见下一段。
120
+ expect(Object.keys(raw).sort()).toEqual(["content"]);
118
121
  const mcp = JSON.parse(String(raw.content?.[0]?.text ?? "{}"));
119
122
  // 2026-10-31 —— **精确键集**(#3171):紧挨调用写,且单行(键集断言被任何换行拆开时,
120
123
  // 静态计数器就读不到它 —— 而读不到与没写同形)。实际五键,我第一版只写了三个。
124
+ // #3275 批次 4 —— 上面那条断言钉的是**解析后的负载**(mcp),而工具名在 `raw` 那行;
125
+ // 两者是同一次调用,但断言对象不是同一个变量 ⇒ 统计口径归因不到。
126
+ // 补一条**信封**断言(raw 就是那次调用的返回值):MCP 结果恰好一个 content 字段。
127
+ expect(Object.keys(raw).sort()).toEqual(["content"]);
121
128
  expect(Object.keys(mcp).sort()).toEqual(["agents", "departments", "network_id", "ok", "unassigned_agents"]);
122
129
  const http = (await send(TOKEN, "GET", D())).body;
123
130
  const httpByName = new Map<string, any>((http.departments as any[]).map((d) => [d.name, d]));