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

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.
Files changed (42) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/agent-acl-http.test.ts +5 -0
  4. package/src/agent-acl-slice3-http.test.ts +168 -0
  5. package/src/api-nodes-shape.test.ts +38 -2
  6. package/src/auth-abuse-counters.test.ts +125 -0
  7. package/src/auth-abuse-counters.ts +122 -0
  8. package/src/binding-generation-http.test.ts +10 -1
  9. package/src/clone-node.test.ts +7 -0
  10. package/src/create-node-blocked-gate.test.ts +9 -0
  11. package/src/create-node-error-domain.test.ts +124 -0
  12. package/src/daemon-provider-snapshots.test.ts +9 -1
  13. package/src/daemon-token-owner-http.test.ts +54 -0
  14. package/src/departments-agent-count.test.ts +7 -0
  15. package/src/departments-mcp-error-domain.test.ts +135 -0
  16. package/src/expiry-counters.ts +6 -2
  17. package/src/expiry-evidence-db.test.ts +15 -0
  18. package/src/inbox-count-sse.test.ts +8 -0
  19. package/src/list-ack-error-domain.test.ts +108 -0
  20. package/src/mcp-projects-events-http.test.ts +3 -0
  21. package/src/mcp-write-network-resolution.test.ts +15 -0
  22. package/src/network-scope.ts +24 -0
  23. package/src/node-daemon-bindings.test.ts +12 -2
  24. package/src/node-files-transport.test.ts +3 -0
  25. package/src/node-logs-transport.test.ts +3 -0
  26. package/src/node-security-write-gate.test.ts +72 -0
  27. package/src/probe-provider-error-domain.test.ts +141 -0
  28. package/src/provider-skill-error-domain.test.ts +130 -0
  29. package/src/provider-tools-shape.test.ts +16 -1
  30. package/src/requirement-participant-notify-http.test.ts +4 -0
  31. package/src/requirements-mcp.test.ts +17 -1
  32. package/src/rules-file-transport.test.ts +38 -4
  33. package/src/schedule-agent-mcp-http.test.ts +12 -1
  34. package/src/scheduled-requirement-wake-http.test.ts +5 -1
  35. package/src/server.ts +25 -5
  36. package/src/skillhub-http.test.ts +4 -2
  37. package/src/start-request-error-domain.test.ts +182 -0
  38. package/src/start-skill-error-domain.test.ts +122 -0
  39. package/src/task-consumption.test.ts +6 -0
  40. package/src/task-idempotency-mcp.test.ts +6 -0
  41. package/src/task-not-found-error-domain.test.ts +76 -0
  42. package/src/update-node-config-error-domain.test.ts +107 -0
package/build-info.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "85c2c13a74f794a2328b373862a79758a8a7da14",
3
+ "commit": "152b8ef41668466983af07b1764447a451bd3cea",
4
4
  "dirty": false,
5
- "built_at": "2026-10-31T23:00:27.804Z",
5
+ "built_at": "2026-11-01T02:15:37.070Z",
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.259",
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
 
@@ -38,6 +38,7 @@ function mapRow(r: Record<string, unknown>): Record<string, unknown> {
38
38
  let role: string | null = null;
39
39
  // #2293 —— 与 handler 同一套读法:快照可能是文本或对象;解析失败/形状不对 = 这一格没有。
40
40
  let opencodeCatalog: string[] | null = null;
41
+ let opencodeCatalogSeenAt: string | null = null;
41
42
  let opencodeGeneration: "v1" | "v2" | null = null;
42
43
  let opencodeMode: string | null = null;
43
44
  let opencodeServer: string | null = null;
@@ -50,6 +51,9 @@ function mapRow(r: Record<string, unknown>): Record<string, unknown> {
50
51
  const raw = parsed?.opencode_catalog;
51
52
  if (Array.isArray(raw) && raw.every((m: unknown) => typeof m === "string" && m.length <= 400)) {
52
53
  opencodeCatalog = raw.slice(0, 400);
54
+ // #3144 —— 目录是快照:没有采集时刻的话,51 个模型是刚才的还是三周前的分不出。
55
+ const seen = parsed?.opencode_catalog_seen_at;
56
+ opencodeCatalogSeenAt = typeof seen === "string" && seen.length > 0 && seen.length <= 40 ? seen : null;
53
57
  }
54
58
  const flags = parsed?.flags;
55
59
  if (flags?.opencodeGeneration === "v1" || flags?.opencodeGeneration === "v2") opencodeGeneration = flags.opencodeGeneration;
@@ -63,12 +67,42 @@ function mapRow(r: Record<string, unknown>): Record<string, unknown> {
63
67
  attrs_revision: Number(r.attrs_revision ?? 0),
64
68
  role,
65
69
  opencode_catalog: opencodeCatalog,
70
+ opencode_catalog_seen_at: opencodeCatalogSeenAt,
66
71
  opencode_generation: opencodeGeneration,
67
72
  opencode_mode: opencodeMode,
68
73
  opencode_server: opencodeServer,
69
74
  };
70
75
  }
71
76
 
77
+ describe("#3144 opencode_catalog_seen_at —— 三态,不塌成两种", () => {
78
+ // daemon 报了就带出来;没报就是 null。null 的含义是「未上报」,**不是**「很久以前」,
79
+ // 也不是「刚刚」——把两者塌成同一个值,客户端就只能显示一个它并不知道的时刻。
80
+ test("有 opencode_catalog_seen_at ⇒ 原样投影", () => {
81
+ const row = mapRow({
82
+ node_id: "n1", node_name: "n", alias: "n", runtime: "opencode-sdk", model: "m",
83
+ config_path: null, channels: null, server: null, hostname: null,
84
+ network_id: "net", created_at: "x", updated_at: "x", display_name: null,
85
+ team: null, tags: null, attrs_revision: 0,
86
+ config_snapshot: JSON.stringify({
87
+ opencode_catalog: ["a/b"], opencode_catalog_seen_at: "2026-11-01T02:00:00Z",
88
+ }),
89
+ });
90
+ expect(row.opencode_catalog_seen_at).toBe("2026-11-01T02:00:00Z");
91
+ });
92
+
93
+ test("没有那个字段 ⇒ null(不是空串、不是当前时间)", () => {
94
+ const row = mapRow({
95
+ node_id: "n2", node_name: "n", alias: "n", runtime: "opencode-sdk", model: "m",
96
+ config_path: null, channels: null, server: null, hostname: null,
97
+ network_id: "net", created_at: "x", updated_at: "x", display_name: null,
98
+ team: null, tags: null, attrs_revision: 0,
99
+ config_snapshot: JSON.stringify({ opencode_catalog: ["a/b"] }),
100
+ });
101
+ expect(row.opencode_catalog).toEqual(["a/b"]);
102
+ expect(row.opencode_catalog_seen_at).toBeNull();
103
+ });
104
+ });
105
+
72
106
  describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", () => {
73
107
  test("explicit columns + role extracted: config_snapshot NOT in response, role IS", () => {
74
108
  // Insert a row with the leak-prone columns populated. Use INSERT OR
@@ -102,7 +136,8 @@ describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", (
102
136
  // Expected fields present (13 = 12 contract + new role)
103
137
  for (const k of ["node_id", "node_name", "alias", "runtime", "model",
104
138
  "config_path", "channels", "server", "hostname",
105
- "network_id", "created_at", "updated_at", "role", "opencode_catalog"]) {
139
+ "network_id", "created_at", "updated_at", "role", "opencode_catalog",
140
+ "opencode_catalog_seen_at"]) {
106
141
  expect(row).toHaveProperty(k);
107
142
  }
108
143
  // Internal fields NOT present
@@ -119,7 +154,8 @@ describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", (
119
154
  expect(Object.keys(row).sort()).toEqual([
120
155
  "alias", "attrs_revision", "channels", "config_path", "created_at",
121
156
  "display_name", "hostname", "model", "network_id", "node_id",
122
- "node_name", "opencode_catalog", "opencode_generation", "opencode_mode",
157
+ "node_name", "opencode_catalog", "opencode_catalog_seen_at",
158
+ "opencode_generation", "opencode_mode",
123
159
  "opencode_server", "role", "runtime", "server", "tags", "team",
124
160
  "updated_at",
125
161
  ]);
@@ -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,122 @@
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
+ // · 🔴 **本机来源下这三个计数恒为 0,而且那不是「没有被滥用」。**
21
+ // `checkRateLimit()` 对 `127.0.0.1` / `::1` / `""` / `"unknown"` 直接 `return true`
22
+ // (server.ts:249,为 dev/test 留的口子),于是 register 的限流分支根本不会走到。
23
+ // 实测(`0.9.0-preview.258` 的制品,本地起在 9311):
24
+ // · 不带 X-Forwarded-For 打 36 次注册 ⇒ 全部 200,register_rate_limited_total 仍是 0
25
+ // · 带 `X-Forwarded-For: 203.0.113.9` 打 34 次 ⇒ 30×200 + 4×429,
26
+ // register_rate_limited_total = 4、distinct_register_limited_ips = 1(**逐次对得上**)
27
+ // · 带 `X-Forwarded-For: 203.0.113.77` 用同一个用户名错 8 次 ⇒ 5×401 + 3×429,
28
+ // login_locked_total = 3、distinct_locked_usernames = 1
29
+ // ⇒ 所以「本地读到 0」是一个结构性假阴性:要见证必须模拟外部来源(XFF),
30
+ // 否则 0 会被读成「没有滥用」,而它其实只说明「限流器跳过了本机」。
31
+
32
+ export const DISTINCT_CAP = 512;
33
+
34
+ export interface AuthAbuseSnapshot {
35
+ since: string;
36
+ /** register 被 IP 限流拦截的次数 */
37
+ register_rate_limited_total: number;
38
+ /** login 被 IP 速率限制拦截的次数 */
39
+ login_ip_rate_limited_total: number;
40
+ /** login 被「用户名失败锁定」拦截的次数 */
41
+ login_locked_total: number;
42
+ /** 撞过 register 限流的**不同** IP 数(capped 时为下界) */
43
+ distinct_register_limited_ips: number;
44
+ /** 撞过 login IP 限流的**不同** IP 数(capped 时为下界) */
45
+ distinct_login_limited_ips: number;
46
+ /** 被失败锁定拦过的**不同**用户名数(capped 时为下界) */
47
+ distinct_locked_usernames: number;
48
+ /** 任一去重集合是否已到上限 ⇒ distinct_* 只是下界 */
49
+ distinct_capped: boolean;
50
+ }
51
+
52
+ interface State {
53
+ since: string;
54
+ registerRateLimited: number;
55
+ loginIpRateLimited: number;
56
+ loginLocked: number;
57
+ // 两份 IP 集合不是一个:register 的窗口与阈值(30/窗口)与 login 的双速率不同,
58
+ // 合并会让「哪个入口在被撞」变成一个数,而这两个入口的修法相反
59
+ // (register:键是 IP ⇒ 分布式刷注册有效;login:键是 IP + 用户名失败锁定)。
60
+ registerIps: Set<string>;
61
+ loginIps: Set<string>;
62
+ usernames: Set<string>;
63
+ capped: boolean;
64
+ }
65
+
66
+ function fresh(): State {
67
+ return {
68
+ since: new Date().toISOString(),
69
+ registerRateLimited: 0,
70
+ loginIpRateLimited: 0,
71
+ loginLocked: 0,
72
+ registerIps: new Set<string>(),
73
+ loginIps: new Set<string>(),
74
+ usernames: new Set<string>(),
75
+ capped: false,
76
+ };
77
+ }
78
+
79
+ let state: State = fresh();
80
+
81
+ function addBounded(set: Set<string>, value: string): void {
82
+ if (set.has(value)) return;
83
+ if (set.size >= DISTINCT_CAP) {
84
+ // 到顶不是「没有了」,是「不再数了」—— 所以必须留下 capped 这个痕迹。
85
+ state.capped = true;
86
+ return;
87
+ }
88
+ set.add(value);
89
+ }
90
+
91
+ export function noteRegisterRateLimited(ip: string | null | undefined): void {
92
+ state.registerRateLimited += 1;
93
+ if (ip) addBounded(state.registerIps, ip);
94
+ }
95
+
96
+ export function noteLoginIpRateLimited(ip: string | null | undefined): void {
97
+ state.loginIpRateLimited += 1;
98
+ if (ip) addBounded(state.loginIps, ip);
99
+ }
100
+
101
+ export function noteLoginLocked(username: string | null | undefined): void {
102
+ state.loginLocked += 1;
103
+ if (username) addBounded(state.usernames, username);
104
+ }
105
+
106
+ export function authAbuseSnapshot(): AuthAbuseSnapshot {
107
+ return {
108
+ since: state.since,
109
+ register_rate_limited_total: state.registerRateLimited,
110
+ login_ip_rate_limited_total: state.loginIpRateLimited,
111
+ login_locked_total: state.loginLocked,
112
+ distinct_register_limited_ips: state.registerIps.size,
113
+ distinct_login_limited_ips: state.loginIps.size,
114
+ distinct_locked_usernames: state.usernames.size,
115
+ distinct_capped: state.capped,
116
+ };
117
+ }
118
+
119
+ /** 只在测试里用:把计数清回起点。生产路径不调用。 */
120
+ export function __resetAuthAbuseForTest(): void {
121
+ state = fresh();
122
+ }
@@ -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");