@sleep2agi/commhub-server 0.9.0-preview.220 → 0.9.0-preview.222

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.220",
3
+ "version": "0.9.0-preview.222",
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",
@@ -12,7 +12,7 @@
12
12
  // 判据:写一个允许清单的默认值之前,先写出它的**最松值**。
13
13
  // 这里最松值不是空(空 = 谁都不许 = 最严),而是 `*`。所以空绝不能被读成「用默认」。
14
14
  import { describe, expect, test } from "bun:test";
15
- import { parseCorsOrigins } from "./server.js";
15
+ import { normalizeOrigin, parseCorsOrigins } from "./server.js";
16
16
 
17
17
  describe("parseCorsOrigins: 未设 / 设空 / 设值 三态", () => {
18
18
  test("未设 ⇒ 开发默认(localhost 两个端口)", () => {
@@ -31,10 +31,26 @@ describe("parseCorsOrigins: 未设 / 设空 / 设值 三态", () => {
31
31
  expect(parseCorsOrigins("https://a.example,")).toEqual(["https://a.example"]);
32
32
  });
33
33
 
34
- test("must-fire:'*' 不会被当成通配(本实现是精确匹配清单)", () => {
35
- // 如果哪天有人把 '*' 当通配实现,这条仍会过 —— 但 corsHeaders 用的是 includes,
36
- // 所以这里钉的是「清单里有什么就是什么」,不是「* 有特殊含义」。
37
- expect(parseCorsOrigins("*")).toEqual(["*"]);
34
+ // 2026-10-31 —— **语义变更(更严)**:非法条目现在被丢弃,而不是原样保留。
35
+ // 旧实现保留 "*",于是运行期 `includes(origin)` 永远不命中 ——
36
+ // 「保留一条永不匹配的项」与「丢弃它」在行为上相同,但前者会让运维以为已经放行。
37
+ test("非法条目被丢弃('*' / 裸主机名 / 非 http(s))", () => {
38
+ expect(parseCorsOrigins("*")).toEqual([]);
39
+ expect(parseCorsOrigins("a.example")).toEqual([]);
40
+ expect(parseCorsOrigins("ftp://a.example")).toEqual([]);
38
41
  expect(parseCorsOrigins(undefined)).not.toContain("*");
39
42
  });
43
+
44
+ // 外部复核 ①:`https://host` 与 `https://host:443` 在字符串上不等、在 origin 上相等。
45
+ test("默认端口与大小写被规范化 —— 字符串比较会在这里判不同", () => {
46
+ expect(normalizeOrigin("https://A.Example:443")).toBe("https://a.example");
47
+ expect(normalizeOrigin("https://a.example")).toBe("https://a.example");
48
+ expect(normalizeOrigin("http://a.example:80")).toBe("http://a.example");
49
+ expect(normalizeOrigin("https://a.example:8443")).toBe("https://a.example:8443");
50
+ expect(normalizeOrigin("https://a.example/")).toBe("https://a.example");
51
+ // 清单写成带默认端口 ⇒ 规范化后与不带端口的请求相等(这正是那批「地址栏正常却全 403」的用户)
52
+ expect(parseCorsOrigins("https://a.example:443")).toEqual(["https://a.example"]);
53
+ // 去重:同一 origin 的两种写法只留一条
54
+ expect(parseCorsOrigins("https://a.example,https://a.example:443/")).toEqual(["https://a.example"]);
55
+ });
40
56
  });
@@ -1030,6 +1030,30 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1030
1030
  // 它却一直躺在那里,看起来「这个字段是公开的」⇒ 下一个人把同名字段加回来时**默认就是公开的**。
1031
1031
  // ⇒ 白名单会从「审批记录」退化成「历史残留」。
1032
1032
  // 这与今晚那条镜像规则同构:否定断言必须配肯定断言,否则前者可被「永远不给」满足。
1033
+ // 2026-10-31 —— **2×2 的第四格**(外部复核 (e):「等价性断言必须按 (通道 × 配置) 组合进行」)。
1034
+ // 本仓的 /health 有两个维度:谁在读(匿名 / 鉴权)× 有没有带 X-Probe-Nonce。
1035
+ // 前面只覆盖了三格(匿名、匿名+探针、鉴权),**鉴权+探针**这一格没测过 ——
1036
+ // 而它正是「探针回显会不会被鉴权分支吃掉」的唯一读数。
1037
+ test("all four cells of (audience × probe-header) carry the fields they must", async () => {
1038
+ const anon = await (await fetch(`${BASE}/health`)).json() as any;
1039
+ const anonProbe = await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": "cell-anon" } })).json() as any;
1040
+ const authed = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
1041
+ const authedProbe = await (await fetch(`${BASE}/health`, {
1042
+ headers: { Authorization: `Bearer ${adminToken}`, "X-Probe-Nonce": "cell-authed" },
1043
+ })).json() as any;
1044
+
1045
+ // 探针格:带头的两格都必须回显 nonce,且 served_at 都在(窗口两端同域)
1046
+ expect(anonProbe.probe_nonce).toBe("cell-anon");
1047
+ expect(authedProbe.probe_nonce).toBe("cell-authed");
1048
+ for (const body of [anon, anonProbe, authed, authedProbe]) {
1049
+ expect(typeof body.served_at).toBe("string");
1050
+ }
1051
+ // 不带头的一格不该出现 probe_nonce(否则「这一次的凭据」变成常驻字段)
1052
+ expect("probe_nonce" in anon).toBe(false);
1053
+ // 鉴权格必须比匿名格多(否则白名单形同虚设)——第四格同样成立
1054
+ expect(Object.keys(authedProbe).length).toBeGreaterThan(Object.keys(anonProbe).length);
1055
+ });
1056
+
1033
1057
  test("no dead entries: every allow-listed key is actually served to anonymous callers", async () => {
1034
1058
  const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
1035
1059
  const plain = await (await fetch(`${BASE}/health`)).json() as any;
@@ -1037,6 +1061,15 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1037
1061
  const probed = await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": "dead-entry-check" } })).json() as any;
1038
1062
  const seen = new Set([...Object.keys(plain), ...Object.keys(probed)]);
1039
1063
  const dead = [...PUBLIC_HEALTH_KEYS].filter((k) => !seen.has(k));
1064
+ // 2026-10-31 —— 失败时必须点名(外部复核 ③):只说 `toEqual([])` 的失败信息里
1065
+ // 没有「是哪几个键」,而修它需要的正是那几个名字。
1066
+ if (dead.length) {
1067
+ throw new Error(
1068
+ `白名单里有 ${dead.length} 个键在任何投影里都不出现(死条目):${dead.join(", ")}\n` +
1069
+ " ⇒ 要么从 PUBLIC_HEALTH_KEYS 删掉,要么让 body 真的产出它;" +
1070
+ "留着等于给未来的同名字段预授权。",
1071
+ );
1072
+ }
1040
1073
  expect(dead).toEqual([]);
1041
1074
  });
1042
1075
 
@@ -109,6 +109,24 @@ afterAll(() => {
109
109
  try { rmSync(DIR, { recursive: true, force: true }); } catch {}
110
110
  });
111
111
 
112
+ // 2026-10-31 —— **穷尽映射的运行时钉**(外部复核 (c):「应改成 Record<ErrorCode, number> 由 tsc 报红」)。
113
+ // 本仓 server 没有 tsc 门(只有 agent-network 在 e2e-docker 里 typecheck),
114
+ // 所以那条约束只有写成运行时断言才真的存在:
115
+ // 码集合 = TAG_CREATE_ERRORS(唯一来源)|映射键必须与它逐字相等|每个值必须是合法 HTTP 状态
116
+ test("tag create: every error code has a status, and nothing else does", async () => {
117
+ const { TAG_CREATE_ERRORS, TAG_CREATE_STATUS } = await import("./requirements.js");
118
+ expect(Object.keys(TAG_CREATE_STATUS).sort()).toEqual([...TAG_CREATE_ERRORS].sort());
119
+ for (const code of TAG_CREATE_ERRORS) {
120
+ const status = TAG_CREATE_STATUS[code];
121
+ expect(Number.isInteger(status)).toBe(true);
122
+ expect(status).toBeGreaterThanOrEqual(400);
123
+ expect(status).toBeLessThan(500);
124
+ }
125
+ // 反例守卫:默认分支的「未映射 ⇒ 400」不许再出现(那正是被替换掉的那行)
126
+ const src = await (await import("node:fs")).readFileSync(new URL("./requirements.ts", import.meta.url), "utf8");
127
+ expect(src).not.toMatch(/result\.error === "tag_exists" \? 409/);
128
+ });
129
+
112
130
  describe("GET /api/requirements/tags", () => {
113
131
  test("owner:tags 仍是排序后的字符串数组(旧 App 形状不变),多出 counts / colors / can_manage", async () => {
114
132
  const r = await tagsOf(admin.token);
@@ -683,8 +683,29 @@ function networkTagNames(networkId: string): Set<string> {
683
683
  return names;
684
684
  }
685
685
 
686
+ /**
687
+ * 2026-10-31 —— **状态码是 code 的函数,映射表必须穷尽**(外部复核 (c):
688
+ * 「三元式默认分支 = 未映射与某个真实含义同值 ⇒ 口令字段;应改成
689
+ * `Record<ErrorCode, number>` 由 tsc 报红」)。
690
+ *
691
+ * 原来是 `code === "tag_exists" ? 409 : code === "tag_parent_not_found" ? 404 : 400`:
692
+ * 新增一个错误码时它**默认落到 400**,而有些码 400 是错的(冲突应是 409),且没人会提醒你。
693
+ * 改成穷尽表之后,漏一个码 = tsc 红。
694
+ */
695
+ // 2026-10-31 —— **本仓 server 没有 tsc 门**(只有 agent-network 在 e2e-docker 里 typecheck),
696
+ // 所以「漏一个码 = tsc 红」在这里是空头支票。⇒ 用运行时钉住:
697
+ // 码集合由这个数组当**唯一来源**,测试断言映射表的键与它逐字相等。
698
+ // 这样新增一个码只改一处(数组),而「忘了加 status」会红在测试里,不依赖编辑器。
699
+ export const TAG_CREATE_ERRORS = ["tag_exists", "tag_parent_not_found", "tag_depth_exceeded"] as const;
700
+ export type TagCreateError = (typeof TAG_CREATE_ERRORS)[number];
701
+ export const TAG_CREATE_STATUS: Record<TagCreateError, number> = {
702
+ tag_exists: 409,
703
+ tag_parent_not_found: 404,
704
+ tag_depth_exceeded: 400,
705
+ };
706
+
686
707
  type CreateTagOutcome =
687
- | { error: "tag_exists" | "tag_parent_not_found" | "tag_depth_exceeded" }
708
+ | { error: TagCreateError }
688
709
  | { name: string; parent: string | null; depth: number; parentRegistered: boolean };
689
710
 
690
711
  /** POST /api/requirements/tags/create —— 建标签(可带父)。原子、整网络判重、父不存在就报错。 */
@@ -724,8 +745,7 @@ async function handleTagCreate(ctx: RequirementsRequestContext): Promise<Respons
724
745
  return { name: input.name, parent: input.parent, depth: tagDepth(input.name, parentOf), parentRegistered };
725
746
  });
726
747
  if ("error" in result) {
727
- const status = result.error === "tag_exists" ? 409 : result.error === "tag_parent_not_found" ? 404 : 400;
728
- return jsonError(result.error, status);
748
+ return jsonError(result.error, TAG_CREATE_STATUS[result.error]);
729
749
  }
730
750
  if (ctx.auth) logAudit(ctx.auth.userId, ctx.auth.username || null, "requirement_tag_create", "requirement_tag", result.name, JSON.stringify({ parent_id: result.parent, depth: result.depth }).slice(0, 1000), undefined, networkId);
731
751
  return Response.json({ ok: true, tag: { name: result.name, parent_id: result.parent, depth: result.depth }, parent_registered: result.parentRegistered }, { status: 201 });
package/src/server.ts CHANGED
@@ -921,9 +921,36 @@ const BroadcastSchema = z.object({
921
921
  * 这是「空必须落在更严的一侧」在本字段上的具体落点:
922
922
  * 这个字段的**最松值**不是空,而是 `*`;所以空不能被读成「用默认」。
923
923
  */
924
+ /**
925
+ * 2026-10-31 —— **Origin 必须「解析后比较」,不能「字符串比较」**
926
+ * (外部复核 ①:`https://host` 与 `https://host:443` 在字符串上不等,在 origin 上相等;
927
+ * 若按字符串比,那一批用户全部被 CORS 挡掉,而他们的地址栏看起来完全正常)。
928
+ *
929
+ * `new URL(x).origin` 做的正是规范化:主机小写、**丢弃默认端口**、去掉尾斜杠与路径。
930
+ * 非 http(s) 或解析失败的条目返回空串(= 丢弃)——
931
+ * 因为「一条永远匹配不上的清单项」与「没有这一项」在行为上相同,
932
+ * 而前者会让运维以为已经放行了。
933
+ */
934
+ export function normalizeOrigin(raw: string): string {
935
+ const s = raw.trim();
936
+ if (!s) return "";
937
+ try {
938
+ const u = new URL(s);
939
+ if (u.protocol !== "http:" && u.protocol !== "https:") return "";
940
+ return u.origin;
941
+ } catch {
942
+ return "";
943
+ }
944
+ }
945
+
924
946
  export function parseCorsOrigins(raw: string | undefined): string[] {
925
947
  if (raw === undefined) return ["http://localhost:3000", "http://localhost:3001"];
926
- return raw.split(",").map((s) => s.trim()).filter(Boolean); // 空串 / 全逗号 ⇒ 空清单(更严)
948
+ const out: string[] = [];
949
+ for (const part of raw.split(",")) {
950
+ const norm = normalizeOrigin(part);
951
+ if (norm && !out.includes(norm)) out.push(norm); // 空串 / 全逗号 / 非法 ⇒ 空清单(更严)
952
+ }
953
+ return out;
927
954
  }
928
955
 
929
956
  const CORS_ORIGINS = parseCorsOrigins(
@@ -936,7 +963,10 @@ function corsHeaders(req: Request): Record<string, string> {
936
963
  // Default (env unset) allows localhost dev origins only — see CORS_ORIGINS above.
937
964
  // No author-specific domains are hardcoded; production deployments must set
938
965
  // COMMHUB_CORS_ORIGINS explicitly. See docs/concepts/security.md "CORS 配置".
939
- const allowed = CORS_ORIGINS.includes(origin) ? origin : "";
966
+ // 比较的是**规范化后的 origin**,回写给浏览器的也是规范化后的值。
967
+ // (回写原始字符串会让「带默认端口」的请求拿到一个与自身不符的 allow-origin。)
968
+ const normalized = normalizeOrigin(origin);
969
+ const allowed = normalized && CORS_ORIGINS.includes(normalized) ? normalized : "";
940
970
  return {
941
971
  "Access-Control-Allow-Origin": allowed,
942
972
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",