@sleep2agi/commhub-server 0.9.0-preview.0 → 0.9.0-preview.100

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 (273) hide show
  1. package/README.md +130 -10
  2. package/bin/commhub.ts +92 -11
  3. package/package.json +8 -7
  4. package/src/ack-create-request-transport.test.ts +159 -0
  5. package/src/ack-create-request.test.ts +331 -0
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/agent-access-batch.test.ts +210 -0
  9. package/src/agent-access.ts +487 -0
  10. package/src/agent-acl-groups-http.test.ts +247 -0
  11. package/src/agent-acl-http.test.ts +520 -0
  12. package/src/agent-acl-slice3-http.test.ts +267 -0
  13. package/src/agent-groups-perf.test.ts +190 -0
  14. package/src/agent-notice.ts +48 -0
  15. package/src/alias-filter.test.ts +72 -0
  16. package/src/alias-filter.ts +42 -0
  17. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  18. package/src/api-host-supervisors-fallback.test.ts +271 -0
  19. package/src/api-nodes-shape.test.ts +188 -0
  20. package/src/auth-kdf-migration.test.ts +378 -0
  21. package/src/auth-sessions-http.test.ts +250 -0
  22. package/src/auth-tokens.test.ts +18 -9
  23. package/src/auth-validate.test.ts +5 -1
  24. package/src/auth.ts +554 -38
  25. package/src/avatar-validate.test.ts +163 -0
  26. package/src/avatar-validate.ts +103 -0
  27. package/src/blocked-exit-on-reply.test.ts +122 -0
  28. package/src/boot-side-effect.test.ts +124 -0
  29. package/src/commhub-bin-args.test.ts +85 -0
  30. package/src/config-apply-sec1.test.ts +830 -0
  31. package/src/config-apply-validate.test.ts +352 -0
  32. package/src/config-apply-validate.ts +249 -0
  33. package/src/create-node-blocked-gate.test.ts +356 -0
  34. package/src/create-node-tool-schema.test.ts +39 -0
  35. package/src/create-node-validate.test.ts +275 -0
  36. package/src/create-node-validate.ts +288 -0
  37. package/src/create-node-workdir.test.ts +255 -0
  38. package/src/create-node.test.ts +354 -0
  39. package/src/create-node.ts +349 -0
  40. package/src/cross-tenant-injection.test.ts +110 -0
  41. package/src/dashboard-slash-routing-http.test.ts +107 -0
  42. package/src/db-adapter-guard.test.ts +148 -0
  43. package/src/db-adapter-translate.test.ts +128 -0
  44. package/src/db-adapter.ts +323 -87
  45. package/src/db-timestamp.test.ts +38 -0
  46. package/src/db-timestamp.ts +15 -0
  47. package/src/db.ts +1268 -42
  48. package/src/delivered-without-push.test.ts +140 -0
  49. package/src/department-groups-http.test.ts +209 -0
  50. package/src/department-groups-sync-http.test.ts +328 -0
  51. package/src/department-groups.ts +434 -0
  52. package/src/department-heads-http.test.ts +329 -0
  53. package/src/department-heads.ts +226 -0
  54. package/src/departments-http.test.ts +185 -0
  55. package/src/departments.ts +260 -0
  56. package/src/desktop-message-seam.test.ts +150 -0
  57. package/src/desktop-message.test.ts +368 -0
  58. package/src/dm-file-scope-http.test.ts +178 -0
  59. package/src/ext-token-shared.test.ts +60 -0
  60. package/src/ext-validation-regression.test.ts +131 -0
  61. package/src/external-schedule-edits-http.test.ts +321 -0
  62. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  63. package/src/external-schedule-edits.ts +327 -0
  64. package/src/file-download-authz-dev-open.test.ts +135 -0
  65. package/src/file-download-authz.test.ts +404 -0
  66. package/src/file-download-date-bucket.test.ts +436 -0
  67. package/src/file-network-scope-dev-open.test.ts +97 -0
  68. package/src/file-network-scope.test.ts +732 -0
  69. package/src/group-membership-events-http.test.ts +264 -0
  70. package/src/group-messages-http.test.ts +482 -0
  71. package/src/group-messages.ts +297 -0
  72. package/src/health-redaction.test.ts +642 -0
  73. package/src/http-gzip.test.ts +94 -0
  74. package/src/http-gzip.ts +112 -0
  75. package/src/hub-timestamp.test.ts +38 -0
  76. package/src/hub-timestamp.ts +27 -0
  77. package/src/human-dm.ts +215 -0
  78. package/src/inbox-count-sse.test.ts +310 -0
  79. package/src/inbox-count.ts +29 -0
  80. package/src/index.ts +15 -2128
  81. package/src/lifecycle-guard.ts +50 -0
  82. package/src/list-host-supervisors.test.ts +314 -0
  83. package/src/mcp-context-cost-http.test.ts +119 -0
  84. package/src/mcp-projects-events-http.test.ts +162 -0
  85. package/src/mcp-route-label-http.test.ts +120 -0
  86. package/src/mcp-write-network-resolution.test.ts +429 -0
  87. package/src/member-audit-network-id-http.test.ts +93 -0
  88. package/src/member-presence-http.test.ts +206 -0
  89. package/src/messages-ack-by-agent-http.test.ts +142 -0
  90. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  91. package/src/migrate-sqlite-to-pg.ts +263 -0
  92. package/src/model-auth-notify-http.test.ts +181 -0
  93. package/src/model-auth-notify.ts +116 -0
  94. package/src/network-name-http.test.ts +75 -0
  95. package/src/network-scope.ts +224 -0
  96. package/src/network-token-membership-http.test.ts +139 -0
  97. package/src/node-attrs-validate.ts +88 -0
  98. package/src/node-attrs.test.ts +217 -0
  99. package/src/node-create-request-status-http.test.ts +92 -0
  100. package/src/node-files-transport.test.ts +344 -0
  101. package/src/node-health-dispatch-http.test.ts +279 -0
  102. package/src/node-health-guard.ts +105 -0
  103. package/src/node-health-passthrough.test.ts +115 -0
  104. package/src/node-health-store.ts +72 -0
  105. package/src/node-id-alias.test.ts +188 -0
  106. package/src/node-identity-conflict-http.test.ts +269 -0
  107. package/src/node-identity-conflict.ts +142 -0
  108. package/src/node-identity-mismatch.test.ts +74 -0
  109. package/src/node-lifecycle-controllable.test.ts +64 -0
  110. package/src/node-lifecycle-controllable.ts +51 -0
  111. package/src/node-logs-transport.test.ts +263 -0
  112. package/src/node-permissions-http.test.ts +276 -0
  113. package/src/node-permissions.ts +242 -0
  114. package/src/node-request-retention.test.ts +281 -0
  115. package/src/node-request-retention.ts +120 -0
  116. package/src/node-skills-transport.test.ts +209 -0
  117. package/src/node-token-privilege-http.test.ts +149 -0
  118. package/src/observer-avatar-http.test.ts +431 -0
  119. package/src/observer-push.test.ts +252 -0
  120. package/src/package-version-consistency.test.ts +25 -0
  121. package/src/peer-reply-atomic.test.ts +455 -0
  122. package/src/peer-reply-capability.test.ts +70 -0
  123. package/src/pg-worker.ts +87 -0
  124. package/src/probe-validate.test.ts +221 -0
  125. package/src/probe-validate.ts +104 -0
  126. package/src/probe.test.ts +80 -0
  127. package/src/probe.ts +200 -0
  128. package/src/project-viewer-can-http.test.ts +114 -0
  129. package/src/push.ts +429 -10
  130. package/src/redact-tokens.test.ts +65 -0
  131. package/src/redact-tokens.ts +40 -0
  132. package/src/rename.ts +7 -2
  133. package/src/reply-target-derivation.test.ts +96 -0
  134. package/src/report-status-host-schema.test.ts +211 -0
  135. package/src/report-status-resume-id-handover.test.ts +150 -0
  136. package/src/require-explicit-test-db.ts +9 -0
  137. package/src/requirement-due-reminders-http.test.ts +390 -0
  138. package/src/requirement-due-reminders.ts +310 -0
  139. package/src/requirement-events-http.test.ts +257 -0
  140. package/src/requirement-events.test.ts +45 -0
  141. package/src/requirement-events.ts +144 -0
  142. package/src/requirement-notify.ts +165 -0
  143. package/src/requirement-participant-notify-http.test.ts +309 -0
  144. package/src/requirement-tag-ops-http.test.ts +266 -0
  145. package/src/requirement-tags.ts +89 -0
  146. package/src/requirements-comment-http.test.ts +165 -0
  147. package/src/requirements-completed-at-migration.test.ts +70 -0
  148. package/src/requirements-errors-mcp-http.test.ts +164 -0
  149. package/src/requirements-errors.ts +143 -0
  150. package/src/requirements-etag-http.test.ts +91 -0
  151. package/src/requirements-http.test.ts +709 -0
  152. package/src/requirements-last-event-http.test.ts +344 -0
  153. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  154. package/src/requirements-list-slim-http.test.ts +319 -0
  155. package/src/requirements-mcp.test.ts +163 -0
  156. package/src/requirements-migrate.ts +225 -0
  157. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  158. package/src/requirements-people-http.test.ts +114 -0
  159. package/src/requirements-people-mcp-http.test.ts +225 -0
  160. package/src/requirements-people.ts +127 -0
  161. package/src/requirements-priority-lowest.test.ts +114 -0
  162. package/src/requirements-search-http.test.ts +182 -0
  163. package/src/requirements-search.test.ts +32 -0
  164. package/src/requirements-search.ts +145 -0
  165. package/src/requirements-seq-http.test.ts +193 -0
  166. package/src/requirements-seq-migration.test.ts +63 -0
  167. package/src/requirements-start-date.test.ts +125 -0
  168. package/src/requirements-stats-http.test.ts +288 -0
  169. package/src/requirements-stats.ts +164 -0
  170. package/src/requirements-status-participants-http.test.ts +220 -0
  171. package/src/requirements-upgrade-e2e.test.ts +126 -0
  172. package/src/requirements-upgrade-migration.test.ts +98 -0
  173. package/src/requirements.ts +1761 -0
  174. package/src/resolve-port.test.ts +57 -0
  175. package/src/resolve-port.ts +44 -0
  176. package/src/response-charset.test.ts +130 -0
  177. package/src/rest-explicit-columns-http.test.ts +222 -0
  178. package/src/rest-identity.test.ts +129 -0
  179. package/src/rest-identity.ts +100 -0
  180. package/src/rest-projections.ts +68 -0
  181. package/src/rest-write-network-resolution.test.ts +133 -0
  182. package/src/restricted-files.ts +73 -0
  183. package/src/retention.test.ts +450 -0
  184. package/src/retention.ts +281 -0
  185. package/src/route-callers-http.test.ts +120 -0
  186. package/src/route-timing.test.ts +211 -0
  187. package/src/route-timing.ts +258 -0
  188. package/src/rules-file-duplicate-alias.test.ts +234 -0
  189. package/src/rules-file-session-target.test.ts +207 -0
  190. package/src/rules-file-transport.test.ts +237 -0
  191. package/src/runtime-label.test.ts +22 -0
  192. package/src/runtime-label.ts +21 -0
  193. package/src/scheduled-doorbell-nodeless-session.test.ts +130 -0
  194. package/src/scheduled-reply-unread-http.test.ts +212 -0
  195. package/src/scheduled-run-terminal.test.ts +268 -0
  196. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  197. package/src/scheduled-stuck-http.test.ts +238 -0
  198. package/src/scheduled-stuck.ts +153 -0
  199. package/src/scheduled-tasks-http.test.ts +638 -0
  200. package/src/scheduled-tasks.ts +641 -0
  201. package/src/send-dedup-request-id.test.ts +229 -0
  202. package/src/send-reply-agent-warning.test.ts +202 -0
  203. package/src/send-reply-alias-optional.test.ts +131 -0
  204. package/src/send-reply-attachments.test.ts +458 -0
  205. package/src/send_dedup.test.ts +54 -0
  206. package/src/send_dedup.ts +52 -6
  207. package/src/serve-error.test.ts +38 -0
  208. package/src/serve-error.ts +27 -0
  209. package/src/server.ts +5038 -0
  210. package/src/shared/external-schedule-contract.ts +60 -0
  211. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  212. package/src/shared/probe-host-allowlist.ts +128 -0
  213. package/src/shared/reserved-env-drift.test.ts +43 -0
  214. package/src/shared/reserved-env.test.ts +35 -0
  215. package/src/shared/reserved-env.ts +31 -0
  216. package/src/side-thread-command-transport.test.ts +312 -0
  217. package/src/side-thread-command-transport.ts +318 -0
  218. package/src/side-thread-http-integration.test.ts +233 -0
  219. package/src/side-thread-http.ts +504 -0
  220. package/src/side-thread-production.test.ts +72 -0
  221. package/src/side-thread-production.ts +118 -0
  222. package/src/side-thread.test.ts +1067 -0
  223. package/src/side-thread.ts +2499 -0
  224. package/src/skillhub-http.test.ts +108 -0
  225. package/src/sqlite-close-checkpoint.test.ts +78 -0
  226. package/src/stale-sweeper.test.ts +181 -0
  227. package/src/stale-sweeper.ts +114 -0
  228. package/src/start-node.test.ts +109 -0
  229. package/src/status-alias-filter-http.test.ts +106 -0
  230. package/src/status-alias-resolver-http.test.ts +163 -0
  231. package/src/status-alias-resolver.ts +19 -0
  232. package/src/status-node-id-filter-http.test.ts +161 -0
  233. package/src/status-read-cache-http.test.ts +229 -0
  234. package/src/status-read-cache.ts +122 -0
  235. package/src/stop-delete-node.test.ts +1164 -0
  236. package/src/task-access-http.test.ts +379 -0
  237. package/src/task-access.ts +413 -0
  238. package/src/task-auth-origin-http.test.ts +91 -0
  239. package/src/task-auth-origin.test.ts +24 -0
  240. package/src/task-auth-origin.ts +7 -0
  241. package/src/task-consumption.test.ts +482 -0
  242. package/src/task-diagnostic-http.test.ts +149 -0
  243. package/src/task-diagnostic.test.ts +115 -0
  244. package/src/task-diagnostic.ts +118 -0
  245. package/src/task-expiry-notice-http.test.ts +287 -0
  246. package/src/task-expiry-notice.ts +313 -0
  247. package/src/task-idempotency-mcp.test.ts +142 -0
  248. package/src/task-idempotency.test.ts +60 -0
  249. package/src/task-idempotency.ts +75 -0
  250. package/src/task-lifecycle-watcher.test.ts +204 -0
  251. package/src/task-lifecycle-watcher.ts +49 -0
  252. package/src/task-network-resolution-http.test.ts +141 -0
  253. package/src/task-queue-ahead-http.test.ts +309 -0
  254. package/src/task-queue-ahead-scale.test.ts +211 -0
  255. package/src/task-queue-ahead.ts +186 -0
  256. package/src/task-stale-open-http.test.ts +290 -0
  257. package/src/task-stale-open.ts +103 -0
  258. package/src/tasks-pagination-http.test.ts +141 -0
  259. package/src/tool-audience-http.test.ts +195 -0
  260. package/src/tool-audience.ts +109 -0
  261. package/src/tools-list-json-schema.test.ts +67 -0
  262. package/src/tools.ts +5426 -275
  263. package/src/update-provider.test.ts +234 -0
  264. package/src/upload-early-reject-guard.test.ts +155 -0
  265. package/src/uploads-http.test.ts +97 -15
  266. package/src/uploads.test.ts +66 -0
  267. package/src/uploads.ts +138 -5
  268. package/src/user-inbox-by-agent-http.test.ts +161 -0
  269. package/src/user-inbox-netid-notnull.test.ts +122 -0
  270. package/src/user-inbox-read-http.test.ts +223 -0
  271. package/src/user-inbox-schema.test.ts +54 -0
  272. package/src/vault.test.ts +200 -0
  273. package/src/vault.ts +156 -0
package/src/auth.ts CHANGED
@@ -1,8 +1,34 @@
1
1
  /**
2
2
  * V3 Auth module — user registration, login, token management
3
3
  */
4
- import { db, generateId, hashPassword, hashToken, generateToken, generateUserToken, generateNetworkToken, uuidv4 } from "./db.js";
4
+ import { db, generateId, hashPassword, verifyPassword, hashToken, generateToken, generateUserToken, generateNetworkToken, uuidv4 } from "./db.js"; import { deleteDepartmentsForNetwork, groupTx, removeMemberFromChatGroups } from "./departments.js"; // #419: also ensures network_members.department_id exists (same line on purpose: docs pin auth.ts line numbers)
5
5
  import { WEAK_PASSWORDS } from "./password-dict.js";
6
+ import { NETWORK_REST_COLUMNS, NETWORK_REST_SELECT, sqlColumns } from "./rest-projections.js";
7
+ import { deleteAgentGrants, isAgentRestricted } from "./agent-access.js"; import { deleteTaskGrantsForMember, NEW_MEMBER_TASK_ACCESS, type TaskAccessMode } from "./task-access.js"; // 一行两个 import:文档钉着 auth.ts 的行号
8
+
9
+ // Round-6 A1 hardening — dummy hash for username-enumeration timing
10
+ // close. We compute ONE scrypt hash of a throwaway password and reuse
11
+ // it on every `!user` branch in login. The verify call against this
12
+ // dummy always fails the timingSafeEqual (the candidate password is
13
+ // unrelated), but the wall-clock cost of the scrypt() invocation is
14
+ // identical to the user-exists path — closing the ~50ms username-
15
+ // exists oracle that opened up when we moved off SHA-256 to scrypt.
16
+ //
17
+ // **Lazy** (memoized) rather than module-load constant: COMMHUB_SCRYPT_N
18
+ // may be set after this module loads (tests do this), and the dummy
19
+ // MUST match the current N so its scrypt cost matches the cost of
20
+ // verifying a real stored hash. Computing on first use captures the
21
+ // env-current N. After that it's a single fixed string for the
22
+ // process lifetime — one scrypt per process, not per request.
23
+ let _enumerationDummyHash: string | null = null;
24
+ function getEnumerationDummyHash(): string {
25
+ if (_enumerationDummyHash === null) {
26
+ _enumerationDummyHash = hashPassword(
27
+ "agent-network::enumeration-oracle-close::do-not-match"
28
+ );
29
+ }
30
+ return _enumerationDummyHash;
31
+ }
6
32
 
7
33
  export interface AuthUser {
8
34
  user_id: string;
@@ -17,6 +43,7 @@ export interface AuthResult {
17
43
  error?: string;
18
44
  user?: AuthUser;
19
45
  token?: string; // user token (utok_)
46
+ token_id?: string; // api_tokens.token_id of `token` — lets a client tell which row in GET /api/auth/sessions is itself
20
47
  network_token?: string; // network token (ntok_) for default network
21
48
  network_id?: string;
22
49
  // #261 P0-2 (2026-06-28): true when the logged-in user still has the
@@ -35,7 +62,7 @@ function validatePasswordStrength(password: string, label = "password"): string
35
62
  return null;
36
63
  }
37
64
 
38
- export function register(username: string, password: string, email?: string, displayName?: string): AuthResult {
65
+ export function register(username: string, password: string, email?: string, displayName?: string, opts: { issueTokens?: boolean; client?: SessionClientInfo } = {}): AuthResult {
39
66
  if (!username || username.length < 2) return { ok: false, error: "username must be at least 2 characters" };
40
67
  if (username.length > 50) return { ok: false, error: "username too long (max 50)" };
41
68
  if (!/^[a-zA-Z0-9_\-\u4e00-\u9fff]+$/.test(username)) return { ok: false, error: "username contains invalid characters" };
@@ -63,23 +90,54 @@ export function register(username: string, password: string, email?: string, dis
63
90
  [userId, username, pwHash, email || null, displayName || username, isFirstUser ? "admin" : "user"]
64
91
  );
65
92
 
66
- // Auto-create default network + add as owner member
93
+ // Auto-create the user's own network + add as owner member.
94
+ //
95
+ // Name it after the user rather than the literal "default". Every
96
+ // registration used to mint a network called "default", so a hub with N
97
+ // users showed N identical "default" rows in the Dashboard sidebar with
98
+ // no way to tell them apart (23 of them on the live hub, 22 empty).
99
+ // Three CLI call sites (bin/cli.ts debate / demo-social / pr-review) resolve
100
+ // a network as:
101
+ // me.user.default_network_id
102
+ // || networks.find(n => n.network_name === "default")
103
+ // || networks[0]
104
+ // Checked against the live hub: GET /api/auth/me returns
105
+ // {user_id, username, display_name, email, role} — there is no
106
+ // default_network_id field, and nothing in server/ ever writes one. So the
107
+ // first term is always undefined and the name lookup is the operative path,
108
+ // not a fallback.
109
+ //
110
+ // After this change that lookup misses for new users and they land on
111
+ // networks[0]. That still resolves to this network because listNetworks()
112
+ // is `ORDER BY created_at` ascending (auth.ts:296) and this row is the
113
+ // user's oldest. Reordering that query would silently point those three
114
+ // commands at the wrong network.
67
115
  const networkId = generateId("net");
68
116
  db.run(
69
117
  "INSERT INTO networks (network_id, network_name, owner_id, description) VALUES (?1, ?2, ?3, ?4)",
70
- [networkId, "default", userId, "Auto-created default network"]
118
+ [networkId, username, userId, `Auto-created network for ${username}`]
71
119
  );
72
120
  db.run(
73
121
  "INSERT INTO network_members (network_id, user_id, role) VALUES (?1, ?2, 'owner')",
74
122
  [networkId, userId]
75
123
  );
76
124
 
125
+ // 管理员代建账号(POST /api/admin/users)时不给管理员发这个用户的令牌:
126
+ // 令牌只该由用户本人登录时拿到。
127
+ if (opts.issueTokens === false) {
128
+ return {
129
+ ok: true,
130
+ user: { user_id: userId, username, display_name: displayName || username, email: email || null, role: isFirstUser ? "admin" : "user" },
131
+ network_id: networkId,
132
+ };
133
+ }
134
+
77
135
  // User token (utok_) — not bound to network, for CLI/Dashboard login
78
136
  const userToken = generateUserToken();
79
137
  const userTokenId = generateId("tok");
80
138
  db.run(
81
- "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
82
- [userTokenId, hashToken(userToken), userId, null, "user-login", "user"]
139
+ "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, client_label, user_agent) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
140
+ [userTokenId, hashToken(userToken), userId, null, "user-login", "user", cleanClientField(opts.client?.label, 64), cleanClientField(opts.client?.userAgent, 256)]
83
141
  );
84
142
 
85
143
  // Network token (ntok_) — bound to default network, for agent-node
@@ -94,18 +152,49 @@ export function register(username: string, password: string, email?: string, dis
94
152
  ok: true,
95
153
  user: { user_id: userId, username, display_name: displayName || username, email: email || null, role: isFirstUser ? "admin" : "user" },
96
154
  token: userToken,
155
+ token_id: userTokenId,
97
156
  network_token: networkToken,
98
157
  network_id: networkId,
99
158
  };
100
159
  }
101
160
 
102
- export function login(username: string, password: string): AuthResult {
161
+ export function login(username: string, password: string, client: SessionClientInfo = {}): AuthResult {
103
162
  const user = db.get<any>(
104
163
  "SELECT user_id, username, password_hash, display_name, email, role, must_change_password FROM users WHERE username = ?1",
105
164
  username);
106
165
 
107
- if (!user) return { ok: false, error: "invalid username or password" };
108
- if (user.password_hash !== hashPassword(password)) return { ok: false, error: "invalid username or password" };
166
+ if (!user) {
167
+ // Round-6 A1 hardening (timing-oracle close): pre-A1 the user-
168
+ // exists vs user-doesn't-exist branches both ran a µs-scale
169
+ // SHA-256, so wall-clock difference was lost in noise. Post-A1
170
+ // the user-exists path runs ~50ms scrypt while user-doesn't
171
+ // returns sub-ms — that ~50ms gap is web-measurable and turns
172
+ // login into a username-enumeration oracle (rate limiter only
173
+ // partially mitigates). Equalize by running scrypt against a
174
+ // module-constant dummy hash on the not-found path. Dummy is
175
+ // pre-generated at module load (not per call) so we don't burn
176
+ // a fresh scryptSync on every miss.
177
+ verifyPassword(password, getEnumerationDummyHash());
178
+ return { ok: false, error: "invalid username or password" };
179
+ }
180
+ // Round-6 A1: verifyPassword accepts both new scrypt format and
181
+ // legacy bare-sha256. On successful legacy verify, lazy-upgrade the
182
+ // stored hash in place (zero downtime, no forced password change).
183
+ const verify = verifyPassword(password, user.password_hash);
184
+ if (!verify.ok) return { ok: false, error: "invalid username or password" };
185
+ if (verify.needsRehash) {
186
+ try {
187
+ const upgraded = hashPassword(password);
188
+ db.run(
189
+ "UPDATE users SET password_hash = ?1, updated_at = datetime('now') WHERE user_id = ?2",
190
+ [upgraded, user.user_id]
191
+ );
192
+ } catch (e: any) {
193
+ // Don't fail the login if the rehash write hits a transient
194
+ // error — the user authenticated, we'll try again next login.
195
+ console.log(`[commhub auth] lazy-rehash failed for user ${user.user_id}: ${e?.message ?? e}`);
196
+ }
197
+ }
109
198
 
110
199
  // Issue a NEW user token — do NOT rotate/invalidate existing ones. Each
111
200
  // login (cli, dashboard, second machine) gets its own row so they don't
@@ -113,8 +202,8 @@ export function login(username: string, password: string): AuthResult {
113
202
  const userToken = generateUserToken();
114
203
  const tokenId = generateId("tok");
115
204
  db.run(
116
- "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
117
- [tokenId, hashToken(userToken), user.user_id, null, "user-login", "user"]
205
+ "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, client_label, user_agent) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
206
+ [tokenId, hashToken(userToken), user.user_id, null, "user-login", "user", cleanClientField(client.label, 64), cleanClientField(client.userAgent, 256)]
118
207
  );
119
208
 
120
209
  // Find default network
@@ -130,6 +219,7 @@ export function login(username: string, password: string): AuthResult {
130
219
  ok: true,
131
220
  user: { user_id: user.user_id, username: user.username, display_name: user.display_name, email: user.email, role: user.role },
132
221
  token,
222
+ token_id: tokenId,
133
223
  network_id: networkId,
134
224
  // #261 P0-2 — only include field when truthy (back-compat; old clients
135
225
  // don't see this field at all unless their account is flagged).
@@ -137,33 +227,171 @@ export function login(username: string, password: string): AuthResult {
137
227
  };
138
228
  }
139
229
 
140
- /** Create a network-scoped token (ntok_) for a specific node */
141
- export function createNetworkTokenForNode(userId: string, networkId: string, nodeName: string): { ok: boolean; token?: string; error?: string } {
230
+ /**
231
+ * Create a network-scoped token (ntok_) for a specific node.
232
+ *
233
+ * RFC-036: callers that provide nodeId atomically establish the immutable
234
+ * node-owner binding before the plaintext token is returned. The 3-argument
235
+ * legacy form remains available for old clients, but its token has no bound
236
+ * node id and therefore cannot consume external-schedule edit intents.
237
+ */
238
+ export function createNetworkTokenForNode(userId: string, networkId: string, nodeName: string, nodeId?: string): { ok: boolean; token?: string; token_id?: string; node_id?: string; error?: string } {
142
239
  // Verify user is a member of this network with write access
143
240
  const role = getUserNetworkRole(userId, networkId);
144
241
  if (!role || role === "viewer") return { ok: false, error: "no write access to this network" };
242
+ if (isAgentRestricted(userId, networkId)) return { ok: false, error: "restricted members cannot create network tokens" };
243
+ if (!nodeName || nodeName.length > 200) return { ok: false, error: "invalid_node_name" };
244
+ if (nodeId !== undefined && (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(nodeId))) {
245
+ return { ok: false, error: "invalid_node_id" };
246
+ }
145
247
  const token = generateNetworkToken();
146
248
  const tokenId = generateId("tok");
147
- db.run(
148
- "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
149
- [tokenId, hashToken(token), userId, networkId, `node:${nodeName}`, "network"]
150
- );
151
- return { ok: true, token };
249
+ try {
250
+ db.transaction(() => {
251
+ if (nodeId) {
252
+ const existing = db.get<{ network_id: string | null; owner_user_id: string | null }>(
253
+ "SELECT network_id, owner_user_id FROM nodes WHERE node_id = ?1",
254
+ nodeId,
255
+ );
256
+ if (existing?.network_id && existing.network_id !== networkId) throw new Error("cross_network_node");
257
+ // Existing pre-RFC-036 rows have no trustworthy owner anchor. A token
258
+ // refresh must not turn knowledge of a legacy node_id into ownership.
259
+ // They remain read-only until a separately authorized migration.
260
+ if (existing && !existing.owner_user_id) throw new Error("node_owner_unclaimed");
261
+ if (existing?.owner_user_id && existing.owner_user_id !== userId) throw new Error("node_owner_mismatch");
262
+ db.run(
263
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, owner_user_id, updated_at)
264
+ VALUES (?1, ?2, ?2, ?3, ?4, datetime('now'))
265
+ ON CONFLICT(node_id) DO UPDATE SET
266
+ node_name = COALESCE(nodes.node_name, ?2),
267
+ alias = COALESCE(nodes.alias, ?2),
268
+ network_id = COALESCE(nodes.network_id, ?3),
269
+ owner_user_id = COALESCE(nodes.owner_user_id, ?4),
270
+ updated_at = datetime('now')`,
271
+ [nodeId, nodeName, networkId, userId],
272
+ );
273
+ if (!existing) {
274
+ db.run(
275
+ `INSERT INTO audit_log (user_id, action, target_type, target_id, detail, network_id)
276
+ VALUES (?1, 'external_schedule.owner_claimed', 'node', ?2, ?3, ?4)`,
277
+ [userId, nodeId, JSON.stringify({ node_id: nodeId, network_id: networkId }), networkId],
278
+ );
279
+ }
280
+ }
281
+ db.run(
282
+ "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, bound_node_id) VALUES (?1, ?2, ?3, ?4, ?5, 'network', ?6)",
283
+ [tokenId, hashToken(token), userId, networkId, `node:${nodeName}`, nodeId ?? null],
284
+ );
285
+ });
286
+ } catch (error: any) {
287
+ const code = String(error?.message || "node_token_create_failed");
288
+ if (code === "cross_network_node" || code === "node_owner_unclaimed" || code === "node_owner_mismatch") return { ok: false, error: code };
289
+ throw error;
290
+ }
291
+ return { ok: true, token, token_id: tokenId, ...(nodeId ? { node_id: nodeId } : {}) };
152
292
  }
153
293
 
154
- export function resolveToken(token: string): { user: AuthUser; networkId: string | null; tokenName: string | null; tokenId: string | null } | null {
294
+ // ── 登录会话(login session)令牌 ──
295
+ // 「会话令牌」= scope='user' 且不绑网络的 utok_:登录 / 注册签发的 user-login、改密码后换发的
296
+ // password-change、管理员重置签发的 admin-reset。它们代表「某台设备上的一次登录」,
297
+ // 由 GET /api/auth/sessions 列出、可被「退出其他设备」撤销,并且**闲置 N 天自动过期**(滑动窗口,
298
+ // 以 last_used_at 计,从没用过的以 created_at 计)。
299
+ // 不受影响:POST /api/auth/tokens 显式创建的 API 令牌(scope='full')、节点 / 网络令牌(network_id 非空)。
300
+ // 它们是给脚本和节点长期用的凭据,由各自的管理入口撤销,不该因为一段时间没被用就失效。
301
+ const SESSION_TOKEN_SQL = "scope = 'user' AND network_id IS NULL";
302
+ // last_used_at 最多每小时写一次:每个请求都会解析令牌,原来每次都 UPDATE。
303
+ // 以小时为粒度对一个以天计的闲置窗口没有影响。
304
+ const LAST_USED_WRITE_INTERVAL_SECONDS = 3600;
305
+
306
+ export type SessionClientInfo = { label?: unknown; userAgent?: unknown };
307
+
308
+ function cleanClientField(value: unknown, max: number): string | null {
309
+ if (typeof value !== "string") return null;
310
+ const cleaned = value.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
311
+ return cleaned || null;
312
+ }
313
+
314
+ /** 会话令牌闲置多少天后过期;COMMHUB_SESSION_IDLE_DAYS,默认 30,0 = 关闭闲置过期。每次读,测试可以改。 */
315
+ export function sessionIdleDays(): number {
316
+ const raw = process.env.COMMHUB_SESSION_IDLE_DAYS;
317
+ if (raw === undefined || raw.trim() === "") return 30;
318
+ const n = Number(raw);
319
+ return Number.isFinite(n) && n >= 0 ? n : 30;
320
+ }
321
+
322
+ // datetime('now', ?N) 的偏移参数;PgAdapter 把它译成 NOW() + $N::INTERVAL。
323
+ function idleCutoffOffset(): string | null {
324
+ const days = sessionIdleDays();
325
+ return days > 0 ? `-${Math.round(days * 86400)} seconds` : null;
326
+ }
327
+
328
+ // 已按闲置过期的会话令牌:只有 resolveToken 拒绝之后才查,用来把 401 说清楚是「过期」而不是「无效」。
329
+ export function isExpiredSessionToken(token: string): boolean {
330
+ const cutoff = idleCutoffOffset();
331
+ if (!token || !cutoff) return false;
332
+ const row = db.get<any>(
333
+ `SELECT token_id FROM api_tokens
334
+ WHERE token_hash = ?1 AND ${SESSION_TOKEN_SQL} AND revoked_at IS NULL
335
+ AND COALESCE(last_used_at, created_at) < datetime('now', ?2)`,
336
+ hashToken(token), cutoff);
337
+ return !!row;
338
+ }
339
+
340
+ export type TokenRejection = "node_owner_restricted" | "not_network_member";
341
+
342
+ /** 查令牌行并判它能不能用:没有这一行 → null;有但被拒 → { rejected };能用 → { row }。 */
343
+ function lookupToken(token: string): { row: any; rejected?: undefined } | { row?: undefined; rejected: TokenRejection } | null {
155
344
  const tHash = hashToken(token);
345
+ const cutoff = idleCutoffOffset();
156
346
  const row = db.get<any>(
157
347
  `SELECT t.token_id, t.user_id, t.network_id, t.scope, t.name AS token_name,
158
- u.username, u.display_name, u.email, u.role
348
+ u.username, u.display_name, u.email, u.role,
349
+ CASE WHEN t.network_id IS NULL THEN 1
350
+ WHEN EXISTS (SELECT 1 FROM network_members nm WHERE nm.network_id = t.network_id AND nm.user_id = t.user_id) THEN 1
351
+ ELSE 0 END AS is_member
159
352
  FROM api_tokens t JOIN users u ON t.user_id = u.user_id
160
- WHERE t.token_hash = ?1 AND (t.expires_at IS NULL OR t.expires_at > datetime('now'))`,
161
- tHash);
353
+ WHERE t.token_hash = ?1
354
+ AND (t.expires_at IS NULL OR t.expires_at > datetime('now'))
355
+ AND t.revoked_at IS NULL${cutoff ? `
356
+ AND NOT (t.scope = 'user' AND t.network_id IS NULL AND COALESCE(t.last_used_at, t.created_at) < datetime('now', ?2))` : ""}`,
357
+ ...(cutoff ? [tHash, cutoff] : [tHash]));
162
358
 
163
359
  if (!row) return null;
164
360
 
165
- // Update last_used
166
- db.run("UPDATE api_tokens SET last_used_at = datetime('now') WHERE token_hash = ?1", [tHash]);
361
+ // #488 —— 网络令牌只在它的用户还是这个网络的成员时有效。被移出网络的人留下的令牌(移出前签发的、
362
+ // 或移出时还没自动吊销的老数据)以前照样解析:MCP 每个工具都拒,REST 读却能拿到整个网络的名册。
363
+ if (row.network_id && !Number(row.is_member)) return { rejected: "not_network_member" };
364
+
365
+ // 多用户 Agent 权限:网络令牌(ntok_ / 邀请码令牌)的权限是「这个网络里的一切」,
366
+ // 受限成员在受限网络里不能持有它 —— 否则拿它就绕过了授权过滤。这里是唯一的解析入口,
367
+ // 在这里拒绝,所有 REST / MCP / SSE 路径一起生效(含升级前就签发、后来才被设为受限的令牌)。
368
+ if (row.network_id && isAgentRestricted(row.user_id, row.network_id)) return { rejected: "node_owner_restricted" };
369
+ return { row };
370
+ }
371
+
372
+ /**
373
+ * 令牌存在、但因为主人的网络成员身份被拒时,说清楚为什么(给 401 带上 reason / hint)。
374
+ * 只在调用者真的持有这枚令牌时才有输出 —— 不认识的令牌一律 null,不泄露任何东西。
375
+ */
376
+ export function tokenRejection(token: string | null | undefined): { reason: TokenRejection; hint: string } | null {
377
+ if (!token) return null;
378
+ const r = lookupToken(token);
379
+ if (!r?.rejected) return null;
380
+ return r.rejected === "not_network_member"
381
+ ? { reason: r.rejected, hint: "this token's owner is no longer a member of its network; ask a network admin to re-invite them, then create a new token" }
382
+ : { reason: r.rejected, hint: "this token's owner only has access to granted Agents in this network, and network tokens need full Agent access; ask a network admin to set the owner's Agent access to all" };
383
+ }
384
+
385
+ export function resolveToken(token: string): { user: AuthUser; networkId: string | null; tokenName: string | null; tokenId: string | null } | null {
386
+ const found = lookupToken(token);
387
+ if (!found?.row) return null;
388
+ const row = found.row;
389
+
390
+ // Update last_used(节流:见 LAST_USED_WRITE_INTERVAL_SECONDS)
391
+ db.run(
392
+ "UPDATE api_tokens SET last_used_at = datetime('now') WHERE token_id = ?1 AND (last_used_at IS NULL OR last_used_at < datetime('now', ?2))",
393
+ [row.token_id, `-${LAST_USED_WRITE_INTERVAL_SECONDS} seconds`]
394
+ );
167
395
 
168
396
  return {
169
397
  user: { user_id: row.user_id, username: row.username, display_name: row.display_name, email: row.email, role: row.role },
@@ -179,7 +407,7 @@ export function resolveToken(token: string): { user: AuthUser; networkId: string
179
407
 
180
408
  export function getUserNetworks(userId: string) {
181
409
  return db.all<any>(
182
- "SELECT * FROM networks WHERE owner_id = ?1 ORDER BY created_at",
410
+ `SELECT ${NETWORK_REST_SELECT} FROM networks WHERE owner_id = ?1 ORDER BY created_at`,
183
411
  userId);
184
412
  }
185
413
 
@@ -224,7 +452,7 @@ export function listTokens(userId: string) {
224
452
  }
225
453
 
226
454
  export function renameNetwork(userId: string, networkId: string, newName: string): { ok: boolean; error?: string } {
227
- const net = db.get<any>("SELECT * FROM networks WHERE network_id = ?1", networkId);
455
+ const net = db.get<any>("SELECT owner_id FROM networks WHERE network_id = ?1", networkId);
228
456
  if (!net) return { ok: false, error: "network not found" };
229
457
  if (net.owner_id !== userId) return { ok: false, error: "not your network" };
230
458
  const dup = db.get<any>("SELECT network_id FROM networks WHERE owner_id = ?1 AND network_name = ?2", userId, newName);
@@ -234,13 +462,21 @@ export function renameNetwork(userId: string, networkId: string, newName: string
234
462
  }
235
463
 
236
464
  export function deleteNetwork(userId: string, networkId: string): { ok: boolean; error?: string } {
237
- const net = db.get<any>("SELECT * FROM networks WHERE network_id = ?1", networkId);
465
+ const net = db.get<any>("SELECT owner_id FROM networks WHERE network_id = ?1", networkId);
238
466
  if (!net) return { ok: false, error: "network not found" };
239
467
  if (net.owner_id !== userId) return { ok: false, error: "not your network" };
240
468
  // Check if any sessions/tasks still reference this network
241
469
  const sessions = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM sessions WHERE network_id = ?1", networkId);
242
470
  if (sessions && sessions.cnt > 0) return { ok: false, error: `network has ${sessions.cnt} active session(s) — stop them first` };
243
- db.run("DELETE FROM networks WHERE network_id = ?1 AND owner_id = ?2", [networkId, userId]);
471
+ db.transaction(() => {
472
+ db.run("DELETE FROM networks WHERE network_id = ?1 AND owner_id = ?2", [networkId, userId]);
473
+ // PR #519 codex catch: leaving membership rows behind made deleted
474
+ // networks count toward getUserNetworkIds — a stale row could flip a
475
+ // single-network user to "ambiguous" or auto-resolve writes INTO the
476
+ // deleted network. Remove memberships with the network.
477
+ db.run("DELETE FROM network_members WHERE network_id = ?1", [networkId]);
478
+ deleteNetworkAgentGroups(networkId); deleteDepartmentsForNetwork(networkId); // #2144, #419 (one line: docs pin auth.ts line numbers)
479
+ });
244
480
  return { ok: true };
245
481
  }
246
482
 
@@ -250,6 +486,7 @@ export function createToken(userId: string, name: string, networkId?: string): {
250
486
  const role = getUserNetworkRole(userId, networkId);
251
487
  if (!role) return { ok: false, error: "not a member of this network" };
252
488
  if (role === "viewer") return { ok: false, error: "viewer cannot create full-access network tokens" };
489
+ if (isAgentRestricted(userId, networkId)) return { ok: false, error: "restricted members cannot create network tokens" };
253
490
  }
254
491
  const token = generateToken();
255
492
  const tokenId = generateId("tok");
@@ -282,12 +519,57 @@ export function revokeOtherUserTokens(userId: string, exceptTokenId?: string | n
282
519
  return result.changes;
283
520
  }
284
521
 
522
+ export type LoginSession = {
523
+ token_id: string;
524
+ name: string;
525
+ created_at: string;
526
+ last_used_at: string | null;
527
+ client_label: string | null;
528
+ user_agent: string | null;
529
+ is_current: boolean;
530
+ };
531
+
532
+ /** 我的登录会话(未过期、未撤销),最近使用的在前。 */
533
+ export function listSessions(userId: string, currentTokenId: string | null): LoginSession[] {
534
+ const cutoff = idleCutoffOffset();
535
+ const rows = db.all<any>(
536
+ `SELECT token_id, name, created_at, last_used_at, client_label, user_agent FROM api_tokens
537
+ WHERE user_id = ?1 AND ${SESSION_TOKEN_SQL} AND revoked_at IS NULL${cutoff ? `
538
+ AND COALESCE(last_used_at, created_at) >= datetime('now', ?2)` : ""}
539
+ ORDER BY COALESCE(last_used_at, created_at) DESC, created_at DESC`,
540
+ ...(cutoff ? [userId, cutoff] : [userId]));
541
+ return rows.map((r) => ({
542
+ token_id: r.token_id,
543
+ name: r.name,
544
+ created_at: r.created_at,
545
+ last_used_at: r.last_used_at ?? null,
546
+ client_label: r.client_label ?? null,
547
+ user_agent: r.user_agent ?? null,
548
+ is_current: !!currentTokenId && r.token_id === currentTokenId,
549
+ }));
550
+ }
551
+
552
+ /** 撤销我的一个登录会话;可以是当前这个(= 退出登录)。不是会话令牌(API 令牌 / 节点令牌)时当作不存在。 */
553
+ export function revokeSession(userId: string, tokenId: string): { ok: boolean; error?: string } {
554
+ const result = db.run(`DELETE FROM api_tokens WHERE token_id = ?1 AND user_id = ?2 AND ${SESSION_TOKEN_SQL}`, [tokenId, userId]);
555
+ return result.changes > 0 ? { ok: true } : { ok: false, error: "session_not_found" };
556
+ }
557
+
558
+ /** 退出其他所有设备:撤销我除当前之外的全部登录会话(含已闲置过期的)。API 令牌、节点令牌不动。 */
559
+ export function revokeOtherSessions(userId: string, currentTokenId: string): number {
560
+ return db.run(`DELETE FROM api_tokens WHERE user_id = ?1 AND ${SESSION_TOKEN_SQL} AND token_id != ?2`, [userId, currentTokenId]).changes;
561
+ }
562
+
285
563
  export function changePassword(userId: string, oldPassword: string, newPassword: string, currentTokenId?: string | null): { ok: boolean; error?: string; revoked?: number } {
286
564
  const passwordError = validatePasswordStrength(newPassword, "new password");
287
565
  if (passwordError) return { ok: false, error: passwordError };
288
566
  const user = db.get<any>("SELECT password_hash FROM users WHERE user_id = ?1", userId);
289
567
  if (!user) return { ok: false, error: "user not found" };
290
- if (user.password_hash !== hashPassword(oldPassword)) return { ok: false, error: "incorrect current password" };
568
+ // Round-6 A1: verifyPassword accepts both formats. No need to
569
+ // lazy-rehash here separately because we're about to overwrite
570
+ // password_hash with the new password's scrypt hash below anyway.
571
+ const verify = verifyPassword(oldPassword, user.password_hash);
572
+ if (!verify.ok) return { ok: false, error: "incorrect current password" };
291
573
  // #261 P0-2 — clearing must_change_password as a side-effect of a real
292
574
  // password change. If the user changes via `anet passwd`, the bootstrap
293
575
  // nudge goes away on next login. SET to 0 explicitly (rather than skip)
@@ -331,22 +613,61 @@ export function resetUserPassword(targetUsername: string, callerIsHubAdmin: bool
331
613
 
332
614
  export function getNetworkMembers(networkId: string) {
333
615
  return db.all<any>(
334
- `SELECT nm.user_id, nm.role, nm.joined_at, nm.invited_by, u.username, u.display_name
616
+ `SELECT nm.user_id, nm.role, nm.joined_at, nm.invited_by, u.username, u.display_name,
617
+ CASE WHEN u.role = 'admin' OR nm.role IN ('owner', 'admin') OR nm.agent_access = 'all' THEN 'all' ELSE 'granted' END AS agent_access,
618
+ (SELECT COUNT(*) FROM network_member_agent_grants g WHERE g.network_id = nm.network_id AND g.user_id = nm.user_id) AS agent_grant_count,
619
+ CASE WHEN u.role = 'admin' OR nm.role IN ('owner', 'admin') OR nm.task_access = 'all' THEN 'all' ELSE 'scoped' END AS task_access,
620
+ (SELECT COUNT(*) FROM network_member_project_grants pg WHERE pg.network_id = nm.network_id AND pg.user_id = nm.user_id) AS task_project_count,
621
+ (SELECT COUNT(*) FROM network_member_group_grants gg WHERE gg.network_id = nm.network_id AND gg.user_id = nm.user_id) AS agent_group_count,
622
+ nm.department_id
335
623
  FROM network_members nm JOIN users u ON nm.user_id = u.user_id
336
624
  WHERE nm.network_id = ?1 ORDER BY nm.joined_at`,
337
625
  networkId);
338
626
  }
339
627
 
628
+ /** 网络里的人类成员(给受限成员也能看的通讯录):只有身份字段,不含角色与授权。 */
629
+ export function getNetworkHumans(networkId: string) {
630
+ return db.all<{ user_id: string; username: string; display_name: string | null }>(
631
+ `SELECT u.user_id, u.username, u.display_name
632
+ FROM network_members nm JOIN users u ON nm.user_id = u.user_id
633
+ WHERE nm.network_id = ?1 ORDER BY COALESCE(NULLIF(u.display_name, ''), u.username), u.user_id`,
634
+ networkId);
635
+ }
636
+
340
637
  export function getUserNetworkRole(userId: string, networkId: string): string | null {
341
638
  const row = db.get<any>("SELECT role FROM network_members WHERE network_id = ?1 AND user_id = ?2", networkId, userId);
342
639
  return row?.role || null;
343
640
  }
344
641
 
345
- export function addNetworkMember(networkId: string, userId: string, role: string, invitedBy?: string): { ok: boolean; error?: string } {
642
+ const MEMBER_ROLES = new Set(["admin", "member", "viewer"]);
643
+
644
+ /**
645
+ * 用户名与本网络某个 Agent 的 alias 相同时不能入网:用户的私人 SSE 频道、inbox、
646
+ * 任务往来都按「用户名」寻址,与 alias 撞名会让受限成员收到那个 Agent 的流量。
647
+ * 只在入网时查(管理员 / 邀请码持有者才触发),不放在公开的 /api/auth/register 上,
648
+ * 免得注册接口变成 alias 探测器。
649
+ */
650
+ export function usernameCollidesWithAgent(networkId: string, userId: string): boolean {
651
+ return !!db.get(
652
+ `SELECT 1 FROM users u WHERE u.user_id = ?2 AND (
653
+ EXISTS (SELECT 1 FROM sessions s WHERE s.network_id = ?1 AND s.alias = u.username)
654
+ OR EXISTS (SELECT 1 FROM nodes n WHERE n.network_id = ?1 AND n.alias = u.username))`,
655
+ networkId, userId,
656
+ );
657
+ }
658
+
659
+ // 新成员默认 agent_access='granted'(零 Agent 权限),owner/admin 角色不看这一列。
660
+ export function addNetworkMember(networkId: string, userId: string, role: string, invitedBy?: string, opts: { agentAccess?: "all" | "granted"; taskAccess?: TaskAccessMode } = {}): { ok: boolean; error?: string } {
661
+ if (!MEMBER_ROLES.has(role)) return { ok: false, error: "invalid role" };
662
+ const agentAccess = opts.agentAccess === "all" ? "all" : "granted";
663
+ // 任务范围:新成员默认 NEW_MEMBER_TASK_ACCESS(task-access.ts 一处定义)。
664
+ const taskAccess: TaskAccessMode = opts.taskAccess === "all" || opts.taskAccess === "scoped" ? opts.taskAccess : NEW_MEMBER_TASK_ACCESS;
665
+ if (!db.get("SELECT 1 FROM users WHERE user_id = ?1", userId)) return { ok: false, error: "user not found" };
346
666
  const existing = db.get<any>("SELECT 1 FROM network_members WHERE network_id = ?1 AND user_id = ?2", networkId, userId);
347
667
  if (existing) return { ok: false, error: "user already a member" };
348
- db.run("INSERT INTO network_members (network_id, user_id, role, invited_by) VALUES (?1, ?2, ?3, ?4)",
349
- [networkId, userId, role, invitedBy || null]);
668
+ if (usernameCollidesWithAgent(networkId, userId)) return { ok: false, error: "username_collides_with_agent_alias" };
669
+ db.run("INSERT INTO network_members (network_id, user_id, role, invited_by, agent_access, task_access) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
670
+ [networkId, userId, role, invitedBy || null, agentAccess, taskAccess]);
350
671
  return { ok: true };
351
672
  }
352
673
 
@@ -361,7 +682,13 @@ export function removeNetworkMember(networkId: string, userId: string): { ok: bo
361
682
  const member = db.get<any>("SELECT role FROM network_members WHERE network_id = ?1 AND user_id = ?2", networkId, userId);
362
683
  if (!member) return { ok: false, error: "not a member" };
363
684
  if (member.role === "owner") return { ok: false, error: "cannot remove owner" };
364
- db.run("DELETE FROM network_members WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
685
+ groupTx(() => { // RFC-042 §9.3:同 db.transaction,另在提交后推 group_membership_changed(移出网络 → 他所在每个群)
686
+ db.run("DELETE FROM network_members WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
687
+ // #488 —— 他在这个网络里的令牌(节点令牌 / 邀请码令牌)一起吊销;resolveToken 也会拒非成员的令牌,这里让库里的状态如实。
688
+ db.run("UPDATE api_tokens SET revoked_at = datetime('now') WHERE network_id = ?1 AND user_id = ?2 AND revoked_at IS NULL", [networkId, userId]);
689
+ deleteAgentGrants(networkId, userId);
690
+ deleteTaskGrantsForMember(networkId, userId); removeMemberFromChatGroups(networkId, userId); // RFC-042:他在本网络所有群里的行(不论来源)。同一行:文档钉着 auth.ts 的行号
691
+ });
365
692
  return { ok: true };
366
693
  }
367
694
 
@@ -384,7 +711,10 @@ export function createInvite(networkId: string, createdBy: string, role: string
384
711
  }
385
712
 
386
713
  export function joinByInvite(inviteCode: string, userId: string): { ok: boolean; network_id?: string; role?: string; error?: string } {
387
- const invite = db.get<any>("SELECT * FROM network_invites WHERE invite_code = ?1", inviteCode);
714
+ const invite = db.get<any>(
715
+ "SELECT invite_code, network_id, role, created_by, max_uses, used_count, expires_at, created_at FROM network_invites WHERE invite_code = ?1",
716
+ inviteCode,
717
+ );
388
718
  if (!invite) return { ok: false, error: "invalid invite code" };
389
719
  if (invite.max_uses > 0 && invite.used_count >= invite.max_uses) return { ok: false, error: "invite code fully used" };
390
720
  if (invite.expires_at) {
@@ -394,10 +724,13 @@ export function joinByInvite(inviteCode: string, userId: string): { ok: boolean;
394
724
  // Check not already member
395
725
  const existing = db.get<any>("SELECT 1 FROM network_members WHERE network_id = ?1 AND user_id = ?2", invite.network_id, userId);
396
726
  if (existing) return { ok: false, error: "already a member of this network" };
727
+ if (usernameCollidesWithAgent(invite.network_id, userId)) return { ok: false, error: "username_collides_with_agent_alias" };
397
728
  // Add member + increment used count
398
- db.run("INSERT INTO network_members (network_id, user_id, role, invited_by) VALUES (?1, ?2, ?3, ?4)",
399
- [invite.network_id, userId, invite.role, invite.created_by]);
729
+ db.run("INSERT INTO network_members (network_id, user_id, role, invited_by, agent_access, task_access) VALUES (?1, ?2, ?3, ?4, 'granted', ?5)",
730
+ [invite.network_id, userId, invite.role, invite.created_by, NEW_MEMBER_TASK_ACCESS]);
400
731
  db.run("UPDATE network_invites SET used_count = used_count + 1 WHERE invite_code = ?1", [inviteCode]);
732
+ // 受限成员不能持有网络令牌(resolveToken 会拒),别签一个用不了的。
733
+ if (isAgentRestricted(userId, invite.network_id)) return { ok: true, network_id: invite.network_id, role: invite.role };
401
734
  // Auto-create a token for this network
402
735
  const token = generateToken();
403
736
  const tokenId = generateId("tok");
@@ -409,8 +742,191 @@ export function joinByInvite(inviteCode: string, userId: string): { ok: boolean;
409
742
  /** Get all networks a user is a member of (replaces owner-only query) */
410
743
  export function getUserAllNetworks(userId: string) {
411
744
  return db.all<any>(
412
- `SELECT n.*, nm.role as member_role
745
+ `SELECT ${sqlColumns(NETWORK_REST_COLUMNS, "n")}, nm.role as member_role,
746
+ -- 多用户 Agent 权限:客户端据此显示「还没有被分配任何 Agent,请联系管理员」。
747
+ CASE WHEN u.role = 'admin' OR nm.role IN ('owner', 'admin') OR nm.agent_access = 'all' THEN 'all' ELSE 'granted' END AS agent_access,
748
+ -- 任务权限(RFC-038 §9):客户端据此显示只读提示与「还没有与你相关的任务」。
749
+ CASE WHEN u.role = 'admin' OR nm.role IN ('owner', 'admin') OR nm.task_access = 'all' THEN 'all' ELSE 'scoped' END AS task_access
413
750
  FROM networks n JOIN network_members nm ON n.network_id = nm.network_id
751
+ JOIN users u ON u.user_id = nm.user_id
414
752
  WHERE nm.user_id = ?1 ORDER BY nm.role = 'owner' DESC, n.created_at`,
415
753
  userId);
416
754
  }
755
+
756
+ // ══════════════════════════════════════
757
+ // 多用户账号:管理员建号
758
+ // ══════════════════════════════════════
759
+
760
+ export type AdminCreateUserInput = {
761
+ username?: unknown;
762
+ password?: unknown;
763
+ display_name?: unknown;
764
+ email?: unknown;
765
+ network_id?: unknown;
766
+ role?: unknown;
767
+ };
768
+
769
+ export type AdminCreateUserResult =
770
+ | { ok: true; user: AuthUser; network_id: string; membership: { network_id: string; role: string; agent_access: "granted" } | null }
771
+ | { ok: false; error: string; status: number };
772
+
773
+ /**
774
+ * 管理员(或某网络的 owner/admin,限于把人建进自己管的网络)代建账号。
775
+ * 走 register() 的全部规则(用户名、密码 ≥ 8 且不是弱密码、自动建个人网络),
776
+ * 但不签发令牌 —— 用户自己登录才拿令牌。
777
+ * 可选一步把新用户加进 network_id,默认 role=member、agent_access='granted'(零 Agent 权限)。
778
+ * 建号与入网在同一事务里:入网失败(如用户名与 Agent alias 撞名)时账号也不落库。
779
+ */
780
+ export function adminCreateUser(input: AdminCreateUserInput, actor: { userId: string; isHubAdmin: boolean }): AdminCreateUserResult {
781
+ const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
782
+ const username = str(input.username);
783
+ const password = typeof input.password === "string" ? input.password : "";
784
+ const displayName = str(input.display_name) || undefined;
785
+ const email = str(input.email) || undefined;
786
+ const networkId = str(input.network_id) || null;
787
+ const role = str(input.role) || "member";
788
+
789
+ if (networkId) {
790
+ if (!db.get("SELECT 1 FROM networks WHERE network_id = ?1", networkId)) return { ok: false, error: "network_not_found", status: 404 };
791
+ if (!MEMBER_ROLES.has(role)) return { ok: false, error: "invalid role", status: 400 };
792
+ const actorRole = getUserNetworkRole(actor.userId, networkId);
793
+ if (!actor.isHubAdmin && actorRole !== "owner" && actorRole !== "admin") return { ok: false, error: "owner/admin required", status: 403 };
794
+ // 网络 admin 不能建出和自己平级的 admin;只有 owner / Hub 管理员可以。
795
+ if (role === "admin" && !actor.isHubAdmin && actorRole !== "owner") return { ok: false, error: "owner required to add admins", status: 403 };
796
+ } else if (!actor.isHubAdmin) {
797
+ return { ok: false, error: "admin required", status: 403 };
798
+ }
799
+ // 首个用户会被 register() 自动设成 Hub 管理员;代建路径上永远不会是首个用户(调用者本身就是用户)。
800
+ // 但仍显式拒绝,防止空库 + 旧令牌之类的边角把代建变成「造管理员」。
801
+ const userCount = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM users");
802
+ if (!userCount || userCount.cnt === 0) return { ok: false, error: "bootstrap_via_register", status: 400 };
803
+
804
+ class Rollback extends Error { constructor(readonly result: AdminCreateUserResult) { super("rollback"); } }
805
+ try {
806
+ return db.transaction(() => {
807
+ const created = register(username, password, email, displayName, { issueTokens: false });
808
+ if (!created.ok || !created.user) throw new Rollback({ ok: false, error: created.error || "register_failed", status: 400 });
809
+ if (!networkId) return { ok: true as const, user: created.user, network_id: created.network_id!, membership: null };
810
+ const added = addNetworkMember(networkId, created.user.user_id, role, actor.userId);
811
+ if (!added.ok) throw new Rollback({ ok: false, error: added.error || "add_member_failed", status: added.error === "username_collides_with_agent_alias" ? 409 : 400 });
812
+ return {
813
+ ok: true as const,
814
+ user: created.user,
815
+ network_id: created.network_id!,
816
+ membership: { network_id: networkId, role, agent_access: "granted" as const },
817
+ };
818
+ });
819
+ } catch (error) {
820
+ if (error instanceof Rollback) return error.result;
821
+ throw error;
822
+ }
823
+ }
824
+
825
+ /** Hub 管理员的用户列表:每个用户带上他所在的网络与角色、agent_access。不含密码哈希。 */
826
+ export function listUsersWithMemberships() {
827
+ const users = db.all<{ user_id: string; username: string; display_name: string | null; email: string | null; role: string; created_at: string }>(
828
+ "SELECT user_id, username, display_name, email, role, created_at FROM users ORDER BY created_at",
829
+ );
830
+ const memberships = db.all<{ user_id: string; network_id: string; network_name: string | null; role: string; agent_access: string | null }>(
831
+ `SELECT nm.user_id, nm.network_id, n.network_name, nm.role, nm.agent_access
832
+ FROM network_members nm JOIN networks n ON n.network_id = nm.network_id`,
833
+ );
834
+ const byUser = new Map<string, Array<{ network_id: string; network_name: string | null; role: string; agent_access: "all" | "granted" }>>();
835
+ for (const m of memberships) {
836
+ const list = byUser.get(m.user_id) ?? [];
837
+ list.push({ network_id: m.network_id, network_name: m.network_name, role: m.role, agent_access: m.agent_access === "all" ? "all" : "granted" });
838
+ byUser.set(m.user_id, list);
839
+ }
840
+ return users.map((u) => ({ ...u, networks: byUser.get(u.user_id) ?? [] }));
841
+ }
842
+
843
+ // Hub 管理员删**别人的**网络(清理旧测试账号留下的个人网络)。只删空网络:
844
+ // 下面每张表里有一行就拒(409),并把计数原样回给调用方。表是按 schema 里所有带
845
+ // network_id 的表逐个分类的,不是凭记忆 —— 新加一张带 network_id 的表要在这里归一类。
846
+ // 阻断:真实内容,或会在删后重新长出节点的在途请求。
847
+ // 清理:只描述「这个网络」本身的元数据/历史,网络没了它们就悬空。
848
+ // 保留:audit_log(删除记录本身要留下)。
849
+ const NETWORK_CONTENT_CHECKS: Array<[label: string, sql: string]> = [
850
+ ["nodes", "SELECT COUNT(*) AS cnt FROM nodes WHERE network_id = ?1"],
851
+ ["sessions", "SELECT COUNT(*) AS cnt FROM sessions WHERE network_id = ?1"],
852
+ ["tasks", "SELECT COUNT(*) AS cnt FROM tasks WHERE network_id = ?1"],
853
+ ["inbox", "SELECT COUNT(*) AS cnt FROM inbox WHERE network_id = ?1"],
854
+ ["user_inbox", "SELECT COUNT(*) AS cnt FROM user_inbox WHERE network_id = ?1"],
855
+ ["requirements", "SELECT COUNT(*) AS cnt FROM requirements WHERE network_id = ?1"],
856
+ ["requirement_projects", "SELECT COUNT(*) AS cnt FROM requirement_projects WHERE network_id = ?1"],
857
+ ["scheduled_tasks", "SELECT COUNT(*) AS cnt FROM scheduled_tasks WHERE network_id = ?1"],
858
+ ["providers", "SELECT COUNT(*) AS cnt FROM providers WHERE network_id = ?1"],
859
+ ["network_secrets", "SELECT COUNT(*) AS cnt FROM network_secrets WHERE network_id = ?1"],
860
+ ["skillhub_skills", "SELECT COUNT(*) AS cnt FROM skillhub_skills WHERE network_id = ?1"],
861
+ ["side_chats", "SELECT COUNT(*) AS cnt FROM side_chats WHERE network_id = ?1"],
862
+ // #2144 —— 组是管理员手工建的配置,和 requirements 一样算内容:有组就拒,别替人删掉。
863
+ ["agent_groups", "SELECT COUNT(*) AS cnt FROM agent_groups WHERE network_id = ?1"],
864
+ ["pending_node_create_requests", "SELECT COUNT(*) AS cnt FROM node_create_requests WHERE network_id = ?1 AND status IN ('pending', 'delivered')"],
865
+ ["pending_node_start_requests", "SELECT COUNT(*) AS cnt FROM node_start_requests WHERE network_id = ?1 AND status IN ('pending', 'delivered')"],
866
+ ];
867
+ const NETWORK_CLEANUP_TABLES = [
868
+ "network_members", "network_member_agent_grants", "network_invites", "api_tokens",
869
+ "node_create_requests", "node_start_requests", "node_stop_requests", "node_rules_requests",
870
+ "node_config_updates", "rename_txn", "probe_results", "agent_telemetry", "completions",
871
+ "task_events", "task_terminal_events", "scheduled_task_runs", "external_schedule_edits",
872
+ // 标签颜色:网络本身的元数据(标签本体在 requirements 行里,那张表是阻断项)。
873
+ "network_tags",
874
+ // 组织架构(board #419):部门是网络本身的元数据。
875
+ "network_departments",
876
+ ];
877
+
878
+ function tableExists(name: string): boolean {
879
+ return db.dialect === "postgres"
880
+ ? !!db.get("SELECT 1 AS x FROM information_schema.tables WHERE table_name = ?1", name)
881
+ : !!db.get("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?1", name);
882
+ }
883
+
884
+ export function countNetworkContents(networkId: string): Record<string, number> {
885
+ const counts: Record<string, number> = {};
886
+ for (const [label, sql] of NETWORK_CONTENT_CHECKS) {
887
+ const table = sql.match(/FROM (\w+)/)![1];
888
+ // 按需建表的模块(requirements / side-thread)在没用过的库上可能还没有这张表 —— 那就是 0 行。
889
+ if (!tableExists(table)) continue;
890
+ const cnt = db.get<{ cnt: number }>(sql, networkId)?.cnt ?? 0;
891
+ if (cnt > 0) counts[label] = cnt;
892
+ }
893
+ return counts;
894
+ }
895
+
896
+ export type AdminDeleteNetworkResult =
897
+ | { ok: true; owner_id: string; network_name: string; cleaned: Record<string, number> }
898
+ | { ok: false; status: number; error: string; counts?: Record<string, number> };
899
+
900
+ // extraCounts:库外的内容(上传文件的索引在磁盘上),由调用方数好传进来,和库内计数一起判。
901
+ export function adminDeleteEmptyNetwork(networkId: string, extraCounts: Record<string, number> = {}): AdminDeleteNetworkResult {
902
+ if (networkId === "default") return { ok: false, status: 409, error: "the default network cannot be deleted" };
903
+ return db.transaction((): AdminDeleteNetworkResult => {
904
+ const net = db.get<{ owner_id: string; network_name: string }>("SELECT owner_id, network_name FROM networks WHERE network_id = ?1", networkId);
905
+ if (!net) return { ok: false, status: 404, error: "network not found" };
906
+ const counts = { ...countNetworkContents(networkId) };
907
+ for (const [k, v] of Object.entries(extraCounts)) if (v > 0) counts[k] = v;
908
+ if (Object.keys(counts).length > 0) {
909
+ const summary = Object.entries(counts).map(([k, v]) => `${k}=${v}`).join(", ");
910
+ return { ok: false, status: 409, error: `network is not empty (${summary}); only empty networks can be deleted by a hub admin`, counts };
911
+ }
912
+ const cleaned: Record<string, number> = {};
913
+ for (const table of NETWORK_CLEANUP_TABLES) {
914
+ if (!tableExists(table)) continue;
915
+ const changes = db.run(`DELETE FROM ${table} WHERE network_id = ?1`, [networkId]).changes;
916
+ if (changes > 0) cleaned[table] = changes;
917
+ }
918
+ for (const [table, changes] of Object.entries(deleteNetworkAgentGroups(networkId))) if (changes > 0) cleaned[table] = changes;
919
+ db.run("DELETE FROM networks WHERE network_id = ?1", [networkId]);
920
+ return { ok: true, owner_id: net.owner_id, network_name: net.network_name, cleaned };
921
+ });
922
+ }
923
+
924
+ // #2144 —— Agent 分组(#2131)的三张表跟着网络一起删。agent_group_members 没有 network_id 列,
925
+ // 只能按该网络的 group_id 删,所以必须在删 agent_groups 之前删它。owner 删网络与管理员删空网络共用。
926
+ export function deleteNetworkAgentGroups(networkId: string): Record<string, number> {
927
+ return {
928
+ network_member_group_grants: db.run("DELETE FROM network_member_group_grants WHERE network_id = ?1", [networkId]).changes,
929
+ agent_group_members: db.run("DELETE FROM agent_group_members WHERE group_id IN (SELECT group_id FROM agent_groups WHERE network_id = ?1)", [networkId]).changes,
930
+ agent_groups: db.run("DELETE FROM agent_groups WHERE network_id = ?1", [networkId]).changes,
931
+ };
932
+ }