@sleep2agi/commhub-server 0.9.0-preview.263 → 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.
@@ -17,7 +17,7 @@ const DIR = mkdtempSync(join(tmpdir(), "anet-ntok-priv-"));
17
17
  let BASE = "";
18
18
  let hub: any = null;
19
19
  const PW = "NtokPrivPassw0rd!";
20
- let adminToken = "", adminId = "", NET = "", OTHER_NET = "", ntok = "";
20
+ let adminToken = "", adminId = "", NET = "", OTHER_NET = "", ntok = "", adminUsername = "";
21
21
 
22
22
  const auth = (t: string) => ({ Authorization: `Bearer ${t}` });
23
23
  async function call(token: string, method: string, path: string, body?: unknown) {
@@ -33,7 +33,8 @@ beforeAll(async () => {
33
33
  process.env.COMMHUB_DB ||= join(DIR, "hub.db");
34
34
  process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
35
35
  process.env.HOST = "127.0.0.1";
36
- const admin = register(`ntok_admin_${Date.now()}`, PW);
36
+ adminUsername = `ntok_admin_${Date.now()}`;
37
+ const admin = register(adminUsername, PW);
37
38
  adminToken = admin.token!; adminId = admin.user!.user_id; NET = admin.network_id!;
38
39
  db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [adminId]);
39
40
  const other = createNetwork(adminId, "ntok-other");
@@ -80,28 +81,71 @@ describe("hub-admin powers need a user token", () => {
80
81
  void sub;
81
82
  });
82
83
  test("POST /api/admin/users and agent-grants", async () => {
84
+ // #3354 —— 拒绝之外钉「没有建出用户」:建用户的副作用是**多一行 users**。
85
+ const userRows = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM users")!.n;
86
+ const beforeUsers = userRows();
83
87
  expect((await call(ntok, "POST", "/api/admin/users", { username: "ntok_made", password: PW })).status).toBe(403);
88
+ expect(userRows()).toBe(beforeUsers);
89
+ expect(db.get("SELECT 1 FROM users WHERE username = 'ntok_made'")).toBeFalsy();
90
+ // #3354 —— 写 side:节点令牌不能改 agent-grants(读的 403 上面已有)。
91
+ // 副作用是**多一条授权**(那意味着一个 Agent 对这个人可见)。
92
+ const grants = () => db.get<{ n: number }>(
93
+ "SELECT COUNT(*) AS n FROM network_member_agent_grants WHERE network_id = ?1", NET)!.n;
94
+ const beforeGrants = grants();
84
95
  expect((await call(ntok, "GET", `/api/networks/${NET}/members/${adminId}/agent-grants`)).status).toBe(403);
96
+ expect((await call(ntok, "PUT", `/api/networks/${NET}/members/${adminId}/agent-grants`, { node_ids: ["n_x"] })).status).toBe(403);
97
+ expect(grants()).toBe(beforeGrants);
85
98
  });
86
99
  });
87
100
 
88
101
  describe("account and network management need a user token", () => {
89
102
  test("token management: cannot list, mint user tokens, mint node tokens or revoke", async () => {
103
+ // #3354 —— 拒绝之外还要钉「没有新令牌」:发令牌的副作用是**多一行 api_tokens**。
104
+ // 只断 403 时,「拒了但令牌已经发出来了」也会绿 —— 而那一枚令牌是能真的用的。
105
+ const tokenRows = () => db.get<{ n: number }>(
106
+ "SELECT COUNT(*) AS n FROM api_tokens WHERE user_id = ?1", adminId)!.n;
107
+ const beforeTokens = tokenRows();
90
108
  expect((await call(ntok, "GET", "/api/auth/tokens")).status).toBe(403);
91
109
  const minted = await call(ntok, "POST", "/api/auth/tokens", { name: "escalate" });
92
110
  expect(minted.status).toBe(403);
93
111
  expect(minted.body.token).toBeUndefined();
94
112
  expect((await call(ntok, "POST", "/api/auth/node-token", { network_id: OTHER_NET, node_name: "x" })).status).toBe(403);
113
+ // 两条被拒的发放都不许留下任何一行
114
+ expect(tokenRows()).toBe(beforeTokens);
115
+ expect(db.get("SELECT 1 FROM api_tokens WHERE name = 'escalate'")).toBeFalsy();
95
116
  expect((await call(ntok, "DELETE", "/api/auth/tokens/tok_whatever")).status).toBe(403);
96
117
  expect((await call(adminToken, "GET", "/api/auth/tokens")).status).toBe(200);
97
118
  });
119
+ // #3354 —— DELETE /api/auth/tokens/:id:拒绝之后**那一行必须还在**。
120
+ // 吊销是不可逆的副作用(令牌一旦删掉,用户的脚本当场断掉),所以拒绝时更不能碰它。
121
+ test("节点令牌不能吊销用户令牌:403 且目标行仍在", async () => {
122
+ const mint = await call(adminToken, "POST", "/api/auth/tokens", { name: "revoke-target" });
123
+ expect(mint.status).toBe(200);
124
+ const targetId = mint.body.token_id as string;
125
+ expect(db.get("SELECT 1 FROM api_tokens WHERE token_id = ?1", targetId)).toBeTruthy();
126
+ const denied = await call(ntok, "DELETE", `/api/auth/tokens/${targetId}`);
127
+ expect(denied.status).toBe(403);
128
+ // 拒绝的第二半:那一行还在(只断 403 时,「拒了但已经吊销了」也会绿)
129
+ expect(db.get("SELECT 1 FROM api_tokens WHERE token_id = ?1", targetId)).toBeTruthy();
130
+ });
131
+
98
132
  test("cannot edit the owner's profile or password", async () => {
99
133
  expect((await call(ntok, "PUT", "/api/auth/me", { display_name: "pwned" })).status).toBe(403);
100
134
  expect(db.get<{ display_name: string }>("SELECT display_name FROM users WHERE user_id = ?1", adminId)?.display_name).not.toBe("pwned");
101
135
  expect((await call(ntok, "POST", "/api/auth/password", { old_password: PW, new_password: "AnotherPassw0rd!" })).status).toBe(403);
136
+ // #3354 —— 拒绝的第二半:**旧密码仍然可用**(改密的副作用是旧密码立刻失效)。
137
+ // 只断 403 时,「拒了但密码已经被改掉」也会绿 —— 那会让主人当场登不进来。
138
+ const relogin = await call("", "POST", "/api/auth/login", { username: adminUsername, password: PW });
139
+ expect(relogin.status).toBe(200);
102
140
  });
103
141
  test("cannot create, rename or delete networks", async () => {
142
+ // #3354 —— 拒绝之外还要钉「没有副作用」:建网络的副作用是**多一行 networks**。
143
+ // 只断 403 时,「拒了但已经建出来了」也会绿 —— 而那是一个节点令牌自己开了租户。
144
+ const netCount = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM networks")!.n;
145
+ const beforeNets = netCount();
104
146
  expect((await call(ntok, "POST", "/api/networks", { name: "ntok-made" })).status).toBe(403);
147
+ expect(netCount()).toBe(beforeNets);
148
+ expect(db.get("SELECT 1 FROM networks WHERE network_name = 'ntok-made'")).toBeFalsy();
105
149
  expect((await call(ntok, "PUT", `/api/networks/${OTHER_NET}`, { name: "renamed" })).status).toBe(403);
106
150
  expect((await call(ntok, "DELETE", `/api/networks/${OTHER_NET}`)).status).toBe(403);
107
151
  expect(db.get("SELECT 1 FROM networks WHERE network_id = ?1", OTHER_NET)).toBeTruthy();
@@ -109,19 +153,41 @@ describe("account and network management need a user token", () => {
109
153
  test("cannot manage members, invites or join", async () => {
110
154
  expect((await call(ntok, "GET", `/api/networks/${NET}/members`)).status).toBe(403);
111
155
  expect((await call(ntok, "POST", `/api/networks/${NET}/members`, { user_id: "u_x" })).status).toBe(403);
156
+ // #3354 —— 邀请的副作用是**多一行 invite**(那行能换出一个新成员)。
157
+ const invites = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM network_invites")!.n;
158
+ const beforeInvites = invites();
112
159
  expect((await call(ntok, "POST", `/api/networks/${NET}/invite`, { role: "admin" })).status).toBe(403);
160
+ expect(invites()).toBe(beforeInvites);
161
+ // #3354 —— 拒绝之外还要钉「没加入任何网络」:join 的副作用是**多一行 network_members**。
162
+ // 只断 403 时,「拒了但已经加进去了」也会绿 —— 而那意味着节点令牌借邀请码混进了别人的租户。
163
+ const memberships = () => db.get<{ n: number }>(
164
+ "SELECT COUNT(*) AS n FROM network_members WHERE user_id = ?1", adminId)!.n;
165
+ const beforeJoin = memberships();
113
166
  expect((await call(ntok, "POST", "/api/networks/join", { invite_code: "inv_x" })).status).toBe(403);
167
+ expect(memberships()).toBe(beforeJoin);
114
168
  expect((await call(adminToken, "GET", `/api/networks/${NET}/members`)).status).toBe(200);
115
169
  });
116
170
  test("renames: a node token may only rename ITSELF in its bound network", async () => {
117
171
  // 别的网络 / 别的节点 → user_token_required
172
+ // #3354 —— 拒绝之外钉「没有开出事务」:prepare 的副作用是多一行 rename_txn。
173
+ const txns = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM rename_txn")!.n;
174
+ const beforeTxns = txns();
118
175
  expect((await call(ntok, "POST", "/api/node-rename/prepare", { network_id: OTHER_NET, old_alias: "ntok-node", new_alias: "b" })).status).toBe(403);
176
+ expect(txns()).toBe(beforeTxns);
119
177
  db.run(`INSERT INTO sessions (resume_id, alias, status, network_id) VALUES ('r_other_node', 'other-node', 'idle', ?1)`, [NET]);
120
178
  expect((await call(ntok, "POST", "/api/node-rename/prepare", { network_id: NET, old_alias: "other-node", new_alias: "b" })).status).toBe(403);
121
179
  // 另一个节点(管理员用户令牌)开的事务,本节点不能提交
122
180
  const foreign = await call(adminToken, "POST", "/api/node-rename/prepare", { network_id: NET, old_alias: "other-node", new_alias: "other-node-2" });
123
181
  expect(foreign.body.ok).toBe(true);
124
182
  expect((await call(ntok, "POST", "/api/node-rename/commit", { txn_id: foreign.body.txn_id })).status).toBe(403);
183
+ // #3354 —— 同理,abort 别人的事务也要被拒,且**拒绝之后那行事务还在**(状态仍是 prepared)。
184
+ // 只断 403 时,「拒了但已经把事务作废」也会绿 —— 而那会让真正的事务主人 abort 时拿到「已结束」。
185
+ const txnStatus = () => db.get<{ status: string }>(
186
+ "SELECT status FROM rename_txn WHERE txn_id = ?1", foreign.body.txn_id)?.status;
187
+ const statusBefore = txnStatus();
188
+ expect((await call(ntok, "POST", "/api/node-rename/abort", { txn_id: foreign.body.txn_id })).status).toBe(403);
189
+ expect(txnStatus()).toBe(statusBefore);
190
+ // 事务仍可被它的主人 abort(拒绝不许消耗掉它)
125
191
  expect((await call(adminToken, "POST", "/api/node-rename/abort", { txn_id: foreign.body.txn_id })).body.ok).toBe(true);
126
192
  // 自己:照常(anet node rename 就是这么用的)
127
193
  db.run(`INSERT INTO sessions (resume_id, alias, status, network_id) VALUES ('r_self_node', 'ntok-node', 'idle', ?1)`, [NET]);
package/src/server.ts CHANGED
@@ -107,6 +107,7 @@ import { assertScheduledTaskBackendSupported, handleScheduledTaskRequest, startS
107
107
  import { startDueReminderTimer } from "./requirement-due-reminders.js";
108
108
  import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
109
109
  import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
110
+ import { readLastConfigUpdate } from "./node-config-last-update.js";
110
111
  import { readBuildInfo } from "./build-info.js";
111
112
  import { requestProviderApplication } from "./daemon-provider-snapshots.js";
112
113
  import { requestNodeSecrets, getScopedSecrets } from "./scoped-secrets.js";
@@ -6400,6 +6401,14 @@ return Bun.serve({
6400
6401
  if (node.config_snapshot) {
6401
6402
  try { snapshot = JSON.parse(node.config_snapshot); } catch { snapshot = {}; }
6402
6403
  }
6404
+ // #3146 —— 上一次下发的**结局**。没有这一格时,客户端只能靠
6405
+ // 「config_revision 有没有涨」推断,涨不了就一律显示成 timeout(「90s 内没回来,去看日志」),
6406
+ // 而生产上真实结局是 rejected,原因(OpenCode V2 session is not running)就写在本库里。
6407
+ // ⇒ 读者拿不到答案,于是被指去机器上看日志 —— 一句话把人送错了层。
6408
+ const lastUpdate = readLastConfigUpdate(
6409
+ (sql: string, ...params: any[]) => (db.get as any)(sql, ...params),
6410
+ node.node_id,
6411
+ );
6403
6412
  return withCors(req, Response.json({
6404
6413
  ok: true,
6405
6414
  node_id: node.node_id,
@@ -6409,6 +6418,8 @@ return Bun.serve({
6409
6418
  model: snapshot.model ?? null,
6410
6419
  flags: snapshot.flags ?? {},
6411
6420
  config_update_capable: snapshot.config_update_capable ?? false,
6421
+ // null = 这个节点从来没有被下发过配置(与「下发过但还没终局」是两件事)
6422
+ last_update: lastUpdate,
6412
6423
  }));
6413
6424
  }
6414
6425
 
@@ -200,7 +200,12 @@ describe("默认值与授权接口", () => {
200
200
  const keep = await send(admin.token, "PUT", `/api/networks/${NET}/members/${alice.id}/task-grants`, { task_access: "scoped" });
201
201
  expect(keep.body.project_grants.length).toBe(2);
202
202
  expect((await send(alice.token, "GET", `/api/networks/${NET}/members/${alice.id}/task-grants`)).status).toBe(403);
203
+ // #3354 —— 拒绝之外钉「授权没变」:读回来的 project_grants 必须仍是原来那两条。
204
+ // 只断 403 时,「拒了但已经把 task_access 改成 all」也会绿 —— 那是一次越权的权限提升。
203
205
  expect((await send(carol.token, "PUT", `/api/networks/${NET}/members/${alice.id}/task-grants`, { task_access: "all" })).status).toBe(403);
206
+ const afterDenied = await get(admin.token, `/api/networks/${NET}/members/${alice.id}/task-grants`);
207
+ expect(afterDenied.body.task_access).toBe("scoped");
208
+ expect(afterDenied.body.project_grants.length).toBe(2);
204
209
  const nt = await send(admin.token, "POST", "/api/auth/node-token", { network_id: NET, node_name: "ta-node", node_id: "node_ta_1" });
205
210
  expect((await get(nt.body.token, `/api/networks/${NET}/members/${alice.id}/task-grants`)).status).toBe(403);
206
211
  expect(db.get("SELECT 1 FROM audit_log WHERE action = 'member_task_grants_changed' AND network_id = ?1", NET)).toBeTruthy();
@@ -100,8 +100,13 @@ test("account avatar upload: user token only, PNG limits, visibility by shared n
100
100
  expect(db.get("SELECT 1 AS ok FROM network_members m WHERE m.user_id=?1 AND m.network_id=?2", outsider.user!.user_id, a.network_id!)).toBeNull();
101
101
 
102
102
  // 匿名/节点令牌都不是「本人」。
103
+ // #3354 —— 拒绝之外钉「没有留下一行上传记录」:一次被拒的上传若仍写进 user_avatar_uploads,
104
+ // 它会占配额、也说明「拒绝」发生在落盘之后。
105
+ const uploadRows = () => db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_avatar_uploads")!.n;
106
+ const beforeNeg = uploadRows();
103
107
  expect((await upload(null, PNG_1X1)).status).toBe(401);
104
108
  expect((await upload(node.token!, PNG_1X1)).status).toBe(403);
109
+ expect(uploadRows()).toBe(beforeNeg);
105
110
 
106
111
  // 畸形输入:非 PNG、超边长、空、多字段、非 multipart。
107
112
  expect((await upload(a.token!, Buffer.from("not a png"))).body.error).toBe("invalid_image");
@@ -151,6 +151,30 @@ describe("#1828 POST /api/messages/ack covers inbox reply rows", () => {
151
151
  expect(again.body.acked).toBe(0);
152
152
  });
153
153
 
154
+ // #3354 —— 拒绝路径:未认证必须 401,且**一条都不许 ack**。
155
+ // 这条路由的门是 `restAuth?.userId`(没有它就没有"我的消息"这个概念)。
156
+ test("🔴 未认证 ⇒ 401,且 A 的未读数一条都不减(拒绝不许有副作用)", async () => {
157
+ const before = await get("/api/messages?scope=user", aToken);
158
+ const res = await fetch(`${base}/api/messages/ack`, {
159
+ method: "POST",
160
+ headers: { "Content-Type": "application/json" },
161
+ body: JSON.stringify({ message_ids: ["ib_a1"] }),
162
+ });
163
+ expect(res.status).toBe(401);
164
+ const after = await get("/api/messages?scope=user", aToken);
165
+ expect(after.body.unread_total).toBe(before.body.unread_total);
166
+ });
167
+
168
+ // 同时给 agent 与 message_ids 是歧义的:拒收,且不 ack 任何一边
169
+ test("🔴 {agent} 与 {message_ids} 同给 ⇒ 400 ambiguous_ack,且两边都不动", async () => {
170
+ const before = await get("/api/messages?scope=user", aToken);
171
+ const { status, body } = await post("/api/messages/ack", aToken, { agent: "peer-1", message_ids: ["ib_a1"] }) as any;
172
+ expect(status).toBe(400);
173
+ expect(body.error).toBe("ambiguous_ack");
174
+ const after = await get("/api/messages?scope=user", aToken);
175
+ expect(after.body.unread_total).toBe(before.body.unread_total);
176
+ });
177
+
154
178
  test("status 类 inbox 行不会被用户 ack 掉(不是发给用户的消息)", async () => {
155
179
  const { body } = await post("/api/messages/ack", aToken, { message_ids: ["ib_a_status"] });
156
180
  expect(body.acked_inbox).toBe(0);