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

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.221",
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
  });
@@ -1037,6 +1037,15 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1037
1037
  const probed = await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": "dead-entry-check" } })).json() as any;
1038
1038
  const seen = new Set([...Object.keys(plain), ...Object.keys(probed)]);
1039
1039
  const dead = [...PUBLIC_HEALTH_KEYS].filter((k) => !seen.has(k));
1040
+ // 2026-10-31 —— 失败时必须点名(外部复核 ③):只说 `toEqual([])` 的失败信息里
1041
+ // 没有「是哪几个键」,而修它需要的正是那几个名字。
1042
+ if (dead.length) {
1043
+ throw new Error(
1044
+ `白名单里有 ${dead.length} 个键在任何投影里都不出现(死条目):${dead.join(", ")}\n` +
1045
+ " ⇒ 要么从 PUBLIC_HEALTH_KEYS 删掉,要么让 body 真的产出它;" +
1046
+ "留着等于给未来的同名字段预授权。",
1047
+ );
1048
+ }
1040
1049
  expect(dead).toEqual([]);
1041
1050
  });
1042
1051
 
@@ -683,8 +683,24 @@ 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
+ type TagCreateError = "tag_exists" | "tag_parent_not_found" | "tag_depth_exceeded";
696
+ const TAG_CREATE_STATUS: Record<TagCreateError, number> = {
697
+ tag_exists: 409,
698
+ tag_parent_not_found: 404,
699
+ tag_depth_exceeded: 400,
700
+ };
701
+
686
702
  type CreateTagOutcome =
687
- | { error: "tag_exists" | "tag_parent_not_found" | "tag_depth_exceeded" }
703
+ | { error: TagCreateError }
688
704
  | { name: string; parent: string | null; depth: number; parentRegistered: boolean };
689
705
 
690
706
  /** POST /api/requirements/tags/create —— 建标签(可带父)。原子、整网络判重、父不存在就报错。 */
@@ -724,8 +740,7 @@ async function handleTagCreate(ctx: RequirementsRequestContext): Promise<Respons
724
740
  return { name: input.name, parent: input.parent, depth: tagDepth(input.name, parentOf), parentRegistered };
725
741
  });
726
742
  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);
743
+ return jsonError(result.error, TAG_CREATE_STATUS[result.error]);
729
744
  }
730
745
  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
746
  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",