@sleep2agi/commhub-server 0.9.0-preview.262 → 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.
- package/build-info.json +2 -2
- package/package.json +1 -1
- package/src/admin-delete-network-http.test.ts +3 -2
- package/src/agent-acl-http.test.ts +13 -2
- package/src/auth-layer-shape.test.ts +105 -0
- package/src/auth.ts +32 -12
- package/src/dm-file-scope-http.test.ts +50 -1
- package/src/health-identity-root.test.ts +98 -0
- package/src/health-status-reasons.test.ts +84 -0
- package/src/hub-catalog-read-http.test.ts +23 -0
- package/src/license-state.test.ts +49 -0
- package/src/network-quota-config.test.ts +100 -0
- package/src/node-config-last-update.test.ts +126 -0
- package/src/node-config-last-update.ts +107 -0
- package/src/node-health-guard-origin.test.ts +98 -0
- package/src/node-permissions-http.test.ts +173 -0
- package/src/node-token-privilege-http.test.ts +68 -2
- package/src/server.ts +25 -0
- package/src/task-access-http.test.ts +5 -0
- package/src/user-avatar-upload-http.test.ts +5 -0
- package/src/user-inbox-by-agent-http.test.ts +24 -0
package/build-info.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
3
|
+
"version": "0.9.0-preview.264",
|
|
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",
|
|
@@ -54,8 +54,9 @@ beforeAll(async () => {
|
|
|
54
54
|
memberUserId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", `member_delnet_${stamp}`)!.user_id;
|
|
55
55
|
expect(db.get<{ role: string }>("SELECT role FROM users WHERE user_id = ?1", adminUserId)!.role).toBe("admin");
|
|
56
56
|
expect(db.get<{ role: string }>("SELECT role FROM users WHERE user_id = ?1", memberUserId)!.role).not.toBe("admin");
|
|
57
|
-
//
|
|
58
|
-
|
|
57
|
+
// 本文件要建七八个网络,而默认每用户上限是 2(#2980 之前靠把 plan 改成 'pro' 绕过)。
|
|
58
|
+
// 现在没有 plan 概念了:上限由 COMMHUB_MAX_NETWORKS_PER_USER 决定 ⇒ 用它把闸抬高。
|
|
59
|
+
process.env.COMMHUB_MAX_NETWORKS_PER_USER = "50";
|
|
59
60
|
|
|
60
61
|
const minted = auth.createNetworkTokenForNode(memberUserId, member.network_id!, "delnet-node");
|
|
61
62
|
expect(minted.ok).toBe(true);
|
|
@@ -204,14 +204,25 @@ describe("restricted member with NO grants sees no agents (one test per path)",
|
|
|
204
204
|
expect((await get(aliceToken, `/api/messages?alias=${X.alias}&since=2000-01-01`)).body.messages).toEqual([]);
|
|
205
205
|
});
|
|
206
206
|
test("POST /api/task to an agent → 403 agent_not_granted; nonexistent alias gets the identical response", async () => {
|
|
207
|
+
// #3354 —— 拒绝之外还要钉「没有副作用」:派单的副作用是**写一条 tasks**,
|
|
208
|
+
// 只断 403 时,「拒了但任务已经进了队列」也会绿 —— 而那条任务会被目标真的执行。
|
|
209
|
+
const taskRows = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM tasks WHERE network_id = ?1", NET)!.n;
|
|
210
|
+
const before = taskRows();
|
|
207
211
|
const real = await send(aliceToken, "POST", "/api/task", { alias: X.alias, task: "hi", network_id: NET });
|
|
208
212
|
const fake = await send(aliceToken, "POST", "/api/task", { alias: "no-such-agent", task: "hi", network_id: NET });
|
|
209
213
|
expect(real.status).toBe(403);
|
|
210
214
|
expect(real.body.error).toBe("agent_not_granted");
|
|
211
215
|
expect(fake).toEqual(real);
|
|
212
|
-
|
|
213
|
-
|
|
216
|
+
expect(taskRows()).toBe(before); // 两条被拒的派单都不许落库
|
|
217
|
+
});
|
|
218
|
+
// #3354 —— 403 之外还要钉「没有副作用」:广播的副作用是**给每个目标写一条 inbox**,
|
|
219
|
+
// 只断状态码时,「拒了但已经把消息塞进大家收件箱」也会绿。
|
|
220
|
+
test("POST /api/broadcast → 403 且**一条 inbox 都没写**(拒绝不许有副作用)", async () => {
|
|
221
|
+
const inboxRows = () => db.get<{ n: number }>(
|
|
222
|
+
"SELECT COUNT(*) AS n FROM inbox WHERE network_id = ?1", NET)!.n;
|
|
223
|
+
const before = inboxRows();
|
|
214
224
|
expect((await send(aliceToken, "POST", `/api/broadcast?network_id=${NET}`, { message: "hi" })).status).toBe(403);
|
|
225
|
+
expect(inboxRows()).toBe(before);
|
|
215
226
|
});
|
|
216
227
|
|
|
217
228
|
// 2026-10-31 —— #3214:`/api/broadcast` 此前只测过 403(拒绝路径),**成功体的形状从未被钉**。
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// 鉴权层的**形状**:同一条未认证请求,最终是谁答的。
|
|
2
|
+
//
|
|
3
|
+
// ## 为什么要钉这个
|
|
4
|
+
//
|
|
5
|
+
// 2026-11-01(#3374):34 条写路由逐条发未认证请求,响应体分三种:
|
|
6
|
+
//
|
|
7
|
+
// {"error":"unauthorized"} ⇒ 全局鉴权层先答 ⇒ handler 内那条 401 分支**从不执行**
|
|
8
|
+
// {"ok":false,"error":"auth required"} ⇒ handler 自己就是门
|
|
9
|
+
// {"ok":false,"error":"token required"} ⇒ handler 自己就是门(另一句文案)
|
|
10
|
+
//
|
|
11
|
+
// 这三者对外都是「401」,对内却决定「那条分支是否可达」。差别不是风格:
|
|
12
|
+
// 把第二种当成第一种删掉,就等于删掉一道真的门(实测 18 条是这种)。
|
|
13
|
+
//
|
|
14
|
+
// ## 这张表断言什么
|
|
15
|
+
//
|
|
16
|
+
// 每行:一条路由 + 它今天由谁答。它钉的是**分层**,不是措辞:
|
|
17
|
+
// 措辞变了不算破坏契约,但**答话的人变了**是 —— 那意味着有一道门换了位置。
|
|
18
|
+
//
|
|
19
|
+
// ## 它是抽样(12 条),不是全集
|
|
20
|
+
//
|
|
21
|
+
// 全集的分档要么逐条请求(脚本 report-inner-auth-branches.py 记录方法),
|
|
22
|
+
// 要么需要可枚举的中间件栈(本仓没有)。这张表选的是**每类各取几条**,
|
|
23
|
+
// 目的是让「分层被改动」这件事变红,而不是声称覆盖率。
|
|
24
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
25
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { tmpdir } from "node:os";
|
|
28
|
+
import { register } from "./auth.js";
|
|
29
|
+
|
|
30
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-auth-layer-"));
|
|
31
|
+
const PW = "AuthLayerPassw0rd!";
|
|
32
|
+
let BASE = "";
|
|
33
|
+
let hub: any = null;
|
|
34
|
+
let NET = "";
|
|
35
|
+
|
|
36
|
+
type Shape = "global_unauthorized" | "handler_auth" | "handler_token" | "public_input";
|
|
37
|
+
|
|
38
|
+
const classify = (status: number, body: string): Shape => {
|
|
39
|
+
if (body.includes('"unauthorized"')) return "global_unauthorized";
|
|
40
|
+
if (body.includes('"auth required"')) return "handler_auth";
|
|
41
|
+
if (body.includes('"token required"')) return "handler_token";
|
|
42
|
+
return "public_input"; // 公开路由:直接进入参数校验
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
beforeAll(async () => {
|
|
46
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
47
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
48
|
+
process.env.HOST = "127.0.0.1";
|
|
49
|
+
const a = register(`al_${Date.now()}`, PW);
|
|
50
|
+
NET = a.network_id!;
|
|
51
|
+
const mod: any = await import("./server.js");
|
|
52
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
53
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
54
|
+
}, 30_000);
|
|
55
|
+
|
|
56
|
+
afterAll(() => {
|
|
57
|
+
try { hub?.stop?.(true); } catch {}
|
|
58
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// [方法, 路径, 今天由谁答, 备注]
|
|
62
|
+
const TABLE: Array<[string, string, Shape, string]> = [
|
|
63
|
+
["GET", "/api/nodes", "global_unauthorized", "读路由,全局层先答"],
|
|
64
|
+
["GET", "/api/providers", "global_unauthorized", "读路由"],
|
|
65
|
+
["PUT", "/api/providers", "global_unauthorized", "写路由,全局层先答"],
|
|
66
|
+
["GET", "/api/networks/:NET/node-permission-report", "global_unauthorized", "报表"],
|
|
67
|
+
["POST", "/api/auth/tokens", "handler_auth", "handler 自己就是门(换令牌的入口不能被别的层替它把关)"],
|
|
68
|
+
["POST", "/api/node-rename/prepare", "handler_auth", "同上"],
|
|
69
|
+
["POST", "/api/node-rename/commit", "handler_auth", "同上"],
|
|
70
|
+
["DELETE", "/api/auth/tokens/tok_x", "handler_auth", "同上"],
|
|
71
|
+
["PUT", "/api/auth/me", "handler_token", "handler 取 token 并给出 token required"],
|
|
72
|
+
["POST", "/api/networks", "handler_token", "同上"],
|
|
73
|
+
// 读路由也分档(2026-11-01 抽样 24 条读路由:7 全局层 / 3 handler_token / 1 404 / 1 公开)
|
|
74
|
+
["GET", "/api/auth/tokens", "handler_auth", "读路由里 handler 自己把关的一类"],
|
|
75
|
+
["GET", "/api/networks/:NET/rules", "handler_auth", "同上"],
|
|
76
|
+
["GET", "/api/users/x/avatar/y.png", "handler_token", "handler 取 token 并给出 token required"],
|
|
77
|
+
["POST", "/api/auth/register", "public_input", "按设计公开:直接进参数校验"],
|
|
78
|
+
["POST", "/api/auth/login", "public_input", "按设计公开"],
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
describe("鉴权层形状(谁答这条未认证请求)", () => {
|
|
82
|
+
for (const [method, rawPath, expected, why] of TABLE) {
|
|
83
|
+
const path = rawPath.replace(":NET", "net_placeholder");
|
|
84
|
+
test(`${method} ${rawPath} ⇒ ${expected}(${why})`, async () => {
|
|
85
|
+
const url = `${BASE}${path}${path.includes("?") ? "&" : "?"}network_id=${NET}`;
|
|
86
|
+
const r = await fetch(url, {
|
|
87
|
+
method,
|
|
88
|
+
headers: { "content-type": "application/json" },
|
|
89
|
+
body: method === "GET" ? undefined : "{}",
|
|
90
|
+
});
|
|
91
|
+
const body = await r.text();
|
|
92
|
+
expect(classify(r.status, body)).toBe(expected);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// 分层被改动时,最容易被误判的是这两条:它们**不是**全局层答的。
|
|
97
|
+
test("抽查:handler 就是门的那几条,响应体里带 ok:false(不是裸 error)", async () => {
|
|
98
|
+
const r = await fetch(`${BASE}/api/auth/tokens?network_id=${NET}`, {
|
|
99
|
+
method: "POST", headers: { "content-type": "application/json" }, body: "{}",
|
|
100
|
+
});
|
|
101
|
+
const body = await r.json() as any;
|
|
102
|
+
expect(body.ok).toBe(false);
|
|
103
|
+
expect(body.error).toBe("auth required");
|
|
104
|
+
});
|
|
105
|
+
});
|
package/src/auth.ts
CHANGED
|
@@ -451,21 +451,41 @@ export function getUserNetworks(userId: string) {
|
|
|
451
451
|
userId);
|
|
452
452
|
}
|
|
453
453
|
|
|
454
|
-
//
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
454
|
+
// 2026-11-01(#2980)—— 自建 Hub 的**单一上限**,不再有 free/pro 套餐概念。
|
|
455
|
+
//
|
|
456
|
+
// 原来是一张 `QUOTAS` 表:free 2/3、pro 10/20、admin 无限。
|
|
457
|
+
// `pro` 那一行**没有任何路径能到达**(没有代码把 plan 设成 pro),
|
|
458
|
+
// 而它对自部署的人是可见的 —— 报错写的是「max 2 networks for free plan」,
|
|
459
|
+
// 这句话在纯开源语境里无法解释(哪来的套餐?谁在收费?)。
|
|
460
|
+
//
|
|
461
|
+
// ⇒ 改成「一个可配置的上限」:默认仍是 2(**零行为变化**),
|
|
462
|
+
// 但「为什么是 2」变成可解释、可调整的:COMMHUB_MAX_NETWORKS_PER_USER。
|
|
463
|
+
// `users.plan` 列保留但不参与判定(与 licenses 表同样处理:不删列,避免迁移风险)。
|
|
464
|
+
export const DEFAULT_MAX_NETWORKS_PER_USER = 2;
|
|
465
|
+
|
|
466
|
+
/** 每次调用时读环境变量(而不是模块加载时定死):测试与运维都能改。 */
|
|
467
|
+
export function maxNetworksPerUser(): number {
|
|
468
|
+
const raw = process.env.COMMHUB_MAX_NETWORKS_PER_USER;
|
|
469
|
+
if (raw === undefined || raw.trim() === "") return DEFAULT_MAX_NETWORKS_PER_USER;
|
|
470
|
+
const n = Number(raw);
|
|
471
|
+
// 非法值**回落到默认**而不是抛错:这是启动期配置,抛错会让整个 Hub 起不来。
|
|
472
|
+
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT_MAX_NETWORKS_PER_USER;
|
|
473
|
+
}
|
|
460
474
|
|
|
461
475
|
export function createNetwork(userId: string, name: string, description?: string) {
|
|
462
|
-
//
|
|
463
|
-
const user = db.get<any>("SELECT
|
|
464
|
-
const plan = user?.role === "admin" ? "admin" : (user?.plan || "free");
|
|
465
|
-
const quota = QUOTAS[plan] || QUOTAS.free;
|
|
476
|
+
// 上限检查(#2980):admin 无限,其余按 COMMHUB_MAX_NETWORKS_PER_USER(默认 2)
|
|
477
|
+
const user = db.get<any>("SELECT role FROM users WHERE user_id = ?1", userId);
|
|
466
478
|
const ownedCount = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM networks WHERE owner_id = ?1", userId);
|
|
467
|
-
if (
|
|
468
|
-
|
|
479
|
+
if (user?.role !== "admin") {
|
|
480
|
+
const max = maxNetworksPerUser();
|
|
481
|
+
if ((ownedCount?.cnt || 0) >= max) {
|
|
482
|
+
// 文案要能自解释:不出现「套餐」,并说出怎么改。
|
|
483
|
+
return {
|
|
484
|
+
ok: false,
|
|
485
|
+
error: `quota exceeded: max ${max} networks per user on this hub `
|
|
486
|
+
+ `(set COMMHUB_MAX_NETWORKS_PER_USER to change it)`,
|
|
487
|
+
};
|
|
488
|
+
}
|
|
469
489
|
}
|
|
470
490
|
|
|
471
491
|
const existing = db.get<any>(
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// 变成私信文件,之后转进私信也照旧全网成员可见。私信文件只能由看得见它的人再转发。
|
|
7
7
|
|
|
8
8
|
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
9
|
-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
9
|
+
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "fs";
|
|
10
10
|
import { join } from "path";
|
|
11
11
|
import { tmpdir } from "os";
|
|
12
12
|
import { register, addNetworkMember } from "./auth.js";
|
|
@@ -73,6 +73,55 @@ afterAll(() => {
|
|
|
73
73
|
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
+
// #3354 —— POST /api/dm 的 L3 证据:非该网络成员必须被拒,且**一条私信都不许落库**。
|
|
77
|
+
// 这条路由的门是 restAuth + getUserNetworkRole,两处都在 sendHumanDm 里。
|
|
78
|
+
describe("POST /api/dm 的拒绝与镜像", () => {
|
|
79
|
+
const dmRows = (userId: string) =>
|
|
80
|
+
db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE user_id = ?1 AND kind = 'human_dm'", userId)!.n;
|
|
81
|
+
|
|
82
|
+
test("非该网络成员 ⇒ 403,且没有私信落库;成员 ⇒ 200 且真的落了(镜像)", async () => {
|
|
83
|
+
// 造一个「自己有自己的网络、但不是 NET 成员」的人
|
|
84
|
+
const outsider = register(`dmfs_outsider_${Date.now()}`, PW);
|
|
85
|
+
expect(outsider.network_id).not.toBe(NET);
|
|
86
|
+
const before = dmRows(bob.id);
|
|
87
|
+
const denied = await fetch(`${BASE}/api/dm`, {
|
|
88
|
+
method: "POST",
|
|
89
|
+
headers: { ...auth(outsider.token!), "Content-Type": "application/json" },
|
|
90
|
+
body: JSON.stringify({ network_id: NET, to_user_id: bob.id, message: "hi" }),
|
|
91
|
+
});
|
|
92
|
+
expect(denied.status).toBe(403);
|
|
93
|
+
expect((await denied.json() as any).error).toBe("not a member of this network");
|
|
94
|
+
// 拒绝的第二半:**没有落库**(只断状态码时,「拒了但已经写进收件箱」也会绿)
|
|
95
|
+
expect(dmRows(bob.id)).toBe(before);
|
|
96
|
+
// 镜像:成员发给 bob ⇒ 200,且收件箱真的多一条
|
|
97
|
+
const ok = await fetch(`${BASE}/api/dm`, {
|
|
98
|
+
method: "POST",
|
|
99
|
+
headers: { ...auth(alice.token), "Content-Type": "application/json" },
|
|
100
|
+
body: JSON.stringify({ network_id: NET, to_user_id: bob.id, message: "hi from alice" }),
|
|
101
|
+
});
|
|
102
|
+
expect(ok.status).toBe(200);
|
|
103
|
+
expect(dmRows(bob.id)).toBe(before + 1);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// #3354 —— POST /api/upload 的 L3 证据:未认证必须 401,且**一个文件都没落盘**。
|
|
108
|
+
// 这条路由有 8 种拒绝(401 / 403 / 411 / 413 / 415 / 429 / bad_content_length / bad_purpose),
|
|
109
|
+
// 本轮验的是最外一层:没有身份就没有上传。
|
|
110
|
+
describe("POST /api/upload 的拒绝与副作用", () => {
|
|
111
|
+
const indexCount = () => {
|
|
112
|
+
try { return readdirSync(join(DIR, "uploads", ".index")).length; } catch { return 0; }
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
test("未认证 ⇒ 401,且 .index 条目数不变(拒绝不许有副作用)", async () => {
|
|
116
|
+
const before = indexCount();
|
|
117
|
+
const form = new FormData();
|
|
118
|
+
form.append("file", new Blob([new TextEncoder().encode("probe")], { type: "image/png" }), "probe.png");
|
|
119
|
+
const res = await fetch(`${BASE}/api/upload?network_id=${NET}`, { method: "POST", body: form });
|
|
120
|
+
expect(res.status).toBe(401);
|
|
121
|
+
expect(indexCount()).toBe(before);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
76
125
|
describe("upload ?purpose=dm", () => {
|
|
77
126
|
test("marks the index entry; absent purpose writes no scope key (old shape)", async () => {
|
|
78
127
|
expect(entry(await uploadId(alice.token, "p1", "&purpose=dm")).scope).toBe("dm");
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// `git_identity_root: module_dir | cwd | build_info` 的**值域 == 生产者集合**。
|
|
2
|
+
//
|
|
3
|
+
// ## 为什么这一格要一条断言
|
|
4
|
+
//
|
|
5
|
+
// 这个字段存在的唯一理由,是让读者区分「这份身份是从**包内**读到的」与
|
|
6
|
+
// 「是从**启动目录里另一个仓库**读到的」——两者在 `git_commit` 上完全同形。
|
|
7
|
+
//
|
|
8
|
+
// 于是它自己也就有了同一个毛病:
|
|
9
|
+
// · 声明了某个取值、但没有任何分支会产生它 ⇒ 读者按它设计一条不存在的修法
|
|
10
|
+
// · 某个分支产生了一个没声明的取值 ⇒ 读的人拿到一个不认识的字符串
|
|
11
|
+
//
|
|
12
|
+
// ## 这份断言是文本级,且**明确它能看见什么**
|
|
13
|
+
//
|
|
14
|
+
// 两处产生形态:
|
|
15
|
+
// ① 字面量直接写:`root_kind: "build_info"`
|
|
16
|
+
// ② 经由变量写: `root_kind: rootKind`,而 `rootKind` 的值域由它自己的类型注解给出
|
|
17
|
+
// ② 必须跟着走一跳,否则会把「经变量产生」误判成「没人产生」——
|
|
18
|
+
// 第一版正是这样:声明了 cwd,而文本里找不到 `root_kind: "cwd"`,于是报了假阳。
|
|
19
|
+
//
|
|
20
|
+
// 它**看不见**两跳以上的变量链,也看不见运行期拼出来的值。
|
|
21
|
+
// ⇒ 结论读作「文本级(含一层变量解析)0 处未声明 / 0 处未产生」,
|
|
22
|
+
// 不是「运行期不可能出现别的值」。
|
|
23
|
+
import { describe, expect, test } from "bun:test";
|
|
24
|
+
import { readFileSync } from "node:fs";
|
|
25
|
+
|
|
26
|
+
const src = readFileSync(new URL("./server.ts", import.meta.url), "utf8");
|
|
27
|
+
|
|
28
|
+
/** 联合类型里声明的取值。 */
|
|
29
|
+
export function declaredRootKinds(source: string): string[] {
|
|
30
|
+
const m = source.match(/root_kind:\s*([^;]+);/);
|
|
31
|
+
if (!m) return [];
|
|
32
|
+
return [...m[1].matchAll(/"([a-z_]+)"/g)].map((x) => x[1]);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `root_kind: "x"` 形式的产生点。 */
|
|
36
|
+
export function literalRootKinds(source: string): string[] {
|
|
37
|
+
return [...source.matchAll(/root_kind:\s*"([a-z_]+)"/g)].map((m) => m[1]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `root_kind: ident` 形式的产生点 ⇒ 跟着一跳,取 ident 自己声明的值域。 */
|
|
41
|
+
export function variableRootKinds(source: string): Array<{ ident: string; values: string[] }> {
|
|
42
|
+
const out: Array<{ ident: string; values: string[] }> = [];
|
|
43
|
+
for (const m of source.matchAll(/root_kind:\s*([A-Za-z_]\w*)\s*[,}]/g)) {
|
|
44
|
+
const ident = m[1];
|
|
45
|
+
// `const ident: "a" | "b" = …` —— 一行内能看到的两处字面量就是它的值域
|
|
46
|
+
const decl = source.match(new RegExp(`const\\s+${ident}\\s*:\\s*([^=]+)=`));
|
|
47
|
+
const values = decl ? [...decl[1].matchAll(/"([a-z_]+)"/g)].map((x) => x[1]) : [];
|
|
48
|
+
out.push({ ident, values });
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe("git_identity_root 值域 == 生产者集合", () => {
|
|
54
|
+
test("声明集合非空且无重复(否则下面几条会在空集上恒真)", () => {
|
|
55
|
+
const declared = declaredRootKinds(src);
|
|
56
|
+
expect(declared.length).toBeGreaterThanOrEqual(3);
|
|
57
|
+
expect(new Set(declared).size).toBe(declared.length);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("① 每个产生点都在声明范围内(含经变量的那一类)", () => {
|
|
61
|
+
const declared = new Set(declaredRootKinds(src));
|
|
62
|
+
const produced = new Set([
|
|
63
|
+
...literalRootKinds(src),
|
|
64
|
+
...variableRootKinds(src).flatMap((v) => v.values),
|
|
65
|
+
]);
|
|
66
|
+
expect([...produced].filter((x) => !declared.has(x))).toEqual([]);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("② 每个声明值都有产生点(没有死值)", () => {
|
|
70
|
+
const declared = declaredRootKinds(src);
|
|
71
|
+
const produced = new Set([
|
|
72
|
+
...literalRootKinds(src),
|
|
73
|
+
...variableRootKinds(src).flatMap((v) => v.values),
|
|
74
|
+
]);
|
|
75
|
+
expect(declared.filter((x) => !produced.has(x))).toEqual([]);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("③ 三个取值各自的产生方式(向量,不是一个计数)", () => {
|
|
79
|
+
const via = variableRootKinds(src);
|
|
80
|
+
const shape: Record<string, string> = {};
|
|
81
|
+
for (const k of literalRootKinds(src)) shape[k] = "literal";
|
|
82
|
+
for (const v of via) for (const k of v.values) shape[k] = `via ${v.ident}`;
|
|
83
|
+
// 改动这里要有理由:多一条落到同一取值的路径,正是「两个来源同形」的入口。
|
|
84
|
+
expect(shape).toEqual({
|
|
85
|
+
build_info: "literal",
|
|
86
|
+
module_dir: "via rootKind",
|
|
87
|
+
cwd: "via rootKind",
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("④ 经变量的那一类必须能被解析出值域(否则 ①② 会静默漏掉它)", () => {
|
|
92
|
+
const via = variableRootKinds(src);
|
|
93
|
+
expect(via.length).toBeGreaterThan(0);
|
|
94
|
+
for (const v of via) {
|
|
95
|
+
expect(v.values.length).toBeGreaterThan(0);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// `status_reasons` 的**值域**必须与它的**生产者**逐个对应(外部复核的判据)。
|
|
2
|
+
//
|
|
3
|
+
// ## 为什么这一格值得一条断言
|
|
4
|
+
//
|
|
5
|
+
// `/health.status` 只有两个取值(ok / degraded),而 `status_reasons` 是回答
|
|
6
|
+
// 「ok 到底是**真的没问题**,还是**检查没跑**」的唯一读数。它的值域偏离生产者时:
|
|
7
|
+
//
|
|
8
|
+
// 值域比生产者少 ⇒ 两个成因合并成一个字 ⇒ 读的人分不出该修哪(合并)
|
|
9
|
+
// 值域比生产者多 ⇒ 有原因却没有任何代码会产生它 ⇒ 读者为它设计一条不存在的修法(死值)
|
|
10
|
+
//
|
|
11
|
+
// 两种都不红:`status` 照样是 ok/degraded,`status_reasons` 照样是数组。
|
|
12
|
+
//
|
|
13
|
+
// ## 为什么这一份是**声明**而不是引用
|
|
14
|
+
//
|
|
15
|
+
// push 点保留字面量(`statusReasons.push("db_unreadable")`),`STATUS_REASONS` 只做靶子。
|
|
16
|
+
// 改成 `push(STATUS_REASONS[0])` 之后,抽取只能看见下标、看不见成因,
|
|
17
|
+
// 而「哪一行推了什么」正是这条检查要看的东西。
|
|
18
|
+
//
|
|
19
|
+
// ## 断言
|
|
20
|
+
//
|
|
21
|
+
// ① 源码里所有 `statusReasons.push("X")` 的字面量集合 == STATUS_REASONS
|
|
22
|
+
// ② push 点数 == 不同字面量数(同一个成因不许有两处 push —— 那会让「一个成因」看起来像两个)
|
|
23
|
+
// ③ 每个 STATUS_REASONS 的成员都真的在某处被 push(无死值)
|
|
24
|
+
import { describe, expect, test } from "bun:test";
|
|
25
|
+
import { readFileSync } from "node:fs";
|
|
26
|
+
|
|
27
|
+
const src = readFileSync(new URL("./server.ts", import.meta.url), "utf8");
|
|
28
|
+
|
|
29
|
+
/** 源码里所有 `statusReasons.push("literal")` 的字面量(保序、允许重复)。 */
|
|
30
|
+
export function pushedReasonLiterals(source: string): string[] {
|
|
31
|
+
return [...source.matchAll(/statusReasons\s*\.\s*push\(\s*"([a-z0-9_]+)"\s*\)/g)].map((m) => m[1]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe("#status_reasons 值域 == 生产者集合", () => {
|
|
35
|
+
test("① push 的字面量集合与 STATUS_REASONS 相等", async () => {
|
|
36
|
+
const { STATUS_REASONS } = await import("./server.js");
|
|
37
|
+
const pushed = new Set(pushedReasonLiterals(src));
|
|
38
|
+
expect([...pushed].sort()).toEqual([...STATUS_REASONS].sort());
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// ② 报成**向量**而不是一个数:`1,1` 与 `1,2` 在「点数 == 不同值数」这条上都会红,
|
|
42
|
+
// 但前者是「新增了一类成因」,后者是「同一个成因被推了两次」—— 处置相反。
|
|
43
|
+
// 单条计数断言把这两种压成一格,而它读起来更严格。
|
|
44
|
+
test("② 每个成因恰好一个生产者(报向量,不是一个数)", () => {
|
|
45
|
+
const all = pushedReasonLiterals(src);
|
|
46
|
+
const counts: Record<string, number> = {};
|
|
47
|
+
for (const r of all) counts[r] = (counts[r] ?? 0) + 1;
|
|
48
|
+
const vector = Object.entries(counts).sort().map(([k, v]) => `${k}=${v}`).join(" · ");
|
|
49
|
+
expect(vector).toBe(
|
|
50
|
+
"db_unreadable=1 · license_unreadable=1",
|
|
51
|
+
);
|
|
52
|
+
// 上面那条是**精确向量**:新增一类或某类多一处,都会让它红,
|
|
53
|
+
// 而且失败信息里直接看得出是哪种(多了一个 `x=1` 还是某个变成 `=2`)。
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// ⑤ 域不能是空集,也不能是全集 —— 否则上面几条会在空集上恒真。
|
|
57
|
+
// 这正是「取反后仍然绿」的那一格:把 STATUS_REASONS 清空,①(集合相等)与 ③(无死值)
|
|
58
|
+
// 都会通过,因为没有东西可比;而它们看起来仍然在守东西。
|
|
59
|
+
test("⑤ 值域非空且不是全集(至少两类可区分)", async () => {
|
|
60
|
+
const { STATUS_REASONS } = await import("./server.js");
|
|
61
|
+
const pushed = new Set(pushedReasonLiterals(src));
|
|
62
|
+
// 下界:这个字段存在的理由就是区分「真的没问题」与「检查没跑」——至少要两类。
|
|
63
|
+
expect(STATUS_REASONS.length).toBeGreaterThanOrEqual(2);
|
|
64
|
+
// 上界:值域的成员必须都在源码里出现(否则是死值,由 ③ 报)——
|
|
65
|
+
// 这里再钉一条「域不比生产者宽」,因为「全集」正是那种能让谓词恒真的情形。
|
|
66
|
+
expect(STATUS_REASONS.length).toBeLessThanOrEqual(pushed.size + 0 * 0 + 0);
|
|
67
|
+
expect(pushed.size).toBeGreaterThan(0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("③ 没有死值:STATUS_REASONS 每个成员都在源码里被 push 过", async () => {
|
|
71
|
+
const { STATUS_REASONS } = await import("./server.js");
|
|
72
|
+
const pushed = new Set(pushedReasonLiterals(src));
|
|
73
|
+
for (const r of STATUS_REASONS) expect(pushed.has(r)).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("④ status 由 reasons 派生,不是独立写的第二个真相", async () => {
|
|
77
|
+
const { statusFromReasons } = await import("./server.js");
|
|
78
|
+
// 空 ⇒ ok;任一 ⇒ degraded。这条同时钉住「ok 不代表检查跑过」——
|
|
79
|
+
// 它只代表「没有成因被推上来」。
|
|
80
|
+
expect(statusFromReasons([])).toBe("ok");
|
|
81
|
+
expect(statusFromReasons(["db_unreadable"])).toBe("degraded");
|
|
82
|
+
expect(statusFromReasons(["db_unreadable", "license_unreadable"])).toBe("degraded");
|
|
83
|
+
});
|
|
84
|
+
});
|
|
@@ -266,6 +266,29 @@ describe("GET /api/providers", () => {
|
|
|
266
266
|
});
|
|
267
267
|
// 2026-10-31 —— **写侧原来只有 MCP**:客户端能显示「还没有 provider」,却没办法把它变成「有」。
|
|
268
268
|
// 这条把「第一行」确认成一次 HTTP 调用,并核对三件事:落库、读回来一致、revision 冲突是 409。
|
|
269
|
+
// #3354 —— 拒绝路径:别的网络的 owner 来写 ⇒ 403,且**一行都不许写入**。
|
|
270
|
+
// 这条路由改的是「这个网络能用哪些 provider」⇒ 被拒失败等于任何人可改别人的模型配置。
|
|
271
|
+
test("PUT /api/providers 别的网络 owner ⇒ 403 且 providers 列表不变(拒绝不许有副作用)", async () => {
|
|
272
|
+
const before = (await get(`/api/providers?network_id=${ownerNet}`, ownerToken)).body.providers.map((p: any) => p.id).sort();
|
|
273
|
+
const r = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
|
|
274
|
+
method: "PUT",
|
|
275
|
+
headers: { Authorization: `Bearer ${strangerToken}`, "content-type": "application/json" },
|
|
276
|
+
body: JSON.stringify({
|
|
277
|
+
revision: 0,
|
|
278
|
+
provider: {
|
|
279
|
+
id: "hc-stranger", label: "Injected", enabled: true,
|
|
280
|
+
protocol: "openai-chat-completions", baseUrl: "https://evil.example/v1",
|
|
281
|
+
models: ["m"], key: "sk-not-real",
|
|
282
|
+
},
|
|
283
|
+
}),
|
|
284
|
+
});
|
|
285
|
+
expect(r.status).toBe(403);
|
|
286
|
+
// 外网络 caller 在更早的一层就被拒(scope 校验),错误码是 access denied to requested network
|
|
287
|
+
expect(String((await r.json() as any).error)).toMatch(/access denied|permission_denied/);
|
|
288
|
+
const after = (await get(`/api/providers?network_id=${ownerNet}`, ownerToken)).body.providers.map((p: any) => p.id).sort();
|
|
289
|
+
expect(after).toEqual(before);
|
|
290
|
+
});
|
|
291
|
+
|
|
269
292
|
test("PUT /api/providers creates the first row, and the read side sees it", async () => {
|
|
270
293
|
const body = {
|
|
271
294
|
revision: 0,
|
|
@@ -54,3 +54,52 @@ describe("legacyLicenseField", () => {
|
|
|
54
54
|
expect(legacyLicenseField({ type: 0 as unknown })).toBe("none");
|
|
55
55
|
});
|
|
56
56
|
});
|
|
57
|
+
|
|
58
|
+
// 2026-11-01 —— 值域 == 生产者集合,**用穷举**而不是用声明。
|
|
59
|
+
//
|
|
60
|
+
// `LicenseState` 是一个联合类型:它声明了 {known, absent, unknown} 与两个 reason。
|
|
61
|
+
// 声明本身不会红 —— 有人加了第四个分支(例如 expired)而忘了改类型时,
|
|
62
|
+
// TypeScript 会红,但**改类型而不加分支**(往联合里加一个没人产生的成员)不会红,
|
|
63
|
+
// 于是「值域里有它、但没人会产生它」这一格没有任何断言。
|
|
64
|
+
//
|
|
65
|
+
// 这里的域是有限的(failed × 5 种 row)⇒ 可以穷举:
|
|
66
|
+
// ① 产生的 kind 集合 == 声明的 kind 集合
|
|
67
|
+
// ② 产生的 reason 集合 == 声明的 reason 集合
|
|
68
|
+
// ③ 每个输入恰好落在一格里(互斥)
|
|
69
|
+
describe("值域 == 生产者集合(穷举有限域)", () => {
|
|
70
|
+
const ROWS: unknown[] = [
|
|
71
|
+
null, undefined, {}, { type: "" }, { type: " " }, { type: 42 }, { type: "pro" }, { type: " team " },
|
|
72
|
+
];
|
|
73
|
+
const OUT = ROWS.flatMap((r) => [false, true].map((failed) => licenseStateOf(r as any, failed)));
|
|
74
|
+
|
|
75
|
+
test("① kind 集合恰好是 known / absent / unknown 三个", () => {
|
|
76
|
+
expect([...new Set(OUT.map((o) => o.kind))].sort()).toEqual(["absent", "known", "unknown"]);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("② reason 集合恰好是两个(多一个 ⇒ 有值没有生产者;少一个 ⇒ 有生产者没有值)", () => {
|
|
80
|
+
const reasons = OUT.flatMap((o) => (o.kind === "unknown" ? [o.reason] : [])).sort();
|
|
81
|
+
expect([...new Set(reasons)]).toEqual(["license_query_failed", "license_row_without_type"]);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// ④ 声明的值域 vs 产生的值域:只比「产生的」抓不到「声明了但没人产生」。
|
|
85
|
+
// 这一条读源码里的联合类型字面量,与上面 ② 的产出集合对账。
|
|
86
|
+
test("④ 类型里声明的 reason 集合 == 实际产出的集合(无声明无生产者)", async () => {
|
|
87
|
+
const { licenseStateOf: fn } = await import("./license-state.js");
|
|
88
|
+
const src = (await import("node:fs")).readFileSync(new URL("./license-state.ts", import.meta.url), "utf8");
|
|
89
|
+
// 注意结尾:联合类型的**最后一个**成员后面是 ` }` 而不是 `|`,
|
|
90
|
+
// 只写 `(?=\||;)` 会漏掉它 —— 而漏掉的那一个正好是「最后加进去的那个」,
|
|
91
|
+
// 也就是这条断言最该抓到的那一个。
|
|
92
|
+
const declared = [...src.matchAll(/"([a-z_]+)"\s*(?=[|;}])/g)].map((m) => m[1])
|
|
93
|
+
.filter((x) => x.startsWith("license_"));
|
|
94
|
+
const produced = [...new Set(OUT.flatMap((o) => (o.kind === "unknown" ? [o.reason] : [])))].sort();
|
|
95
|
+
expect([...new Set(declared)].sort()).toEqual(produced);
|
|
96
|
+
expect(typeof fn).toBe("function");
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("③ 每个输入恰好落在一格里(互斥,不重叠)", () => {
|
|
100
|
+
for (const o of OUT) {
|
|
101
|
+
const hits = [o.kind === "known", o.kind === "absent", o.kind === "unknown"].filter(Boolean).length;
|
|
102
|
+
expect(hits).toBe(1);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
});
|