@sleep2agi/commhub-server 0.9.0-preview.27 → 0.9.0-preview.271

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 (446) hide show
  1. package/README.md +120 -3
  2. package/bin/commhub.ts +93 -9
  3. package/build-info.json +7 -0
  4. package/package.json +10 -8
  5. package/src/ack-create-request-transport.test.ts +182 -0
  6. package/src/ack-create-request.test.ts +52 -8
  7. package/src/admin-delete-network-http.test.ts +229 -0
  8. package/src/admin-networks-http.test.ts +88 -0
  9. package/src/adoption-candidates-http.test.ts +140 -0
  10. package/src/adoption-candidates.ts +158 -0
  11. package/src/agent-access-batch.test.ts +210 -0
  12. package/src/agent-access.ts +585 -0
  13. package/src/agent-acl-groups-http.test.ts +247 -0
  14. package/src/agent-acl-http.test.ts +691 -0
  15. package/src/agent-acl-slice3-http.test.ts +885 -0
  16. package/src/agent-department-grants.test.ts +129 -0
  17. package/src/agent-department-http.test.ts +215 -0
  18. package/src/agent-groups-perf.test.ts +223 -0
  19. package/src/agent-notice.ts +48 -0
  20. package/src/agent-team-whoami-http.test.ts +98 -0
  21. package/src/agent-teams-http.test.ts +330 -0
  22. package/src/agent-teams.ts +244 -0
  23. package/src/alias-baseline-2571.test.ts +162 -0
  24. package/src/alias-baseline.ts +113 -0
  25. package/src/alias-filter.test.ts +72 -0
  26. package/src/alias-filter.ts +42 -0
  27. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  28. package/src/api-host-supervisors-fallback.test.ts +6 -7
  29. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  30. package/src/api-nodes-shape.test.ts +131 -4
  31. package/src/auth-abuse-counters.test.ts +144 -0
  32. package/src/auth-abuse-counters.ts +122 -0
  33. package/src/auth-layer-shape.test.ts +105 -0
  34. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  35. package/src/auth-sessions-http.test.ts +260 -0
  36. package/src/auth-validate.test.ts +5 -1
  37. package/src/auth-weak-password-login.test.ts +176 -0
  38. package/src/auth.ts +641 -68
  39. package/src/backfill-node-ids-2664.test.ts +128 -0
  40. package/src/binding-generation-http.test.ts +141 -0
  41. package/src/blocked-exit-on-reply.test.ts +122 -0
  42. package/src/broadcast-fanout-2721.test.ts +149 -0
  43. package/src/broadcast-fanout.ts +117 -0
  44. package/src/build-commit-report-http.test.ts +128 -0
  45. package/src/build-info.test.ts +60 -0
  46. package/src/build-info.ts +85 -0
  47. package/src/chain-attempt-dedup.test.ts +447 -0
  48. package/src/clip.test.ts +36 -0
  49. package/src/clip.ts +48 -0
  50. package/src/clone-node.test.ts +269 -0
  51. package/src/clone-node.ts +289 -0
  52. package/src/codex-config-flags.ts +77 -0
  53. package/src/codex-fork-contract.ts +23 -0
  54. package/src/codex-fork-migration.test.ts +38 -0
  55. package/src/commhub-bin-args.test.ts +85 -0
  56. package/src/config-apply-validate.test.ts +188 -1
  57. package/src/config-apply-validate.ts +222 -3
  58. package/src/cors-origins.test.ts +73 -0
  59. package/src/create-node-blocked-gate.test.ts +365 -0
  60. package/src/create-node-error-domain.test.ts +127 -0
  61. package/src/create-node-network-id.test.ts +91 -0
  62. package/src/create-node-tool-schema.test.ts +49 -0
  63. package/src/create-node-unicode-name.test.ts +126 -0
  64. package/src/create-node-validate.test.ts +199 -7
  65. package/src/create-node-validate.ts +232 -15
  66. package/src/create-node-workdir.test.ts +298 -0
  67. package/src/create-node.ts +88 -23
  68. package/src/daemon-provider-snapshots.test.ts +453 -0
  69. package/src/daemon-provider-snapshots.ts +327 -0
  70. package/src/daemon-token-owner-http.test.ts +346 -0
  71. package/src/dashboard-slash-routing-http.test.ts +109 -0
  72. package/src/db-adapter-guard.test.ts +148 -0
  73. package/src/db-adapter-translate.test.ts +128 -0
  74. package/src/db-adapter.ts +377 -91
  75. package/src/db-timestamp.test.ts +38 -0
  76. package/src/db-timestamp.ts +15 -0
  77. package/src/db.ts +1298 -153
  78. package/src/delivered-without-push.test.ts +140 -0
  79. package/src/department-groups-http.test.ts +209 -0
  80. package/src/department-groups-sync-http.test.ts +328 -0
  81. package/src/department-groups.ts +434 -0
  82. package/src/department-heads-http.test.ts +350 -0
  83. package/src/department-heads.ts +226 -0
  84. package/src/departments-agent-count.test.ts +139 -0
  85. package/src/departments-http.test.ts +185 -0
  86. package/src/departments-mcp-error-domain.test.ts +135 -0
  87. package/src/departments-mcp.test.ts +128 -0
  88. package/src/departments.ts +318 -0
  89. package/src/desktop-message-seam.test.ts +150 -0
  90. package/src/desktop-message.test.ts +368 -0
  91. package/src/dm-file-scope-http.test.ts +227 -0
  92. package/src/empty-node-sweeper.test.ts +104 -0
  93. package/src/empty-node-sweeper.ts +88 -0
  94. package/src/env-transport-gate-http.test.ts +240 -0
  95. package/src/env-transport-gate.ts +80 -0
  96. package/src/env-transport-policy.ts +56 -0
  97. package/src/etag-of.test.ts +57 -0
  98. package/src/event-loop-lag.test.ts +180 -0
  99. package/src/event-loop-lag.ts +201 -0
  100. package/src/expiry-counters.test.ts +187 -0
  101. package/src/expiry-counters.ts +227 -0
  102. package/src/expiry-evidence-db.test.ts +103 -0
  103. package/src/ext-token-shared.test.ts +60 -0
  104. package/src/ext-validation-regression.test.ts +10 -17
  105. package/src/external-schedule-edits-http.test.ts +321 -0
  106. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  107. package/src/external-schedule-edits.ts +327 -0
  108. package/src/file-download-authz-dev-open.test.ts +1 -1
  109. package/src/file-download-authz.test.ts +25 -4
  110. package/src/file-download-date-bucket.test.ts +1 -1
  111. package/src/file-network-scope-dev-open.test.ts +1 -1
  112. package/src/file-network-scope.test.ts +7 -6
  113. package/src/group-membership-events-http.test.ts +264 -0
  114. package/src/group-messages-http.test.ts +483 -0
  115. package/src/group-messages.ts +297 -0
  116. package/src/health-anon-readers.ts +67 -0
  117. package/src/health-host-disk-2756.test.ts +71 -0
  118. package/src/health-identity-root.test.ts +98 -0
  119. package/src/health-redaction.test.ts +1599 -7
  120. package/src/health-status-reasons.test.ts +84 -0
  121. package/src/host-supervisor-identity-http.test.ts +152 -0
  122. package/src/host-supervisor-identity.ts +92 -0
  123. package/src/host-supervisors-daemon-version.test.ts +137 -0
  124. package/src/http-gzip.test.ts +94 -0
  125. package/src/http-gzip.ts +112 -0
  126. package/src/hub-catalog-read-http.test.ts +664 -0
  127. package/src/hub-provider-config.test.ts +166 -0
  128. package/src/hub-provider-config.ts +202 -0
  129. package/src/hub-timestamp.test.ts +38 -0
  130. package/src/hub-timestamp.ts +27 -0
  131. package/src/human-dm.ts +215 -0
  132. package/src/human-inbox.ts +42 -0
  133. package/src/inbox-caller.ts +49 -0
  134. package/src/inbox-count-sse.test.ts +318 -0
  135. package/src/inbox-count.ts +29 -0
  136. package/src/index.ts +6 -2
  137. package/src/license-state.test.ts +105 -0
  138. package/src/license-state.ts +48 -0
  139. package/src/lifecycle-error-domain.test.ts +149 -0
  140. package/src/list-ack-error-domain.test.ts +108 -0
  141. package/src/list-host-supervisors.test.ts +15 -4
  142. package/src/list-tasks-omit-default.test.ts +84 -0
  143. package/src/list-tasks-since-last.test.ts +100 -0
  144. package/src/list-tasks-since.test.ts +104 -0
  145. package/src/mcp-context-cost-http.test.ts +127 -0
  146. package/src/mcp-inflight.test.ts +92 -0
  147. package/src/mcp-inflight.ts +38 -0
  148. package/src/mcp-projects-events-http.test.ts +168 -0
  149. package/src/mcp-route-label-http.test.ts +120 -0
  150. package/src/mcp-write-network-resolution.test.ts +21 -0
  151. package/src/member-audit-network-id-http.test.ts +93 -0
  152. package/src/member-presence-http.test.ts +210 -0
  153. package/src/messages-ack-by-agent-http.test.ts +142 -0
  154. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  155. package/src/migrate-sqlite-to-pg.ts +263 -0
  156. package/src/model-auth-notify-http.test.ts +181 -0
  157. package/src/model-auth-notify.ts +116 -0
  158. package/src/network-name-http.test.ts +75 -0
  159. package/src/network-quota-config.test.ts +100 -0
  160. package/src/network-rules-http.test.ts +169 -0
  161. package/src/network-rules.ts +129 -0
  162. package/src/network-scope.ts +222 -3
  163. package/src/network-token-membership-http.test.ts +186 -0
  164. package/src/node-alias-control.ts +12 -0
  165. package/src/node-attrs.test.ts +47 -2
  166. package/src/node-caller-identity-http.test.ts +1108 -0
  167. package/src/node-config-last-update.test.ts +126 -0
  168. package/src/node-config-last-update.ts +107 -0
  169. package/src/node-create-request-status-http.test.ts +105 -0
  170. package/src/node-daemon-bindings.test.ts +142 -0
  171. package/src/node-daemon-bindings.ts +135 -0
  172. package/src/node-failure-alert.test.ts +150 -0
  173. package/src/node-failure-alert.ts +177 -0
  174. package/src/node-files-transport.test.ts +350 -0
  175. package/src/node-health-codex-login.test.ts +120 -0
  176. package/src/node-health-dispatch-http.test.ts +373 -0
  177. package/src/node-health-guard-origin.test.ts +98 -0
  178. package/src/node-health-guard.ts +121 -0
  179. package/src/node-health-passthrough.test.ts +115 -0
  180. package/src/node-health-store.ts +101 -0
  181. package/src/node-id-alias.test.ts +190 -0
  182. package/src/node-identity-conflict-http.test.ts +269 -0
  183. package/src/node-identity-conflict.ts +142 -0
  184. package/src/node-identity-mismatch.test.ts +74 -0
  185. package/src/node-in-flight-tasks.ts +31 -0
  186. package/src/node-lifecycle-controllable.test.ts +64 -0
  187. package/src/node-lifecycle-controllable.ts +53 -0
  188. package/src/node-lifecycle-read-http.test.ts +257 -0
  189. package/src/node-lifecycle-read.ts +124 -0
  190. package/src/node-logs-transport.test.ts +266 -0
  191. package/src/node-peer-allowlist.test.ts +114 -0
  192. package/src/node-permissions-http.test.ts +901 -0
  193. package/src/node-permissions.ts +496 -0
  194. package/src/node-request-retention.test.ts +281 -0
  195. package/src/node-request-retention.ts +120 -0
  196. package/src/node-secret-rest-http.test.ts +190 -0
  197. package/src/node-secret-vault-inject.test.ts +132 -0
  198. package/src/node-security-write-gate.test.ts +72 -0
  199. package/src/node-serviceability.test.ts +86 -0
  200. package/src/node-serviceability.ts +124 -0
  201. package/src/node-session-control-http.test.ts +310 -0
  202. package/src/node-session-control.ts +258 -0
  203. package/src/node-skills-transport.test.ts +212 -0
  204. package/src/node-token-identity.ts +35 -0
  205. package/src/node-token-ownership.ts +51 -0
  206. package/src/node-token-privilege-http.test.ts +224 -0
  207. package/src/node-token-usage.test.ts +90 -0
  208. package/src/node-token-usage.ts +164 -0
  209. package/src/not-found-api-http.test.ts +67 -0
  210. package/src/observer-avatar-http.test.ts +103 -10
  211. package/src/observer-push.test.ts +76 -0
  212. package/src/opencode-catalog-report-http.test.ts +139 -0
  213. package/src/opencode-v2-catalog.test.ts +268 -0
  214. package/src/opencode-v2-catalog.ts +356 -0
  215. package/src/package-version-consistency.test.ts +25 -0
  216. package/src/parent-infer.test.ts +82 -0
  217. package/src/parent-infer.ts +110 -0
  218. package/src/parent-source-marker.test.ts +70 -0
  219. package/src/parent-source-orphan.test.ts +121 -0
  220. package/src/password-network-tokens.ts +25 -0
  221. package/src/peer-reply-atomic.test.ts +462 -0
  222. package/src/peer-reply-capability.test.ts +70 -0
  223. package/src/pg-worker.ts +87 -0
  224. package/src/poll-pacing.test.ts +74 -0
  225. package/src/poll-pacing.ts +123 -0
  226. package/src/probe-provider-error-domain.test.ts +145 -0
  227. package/src/project-dir-warn-clear-http.test.ts +132 -0
  228. package/src/project-viewer-can-http.test.ts +116 -0
  229. package/src/provider-skill-error-domain.test.ts +130 -0
  230. package/src/provider-tools-shape.test.ts +165 -0
  231. package/src/push.test.ts +20 -10
  232. package/src/push.ts +373 -9
  233. package/src/redact-tokens.test.ts +86 -0
  234. package/src/redact-tokens.ts +43 -0
  235. package/src/rejection-counters.test.ts +72 -0
  236. package/src/rejection-counters.ts +173 -0
  237. package/src/rename.ts +38 -10
  238. package/src/reply-target-derivation.test.ts +96 -0
  239. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  240. package/src/report-status-host-schema.test.ts +235 -0
  241. package/src/report-status-resume-id-handover.test.ts +184 -0
  242. package/src/report-status-secret-keys.test.ts +140 -0
  243. package/src/require-explicit-test-db.ts +9 -0
  244. package/src/requirement-due-reminders-http.test.ts +620 -0
  245. package/src/requirement-due-reminders.ts +416 -0
  246. package/src/requirement-events-http.test.ts +318 -0
  247. package/src/requirement-events.test.ts +45 -0
  248. package/src/requirement-events.ts +144 -0
  249. package/src/requirement-notify.ts +165 -0
  250. package/src/requirement-participant-notify-http.test.ts +313 -0
  251. package/src/requirement-tag-ops-http.test.ts +454 -0
  252. package/src/requirement-tag-tree-http.test.ts +275 -0
  253. package/src/requirement-tag-tree.ts +127 -0
  254. package/src/requirement-tags.ts +102 -0
  255. package/src/requirements-abandoned-http.test.ts +236 -0
  256. package/src/requirements-assignee-drift.test.ts +154 -0
  257. package/src/requirements-comment-http.test.ts +174 -0
  258. package/src/requirements-completed-at-migration.test.ts +70 -0
  259. package/src/requirements-errors-mcp-http.test.ts +164 -0
  260. package/src/requirements-errors.ts +158 -0
  261. package/src/requirements-etag-http.test.ts +91 -0
  262. package/src/requirements-http.test.ts +709 -0
  263. package/src/requirements-last-event-http.test.ts +349 -0
  264. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  265. package/src/requirements-list-slim-http.test.ts +324 -0
  266. package/src/requirements-mcp.test.ts +180 -0
  267. package/src/requirements-migrate.ts +283 -0
  268. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  269. package/src/requirements-people-http.test.ts +114 -0
  270. package/src/requirements-people-mcp-http.test.ts +231 -0
  271. package/src/requirements-people.ts +196 -0
  272. package/src/requirements-priority-lowest.test.ts +114 -0
  273. package/src/requirements-projects-network-echo.test.ts +57 -0
  274. package/src/requirements-projects-parent-http.test.ts +123 -0
  275. package/src/requirements-search-http.test.ts +182 -0
  276. package/src/requirements-search.test.ts +32 -0
  277. package/src/requirements-search.ts +145 -0
  278. package/src/requirements-seq-http.test.ts +193 -0
  279. package/src/requirements-seq-migration.test.ts +63 -0
  280. package/src/requirements-start-date.test.ts +125 -0
  281. package/src/requirements-stats-http.test.ts +357 -0
  282. package/src/requirements-stats.ts +195 -0
  283. package/src/requirements-status-participants-http.test.ts +222 -0
  284. package/src/requirements-upgrade-e2e.test.ts +126 -0
  285. package/src/requirements-upgrade-migration.test.ts +98 -0
  286. package/src/requirements.ts +2205 -0
  287. package/src/resolve-port.test.ts +57 -0
  288. package/src/resolve-port.ts +44 -0
  289. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  290. package/src/rest-alias-network-fallback.test.ts +60 -0
  291. package/src/rest-alias-network-fallback.ts +65 -0
  292. package/src/rest-explicit-columns-http.test.ts +266 -0
  293. package/src/rest-identity.test.ts +130 -0
  294. package/src/rest-identity.ts +141 -0
  295. package/src/rest-projections.ts +72 -0
  296. package/src/rest-read-network-real-chain.test.ts +97 -0
  297. package/src/rest-write-network-resolution.test.ts +133 -0
  298. package/src/restart-readiness-http.test.ts +121 -0
  299. package/src/restricted-files.ts +76 -0
  300. package/src/retention-first-sweep-quiet.test.ts +31 -0
  301. package/src/retention.test.ts +100 -40
  302. package/src/retention.ts +423 -104
  303. package/src/route-callers-http.test.ts +120 -0
  304. package/src/route-timing.test.ts +218 -0
  305. package/src/route-timing.ts +262 -0
  306. package/src/rules-file-duplicate-alias.test.ts +234 -0
  307. package/src/rules-file-session-target.test.ts +207 -0
  308. package/src/rules-file-transport.test.ts +271 -0
  309. package/src/runtime-label.test.ts +22 -0
  310. package/src/runtime-label.ts +21 -0
  311. package/src/runtime-readiness.ts +90 -0
  312. package/src/schedule-agent-mcp-http.test.ts +486 -0
  313. package/src/schedule-agent.ts +252 -0
  314. package/src/schedule-starved.test.ts +92 -0
  315. package/src/schedule-starved.ts +114 -0
  316. package/src/scheduled-backoff-http.test.ts +203 -0
  317. package/src/scheduled-backoff.ts +64 -0
  318. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  319. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  320. package/src/scheduled-failure-code.test.ts +73 -0
  321. package/src/scheduled-failure-code.ts +105 -0
  322. package/src/scheduled-failures-http.test.ts +279 -0
  323. package/src/scheduled-failures.ts +425 -0
  324. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  325. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  326. package/src/scheduled-offline.test.ts +131 -0
  327. package/src/scheduled-offline.ts +66 -0
  328. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  329. package/src/scheduled-outcome-guidance.ts +9 -0
  330. package/src/scheduled-reply-unread-http.test.ts +212 -0
  331. package/src/scheduled-requirement-wake-http.test.ts +289 -0
  332. package/src/scheduled-requirement-wake.ts +125 -0
  333. package/src/scheduled-run-terminal.test.ts +290 -0
  334. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  335. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  336. package/src/scheduled-stuck-http.test.ts +316 -0
  337. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  338. package/src/scheduled-stuck.ts +219 -0
  339. package/src/scheduled-tasks-http.test.ts +679 -0
  340. package/src/scheduled-tasks.ts +959 -0
  341. package/src/scheduled-work-outcome-http.test.ts +154 -0
  342. package/src/scheduled-work-outcome.ts +50 -0
  343. package/src/scoped-secrets.ts +167 -0
  344. package/src/secret-echo-negative-control.test.ts +118 -0
  345. package/src/send-dedup-request-id.test.ts +229 -0
  346. package/src/send-reply-agent-warning.test.ts +38 -38
  347. package/src/send-reply-alias-optional.test.ts +131 -0
  348. package/src/send-reply-attachments.test.ts +28 -7
  349. package/src/send_dedup.test.ts +54 -0
  350. package/src/send_dedup.ts +52 -6
  351. package/src/serve-error.test.ts +73 -0
  352. package/src/serve-error.ts +56 -0
  353. package/src/server.ts +4963 -377
  354. package/src/session-task-on-dispatch.ts +14 -0
  355. package/src/session-token-ownership-http.test.ts +122 -0
  356. package/src/shared/codex-inventory.ts +41 -0
  357. package/src/shared/daemon-provider-login.ts +31 -0
  358. package/src/shared/daemon-provider-snapshot.ts +52 -0
  359. package/src/shared/external-schedule-contract.ts +60 -0
  360. package/src/shared/node-name.test.ts +62 -0
  361. package/src/shared/node-name.ts +161 -0
  362. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  363. package/src/shared/provider-application.ts +29 -0
  364. package/src/shared/provider-collection.ts +14 -0
  365. package/src/shared/provider-initialization.ts +8 -0
  366. package/src/shared/reserved-env-drift.test.ts +10 -0
  367. package/src/shared/scoped-secret-contract.ts +5 -0
  368. package/src/shared/task-content-limit-drift.test.ts +28 -0
  369. package/src/shared/task-content-limit.ts +25 -0
  370. package/src/side-thread-command-transport.test.ts +312 -0
  371. package/src/side-thread-command-transport.ts +318 -0
  372. package/src/side-thread-http-integration.test.ts +233 -0
  373. package/src/side-thread-http.ts +504 -0
  374. package/src/side-thread-production.test.ts +72 -0
  375. package/src/side-thread-production.ts +118 -0
  376. package/src/side-thread.test.ts +1067 -0
  377. package/src/side-thread.ts +2499 -0
  378. package/src/skillhub-http.test.ts +144 -0
  379. package/src/sqlite-close-checkpoint.test.ts +78 -0
  380. package/src/start-node.test.ts +265 -0
  381. package/src/start-request-error-domain.test.ts +182 -0
  382. package/src/start-skill-error-domain.test.ts +122 -0
  383. package/src/stats-versions-http.test.ts +65 -0
  384. package/src/status-alias-filter-http.test.ts +106 -0
  385. package/src/status-alias-resolver-http.test.ts +163 -0
  386. package/src/status-alias-resolver.ts +19 -0
  387. package/src/status-node-id-filter-http.test.ts +161 -0
  388. package/src/status-read-cache-http.test.ts +229 -0
  389. package/src/status-read-cache.ts +129 -0
  390. package/src/stop-delete-node.test.ts +567 -1
  391. package/src/task-access-http.test.ts +407 -0
  392. package/src/task-access.ts +420 -0
  393. package/src/task-activity.ts +60 -0
  394. package/src/task-auth-origin-http.test.ts +93 -0
  395. package/src/task-auth-origin.test.ts +24 -0
  396. package/src/task-auth-origin.ts +7 -0
  397. package/src/task-consumption.test.ts +508 -0
  398. package/src/task-diagnostic-http.test.ts +149 -0
  399. package/src/task-diagnostic.test.ts +115 -0
  400. package/src/task-diagnostic.ts +118 -0
  401. package/src/task-expiry-notice-http.test.ts +298 -0
  402. package/src/task-expiry-notice.ts +318 -0
  403. package/src/task-idempotency-mcp.test.ts +148 -0
  404. package/src/task-idempotency.test.ts +76 -0
  405. package/src/task-idempotency.ts +81 -0
  406. package/src/task-late-replies.ts +54 -0
  407. package/src/task-late-reply-http.test.ts +227 -0
  408. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  409. package/src/task-lifecycle-watcher.test.ts +209 -0
  410. package/src/task-lifecycle-watcher.ts +109 -0
  411. package/src/task-network-resolution-http.test.ts +140 -0
  412. package/src/task-not-found-error-domain.test.ts +114 -0
  413. package/src/task-offline-delivery-2668.test.ts +119 -0
  414. package/src/task-offline-delivery.ts +81 -0
  415. package/src/task-orphan-http.test.ts +287 -0
  416. package/src/task-orphan.ts +119 -0
  417. package/src/task-queue-ahead-http.test.ts +309 -0
  418. package/src/task-queue-ahead-scale.test.ts +236 -0
  419. package/src/task-queue-ahead.ts +186 -0
  420. package/src/task-rejection-log-http.test.ts +160 -0
  421. package/src/task-rejection-log.ts +61 -0
  422. package/src/task-sender-http.test.ts +143 -0
  423. package/src/task-stale-open-http.test.ts +292 -0
  424. package/src/task-stale-open.ts +103 -0
  425. package/src/tasks-pagination-http.test.ts +141 -0
  426. package/src/team-rules-status-http.test.ts +90 -0
  427. package/src/team-rules-status.test.ts +59 -0
  428. package/src/team-rules-status.ts +72 -0
  429. package/src/tmux-allowlist.test.ts +48 -0
  430. package/src/tool-audience-http.test.ts +248 -0
  431. package/src/tool-audience.ts +130 -0
  432. package/src/tools-list-json-schema.test.ts +94 -0
  433. package/src/tools.ts +4340 -386
  434. package/src/update-node-config-error-domain.test.ts +107 -0
  435. package/src/uploads-http.test.ts +6 -4
  436. package/src/uploads.ts +23 -4
  437. package/src/user-avatar-http.test.ts +74 -0
  438. package/src/user-avatar-image.ts +160 -0
  439. package/src/user-avatar-migration.test.ts +25 -0
  440. package/src/user-avatar-upload-http.test.ts +353 -0
  441. package/src/user-inbox-by-agent-http.test.ts +189 -0
  442. package/src/user-inbox-netid-notnull.test.ts +122 -0
  443. package/src/user-inbox-read-http.test.ts +223 -0
  444. package/src/user-inbox-schema.test.ts +54 -0
  445. package/src/version-stats.test.ts +66 -0
  446. package/src/version-stats.ts +109 -0
@@ -36,10 +36,29 @@ afterAll(() => {
36
36
  // the dashboard / external clients see.
37
37
  function mapRow(r: Record<string, unknown>): Record<string, unknown> {
38
38
  let role: string | null = null;
39
+ // #2293 —— 与 handler 同一套读法:快照可能是文本或对象;解析失败/形状不对 = 这一格没有。
40
+ let opencodeCatalog: string[] | null = null;
41
+ let opencodeCatalogSeenAt: string | null = null;
42
+ let opencodeGeneration: "v1" | "v2" | null = null;
43
+ let opencodeMode: string | null = null;
44
+ let opencodeServer: string | null = null;
39
45
  const snap = r.config_snapshot;
40
46
  if (snap) {
41
- try { role = (typeof snap === "string" ? JSON.parse(snap) : snap)?.role ?? null; }
42
- catch { /* malformed */ }
47
+ let parsed: any = null;
48
+ try { parsed = typeof snap === "string" ? JSON.parse(snap) : snap; }
49
+ catch { parsed = null; }
50
+ role = parsed?.role ?? null;
51
+ const raw = parsed?.opencode_catalog;
52
+ if (Array.isArray(raw) && raw.every((m: unknown) => typeof m === "string" && m.length <= 400)) {
53
+ opencodeCatalog = raw.slice(0, 400);
54
+ // #3144 —— 目录是快照:没有采集时刻的话,51 个模型是刚才的还是三周前的分不出。
55
+ const seen = parsed?.opencode_catalog_seen_at;
56
+ opencodeCatalogSeenAt = typeof seen === "string" && seen.length > 0 && seen.length <= 40 ? seen : null;
57
+ }
58
+ const flags = parsed?.flags;
59
+ if (flags?.opencodeGeneration === "v1" || flags?.opencodeGeneration === "v2") opencodeGeneration = flags.opencodeGeneration;
60
+ if (typeof flags?.opencodeMode === "string" && flags.opencodeMode.length <= 32) opencodeMode = flags.opencodeMode;
61
+ if (typeof parsed?.opencode_server === "string" && parsed.opencode_server.length <= 200) opencodeServer = parsed.opencode_server;
43
62
  }
44
63
  const { config_snapshot, ...rest } = r;
45
64
  return {
@@ -47,9 +66,43 @@ function mapRow(r: Record<string, unknown>): Record<string, unknown> {
47
66
  tags: parseStoredTags(r.tags),
48
67
  attrs_revision: Number(r.attrs_revision ?? 0),
49
68
  role,
69
+ opencode_catalog: opencodeCatalog,
70
+ opencode_catalog_seen_at: opencodeCatalogSeenAt,
71
+ opencode_generation: opencodeGeneration,
72
+ opencode_mode: opencodeMode,
73
+ opencode_server: opencodeServer,
50
74
  };
51
75
  }
52
76
 
77
+ describe("#3144 opencode_catalog_seen_at —— 三态,不塌成两种", () => {
78
+ // daemon 报了就带出来;没报就是 null。null 的含义是「未上报」,**不是**「很久以前」,
79
+ // 也不是「刚刚」——把两者塌成同一个值,客户端就只能显示一个它并不知道的时刻。
80
+ test("有 opencode_catalog_seen_at ⇒ 原样投影", () => {
81
+ const row = mapRow({
82
+ node_id: "n1", node_name: "n", alias: "n", runtime: "opencode-sdk", model: "m",
83
+ config_path: null, channels: null, server: null, hostname: null,
84
+ network_id: "net", created_at: "x", updated_at: "x", display_name: null,
85
+ team: null, tags: null, attrs_revision: 0,
86
+ config_snapshot: JSON.stringify({
87
+ opencode_catalog: ["a/b"], opencode_catalog_seen_at: "2026-11-01T02:00:00Z",
88
+ }),
89
+ });
90
+ expect(row.opencode_catalog_seen_at).toBe("2026-11-01T02:00:00Z");
91
+ });
92
+
93
+ test("没有那个字段 ⇒ null(不是空串、不是当前时间)", () => {
94
+ const row = mapRow({
95
+ node_id: "n2", node_name: "n", alias: "n", runtime: "opencode-sdk", model: "m",
96
+ config_path: null, channels: null, server: null, hostname: null,
97
+ network_id: "net", created_at: "x", updated_at: "x", display_name: null,
98
+ team: null, tags: null, attrs_revision: 0,
99
+ config_snapshot: JSON.stringify({ opencode_catalog: ["a/b"] }),
100
+ });
101
+ expect(row.opencode_catalog).toEqual(["a/b"]);
102
+ expect(row.opencode_catalog_seen_at).toBeNull();
103
+ });
104
+ });
105
+
53
106
  describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", () => {
54
107
  test("explicit columns + role extracted: config_snapshot NOT in response, role IS", () => {
55
108
  // Insert a row with the leak-prone columns populated. Use INSERT OR
@@ -83,7 +136,8 @@ describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", (
83
136
  // Expected fields present (13 = 12 contract + new role)
84
137
  for (const k of ["node_id", "node_name", "alias", "runtime", "model",
85
138
  "config_path", "channels", "server", "hostname",
86
- "network_id", "created_at", "updated_at", "role"]) {
139
+ "network_id", "created_at", "updated_at", "role", "opencode_catalog",
140
+ "opencode_catalog_seen_at"]) {
87
141
  expect(row).toHaveProperty(k);
88
142
  }
89
143
  // Internal fields NOT present
@@ -100,7 +154,9 @@ describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", (
100
154
  expect(Object.keys(row).sort()).toEqual([
101
155
  "alias", "attrs_revision", "channels", "config_path", "created_at",
102
156
  "display_name", "hostname", "model", "network_id", "node_id",
103
- "node_name", "role", "runtime", "server", "tags", "team",
157
+ "node_name", "opencode_catalog", "opencode_catalog_seen_at",
158
+ "opencode_generation", "opencode_mode",
159
+ "opencode_server", "role", "runtime", "server", "tags", "team",
104
160
  "updated_at",
105
161
  ]);
106
162
  });
@@ -186,3 +242,74 @@ describe("RFC-024 regression — GET /api/nodes response shape (no SELECT *)", (
186
242
  expect(cfgRow?.config_snapshot).toContain("claude-opus");
187
243
  });
188
244
  });
245
+
246
+ // #2293(admin 2026-10-25)—— 节点自报的模型清单必须能到 /api/nodes:
247
+ // 「没有 daemon 绑定」的节点,客户端就是靠这一格给建议列表(否则只能手填)。
248
+ describe("#2293 opencode_catalog projection", () => {
249
+ const insert = (snapshot: unknown) => db.run(
250
+ `INSERT OR REPLACE INTO nodes (node_id, node_name, alias, network_id, config_snapshot)
251
+ VALUES (?1, ?2, ?3, ?4, ?5)`,
252
+ [TEST_NODE, "test-shape", "test-shape", TEST_NETWORK, typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot)],
253
+ );
254
+ const read = () => mapRow(db.get<Record<string, unknown>>(
255
+ `SELECT node_id, node_name, alias, network_id, config_snapshot FROM nodes WHERE node_id = ?1`,
256
+ TEST_NODE,
257
+ )!);
258
+
259
+ test("valid list reaches the row, order kept", () => {
260
+ insert({ opencode_catalog: ["deepseek/deepseek-flash", "opencode/mimo-v2.6-flash-free"] });
261
+ expect(read().opencode_catalog).toEqual(["deepseek/deepseek-flash", "opencode/mimo-v2.6-flash-free"]);
262
+ });
263
+
264
+ test("absent / malformed / wrong shape → null, row still served", () => {
265
+ insert({ model: "x" });
266
+ expect(read().opencode_catalog).toBeNull();
267
+ insert("not-json{");
268
+ expect(read().opencode_catalog).toBeNull();
269
+ // 混了非字符串 → 整格作废(不猜、不部分展示)
270
+ insert({ opencode_catalog: ["a/b", 7] });
271
+ expect(read().opencode_catalog).toBeNull();
272
+ // 空列表是合法但无意义 → 照原样给出(客户端自己判断要不要建列表)
273
+ insert({ opencode_catalog: [] });
274
+ expect(read().opencode_catalog).toEqual([]);
275
+ });
276
+ });
277
+
278
+ // #2293(PR #1092 在真机上拿不到值的原因)—— /api/nodes 不带整个 config_snapshot,
279
+ // 但「Runtime · V2」「OpenCode Server」两行只要三个标量:代际、模式、loopback 端点。
280
+ describe("#2293 opencode_* scalars", () => {
281
+ test("generation / mode / server come from the snapshot, nothing else leaks", () => {
282
+ db.run(
283
+ `INSERT OR REPLACE INTO nodes (node_id, node_name, alias, network_id, config_snapshot)
284
+ VALUES (?1, ?2, ?3, ?4, ?5)`,
285
+ [TEST_NODE, "test-shape", "test-shape", TEST_NETWORK, JSON.stringify({
286
+ flags: { opencodeGeneration: "v2", opencodeMode: "copresence", secretOther: "must-not-leak" },
287
+ opencode_server: "http://127.0.0.1:4096",
288
+ })],
289
+ );
290
+ const row = mapRow(db.get<Record<string, unknown>>(
291
+ `SELECT node_id, node_name, alias, network_id, config_snapshot FROM nodes WHERE node_id = ?1`,
292
+ TEST_NODE,
293
+ )!);
294
+ expect(row.opencode_generation).toBe("v2");
295
+ expect(row.opencode_mode).toBe("copresence");
296
+ expect(row.opencode_server).toBe("http://127.0.0.1:4096");
297
+ expect(row).not.toHaveProperty("config_snapshot");
298
+ expect(JSON.stringify(row)).not.toContain("must-not-leak");
299
+ });
300
+
301
+ test("unknown generation / absent fields → null (old nodes keep rendering)", () => {
302
+ db.run(
303
+ `INSERT OR REPLACE INTO nodes (node_id, node_name, alias, network_id, config_snapshot)
304
+ VALUES (?1, ?2, ?3, ?4, ?5)`,
305
+ [TEST_NODE, "test-shape", "test-shape", TEST_NETWORK, JSON.stringify({ flags: { opencodeGeneration: "v9" } })],
306
+ );
307
+ const row = mapRow(db.get<Record<string, unknown>>(
308
+ `SELECT node_id, node_name, alias, network_id, config_snapshot FROM nodes WHERE node_id = ?1`,
309
+ TEST_NODE,
310
+ )!);
311
+ expect(row.opencode_generation).toBeNull();
312
+ expect(row.opencode_mode).toBeNull();
313
+ expect(row.opencode_server).toBeNull();
314
+ });
315
+ });
@@ -0,0 +1,144 @@
1
+ // #3314 B 类 —— register / login 是**故意匿名**的两条路由(注册与登录本来就发生在
2
+ // 有身份之前),所以「有没有身份门」这个判据对它们不成立,它们的健康度只能从
3
+ // 「限流与锁定实际命中了几次、打到了几个不同来源」读出来。
4
+ //
5
+ // 这里钉的不是「计数器会增加」(那是平凡的),而是三件容易写错的事:
6
+ // ① 去重集合到顶后**不再增长但也不清零**,且置 capped —— 否则「新来源不再出现」
7
+ // 与「数到上限了」同值,而后者需要人去调上限,前者需要人去查攻击。
8
+ // ② 计数与去重数是**两个数**:命中数 ≫ 去重数 ⇒ 单点重试;两者接近 ⇒ 换 IP / 撒网。
9
+ // 只暴露命中数时,这两种完全同形。
10
+ // ③ 快照里**不含** IP 或用户名的值 —— 去重集合只活在进程内。
11
+
12
+ import { test, beforeEach } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import {
15
+ DISTINCT_CAP,
16
+ __resetAuthAbuseForTest,
17
+ authAbuseSnapshot,
18
+ noteLoginIpRateLimited,
19
+ noteLoginLocked,
20
+ noteRegisterRateLimited,
21
+ } from "./auth-abuse-counters.js";
22
+
23
+ beforeEach(() => __resetAuthAbuseForTest());
24
+
25
+ test("三条命中路径各自计数,互不串号", () => {
26
+ noteRegisterRateLimited("1.1.1.1");
27
+ noteLoginIpRateLimited("2.2.2.2");
28
+ noteLoginLocked("alice");
29
+
30
+ const s = authAbuseSnapshot();
31
+ assert.equal(s.register_rate_limited_total, 1);
32
+ assert.equal(s.login_ip_rate_limited_total, 1);
33
+ assert.equal(s.login_locked_total, 1);
34
+ assert.equal(s.distinct_register_limited_ips, 1);
35
+ assert.equal(s.distinct_login_limited_ips, 1);
36
+ assert.equal(s.distinct_locked_usernames, 1);
37
+ assert.equal(s.distinct_capped, false);
38
+ // register 与 login 的 IP 去重是**两份**:合并会让「哪个入口在被撞」变成一个数,
39
+ // 而两者的修法相反(前者限流键是 IP,后者靠用户名失败锁定)。
40
+ });
41
+
42
+ test("同一来源重复命中:命中数涨,去重数不涨", () => {
43
+ for (let i = 0; i < 5; i++) noteRegisterRateLimited("9.9.9.9");
44
+ const s = authAbuseSnapshot();
45
+ assert.equal(s.register_rate_limited_total, 5);
46
+ assert.equal(s.distinct_register_limited_ips, 1);
47
+ // 这个比值才是读数:5/1 ⇒ 单点重试,不是分布式。
48
+ });
49
+
50
+ test("撒网(每次换来源):命中数与去重数同步涨", () => {
51
+ for (let i = 0; i < 5; i++) noteRegisterRateLimited(`10.0.0.${i}`);
52
+ const s = authAbuseSnapshot();
53
+ assert.equal(s.register_rate_limited_total, 5);
54
+ assert.equal(s.distinct_register_limited_ips, 5);
55
+ // 5/5 ⇒ 限流键(IP)在这里是有效的;若换用户名做键,这一行就失效。
56
+ });
57
+
58
+ test("锁定命中按用户名去重:一个人被锁多次 = 1", () => {
59
+ for (let i = 0; i < 7; i++) noteLoginLocked("bob");
60
+ noteLoginLocked("carol");
61
+ const s = authAbuseSnapshot();
62
+ assert.equal(s.login_locked_total, 8);
63
+ assert.equal(s.distinct_locked_usernames, 2);
64
+ });
65
+
66
+ test("缺来源(null / undefined / 空串)仍计数,但不污染去重集合", () => {
67
+ noteRegisterRateLimited(null);
68
+ noteRegisterRateLimited(undefined);
69
+ noteRegisterRateLimited("");
70
+ const s = authAbuseSnapshot();
71
+ assert.equal(s.register_rate_limited_total, 3);
72
+ assert.equal(s.distinct_register_limited_ips, 0);
73
+ // 「来源不明」与「一个来源」不是同一个读数 —— 前者说明连 x-forwarded-for 都没有。
74
+ });
75
+
76
+ test("去重集合到顶:distinct 停在上限、capped 置真、命中数继续涨", () => {
77
+ for (let i = 0; i < DISTINCT_CAP + 50; i++) noteRegisterRateLimited(`ip-${i}`);
78
+ const s = authAbuseSnapshot();
79
+ assert.equal(s.distinct_register_limited_ips, DISTINCT_CAP);
80
+ assert.equal(s.distinct_capped, true);
81
+ assert.equal(s.register_rate_limited_total, DISTINCT_CAP + 50);
82
+ // 关键:capped 之后 distinct 是**下界**。没有这一位,「不再有新来源」与
83
+ // 「已经数满了」会显示成同一个数,而它们要做的事相反。
84
+ });
85
+
86
+ test("上限按「有没有真的丢过一条」判,不按「集合是否已满」", () => {
87
+ // 正好填满不是丢:distinct 仍然准确 ⇒ capped 必须是 false。
88
+ for (let i = 0; i < DISTINCT_CAP; i++) noteLoginIpRateLimited(`ip-${i}`);
89
+ let s = authAbuseSnapshot();
90
+ assert.equal(s.distinct_login_limited_ips, DISTINCT_CAP);
91
+ assert.equal(s.distinct_capped, false, "满员但没丢过 ⇒ 这些数还是真值");
92
+ // 再塞一条才会被拒 ⇒ 从这一刻起 distinct 变成下界。
93
+ noteLoginIpRateLimited("ip-overflow");
94
+ s = authAbuseSnapshot();
95
+ assert.equal(s.distinct_login_limited_ips, DISTINCT_CAP);
96
+ assert.equal(s.distinct_capped, true);
97
+ // 且 login 那份满员不影响 register 那份,也不影响用户名那份。
98
+ assert.equal(s.distinct_register_limited_ips, 0);
99
+ assert.equal(s.distinct_locked_usernames, 0);
100
+ });
101
+
102
+ // 2026-11-01 —— 「同一个对象里」只保证同一次调用;**已读出的那份之后不得再变**。
103
+ // 这条可判:读一次快照 → 再触发计数 → 早先那份的值不许动。
104
+ // 缺它时,一次读取拿到的是**活引用**与**不可变快照**在报告上同形,
105
+ // 而活引用会让「读完之后又涨了」被读成「同一份读数自相矛盾」。
106
+ test("快照是不可变的一份,不是内部状态的活引用", () => {
107
+ noteRegisterRateLimited("10.1.1.1");
108
+ const first = authAbuseSnapshot();
109
+ const before = first.register_rate_limited_total;
110
+ noteRegisterRateLimited("10.1.1.2");
111
+ noteRegisterRateLimited("10.1.1.3");
112
+ // 早先那份必须一字不动
113
+ expect(first.register_rate_limited_total).toBe(before);
114
+ expect(first.distinct_register_limited_ips).toBe(1);
115
+ // 再读一次才看得到新的
116
+ const second = authAbuseSnapshot();
117
+ expect(second.register_rate_limited_total).toBe(before + 2);
118
+ expect(second.distinct_register_limited_ips).toBe(3);
119
+ });
120
+
121
+ test("快照形状固定(键集是契约,不是实现细节)", () => {
122
+ const keys = Object.keys(authAbuseSnapshot()).sort();
123
+ assert.deepEqual(keys, [
124
+ "distinct_capped",
125
+ "distinct_locked_usernames",
126
+ "distinct_login_limited_ips",
127
+ "distinct_register_limited_ips",
128
+ "login_ip_rate_limited_total",
129
+ "login_locked_total",
130
+ "register_rate_limited_total",
131
+ "since",
132
+ ]);
133
+ // 键集固定 ⇒ 加字段会让这条红。这是有意的:/health 的读者按名字取,
134
+ // 静默改名会让他们读到 undefined 而当作 0。
135
+ });
136
+
137
+ test("快照里没有来源本身(IP / 用户名)", () => {
138
+ noteRegisterRateLimited("203.0.113.7");
139
+ noteLoginLocked("erin");
140
+ const serialized = JSON.stringify(authAbuseSnapshot());
141
+ assert.equal(serialized.includes("203.0.113.7"), false);
142
+ assert.equal(serialized.includes("erin"), false);
143
+ // 计数可以公开,来源不行 —— 与 sessions_count 同一条取舍。
144
+ });
@@ -0,0 +1,122 @@
1
+ // 2026-11-01 —— #3314 B 类的读数:**故意匿名**的两条路由(register / login)没有身份门,
2
+ // 所以它们的健康度只能从「限流与锁定实际命中了几次」看出来。
3
+ //
4
+ // 为什么要有这个文件,而不是复用 logAudit:
5
+ // logAudit 写的是**事件**,一条一行,回答「刚才谁被拦了」;
6
+ // 这里记的是**计数与去重数**,回答的是两个结构性问题:
7
+ // ① register 的限流键是 IP ⇒ 命中数远大于去重 IP 数时,是同一个 IP 在撞;
8
+ // 去重 IP 数逼近命中数时,是「换 IP 绕过」在发生(即限流键选错了单位)。
9
+ // ② login 的失败锁定键是**用户名** ⇒ 命中数远大于去重用户名数时,是有人在锁死
10
+ // 某一个账号(针对单人的 DoS);去重用户名数远大于命中数则是撒网。
11
+ // 这两个问题都不是「有没有异常」,而是「键选得对不对」——只能用**比值**读出来。
12
+ //
13
+ // 隐私边界:只暴露计数与去重数,**永不暴露 IP 或用户名的值**。去重集合本身也不导出,
14
+ // 只在进程内存在;`distinct_*` 到顶后计数停止增长并置 capped=true,
15
+ // 这样「去重数不再涨」这件事本身不会被读成「没有新来源」。
16
+ //
17
+ // 已知偏差(写在读数旁边,不写在文档里):
18
+ // · 进程内计数,重启归零 ⇒ 与 /health 的 counters_since 同源,读之前先看 since。
19
+ // · 去重集合有上限(512)⇒ capped=true 时 distinct_* 是**下界**,不是真值。
20
+ // · 🔴 **本机来源下这三个计数恒为 0,而且那不是「没有被滥用」。**
21
+ // `checkRateLimit()` 对 `127.0.0.1` / `::1` / `""` / `"unknown"` 直接 `return true`
22
+ // (server.ts:249,为 dev/test 留的口子),于是 register 的限流分支根本不会走到。
23
+ // 实测(`0.9.0-preview.258` 的制品,本地起在 9311):
24
+ // · 不带 X-Forwarded-For 打 36 次注册 ⇒ 全部 200,register_rate_limited_total 仍是 0
25
+ // · 带 `X-Forwarded-For: 203.0.113.9` 打 34 次 ⇒ 30×200 + 4×429,
26
+ // register_rate_limited_total = 4、distinct_register_limited_ips = 1(**逐次对得上**)
27
+ // · 带 `X-Forwarded-For: 203.0.113.77` 用同一个用户名错 8 次 ⇒ 5×401 + 3×429,
28
+ // login_locked_total = 3、distinct_locked_usernames = 1
29
+ // ⇒ 所以「本地读到 0」是一个结构性假阴性:要见证必须模拟外部来源(XFF),
30
+ // 否则 0 会被读成「没有滥用」,而它其实只说明「限流器跳过了本机」。
31
+
32
+ export const DISTINCT_CAP = 512;
33
+
34
+ export interface AuthAbuseSnapshot {
35
+ since: string;
36
+ /** register 被 IP 限流拦截的次数 */
37
+ register_rate_limited_total: number;
38
+ /** login 被 IP 速率限制拦截的次数 */
39
+ login_ip_rate_limited_total: number;
40
+ /** login 被「用户名失败锁定」拦截的次数 */
41
+ login_locked_total: number;
42
+ /** 撞过 register 限流的**不同** IP 数(capped 时为下界) */
43
+ distinct_register_limited_ips: number;
44
+ /** 撞过 login IP 限流的**不同** IP 数(capped 时为下界) */
45
+ distinct_login_limited_ips: number;
46
+ /** 被失败锁定拦过的**不同**用户名数(capped 时为下界) */
47
+ distinct_locked_usernames: number;
48
+ /** 任一去重集合是否已到上限 ⇒ distinct_* 只是下界 */
49
+ distinct_capped: boolean;
50
+ }
51
+
52
+ interface State {
53
+ since: string;
54
+ registerRateLimited: number;
55
+ loginIpRateLimited: number;
56
+ loginLocked: number;
57
+ // 两份 IP 集合不是一个:register 的窗口与阈值(30/窗口)与 login 的双速率不同,
58
+ // 合并会让「哪个入口在被撞」变成一个数,而这两个入口的修法相反
59
+ // (register:键是 IP ⇒ 分布式刷注册有效;login:键是 IP + 用户名失败锁定)。
60
+ registerIps: Set<string>;
61
+ loginIps: Set<string>;
62
+ usernames: Set<string>;
63
+ capped: boolean;
64
+ }
65
+
66
+ function fresh(): State {
67
+ return {
68
+ since: new Date().toISOString(),
69
+ registerRateLimited: 0,
70
+ loginIpRateLimited: 0,
71
+ loginLocked: 0,
72
+ registerIps: new Set<string>(),
73
+ loginIps: new Set<string>(),
74
+ usernames: new Set<string>(),
75
+ capped: false,
76
+ };
77
+ }
78
+
79
+ let state: State = fresh();
80
+
81
+ function addBounded(set: Set<string>, value: string): void {
82
+ if (set.has(value)) return;
83
+ if (set.size >= DISTINCT_CAP) {
84
+ // 到顶不是「没有了」,是「不再数了」—— 所以必须留下 capped 这个痕迹。
85
+ state.capped = true;
86
+ return;
87
+ }
88
+ set.add(value);
89
+ }
90
+
91
+ export function noteRegisterRateLimited(ip: string | null | undefined): void {
92
+ state.registerRateLimited += 1;
93
+ if (ip) addBounded(state.registerIps, ip);
94
+ }
95
+
96
+ export function noteLoginIpRateLimited(ip: string | null | undefined): void {
97
+ state.loginIpRateLimited += 1;
98
+ if (ip) addBounded(state.loginIps, ip);
99
+ }
100
+
101
+ export function noteLoginLocked(username: string | null | undefined): void {
102
+ state.loginLocked += 1;
103
+ if (username) addBounded(state.usernames, username);
104
+ }
105
+
106
+ export function authAbuseSnapshot(): AuthAbuseSnapshot {
107
+ return {
108
+ since: state.since,
109
+ register_rate_limited_total: state.registerRateLimited,
110
+ login_ip_rate_limited_total: state.loginIpRateLimited,
111
+ login_locked_total: state.loginLocked,
112
+ distinct_register_limited_ips: state.registerIps.size,
113
+ distinct_login_limited_ips: state.loginIps.size,
114
+ distinct_locked_usernames: state.usernames.size,
115
+ distinct_capped: state.capped,
116
+ };
117
+ }
118
+
119
+ /** 只在测试里用:把计数清回起点。生产路径不调用。 */
120
+ export function __resetAuthAbuseForTest(): void {
121
+ state = fresh();
122
+ }
@@ -0,0 +1,105 @@
1
+ // 鉴权层的**形状**:同一条未认证请求,最终是谁答的。
2
+ //
3
+ // ## 为什么要钉这个
4
+ //
5
+ // 2026-11-01(#3374):34 条写路由逐条发未认证请求,响应体分三种:
6
+ //
7
+ // {"error":"unauthorized"} ⇒ 全局鉴权层先答 ⇒ handler 内那条 401 分支**从不执行**
8
+ // {"ok":false,"error":"auth required"} ⇒ handler 自己就是门
9
+ // {"ok":false,"error":"token required"} ⇒ handler 自己就是门(另一句文案)
10
+ //
11
+ // 这三者对外都是「401」,对内却决定「那条分支是否可达」。差别不是风格:
12
+ // 把第二种当成第一种删掉,就等于删掉一道真的门(实测 18 条是这种)。
13
+ //
14
+ // ## 这张表断言什么
15
+ //
16
+ // 每行:一条路由 + 它今天由谁答。它钉的是**分层**,不是措辞:
17
+ // 措辞变了不算破坏契约,但**答话的人变了**是 —— 那意味着有一道门换了位置。
18
+ //
19
+ // ## 它是抽样(12 条),不是全集
20
+ //
21
+ // 全集的分档要么逐条请求(脚本 report-inner-auth-branches.py 记录方法),
22
+ // 要么需要可枚举的中间件栈(本仓没有)。这张表选的是**每类各取几条**,
23
+ // 目的是让「分层被改动」这件事变红,而不是声称覆盖率。
24
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
25
+ import { mkdtempSync, rmSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import { tmpdir } from "node:os";
28
+ import { register } from "./auth.js";
29
+
30
+ const DIR = mkdtempSync(join(tmpdir(), "anet-auth-layer-"));
31
+ const PW = "AuthLayerPassw0rd!";
32
+ let BASE = "";
33
+ let hub: any = null;
34
+ let NET = "";
35
+
36
+ type Shape = "global_unauthorized" | "handler_auth" | "handler_token" | "public_input";
37
+
38
+ const classify = (status: number, body: string): Shape => {
39
+ if (body.includes('"unauthorized"')) return "global_unauthorized";
40
+ if (body.includes('"auth required"')) return "handler_auth";
41
+ if (body.includes('"token required"')) return "handler_token";
42
+ return "public_input"; // 公开路由:直接进入参数校验
43
+ };
44
+
45
+ beforeAll(async () => {
46
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
47
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
48
+ process.env.HOST = "127.0.0.1";
49
+ const a = register(`al_${Date.now()}`, PW);
50
+ NET = a.network_id!;
51
+ const mod: any = await import("./server.js");
52
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
53
+ BASE = `http://127.0.0.1:${hub.port}`;
54
+ }, 30_000);
55
+
56
+ afterAll(() => {
57
+ try { hub?.stop?.(true); } catch {}
58
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
59
+ });
60
+
61
+ // [方法, 路径, 今天由谁答, 备注]
62
+ const TABLE: Array<[string, string, Shape, string]> = [
63
+ ["GET", "/api/nodes", "global_unauthorized", "读路由,全局层先答"],
64
+ ["GET", "/api/providers", "global_unauthorized", "读路由"],
65
+ ["PUT", "/api/providers", "global_unauthorized", "写路由,全局层先答"],
66
+ ["GET", "/api/networks/:NET/node-permission-report", "global_unauthorized", "报表"],
67
+ ["POST", "/api/auth/tokens", "handler_auth", "handler 自己就是门(换令牌的入口不能被别的层替它把关)"],
68
+ ["POST", "/api/node-rename/prepare", "handler_auth", "同上"],
69
+ ["POST", "/api/node-rename/commit", "handler_auth", "同上"],
70
+ ["DELETE", "/api/auth/tokens/tok_x", "handler_auth", "同上"],
71
+ ["PUT", "/api/auth/me", "handler_token", "handler 取 token 并给出 token required"],
72
+ ["POST", "/api/networks", "handler_token", "同上"],
73
+ // 读路由也分档(2026-11-01 抽样 24 条读路由:7 全局层 / 3 handler_token / 1 404 / 1 公开)
74
+ ["GET", "/api/auth/tokens", "handler_auth", "读路由里 handler 自己把关的一类"],
75
+ ["GET", "/api/networks/:NET/rules", "handler_auth", "同上"],
76
+ ["GET", "/api/users/x/avatar/y.png", "handler_token", "handler 取 token 并给出 token required"],
77
+ ["POST", "/api/auth/register", "public_input", "按设计公开:直接进参数校验"],
78
+ ["POST", "/api/auth/login", "public_input", "按设计公开"],
79
+ ];
80
+
81
+ describe("鉴权层形状(谁答这条未认证请求)", () => {
82
+ for (const [method, rawPath, expected, why] of TABLE) {
83
+ const path = rawPath.replace(":NET", "net_placeholder");
84
+ test(`${method} ${rawPath} ⇒ ${expected}(${why})`, async () => {
85
+ const url = `${BASE}${path}${path.includes("?") ? "&" : "?"}network_id=${NET}`;
86
+ const r = await fetch(url, {
87
+ method,
88
+ headers: { "content-type": "application/json" },
89
+ body: method === "GET" ? undefined : "{}",
90
+ });
91
+ const body = await r.text();
92
+ expect(classify(r.status, body)).toBe(expected);
93
+ });
94
+ }
95
+
96
+ // 分层被改动时,最容易被误判的是这两条:它们**不是**全局层答的。
97
+ test("抽查:handler 就是门的那几条,响应体里带 ok:false(不是裸 error)", async () => {
98
+ const r = await fetch(`${BASE}/api/auth/tokens?network_id=${NET}`, {
99
+ method: "POST", headers: { "content-type": "application/json" }, body: "{}",
100
+ });
101
+ const body = await r.json() as any;
102
+ expect(body.ok).toBe(false);
103
+ expect(body.error).toBe("auth required");
104
+ });
105
+ });