@sleep2agi/commhub-server 0.9.0-preview.23 → 0.9.0-preview.230

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 (408) hide show
  1. package/README.md +129 -9
  2. package/bin/commhub.ts +93 -9
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +654 -0
  15. package/src/agent-department-http.test.ts +215 -0
  16. package/src/agent-groups-perf.test.ts +223 -0
  17. package/src/agent-notice.ts +48 -0
  18. package/src/agent-team-whoami-http.test.ts +98 -0
  19. package/src/agent-teams-http.test.ts +330 -0
  20. package/src/agent-teams.ts +244 -0
  21. package/src/alias-baseline-2571.test.ts +162 -0
  22. package/src/alias-baseline.ts +113 -0
  23. package/src/alias-filter.test.ts +72 -0
  24. package/src/alias-filter.ts +42 -0
  25. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  26. package/src/api-host-supervisors-fallback.test.ts +6 -7
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +95 -4
  29. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  30. package/src/auth-sessions-http.test.ts +250 -0
  31. package/src/auth-validate.test.ts +5 -1
  32. package/src/auth-weak-password-login.test.ts +176 -0
  33. package/src/auth.ts +609 -51
  34. package/src/avatar-validate.test.ts +52 -2
  35. package/src/avatar-validate.ts +35 -1
  36. package/src/backfill-node-ids-2664.test.ts +128 -0
  37. package/src/binding-generation-http.test.ts +121 -0
  38. package/src/blocked-exit-on-reply.test.ts +122 -0
  39. package/src/broadcast-fanout-2721.test.ts +149 -0
  40. package/src/broadcast-fanout.ts +117 -0
  41. package/src/chain-attempt-dedup.test.ts +447 -0
  42. package/src/clip.test.ts +36 -0
  43. package/src/clip.ts +46 -0
  44. package/src/clone-node.test.ts +248 -0
  45. package/src/clone-node.ts +289 -0
  46. package/src/codex-config-flags.ts +77 -0
  47. package/src/codex-fork-contract.ts +23 -0
  48. package/src/codex-fork-migration.test.ts +38 -0
  49. package/src/commhub-bin-args.test.ts +85 -0
  50. package/src/config-apply-validate.test.ts +188 -1
  51. package/src/config-apply-validate.ts +222 -3
  52. package/src/cors-origins.test.ts +73 -0
  53. package/src/create-node-blocked-gate.test.ts +356 -0
  54. package/src/create-node-network-id.test.ts +91 -0
  55. package/src/create-node-tool-schema.test.ts +49 -0
  56. package/src/create-node-unicode-name.test.ts +120 -0
  57. package/src/create-node-validate.test.ts +199 -7
  58. package/src/create-node-validate.ts +232 -15
  59. package/src/create-node-workdir.test.ts +289 -0
  60. package/src/create-node.ts +88 -23
  61. package/src/daemon-provider-snapshots.test.ts +421 -0
  62. package/src/daemon-provider-snapshots.ts +327 -0
  63. package/src/daemon-token-owner-http.test.ts +236 -0
  64. package/src/dashboard-slash-routing-http.test.ts +109 -0
  65. package/src/db-adapter-guard.test.ts +148 -0
  66. package/src/db-adapter-translate.test.ts +128 -0
  67. package/src/db-adapter.ts +377 -91
  68. package/src/db-timestamp.test.ts +38 -0
  69. package/src/db-timestamp.ts +15 -0
  70. package/src/db.ts +1264 -153
  71. package/src/delivered-without-push.test.ts +140 -0
  72. package/src/department-groups-http.test.ts +209 -0
  73. package/src/department-groups-sync-http.test.ts +328 -0
  74. package/src/department-groups.ts +434 -0
  75. package/src/department-heads-http.test.ts +350 -0
  76. package/src/department-heads.ts +226 -0
  77. package/src/departments-agent-count.test.ts +132 -0
  78. package/src/departments-http.test.ts +185 -0
  79. package/src/departments-mcp.test.ts +128 -0
  80. package/src/departments.ts +318 -0
  81. package/src/desktop-message-seam.test.ts +150 -0
  82. package/src/desktop-message.test.ts +368 -0
  83. package/src/dm-file-scope-http.test.ts +178 -0
  84. package/src/empty-node-sweeper.test.ts +104 -0
  85. package/src/empty-node-sweeper.ts +88 -0
  86. package/src/env-transport-gate-http.test.ts +240 -0
  87. package/src/env-transport-gate.ts +80 -0
  88. package/src/env-transport-policy.ts +56 -0
  89. package/src/etag-of.test.ts +57 -0
  90. package/src/event-loop-lag.test.ts +180 -0
  91. package/src/event-loop-lag.ts +201 -0
  92. package/src/ext-token-shared.test.ts +60 -0
  93. package/src/ext-validation-regression.test.ts +131 -0
  94. package/src/external-schedule-edits-http.test.ts +321 -0
  95. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  96. package/src/external-schedule-edits.ts +327 -0
  97. package/src/file-download-authz-dev-open.test.ts +1 -1
  98. package/src/file-download-authz.test.ts +73 -18
  99. package/src/file-download-date-bucket.test.ts +436 -0
  100. package/src/file-network-scope-dev-open.test.ts +97 -0
  101. package/src/file-network-scope.test.ts +732 -0
  102. package/src/group-membership-events-http.test.ts +264 -0
  103. package/src/group-messages-http.test.ts +482 -0
  104. package/src/group-messages.ts +297 -0
  105. package/src/health-anon-readers.ts +60 -0
  106. package/src/health-host-disk-2756.test.ts +71 -0
  107. package/src/health-redaction.test.ts +1721 -2
  108. package/src/host-supervisor-identity-http.test.ts +152 -0
  109. package/src/host-supervisor-identity.ts +92 -0
  110. package/src/host-supervisors-daemon-version.test.ts +137 -0
  111. package/src/http-gzip.test.ts +94 -0
  112. package/src/http-gzip.ts +112 -0
  113. package/src/hub-catalog-read-http.test.ts +409 -0
  114. package/src/hub-provider-config.test.ts +156 -0
  115. package/src/hub-provider-config.ts +170 -0
  116. package/src/hub-timestamp.test.ts +38 -0
  117. package/src/hub-timestamp.ts +27 -0
  118. package/src/human-dm.ts +215 -0
  119. package/src/human-inbox.ts +42 -0
  120. package/src/inbox-caller.ts +49 -0
  121. package/src/inbox-count-sse.test.ts +310 -0
  122. package/src/inbox-count.ts +29 -0
  123. package/src/index.ts +6 -2
  124. package/src/license-state.test.ts +56 -0
  125. package/src/license-state.ts +48 -0
  126. package/src/list-host-supervisors.test.ts +15 -4
  127. package/src/mcp-context-cost-http.test.ts +127 -0
  128. package/src/mcp-inflight.test.ts +92 -0
  129. package/src/mcp-inflight.ts +38 -0
  130. package/src/mcp-projects-events-http.test.ts +165 -0
  131. package/src/mcp-route-label-http.test.ts +120 -0
  132. package/src/mcp-write-network-resolution.test.ts +435 -0
  133. package/src/member-audit-network-id-http.test.ts +93 -0
  134. package/src/member-presence-http.test.ts +210 -0
  135. package/src/messages-ack-by-agent-http.test.ts +142 -0
  136. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  137. package/src/migrate-sqlite-to-pg.ts +263 -0
  138. package/src/model-auth-notify-http.test.ts +181 -0
  139. package/src/model-auth-notify.ts +116 -0
  140. package/src/network-name-http.test.ts +75 -0
  141. package/src/network-rules-http.test.ts +169 -0
  142. package/src/network-rules.ts +129 -0
  143. package/src/network-scope.ts +276 -0
  144. package/src/network-token-membership-http.test.ts +139 -0
  145. package/src/node-alias-control.ts +12 -0
  146. package/src/node-attrs.test.ts +47 -2
  147. package/src/node-caller-identity-http.test.ts +1091 -0
  148. package/src/node-create-request-status-http.test.ts +105 -0
  149. package/src/node-daemon-bindings.test.ts +132 -0
  150. package/src/node-daemon-bindings.ts +135 -0
  151. package/src/node-failure-alert.test.ts +150 -0
  152. package/src/node-failure-alert.ts +177 -0
  153. package/src/node-files-transport.test.ts +344 -0
  154. package/src/node-health-codex-login.test.ts +120 -0
  155. package/src/node-health-dispatch-http.test.ts +335 -0
  156. package/src/node-health-guard.ts +121 -0
  157. package/src/node-health-passthrough.test.ts +115 -0
  158. package/src/node-health-store.ts +101 -0
  159. package/src/node-id-alias.test.ts +190 -0
  160. package/src/node-identity-conflict-http.test.ts +269 -0
  161. package/src/node-identity-conflict.ts +142 -0
  162. package/src/node-identity-mismatch.test.ts +74 -0
  163. package/src/node-in-flight-tasks.ts +31 -0
  164. package/src/node-lifecycle-controllable.test.ts +64 -0
  165. package/src/node-lifecycle-controllable.ts +53 -0
  166. package/src/node-lifecycle-read-http.test.ts +250 -0
  167. package/src/node-lifecycle-read.ts +124 -0
  168. package/src/node-logs-transport.test.ts +263 -0
  169. package/src/node-peer-allowlist.test.ts +114 -0
  170. package/src/node-permissions-http.test.ts +728 -0
  171. package/src/node-permissions.ts +494 -0
  172. package/src/node-request-retention.test.ts +281 -0
  173. package/src/node-request-retention.ts +120 -0
  174. package/src/node-secret-rest-http.test.ts +190 -0
  175. package/src/node-serviceability.test.ts +86 -0
  176. package/src/node-serviceability.ts +124 -0
  177. package/src/node-session-control-http.test.ts +310 -0
  178. package/src/node-session-control.ts +258 -0
  179. package/src/node-skills-transport.test.ts +212 -0
  180. package/src/node-token-identity.ts +35 -0
  181. package/src/node-token-ownership.ts +51 -0
  182. package/src/node-token-privilege-http.test.ts +158 -0
  183. package/src/not-found-api-http.test.ts +67 -0
  184. package/src/observer-avatar-http.test.ts +102 -9
  185. package/src/observer-push.test.ts +76 -0
  186. package/src/opencode-catalog-report-http.test.ts +139 -0
  187. package/src/opencode-v2-catalog.test.ts +268 -0
  188. package/src/opencode-v2-catalog.ts +356 -0
  189. package/src/package-version-consistency.test.ts +25 -0
  190. package/src/parent-source-marker.test.ts +50 -0
  191. package/src/password-network-tokens.ts +25 -0
  192. package/src/peer-reply-atomic.test.ts +457 -0
  193. package/src/peer-reply-capability.test.ts +70 -0
  194. package/src/pg-worker.ts +87 -0
  195. package/src/poll-pacing.test.ts +74 -0
  196. package/src/poll-pacing.ts +123 -0
  197. package/src/project-dir-warn-clear-http.test.ts +132 -0
  198. package/src/project-viewer-can-http.test.ts +116 -0
  199. package/src/push.test.ts +20 -10
  200. package/src/push.ts +382 -9
  201. package/src/redact-tokens.test.ts +86 -0
  202. package/src/redact-tokens.ts +43 -0
  203. package/src/rejection-counters.test.ts +72 -0
  204. package/src/rejection-counters.ts +173 -0
  205. package/src/rename.ts +38 -10
  206. package/src/reply-target-derivation.test.ts +96 -0
  207. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  208. package/src/report-status-host-schema.test.ts +235 -0
  209. package/src/report-status-resume-id-handover.test.ts +184 -0
  210. package/src/report-status-secret-keys.test.ts +140 -0
  211. package/src/require-explicit-test-db.ts +9 -0
  212. package/src/requirement-due-reminders-http.test.ts +620 -0
  213. package/src/requirement-due-reminders.ts +416 -0
  214. package/src/requirement-events-http.test.ts +295 -0
  215. package/src/requirement-events.test.ts +45 -0
  216. package/src/requirement-events.ts +144 -0
  217. package/src/requirement-notify.ts +165 -0
  218. package/src/requirement-participant-notify-http.test.ts +309 -0
  219. package/src/requirement-tag-ops-http.test.ts +443 -0
  220. package/src/requirement-tag-tree-http.test.ts +275 -0
  221. package/src/requirement-tag-tree.ts +127 -0
  222. package/src/requirement-tags.ts +102 -0
  223. package/src/requirements-abandoned-http.test.ts +236 -0
  224. package/src/requirements-comment-http.test.ts +167 -0
  225. package/src/requirements-completed-at-migration.test.ts +70 -0
  226. package/src/requirements-errors-mcp-http.test.ts +164 -0
  227. package/src/requirements-errors.ts +158 -0
  228. package/src/requirements-etag-http.test.ts +91 -0
  229. package/src/requirements-http.test.ts +709 -0
  230. package/src/requirements-last-event-http.test.ts +349 -0
  231. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  232. package/src/requirements-list-slim-http.test.ts +324 -0
  233. package/src/requirements-mcp.test.ts +163 -0
  234. package/src/requirements-migrate.ts +283 -0
  235. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  236. package/src/requirements-people-http.test.ts +114 -0
  237. package/src/requirements-people-mcp-http.test.ts +231 -0
  238. package/src/requirements-people.ts +196 -0
  239. package/src/requirements-priority-lowest.test.ts +114 -0
  240. package/src/requirements-projects-network-echo.test.ts +57 -0
  241. package/src/requirements-projects-parent-http.test.ts +123 -0
  242. package/src/requirements-search-http.test.ts +182 -0
  243. package/src/requirements-search.test.ts +32 -0
  244. package/src/requirements-search.ts +145 -0
  245. package/src/requirements-seq-http.test.ts +193 -0
  246. package/src/requirements-seq-migration.test.ts +63 -0
  247. package/src/requirements-start-date.test.ts +125 -0
  248. package/src/requirements-stats-http.test.ts +357 -0
  249. package/src/requirements-stats.ts +195 -0
  250. package/src/requirements-status-participants-http.test.ts +222 -0
  251. package/src/requirements-upgrade-e2e.test.ts +126 -0
  252. package/src/requirements-upgrade-migration.test.ts +98 -0
  253. package/src/requirements.ts +2064 -0
  254. package/src/resolve-port.test.ts +57 -0
  255. package/src/resolve-port.ts +44 -0
  256. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  257. package/src/rest-alias-network-fallback.test.ts +60 -0
  258. package/src/rest-alias-network-fallback.ts +65 -0
  259. package/src/rest-explicit-columns-http.test.ts +266 -0
  260. package/src/rest-identity.test.ts +130 -0
  261. package/src/rest-identity.ts +141 -0
  262. package/src/rest-projections.ts +72 -0
  263. package/src/rest-read-network-real-chain.test.ts +97 -0
  264. package/src/rest-write-network-resolution.test.ts +133 -0
  265. package/src/restart-readiness-http.test.ts +121 -0
  266. package/src/restricted-files.ts +76 -0
  267. package/src/retention-first-sweep-quiet.test.ts +31 -0
  268. package/src/retention.test.ts +100 -40
  269. package/src/retention.ts +423 -104
  270. package/src/route-callers-http.test.ts +120 -0
  271. package/src/route-timing.test.ts +218 -0
  272. package/src/route-timing.ts +262 -0
  273. package/src/rules-file-duplicate-alias.test.ts +234 -0
  274. package/src/rules-file-session-target.test.ts +207 -0
  275. package/src/rules-file-transport.test.ts +237 -0
  276. package/src/runtime-label.test.ts +22 -0
  277. package/src/runtime-label.ts +21 -0
  278. package/src/runtime-readiness.ts +90 -0
  279. package/src/schedule-agent-mcp-http.test.ts +432 -0
  280. package/src/schedule-agent.ts +252 -0
  281. package/src/schedule-starved.test.ts +92 -0
  282. package/src/schedule-starved.ts +114 -0
  283. package/src/scheduled-backoff-http.test.ts +193 -0
  284. package/src/scheduled-backoff.ts +64 -0
  285. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  286. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  287. package/src/scheduled-failure-code.test.ts +73 -0
  288. package/src/scheduled-failure-code.ts +105 -0
  289. package/src/scheduled-failures-http.test.ts +279 -0
  290. package/src/scheduled-failures.ts +425 -0
  291. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  292. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  293. package/src/scheduled-offline.test.ts +131 -0
  294. package/src/scheduled-offline.ts +66 -0
  295. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  296. package/src/scheduled-outcome-guidance.ts +9 -0
  297. package/src/scheduled-reply-unread-http.test.ts +212 -0
  298. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  299. package/src/scheduled-requirement-wake.ts +125 -0
  300. package/src/scheduled-run-terminal.test.ts +268 -0
  301. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  302. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  303. package/src/scheduled-stuck-http.test.ts +316 -0
  304. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  305. package/src/scheduled-stuck.ts +219 -0
  306. package/src/scheduled-tasks-http.test.ts +679 -0
  307. package/src/scheduled-tasks.ts +959 -0
  308. package/src/scheduled-work-outcome-http.test.ts +154 -0
  309. package/src/scheduled-work-outcome.ts +50 -0
  310. package/src/scoped-secrets.ts +141 -0
  311. package/src/send-dedup-request-id.test.ts +229 -0
  312. package/src/send-reply-agent-warning.test.ts +38 -38
  313. package/src/send-reply-alias-optional.test.ts +131 -0
  314. package/src/send-reply-attachments.test.ts +458 -0
  315. package/src/send_dedup.test.ts +54 -0
  316. package/src/send_dedup.ts +52 -6
  317. package/src/serve-error.test.ts +73 -0
  318. package/src/serve-error.ts +56 -0
  319. package/src/server.ts +5035 -457
  320. package/src/session-task-on-dispatch.ts +14 -0
  321. package/src/session-token-ownership-http.test.ts +122 -0
  322. package/src/shared/codex-inventory.ts +41 -0
  323. package/src/shared/daemon-provider-login.ts +31 -0
  324. package/src/shared/daemon-provider-snapshot.ts +52 -0
  325. package/src/shared/external-schedule-contract.ts +60 -0
  326. package/src/shared/node-name.test.ts +62 -0
  327. package/src/shared/node-name.ts +161 -0
  328. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  329. package/src/shared/provider-application.ts +29 -0
  330. package/src/shared/provider-collection.ts +14 -0
  331. package/src/shared/provider-initialization.ts +8 -0
  332. package/src/shared/reserved-env-drift.test.ts +10 -0
  333. package/src/shared/scoped-secret-contract.ts +5 -0
  334. package/src/shared/task-content-limit-drift.test.ts +28 -0
  335. package/src/shared/task-content-limit.ts +25 -0
  336. package/src/side-thread-command-transport.test.ts +312 -0
  337. package/src/side-thread-command-transport.ts +318 -0
  338. package/src/side-thread-http-integration.test.ts +233 -0
  339. package/src/side-thread-http.ts +504 -0
  340. package/src/side-thread-production.test.ts +72 -0
  341. package/src/side-thread-production.ts +118 -0
  342. package/src/side-thread.test.ts +1067 -0
  343. package/src/side-thread.ts +2499 -0
  344. package/src/skillhub-http.test.ts +142 -0
  345. package/src/sqlite-close-checkpoint.test.ts +78 -0
  346. package/src/start-node.test.ts +264 -0
  347. package/src/status-alias-filter-http.test.ts +106 -0
  348. package/src/status-alias-resolver-http.test.ts +163 -0
  349. package/src/status-alias-resolver.ts +19 -0
  350. package/src/status-node-id-filter-http.test.ts +161 -0
  351. package/src/status-read-cache-http.test.ts +229 -0
  352. package/src/status-read-cache.ts +129 -0
  353. package/src/stop-delete-node.test.ts +567 -1
  354. package/src/task-access-http.test.ts +402 -0
  355. package/src/task-access.ts +420 -0
  356. package/src/task-activity.ts +60 -0
  357. package/src/task-auth-origin-http.test.ts +93 -0
  358. package/src/task-auth-origin.test.ts +24 -0
  359. package/src/task-auth-origin.ts +7 -0
  360. package/src/task-consumption.test.ts +490 -0
  361. package/src/task-diagnostic-http.test.ts +149 -0
  362. package/src/task-diagnostic.test.ts +115 -0
  363. package/src/task-diagnostic.ts +118 -0
  364. package/src/task-expiry-notice-http.test.ts +287 -0
  365. package/src/task-expiry-notice.ts +315 -0
  366. package/src/task-idempotency-mcp.test.ts +142 -0
  367. package/src/task-idempotency.test.ts +76 -0
  368. package/src/task-idempotency.ts +81 -0
  369. package/src/task-late-replies.ts +54 -0
  370. package/src/task-late-reply-http.test.ts +227 -0
  371. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  372. package/src/task-lifecycle-watcher.test.ts +204 -0
  373. package/src/task-lifecycle-watcher.ts +109 -0
  374. package/src/task-network-resolution-http.test.ts +140 -0
  375. package/src/task-offline-delivery-2668.test.ts +119 -0
  376. package/src/task-offline-delivery.ts +81 -0
  377. package/src/task-orphan-http.test.ts +287 -0
  378. package/src/task-orphan.ts +119 -0
  379. package/src/task-queue-ahead-http.test.ts +309 -0
  380. package/src/task-queue-ahead-scale.test.ts +236 -0
  381. package/src/task-queue-ahead.ts +186 -0
  382. package/src/task-rejection-log-http.test.ts +160 -0
  383. package/src/task-rejection-log.ts +61 -0
  384. package/src/task-sender-http.test.ts +143 -0
  385. package/src/task-stale-open-http.test.ts +292 -0
  386. package/src/task-stale-open.ts +103 -0
  387. package/src/tasks-pagination-http.test.ts +141 -0
  388. package/src/team-rules-status-http.test.ts +90 -0
  389. package/src/team-rules-status.test.ts +59 -0
  390. package/src/team-rules-status.ts +72 -0
  391. package/src/tmux-allowlist.test.ts +48 -0
  392. package/src/tool-audience-http.test.ts +230 -0
  393. package/src/tool-audience.ts +127 -0
  394. package/src/tools-list-json-schema.test.ts +94 -0
  395. package/src/tools.ts +4310 -419
  396. package/src/upload-early-reject-guard.test.ts +155 -0
  397. package/src/uploads-http.test.ts +86 -7
  398. package/src/uploads.ts +103 -6
  399. package/src/user-avatar-http.test.ts +74 -0
  400. package/src/user-avatar-image.ts +160 -0
  401. package/src/user-avatar-migration.test.ts +25 -0
  402. package/src/user-avatar-upload-http.test.ts +348 -0
  403. package/src/user-inbox-by-agent-http.test.ts +161 -0
  404. package/src/user-inbox-netid-notnull.test.ts +122 -0
  405. package/src/user-inbox-read-http.test.ts +223 -0
  406. package/src/user-inbox-schema.test.ts +54 -0
  407. package/src/version-stats.test.ts +66 -0
  408. package/src/version-stats.ts +109 -0
@@ -0,0 +1,181 @@
1
+ // #462 —— 节点模型登录失效 → 通知节点主人一次。
2
+ //
3
+ // 钉住:
4
+ // 1. 翻转判定(纯函数):进入 revoked/expired 发一次;坏→坏不再发(含 revoked⇄expired);回到 ok 才重新上膛;
5
+ // unknown / 没报既不发也不上膛。
6
+ // 2. 真 report_status(节点令牌):ok→expired→expired→ok→expired = 恰好 2 条,只给节点主人;
7
+ // 网络 owner 和别的成员 0 条。正文带别名、原因、`codex login` 修法,不教人拷别人的 auth.json。
8
+ // 3. 别的节点 / 用户令牌替它报坏状态 → 不发(与 #448 同一条「只有本节点令牌能替自己说健康」)。
9
+ // 4. Hub 重启(内存标记清空)后第一眼看到坏状态:主人还有没读的同类消息 → 不再发;读过了 → 发。
10
+ //
11
+ // 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/model-auth-notify-http.test.ts
12
+ // PG:COMMHUB_TEST_PG_URL=… COMMHUB_PG_EXPERIMENTAL=1(tests/test2123-hub-postgres-ladder 里注册)
13
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
14
+ import { mkdtempSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { tmpdir } from "node:os";
17
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
18
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
19
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
20
+ import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
21
+ import { db } from "./db.js";
22
+ import { registerTools } from "./tools.js";
23
+ import { clearNodeHealthStore } from "./node-health-store.js";
24
+ import { __resetModelAuthNoticesForTest, decideModelAuthNotice, MODEL_AUTH_NOTICE_KIND, modelAuthNoticeText } from "./model-auth-notify.js";
25
+
26
+ const dir = mkdtempSync(join(tmpdir(), "anet-model-auth-notify-"));
27
+ const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
28
+ if (!activeDbPath) throw new Error("model-auth-notify requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
29
+
30
+ const PW = "ModelAuthNotify123!";
31
+ const stamp = Date.now();
32
+ const NODE = `ma-node-${stamp}`;
33
+ const NODE_ID = `n_ma_node_${stamp}`;
34
+ const PEER = `ma-peer-${stamp}`;
35
+ const PEER_ID = `n_ma_peer_${stamp}`;
36
+ let netId = "";
37
+ let bossId = "", noraId = "", ottoId = "";
38
+ let nodeTokenId = "", peerTokenId = "";
39
+
40
+ async function connectAs(alias: string, userId: string, tokenId: string, isNetworkToken = true) {
41
+ const s = new McpServer({ name: "model-auth-notify", version: "1" });
42
+ registerTools(s, undefined, netId, userId, alias, isNetworkToken, tokenId);
43
+ const client = new Client({ name: "model-auth-notify-client", version: "1" });
44
+ const [ct, st] = InMemoryTransport.createLinkedPair();
45
+ await s.connect(st);
46
+ await client.connect(ct);
47
+ const report = async (model_auth: string | undefined, asAlias = NODE, nodeId = NODE_ID) => {
48
+ const r: any = await client.callTool({
49
+ name: "report_status",
50
+ arguments: { resume_id: `sdk-${nodeId}`, alias: asAlias, status: "idle", node_id: nodeId, network_id: netId, health: { bridge: "ok", ...(model_auth ? { model_auth } : {}) } },
51
+ });
52
+ expect(r.isError === true).toBe(false);
53
+ };
54
+ return { report, close: async () => { await client.close(); await s.close(); } };
55
+ }
56
+
57
+ const notices = (userId: string) => db.all<{ message_id: string; from_session: string; title: string; content: string; severity: string; meta_json: string; acked: number }>(
58
+ "SELECT message_id, from_session, title, content, severity, meta_json, acked FROM user_inbox WHERE user_id = ?1 AND network_id = ?2 AND kind = ?3 ORDER BY created_at, message_id",
59
+ userId, netId, MODEL_AUTH_NOTICE_KIND,
60
+ );
61
+ const clearNotices = () => db.run("DELETE FROM user_inbox WHERE network_id = ?1 AND kind = ?2", [netId, MODEL_AUTH_NOTICE_KIND]);
62
+
63
+ beforeAll(() => {
64
+ process.env.COMMHUB_UPLOADS_DIR = join(dir, "uploads");
65
+ const boss = register(`ma_boss_${stamp}`, PW);
66
+ expect(boss.ok).toBe(true);
67
+ bossId = boss.user!.user_id; netId = boss.network_id!;
68
+ const nora = register(`ma_nora_${stamp}`, PW);
69
+ const otto = register(`ma_otto_${stamp}`, PW);
70
+ noraId = nora.user!.user_id; ottoId = otto.user!.user_id;
71
+ addNetworkMember(netId, noraId, "member", bossId, { agentAccess: "all" });
72
+ addNetworkMember(netId, ottoId, "member", bossId, { agentAccess: "all" });
73
+ // 节点主人是 nora(她铸的节点令牌 → nodes.owner_user_id),不是网络 owner boss。
74
+ const minted = createNetworkTokenForNode(noraId, netId, NODE, NODE_ID);
75
+ expect(minted.ok).toBe(true);
76
+ nodeTokenId = minted.token_id!;
77
+ const peer = createNetworkTokenForNode(ottoId, netId, PEER, PEER_ID);
78
+ expect(peer.ok).toBe(true);
79
+ peerTokenId = peer.token_id!;
80
+ });
81
+ beforeEach(() => { __resetModelAuthNoticesForTest(); clearNodeHealthStore(); clearNotices(); });
82
+ afterAll(() => { clearNotices(); __resetModelAuthNoticesForTest(); clearNodeHealthStore(); });
83
+
84
+ describe("#462 transition logic", () => {
85
+ test("bad once per entry, re-armed only by ok", () => {
86
+ const seq: Array<Parameters<typeof decideModelAuthNotice>[1]> = ["ok", "expired", "expired", "revoked", "unknown", undefined, "expired", "ok", "unknown", "revoked", "revoked"];
87
+ let mark: ReturnType<typeof decideModelAuthNotice>["mark"];
88
+ const fired: boolean[] = [];
89
+ for (const s of seq) { const d = decideModelAuthNotice(mark, s); fired.push(d.notify); mark = d.mark; }
90
+ expect(fired).toEqual([false, true, false, false, false, false, false, false, false, true, false]);
91
+ });
92
+
93
+ test("first sight is bad → notify; unknown/missing never arms", () => {
94
+ expect(decideModelAuthNotice(undefined, "revoked")).toEqual({ notify: true, mark: "notified" });
95
+ expect(decideModelAuthNotice(undefined, "unknown")).toEqual({ notify: false, mark: undefined });
96
+ expect(decideModelAuthNotice("notified", "unknown")).toEqual({ notify: false, mark: "notified" });
97
+ expect(decideModelAuthNotice("notified", undefined)).toEqual({ notify: false, mark: "notified" });
98
+ expect(decideModelAuthNotice("notified", "ok")).toEqual({ notify: false, mark: "armed" });
99
+ });
100
+
101
+ test("text names the node, the cause and the per-node re-login; never says to copy credentials", () => {
102
+ for (const s of ["revoked", "expired"] as const) {
103
+ const { title, text } = modelAuthNoticeText("node-a", s);
104
+ expect(title).toBe("节点登录失效");
105
+ expect(text).toContain("节点 node-a");
106
+ expect(text).toContain("codex login");
107
+ expect(text).toContain("CODEX_HOME=");
108
+ expect(text).toContain("不要拷别的节点的 auth.json");
109
+ }
110
+ expect(modelAuthNoticeText("node-a", "revoked").text).toContain("作废");
111
+ expect(modelAuthNoticeText("node-a", "expired").text).toContain("过期");
112
+ });
113
+ });
114
+
115
+ describe("#462 report_status → owner notice", () => {
116
+ test("ok → expired → expired → ok → expired = exactly 2 notices, owner only", async () => {
117
+ const n = await connectAs(NODE, noraId, nodeTokenId);
118
+ try {
119
+ for (const s of ["ok", "expired", "expired", "ok", "expired"]) await n.report(s);
120
+ } finally { await n.close(); }
121
+ const mine = notices(noraId);
122
+ expect(mine.length).toBe(2);
123
+ for (const m of mine) {
124
+ expect(m.from_session).toBe(NODE);
125
+ expect(m.title).toBe("节点登录失效");
126
+ expect(m.severity).toBe("warning");
127
+ expect(m.content).toContain(`节点 ${NODE}`);
128
+ expect(m.content).toContain("codex login");
129
+ expect(JSON.parse(m.meta_json)).toEqual({ model_auth_notice: { alias: NODE, state: "expired" } });
130
+ }
131
+ expect(notices(bossId).length).toBe(0);
132
+ expect(notices(ottoId).length).toBe(0);
133
+ });
134
+
135
+ test("a node that only ever reports ok / unknown / nothing gets no notice", async () => {
136
+ const n = await connectAs(NODE, noraId, nodeTokenId);
137
+ try {
138
+ for (const s of ["unknown", "ok", undefined, "unknown", "ok"]) await n.report(s);
139
+ } finally { await n.close(); }
140
+ expect(notices(noraId).length).toBe(0);
141
+ });
142
+
143
+ test("another node or a user login cannot trigger a notice for this node", async () => {
144
+ const p = await connectAs(PEER, ottoId, peerTokenId);
145
+ try { await p.report("revoked", NODE, NODE_ID); } finally { await p.close(); }
146
+ const u = await connectAs("", bossId, "", false);
147
+ try { await u.report("revoked", NODE, NODE_ID); } finally { await u.close(); }
148
+ expect(notices(noraId).length).toBe(0);
149
+ expect(notices(bossId).length).toBe(0);
150
+ expect(notices(ottoId).length).toBe(0);
151
+ });
152
+
153
+ test("hub restart: an unread notice suppresses the repeat; once read, the next sight notifies", async () => {
154
+ const n = await connectAs(NODE, noraId, nodeTokenId);
155
+ try {
156
+ await n.report("revoked");
157
+ expect(notices(noraId).length).toBe(1);
158
+ __resetModelAuthNoticesForTest(); // = Hub 重启,内存标记没了
159
+ await n.report("revoked");
160
+ expect(notices(noraId).length).toBe(1);
161
+ db.run("UPDATE user_inbox SET acked = 1 WHERE user_id = ?1 AND network_id = ?2 AND kind = ?3", [noraId, netId, MODEL_AUTH_NOTICE_KIND]);
162
+ __resetModelAuthNoticesForTest();
163
+ await n.report("revoked");
164
+ expect(notices(noraId).length).toBe(2);
165
+ await n.report("revoked");
166
+ expect(notices(noraId).length).toBe(2);
167
+ } finally { await n.close(); }
168
+ });
169
+
170
+ test("owner no longer in the network → nobody is notified", async () => {
171
+ db.run("DELETE FROM network_members WHERE network_id = ?1 AND user_id = ?2", [netId, noraId]);
172
+ try {
173
+ const n = await connectAs(NODE, noraId, nodeTokenId);
174
+ try { await n.report("expired"); } finally { await n.close(); }
175
+ expect(notices(noraId).length).toBe(0);
176
+ expect(notices(bossId).length).toBe(0);
177
+ } finally {
178
+ addNetworkMember(netId, noraId, "member", bossId, { agentAccess: "all" });
179
+ }
180
+ });
181
+ });
@@ -0,0 +1,116 @@
1
+ // #462(#448 的子项)—— 节点模型登录失效时通知节点主人。
2
+ //
3
+ // 现场:codex 节点的 refresh token 被作废 / 过期后,节点自己知道(report_status.health.model_auth),
4
+ // Hub 也会拒绝给它派活(#460 node-health-guard.ts),但**没有人被告诉** —— 主人要等到某次派活被 409
5
+ // 才发现。这里在 report_status 收下健康报告的那一刻看 model_auth 的翻转:进入 revoked / expired 时
6
+ // 给节点主人发**一条**消息,说是哪个节点、出了什么事、怎么重新登录。
7
+ //
8
+ // 🔴 只检测 + 通知。不自动换号、不拷别的节点的 auth.json、不重新 stage 凭据(owner 定的边界)。
9
+ //
10
+ // 去重:每次「进入坏状态」只发一条;回到 ok 才重新上膛。unknown / 没报 model_auth 既不发也不上膛
11
+ // (一次模型调用都还没跑的节点报 unknown,不能把它当「恢复了」,否则 expired→unknown→expired 会刷屏)。
12
+ // revoked ⇄ expired 互相切换不算新的翻转 —— 修法是同一条命令。
13
+ // 状态在内存里(同 node-health-store.ts);Hub 重启后第一次看到坏状态时,先查收件人有没有**还没读**的同类
14
+ // 消息,有就不再发 —— 否则每次升级 Hub 都会给还没修好的节点主人再发一遍。
15
+ //
16
+ // 收件人 = 节点主人:上报令牌绑定的 nodes.owner_user_id(RFC-036,建节点时定死),没有绑定(老令牌)就取
17
+ // 铸这个节点令牌的用户(api_tokens.user_id —— 新令牌里两者相同)。只发给这一个人;不在本网络了就不发。
18
+ // 怎么送:agent-notice.ts(user_inbox + /events/users/me,from_session = 节点别名)。
19
+
20
+ import { db } from "./db.js";
21
+ import { getUserNetworkRole } from "./auth.js";
22
+ import { sendAgentNotice } from "./agent-notice.js";
23
+ import { degradedLayers } from "./node-health-guard.js";
24
+ import type { NodeHealth } from "./node-health-store.js";
25
+
26
+ export const MODEL_AUTH_NOTICE_KIND = "node_model_auth";
27
+ const MAX_TRACKED = 5_000;
28
+
29
+ type ModelAuth = NodeHealth["model_auth"];
30
+ /** armed = 下一次进入坏状态要发;notified = 这一段坏状态已经发过。 */
31
+ export type NoticeMark = "armed" | "notified";
32
+
33
+ export const isBadModelAuth = (s: ModelAuth): s is "revoked" | "expired" => s === "revoked" || s === "expired";
34
+
35
+ /**
36
+ * 纯函数:上一份标记 + 这一份 model_auth → 发不发、新标记。
37
+ * prev = undefined 表示这个 Hub 进程还没见过这个节点(调用方另查库里有没有未读的旧通知)。
38
+ */
39
+ export function decideModelAuthNotice(prev: NoticeMark | undefined, state: ModelAuth): { notify: boolean; mark: NoticeMark | undefined } {
40
+ if (state === "ok") return { notify: false, mark: "armed" };
41
+ if (isBadModelAuth(state)) {
42
+ if (prev === "notified") return { notify: false, mark: "notified" };
43
+ return { notify: true, mark: "notified" };
44
+ }
45
+ return { notify: false, mark: prev }; // unknown / 没报:保持原样
46
+ }
47
+
48
+ export function modelAuthNoticeText(alias: string, state: "revoked" | "expired"): { title: string; text: string } {
49
+ const what = state === "revoked"
50
+ ? "模型登录凭据已被作废(refresh token revoked),需要重新登录"
51
+ : "模型登录已过期,且没能自动刷新";
52
+ // 修法与派发被拒时(#460)给的同一句,别出现两套说法。
53
+ const hint = degradedLayers({ model_auth: state })[0]?.hint ?? "";
54
+ return {
55
+ title: "节点登录失效",
56
+ text: `节点 ${alias} 的${what}。在它恢复之前,派给它的任务会被拒绝。\n\n怎么修:${hint}。\n登录好之后节点会自动报告恢复,不用再做别的。`,
57
+ };
58
+ }
59
+
60
+ const marks = new Map<string, NoticeMark>();
61
+ const keyOf = (networkId: string, alias: string) => `${networkId}\0${alias}`;
62
+
63
+ export function __resetModelAuthNoticesForTest(): void { marks.clear(); }
64
+
65
+ /** 上报令牌对应的节点主人。 */
66
+ function ownerOfNodeToken(tokenId: string, networkId: string): string | null {
67
+ const row = db.get<{ user_id: string | null; owner_user_id: string | null }>(
68
+ `SELECT t.user_id, n.owner_user_id FROM api_tokens t LEFT JOIN nodes n ON n.node_id = t.bound_node_id
69
+ WHERE t.token_id = ?1 AND t.network_id = ?2`,
70
+ tokenId, networkId,
71
+ );
72
+ return row?.owner_user_id || row?.user_id || null;
73
+ }
74
+
75
+ function hasUnreadNotice(userId: string, networkId: string, alias: string): boolean {
76
+ return !!db.get(
77
+ "SELECT 1 AS hit FROM user_inbox WHERE user_id = ?1 AND network_id = ?2 AND from_session = ?3 AND kind = ?4 AND acked = 0 LIMIT 1",
78
+ userId, networkId, alias, MODEL_AUTH_NOTICE_KIND,
79
+ );
80
+ }
81
+
82
+ /**
83
+ * report_status 收下一份(已验过是本节点令牌报的)健康报告之后调用。返回这次通知到的 user_id(测试用;没发 = [])。
84
+ * 任何异常都吞掉:这是附带的通知,不能让一份正常的 report_status 失败。
85
+ */
86
+ export function noteModelAuthHealth(input: { networkId: string; alias: string; tokenId: string; health: NodeHealth }): string[] {
87
+ try {
88
+ const { networkId, alias, tokenId, health } = input;
89
+ const state = health.model_auth;
90
+ const key = keyOf(networkId, alias);
91
+ const prev = marks.get(key);
92
+ const { notify, mark } = decideModelAuthNotice(prev, state);
93
+ if (mark) {
94
+ marks.delete(key);
95
+ marks.set(key, mark);
96
+ if (marks.size > MAX_TRACKED) marks.delete(marks.keys().next().value!);
97
+ }
98
+ if (!notify || !isBadModelAuth(state)) return [];
99
+
100
+ const owner = ownerOfNodeToken(tokenId, networkId);
101
+ if (!owner || !getUserNetworkRole(owner, networkId)) return [];
102
+ // Hub 重启后的第一眼:主人还有一条没读的同类消息 → 这是同一段坏状态,不再发。
103
+ if (prev === undefined && hasUnreadNotice(owner, networkId, alias)) return [];
104
+
105
+ const { title, text } = modelAuthNoticeText(alias, state);
106
+ const sent = sendAgentNotice({
107
+ networkId, userId: owner, fromAlias: alias, kind: MODEL_AUTH_NOTICE_KIND, title, text,
108
+ meta: { model_auth_notice: { alias, state } }, idPrefix: "dm_auth_",
109
+ });
110
+ if (!sent) return [];
111
+ return [owner];
112
+ } catch (e: any) {
113
+ console.error(`[model-auth-notify] ${input.alias}: ${e?.message ?? e}`);
114
+ return [];
115
+ }
116
+ }
@@ -0,0 +1,75 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "fs";
3
+ import { join } from "path";
4
+ import { tmpdir } from "os";
5
+ import { createNetworkTokenForNode, register } from "./auth.js";
6
+ import { db } from "./db.js";
7
+
8
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-network-name-http-"));
9
+ let server: any;
10
+ let base = "";
11
+ let userToken = "";
12
+ let nodeToken = "";
13
+ let networkId = "";
14
+ let username = "";
15
+
16
+ // 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
17
+ // 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
18
+ // (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
19
+ // 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
20
+ beforeAll(async () => {
21
+ process.env.COMMHUB_DB = process.env.COMMHUB_DB || join(PRIVATE_DB_DIR, "hub.db");
22
+ username = `network_name_${Date.now()}_${process.pid}`;
23
+ const registered = register(username, "NetworkName123!", undefined, "seed");
24
+ expect(registered.ok).toBe(true);
25
+ userToken = registered.token!;
26
+ networkId = registered.network_id!;
27
+ const userId = db.get<{ user_id: string }>(
28
+ "SELECT user_id FROM users WHERE username = ?1",
29
+ [username],
30
+ )!.user_id;
31
+ const minted = createNetworkTokenForNode(userId, networkId, "network-name-node");
32
+ expect(minted.ok).toBe(true);
33
+ nodeToken = minted.token!;
34
+ const mod: any = await import("./server.js");
35
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
36
+ base = `http://127.0.0.1:${server.port}`;
37
+ }, 30_000);
38
+
39
+ afterAll(() => {
40
+ try { server?.stop?.(true); } catch {}
41
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
42
+ });
43
+
44
+ async function networks(token: string): Promise<any[]> {
45
+ const response = await fetch(`${base}/api/networks`, {
46
+ headers: { Authorization: `Bearer ${token}` },
47
+ });
48
+ expect(response.status).toBe(200);
49
+ const body = await response.json() as any;
50
+ expect(body.ok).toBe(true);
51
+ return body.networks;
52
+ }
53
+
54
+ describe("GET /api/networks name compatibility (#449)", () => {
55
+ test("utok rows expose equal non-null name and network_name", async () => {
56
+ const rows = await networks(userToken);
57
+ expect(rows).toHaveLength(1);
58
+ expect(rows[0].network_id).toBe(networkId);
59
+ // #449 is about `name` and `network_name` agreeing and being non-null.
60
+ // Pin them to the registered username rather than the literal "default":
61
+ // the auto-created network is named after its owner, so hardcoding the
62
+ // old literal would test the naming scheme instead of the compat shim.
63
+ expect(rows[0].network_name).toBe(username);
64
+ expect(rows[0].name).toBe(username);
65
+ });
66
+
67
+ test("network-bound ntok rows expose the same alias", async () => {
68
+ const rows = await networks(nodeToken);
69
+ expect(rows).toHaveLength(1);
70
+ expect(rows[0].network_id).toBe(networkId);
71
+ expect(rows[0].network_name).toBe(username);
72
+ expect(rows[0].name).toBe(rows[0].network_name);
73
+ expect(rows[0].name).not.toBeNull();
74
+ });
75
+ });
@@ -0,0 +1,169 @@
1
+ // #993 first slice — network-scoped rules: GET / PUT /api/networks/:id/rules
2
+ //
3
+ // The contract this fixes:
4
+ // * any member may READ (the rules are what nodes obey);
5
+ // * only owner/admin may WRITE, and only with a matching `expected_revision`
6
+ // (blind writes would let two people overwrite the document every node inherits);
7
+ // * node tokens cannot write (user_token_required), and non-members cannot read;
8
+ // * reads before any write report revision 0 with empty content, so a client can
9
+ // create with `expected_revision: 0` and no special "create" path;
10
+ // * size is capped in UTF-8 bytes.
11
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
12
+ import "./require-explicit-test-db.js";
13
+ import { register } from "./auth.js";
14
+ import { db } from "./db.js";
15
+
16
+ let BASE = "";
17
+ let server: any = null;
18
+ let adminToken = "";
19
+ let memberToken = "";
20
+ let netId = "";
21
+ let nodeToken = "";
22
+
23
+ async function send(token: string, method: string, path: string, payload?: unknown) {
24
+ const res = await fetch(`${BASE}${path}`, {
25
+ method,
26
+ headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" },
27
+ body: payload === undefined ? undefined : JSON.stringify(payload),
28
+ });
29
+ const text = await res.text();
30
+ let body: any = null;
31
+ try { body = JSON.parse(text); } catch {}
32
+ return { status: res.status, body };
33
+ }
34
+
35
+ beforeAll(async () => {
36
+ process.env.HOST = "127.0.0.1";
37
+ const suffix = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
38
+ const pw = "NetworkRulesPw123Aa!";
39
+ const a = register(`nr_admin_${suffix}`, pw, undefined, "admin");
40
+ if (!a.ok) throw new Error("admin register failed");
41
+ adminToken = a.token!;
42
+ netId = a.network_id!;
43
+ db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [a.user!.user_id]);
44
+
45
+ // The server must be listening before any HTTP call below.
46
+ const { bootServer } = await import("./server.js");
47
+ server = bootServer({ port: 0, hostname: "127.0.0.1" });
48
+ BASE = `http://127.0.0.1:${server.port}`;
49
+
50
+ const m = await send(adminToken, "POST", "/api/admin/users", { username: `nr_member_${suffix}`, password: pw, network_id: netId, role: "member" });
51
+ expect(m.status).toBe(200);
52
+ const login = await send("", "POST", "/api/auth/login", { username: `nr_member_${suffix}`, password: pw });
53
+ expect(login.status).toBe(200);
54
+ memberToken = login.body.token;
55
+
56
+ const { createNetworkTokenForNode } = await import("./auth.js");
57
+ const nt = createNetworkTokenForNode(a.user!.user_id, netId, "rules-node");
58
+ expect(nt.ok).toBe(true);
59
+ nodeToken = nt.token!;
60
+ }, 30_000);
61
+
62
+ afterAll(() => { try { server?.stop?.(true); } catch {} });
63
+
64
+ describe("#993 — network rules storage + CAS write", () => {
65
+ test("a member reads an empty document as revision 0", async () => {
66
+ const r = await send(memberToken, "GET", `/api/networks/${netId}/rules`);
67
+ expect(r.status).toBe(200);
68
+ expect(r.body.rules).toMatchObject({ network_id: netId, content: "", revision: 0, updated_at: null, updated_by: null });
69
+ });
70
+
71
+ test("a plain member cannot write", async () => {
72
+ const r = await send(memberToken, "PUT", `/api/networks/${netId}/rules`, { content: "nope", expected_revision: 0 });
73
+ expect(r.status).toBe(403);
74
+ expect(r.body.error).toBe("owner/admin required");
75
+ });
76
+
77
+ test("admin writes with expected_revision 0 and reads it back", async () => {
78
+ const w = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, {
79
+ content: "# Team rules\n\n- be precise\n", expected_revision: 0,
80
+ });
81
+ expect(w.status).toBe(200);
82
+ expect(w.body.rules.revision).toBe(1);
83
+ expect(w.body.rules.updated_by.username).toBeTruthy();
84
+ const r = await send(memberToken, "GET", `/api/networks/${netId}/rules`);
85
+ expect(r.body.rules.content).toContain("be precise");
86
+ expect(r.body.rules.revision).toBe(1);
87
+ });
88
+
89
+ test("a stale expected_revision is a 409, and nothing is overwritten", async () => {
90
+ const w = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, { content: "clobber", expected_revision: 0 });
91
+ expect(w.status).toBe(409);
92
+ expect(w.body.error).toBe("rules_revision_conflict");
93
+ const r = await send(adminToken, "GET", `/api/networks/${netId}/rules`);
94
+ expect(r.body.rules.content).toContain("be precise");
95
+ expect(r.body.rules.revision).toBe(1);
96
+ });
97
+
98
+ test("a node token cannot write (user_token_required)", async () => {
99
+ const r = await send(nodeToken, "PUT", `/api/networks/${netId}/rules`, { content: "x", expected_revision: 1 });
100
+ expect(r.status).toBe(403);
101
+ expect(r.body.error).toBe("user_token_required");
102
+ });
103
+
104
+ test("oversized content is refused (bytes, not UTF-16 units)", async () => {
105
+ const r = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, { content: "a".repeat(256 * 1024 + 1), expected_revision: 1 });
106
+ expect(r.status).toBe(413);
107
+ expect(r.body.error).toBe("rules_too_large");
108
+ });
109
+
110
+ test("re-writing identical bytes is idempotent (revision does not move, changed=false)", async () => {
111
+ // The next slice injects a managed block keyed by revision; a no-op save that
112
+ // bumped the number would make every node rewrite its file for nothing.
113
+ const before = (await send(adminToken, "GET", `/api/networks/${netId}/rules`)).body.rules;
114
+ const w = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, {
115
+ content: before.content, expected_revision: before.revision,
116
+ });
117
+ expect(w.status).toBe(200);
118
+ expect(w.body.changed).toBe(false);
119
+ expect(w.body.rules.revision).toBe(before.revision);
120
+ // …and a real edit still moves it.
121
+ const w2 = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, {
122
+ content: before.content + "\n- one more line\n", expected_revision: before.revision,
123
+ });
124
+ expect(w2.status).toBe(200);
125
+ expect(w2.body.changed).toBe(true);
126
+ expect(w2.body.rules.revision).toBe(before.revision + 1);
127
+ });
128
+
129
+ test("the 256 KiB cap is the same ruler as write_node_rules_file", async () => {
130
+ // 200 KiB used to be the cap here while node rules allowed 256 KiB — the same text
131
+ // could fit in the Hub and then be refused at the node.
132
+ const atCap = "a".repeat(256 * 1024);
133
+ const rev = (await send(adminToken, "GET", `/api/networks/${netId}/rules`)).body.rules.revision;
134
+ const ok = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, { content: atCap, expected_revision: rev });
135
+ expect(ok.status).toBe(200);
136
+ const rev2 = ok.body.rules.revision;
137
+ const over = await send(adminToken, "PUT", `/api/networks/${netId}/rules`, { content: atCap + "a", expected_revision: rev2 });
138
+ expect(over.status).toBe(413);
139
+ });
140
+
141
+ test("deleting the network deletes its rules row (no orphans)", async () => {
142
+ const own = register(`nr_del_${Date.now()}`, "DelPw123Aa!", undefined, "del");
143
+ expect(own.ok).toBe(true);
144
+ const put = await send(own.token!, "PUT", `/api/networks/${own.network_id}/rules`, { content: "team rules", expected_revision: 0 });
145
+ expect(put.status).toBe(200);
146
+ const del = await send(own.token!, "DELETE", `/api/networks/${own.network_id}`);
147
+ expect(del.status).toBe(200);
148
+ const left = db.get<{ cnt: number }>("SELECT COUNT(*) as cnt FROM network_rules WHERE network_id = ?1", own.network_id!);
149
+ expect(left!.cnt).toBe(0);
150
+ });
151
+
152
+ test("a node token cannot read another network's rules", async () => {
153
+ // The node token belongs to a hub admin (that is how it was minted), so the
154
+ // hubAdmin branch alone would have allowed it. A node stays inside its network.
155
+ const other = register(`nr_net2_${Date.now()}`, "OtherPw123Aa!", undefined, "net2");
156
+ expect(other.ok).toBe(true);
157
+ const r = await send(nodeToken, "GET", `/api/networks/${other.network_id}/rules`);
158
+ expect(r.status).toBe(403);
159
+ expect(r.body.error).toBe("not_a_member");
160
+ });
161
+
162
+ test("a non-member cannot read", async () => {
163
+ const other = register(`nr_other_${Date.now()}`, "OtherPw123Aa!", undefined, "other");
164
+ expect(other.ok).toBe(true);
165
+ const r = await send(other.token!, "GET", `/api/networks/${netId}/rules`);
166
+ expect(r.status).toBe(403);
167
+ expect(r.body.error).toBe("not_a_member");
168
+ });
169
+ });
@@ -0,0 +1,129 @@
1
+ // #993 — network-scoped rules text.
2
+ //
3
+ // First slice: storage + a read/write API with a compare-and-swap revision and an
4
+ // audit entry. Inheritance (Hub → Daemon → node) is NOT implemented here: it needs
5
+ // a precedence and conflict story of its own, and shipping the storage first is
6
+ // what lets that be reviewed against real content.
7
+ //
8
+ // Deliberate choices:
9
+ // * one row per network, text is the whole document (no chunking) — a team rule
10
+ // file is a few kilobytes, and partial reads would make "which revision did I
11
+ // read" ambiguous;
12
+ // * `revision` starts at 1 for the first write; reads before any write report
13
+ // revision 0 and empty content, so a client can PUT with expected_revision 0
14
+ // without a special "create" path;
15
+ // * the size cap is measured in UTF-8 bytes, not UTF-16 units, because the
16
+ // content is a file the node will write to disk.
17
+ import type { DbAdapter } from "./db-adapter.js";
18
+
19
+ /**
20
+ * 256 KiB — deliberately the same ruler as `write_node_rules_file` (tools.ts), because
21
+ * these two texts are meant to end up next to each other on a node. Two different caps
22
+ * for the same kind of document is how "it fit in the Hub but not on the node" happens.
23
+ */
24
+ export const NETWORK_RULES_MAX_BYTES = 256 * 1024;
25
+
26
+ export type NetworkRules = {
27
+ network_id: string;
28
+ content: string;
29
+ revision: number;
30
+ updated_at: string | null;
31
+ updated_by: { user_id: string; username: string | null } | null;
32
+ };
33
+
34
+ type Row = { content: string; revision: number; updated_at: string; updated_by_json: string | null };
35
+
36
+ export function ensureNetworkRules(database: DbAdapter): void {
37
+ database.exec(`
38
+ CREATE TABLE IF NOT EXISTS network_rules (
39
+ network_id TEXT NOT NULL PRIMARY KEY,
40
+ content TEXT NOT NULL,
41
+ revision INTEGER NOT NULL,
42
+ updated_at TEXT NOT NULL,
43
+ updated_by_json TEXT
44
+ );
45
+ `);
46
+ }
47
+
48
+ let ensured = false;
49
+ /** Idempotent: the table is created on first use, not on every request. */
50
+ export function ensureNetworkRulesOnce(database: DbAdapter): void {
51
+ if (ensured) return;
52
+ ensureNetworkRules(database);
53
+ ensured = true;
54
+ }
55
+
56
+ function current(database: DbAdapter, networkId: string): Row | null {
57
+ return database.get<Row>(
58
+ "SELECT content, revision, updated_at, updated_by_json FROM network_rules WHERE network_id = ?1",
59
+ networkId,
60
+ ) ?? null;
61
+ }
62
+
63
+ export function readNetworkRules(database: DbAdapter, networkId: string): NetworkRules {
64
+ const row = current(database, networkId);
65
+ if (!row) return { network_id: networkId, content: "", revision: 0, updated_at: null, updated_by: null };
66
+ let updatedBy: NetworkRules["updated_by"] = null;
67
+ try {
68
+ const parsed = JSON.parse(row.updated_by_json ?? "null");
69
+ if (parsed && typeof parsed === "object" && typeof parsed.user_id === "string") {
70
+ updatedBy = { user_id: parsed.user_id, username: typeof parsed.username === "string" ? parsed.username : null };
71
+ }
72
+ } catch { /* a corrupt actor blob must not make the rules unreadable */ }
73
+ return {
74
+ network_id: networkId,
75
+ content: row.content,
76
+ revision: Number(row.revision) || 0,
77
+ updated_at: row.updated_at,
78
+ updated_by: updatedBy,
79
+ };
80
+ }
81
+
82
+ export type WriteResult =
83
+ | { ok: true; rules: NetworkRules; changed: boolean }
84
+ | { ok: false; status: number; error: "invalid_rules_content" | "rules_too_large" | "rules_revision_conflict" };
85
+
86
+ /**
87
+ * Compare-and-swap write. `expectedRevision` is required: a blind PUT would let two
88
+ * clients overwrite each other, and this is the same document every node in the
89
+ * network would inherit.
90
+ */
91
+ export function writeNetworkRules(
92
+ database: DbAdapter,
93
+ networkId: string,
94
+ content: unknown,
95
+ expectedRevision: unknown,
96
+ actor: { user_id: string; username: string | null },
97
+ now = new Date().toISOString(),
98
+ ): WriteResult {
99
+ if (typeof content !== "string") return { ok: false, status: 400, error: "invalid_rules_content" };
100
+ if (typeof expectedRevision !== "number" || !Number.isSafeInteger(expectedRevision) || expectedRevision < 0) {
101
+ return { ok: false, status: 400, error: "invalid_rules_content" };
102
+ }
103
+ if (Buffer.byteLength(content, "utf8") > NETWORK_RULES_MAX_BYTES) {
104
+ return { ok: false, status: 413, error: "rules_too_large" };
105
+ }
106
+ const row = current(database, networkId);
107
+ const revision = row ? Number(row.revision) || 0 : 0;
108
+ if (revision !== expectedRevision) return { ok: false, status: 409, error: "rules_revision_conflict" };
109
+ // Idempotent revision: writing the same bytes must not mint a new revision.
110
+ // The next slice injects a managed block keyed by revision, so a no-op save that
111
+ // bumped the number would make every node rewrite its file for nothing.
112
+ if (row && row.content === content) {
113
+ return { ok: true, rules: readNetworkRules(database, networkId), changed: false };
114
+ }
115
+ const next = revision + 1;
116
+ const actorJson = JSON.stringify({ user_id: actor.user_id, username: actor.username });
117
+ if (row) {
118
+ database.run(
119
+ "UPDATE network_rules SET content = ?1, revision = ?2, updated_at = ?3, updated_by_json = ?4 WHERE network_id = ?5",
120
+ [content, next, now, actorJson, networkId],
121
+ );
122
+ } else {
123
+ database.run(
124
+ "INSERT INTO network_rules (network_id, content, revision, updated_at, updated_by_json) VALUES (?1, ?2, ?3, ?4, ?5)",
125
+ [networkId, content, next, now, actorJson],
126
+ );
127
+ }
128
+ return { ok: true, rules: readNetworkRules(database, networkId), changed: true };
129
+ }