@sleep2agi/commhub-server 0.9.0-preview.20 → 0.9.0-preview.200

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 (398) hide show
  1. package/README.md +130 -10
  2. package/bin/commhub.ts +99 -11
  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 +267 -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 +21 -12
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +120 -13
  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 +163 -0
  35. package/src/avatar-validate.ts +103 -0
  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/boot-side-effect.test.ts +124 -0
  40. package/src/broadcast-fanout-2721.test.ts +118 -0
  41. package/src/broadcast-fanout.ts +98 -0
  42. package/src/chain-attempt-dedup.test.ts +447 -0
  43. package/src/clone-node.test.ts +248 -0
  44. package/src/clone-node.ts +289 -0
  45. package/src/codex-config-flags.ts +77 -0
  46. package/src/codex-fork-contract.ts +23 -0
  47. package/src/codex-fork-migration.test.ts +38 -0
  48. package/src/commhub-bin-args.test.ts +85 -0
  49. package/src/config-apply-sec1.test.ts +107 -0
  50. package/src/config-apply-validate.test.ts +134 -1
  51. package/src/config-apply-validate.ts +111 -5
  52. package/src/create-node-blocked-gate.test.ts +356 -0
  53. package/src/create-node-network-id.test.ts +79 -0
  54. package/src/create-node-tool-schema.test.ts +49 -0
  55. package/src/create-node-unicode-name.test.ts +120 -0
  56. package/src/create-node-validate.test.ts +199 -7
  57. package/src/create-node-validate.ts +232 -15
  58. package/src/create-node-workdir.test.ts +289 -0
  59. package/src/create-node.ts +88 -23
  60. package/src/daemon-provider-snapshots.test.ts +421 -0
  61. package/src/daemon-provider-snapshots.ts +327 -0
  62. package/src/daemon-token-owner-http.test.ts +236 -0
  63. package/src/dashboard-slash-routing-http.test.ts +109 -0
  64. package/src/db-adapter-guard.test.ts +148 -0
  65. package/src/db-adapter-translate.test.ts +128 -0
  66. package/src/db-adapter.ts +377 -91
  67. package/src/db-timestamp.test.ts +38 -0
  68. package/src/db-timestamp.ts +15 -0
  69. package/src/db.ts +1306 -153
  70. package/src/delivered-without-push.test.ts +140 -0
  71. package/src/department-groups-http.test.ts +209 -0
  72. package/src/department-groups-sync-http.test.ts +328 -0
  73. package/src/department-groups.ts +434 -0
  74. package/src/department-heads-http.test.ts +330 -0
  75. package/src/department-heads.ts +226 -0
  76. package/src/departments-agent-count.test.ts +129 -0
  77. package/src/departments-http.test.ts +185 -0
  78. package/src/departments-mcp.test.ts +128 -0
  79. package/src/departments.ts +318 -0
  80. package/src/desktop-message-seam.test.ts +150 -0
  81. package/src/desktop-message.test.ts +368 -0
  82. package/src/dm-file-scope-http.test.ts +178 -0
  83. package/src/empty-node-sweeper.test.ts +104 -0
  84. package/src/empty-node-sweeper.ts +88 -0
  85. package/src/env-transport-gate-http.test.ts +177 -0
  86. package/src/env-transport-gate.ts +74 -0
  87. package/src/env-transport-policy.ts +21 -0
  88. package/src/event-loop-lag.test.ts +139 -0
  89. package/src/event-loop-lag.ts +150 -0
  90. package/src/ext-token-shared.test.ts +60 -0
  91. package/src/ext-validation-regression.test.ts +131 -0
  92. package/src/external-schedule-edits-http.test.ts +321 -0
  93. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  94. package/src/external-schedule-edits.ts +327 -0
  95. package/src/file-download-authz-dev-open.test.ts +135 -0
  96. package/src/file-download-authz.test.ts +404 -0
  97. package/src/file-download-date-bucket.test.ts +436 -0
  98. package/src/file-network-scope-dev-open.test.ts +97 -0
  99. package/src/file-network-scope.test.ts +732 -0
  100. package/src/group-membership-events-http.test.ts +264 -0
  101. package/src/group-messages-http.test.ts +482 -0
  102. package/src/group-messages.ts +297 -0
  103. package/src/health-host-disk-2756.test.ts +49 -0
  104. package/src/health-redaction.test.ts +685 -0
  105. package/src/host-supervisor-identity-http.test.ts +152 -0
  106. package/src/host-supervisor-identity.ts +92 -0
  107. package/src/host-supervisors-daemon-version.test.ts +137 -0
  108. package/src/http-gzip.test.ts +94 -0
  109. package/src/http-gzip.ts +112 -0
  110. package/src/hub-catalog-read-http.test.ts +187 -0
  111. package/src/hub-provider-config.test.ts +139 -0
  112. package/src/hub-provider-config.ts +105 -0
  113. package/src/hub-timestamp.test.ts +38 -0
  114. package/src/hub-timestamp.ts +27 -0
  115. package/src/human-dm.ts +215 -0
  116. package/src/human-inbox.ts +42 -0
  117. package/src/inbox-caller.ts +49 -0
  118. package/src/inbox-count-sse.test.ts +310 -0
  119. package/src/inbox-count.ts +29 -0
  120. package/src/index.ts +15 -2380
  121. package/src/list-host-supervisors.test.ts +5 -4
  122. package/src/mcp-context-cost-http.test.ts +127 -0
  123. package/src/mcp-inflight.test.ts +92 -0
  124. package/src/mcp-inflight.ts +38 -0
  125. package/src/mcp-projects-events-http.test.ts +162 -0
  126. package/src/mcp-route-label-http.test.ts +120 -0
  127. package/src/mcp-write-network-resolution.test.ts +432 -0
  128. package/src/member-audit-network-id-http.test.ts +93 -0
  129. package/src/member-presence-http.test.ts +210 -0
  130. package/src/messages-ack-by-agent-http.test.ts +142 -0
  131. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  132. package/src/migrate-sqlite-to-pg.ts +263 -0
  133. package/src/model-auth-notify-http.test.ts +181 -0
  134. package/src/model-auth-notify.ts +116 -0
  135. package/src/network-name-http.test.ts +75 -0
  136. package/src/network-rules-http.test.ts +169 -0
  137. package/src/network-rules.ts +129 -0
  138. package/src/network-scope.ts +276 -0
  139. package/src/network-token-membership-http.test.ts +139 -0
  140. package/src/node-alias-control.ts +12 -0
  141. package/src/node-attrs-validate.ts +88 -0
  142. package/src/node-attrs.test.ts +258 -0
  143. package/src/node-caller-identity-http.test.ts +1083 -0
  144. package/src/node-create-request-status-http.test.ts +105 -0
  145. package/src/node-daemon-bindings.test.ts +132 -0
  146. package/src/node-daemon-bindings.ts +135 -0
  147. package/src/node-failure-alert.test.ts +150 -0
  148. package/src/node-failure-alert.ts +177 -0
  149. package/src/node-files-transport.test.ts +344 -0
  150. package/src/node-health-codex-login.test.ts +120 -0
  151. package/src/node-health-dispatch-http.test.ts +279 -0
  152. package/src/node-health-guard.ts +105 -0
  153. package/src/node-health-passthrough.test.ts +115 -0
  154. package/src/node-health-store.ts +101 -0
  155. package/src/node-id-alias.test.ts +190 -0
  156. package/src/node-identity-conflict-http.test.ts +269 -0
  157. package/src/node-identity-conflict.ts +142 -0
  158. package/src/node-identity-mismatch.test.ts +74 -0
  159. package/src/node-in-flight-tasks.ts +31 -0
  160. package/src/node-lifecycle-controllable.test.ts +64 -0
  161. package/src/node-lifecycle-controllable.ts +53 -0
  162. package/src/node-lifecycle-read-http.test.ts +250 -0
  163. package/src/node-lifecycle-read.ts +124 -0
  164. package/src/node-logs-transport.test.ts +263 -0
  165. package/src/node-peer-allowlist.test.ts +79 -0
  166. package/src/node-permissions-http.test.ts +345 -0
  167. package/src/node-permissions.ts +393 -0
  168. package/src/node-request-retention.test.ts +281 -0
  169. package/src/node-request-retention.ts +120 -0
  170. package/src/node-secret-rest-http.test.ts +190 -0
  171. package/src/node-serviceability.test.ts +86 -0
  172. package/src/node-serviceability.ts +124 -0
  173. package/src/node-session-control-http.test.ts +310 -0
  174. package/src/node-session-control.ts +258 -0
  175. package/src/node-skills-transport.test.ts +209 -0
  176. package/src/node-token-identity.ts +35 -0
  177. package/src/node-token-ownership.ts +51 -0
  178. package/src/node-token-privilege-http.test.ts +158 -0
  179. package/src/not-found-api-http.test.ts +67 -0
  180. package/src/observer-avatar-http.test.ts +442 -0
  181. package/src/observer-push.test.ts +252 -0
  182. package/src/opencode-catalog-report-http.test.ts +139 -0
  183. package/src/opencode-v2-catalog.test.ts +268 -0
  184. package/src/opencode-v2-catalog.ts +352 -0
  185. package/src/package-version-consistency.test.ts +25 -0
  186. package/src/parent-source-marker.test.ts +50 -0
  187. package/src/password-network-tokens.ts +25 -0
  188. package/src/peer-reply-atomic.test.ts +455 -0
  189. package/src/peer-reply-capability.test.ts +70 -0
  190. package/src/pg-worker.ts +87 -0
  191. package/src/project-dir-warn-clear-http.test.ts +132 -0
  192. package/src/project-viewer-can-http.test.ts +116 -0
  193. package/src/push.test.ts +20 -10
  194. package/src/push.ts +466 -13
  195. package/src/redact-tokens.test.ts +65 -0
  196. package/src/redact-tokens.ts +40 -0
  197. package/src/rename.ts +38 -10
  198. package/src/reply-target-derivation.test.ts +96 -0
  199. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  200. package/src/report-status-host-schema.test.ts +235 -0
  201. package/src/report-status-resume-id-handover.test.ts +184 -0
  202. package/src/report-status-secret-keys.test.ts +140 -0
  203. package/src/require-explicit-test-db.ts +9 -0
  204. package/src/requirement-due-reminders-http.test.ts +620 -0
  205. package/src/requirement-due-reminders.ts +416 -0
  206. package/src/requirement-events-http.test.ts +268 -0
  207. package/src/requirement-events.test.ts +45 -0
  208. package/src/requirement-events.ts +144 -0
  209. package/src/requirement-notify.ts +165 -0
  210. package/src/requirement-participant-notify-http.test.ts +309 -0
  211. package/src/requirement-tag-ops-http.test.ts +425 -0
  212. package/src/requirement-tag-tree-http.test.ts +275 -0
  213. package/src/requirement-tag-tree.ts +127 -0
  214. package/src/requirement-tags.ts +102 -0
  215. package/src/requirements-abandoned-http.test.ts +236 -0
  216. package/src/requirements-comment-http.test.ts +167 -0
  217. package/src/requirements-completed-at-migration.test.ts +70 -0
  218. package/src/requirements-errors-mcp-http.test.ts +164 -0
  219. package/src/requirements-errors.ts +158 -0
  220. package/src/requirements-etag-http.test.ts +91 -0
  221. package/src/requirements-http.test.ts +709 -0
  222. package/src/requirements-last-event-http.test.ts +349 -0
  223. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  224. package/src/requirements-list-slim-http.test.ts +324 -0
  225. package/src/requirements-mcp.test.ts +163 -0
  226. package/src/requirements-migrate.ts +283 -0
  227. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  228. package/src/requirements-people-http.test.ts +114 -0
  229. package/src/requirements-people-mcp-http.test.ts +231 -0
  230. package/src/requirements-people.ts +196 -0
  231. package/src/requirements-priority-lowest.test.ts +114 -0
  232. package/src/requirements-projects-parent-http.test.ts +123 -0
  233. package/src/requirements-search-http.test.ts +182 -0
  234. package/src/requirements-search.test.ts +32 -0
  235. package/src/requirements-search.ts +145 -0
  236. package/src/requirements-seq-http.test.ts +193 -0
  237. package/src/requirements-seq-migration.test.ts +63 -0
  238. package/src/requirements-start-date.test.ts +125 -0
  239. package/src/requirements-stats-http.test.ts +357 -0
  240. package/src/requirements-stats.ts +195 -0
  241. package/src/requirements-status-participants-http.test.ts +222 -0
  242. package/src/requirements-upgrade-e2e.test.ts +126 -0
  243. package/src/requirements-upgrade-migration.test.ts +98 -0
  244. package/src/requirements.ts +2027 -0
  245. package/src/resolve-port.test.ts +57 -0
  246. package/src/resolve-port.ts +44 -0
  247. package/src/response-charset.test.ts +130 -0
  248. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  249. package/src/rest-alias-network-fallback.test.ts +60 -0
  250. package/src/rest-alias-network-fallback.ts +65 -0
  251. package/src/rest-explicit-columns-http.test.ts +266 -0
  252. package/src/rest-identity.test.ts +130 -0
  253. package/src/rest-identity.ts +141 -0
  254. package/src/rest-projections.ts +72 -0
  255. package/src/rest-read-network-real-chain.test.ts +97 -0
  256. package/src/rest-write-network-resolution.test.ts +133 -0
  257. package/src/restart-readiness-http.test.ts +121 -0
  258. package/src/restricted-files.ts +76 -0
  259. package/src/retention-first-sweep-quiet.test.ts +31 -0
  260. package/src/retention.test.ts +100 -40
  261. package/src/retention.ts +423 -104
  262. package/src/route-callers-http.test.ts +120 -0
  263. package/src/route-timing.test.ts +211 -0
  264. package/src/route-timing.ts +262 -0
  265. package/src/rules-file-duplicate-alias.test.ts +234 -0
  266. package/src/rules-file-session-target.test.ts +207 -0
  267. package/src/rules-file-transport.test.ts +237 -0
  268. package/src/runtime-label.test.ts +22 -0
  269. package/src/runtime-label.ts +21 -0
  270. package/src/runtime-readiness.ts +90 -0
  271. package/src/schedule-agent-mcp-http.test.ts +391 -0
  272. package/src/schedule-agent.ts +192 -0
  273. package/src/schedule-starved.test.ts +92 -0
  274. package/src/schedule-starved.ts +114 -0
  275. package/src/scheduled-backoff-http.test.ts +193 -0
  276. package/src/scheduled-backoff.ts +64 -0
  277. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  278. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  279. package/src/scheduled-failure-code.test.ts +73 -0
  280. package/src/scheduled-failure-code.ts +105 -0
  281. package/src/scheduled-failures-http.test.ts +279 -0
  282. package/src/scheduled-failures.ts +377 -0
  283. package/src/scheduled-noprogress-backoff-2622.test.ts +133 -0
  284. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  285. package/src/scheduled-offline.test.ts +131 -0
  286. package/src/scheduled-offline.ts +66 -0
  287. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  288. package/src/scheduled-outcome-guidance.ts +9 -0
  289. package/src/scheduled-reply-unread-http.test.ts +212 -0
  290. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  291. package/src/scheduled-requirement-wake.ts +125 -0
  292. package/src/scheduled-run-terminal.test.ts +268 -0
  293. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  294. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  295. package/src/scheduled-stuck-http.test.ts +312 -0
  296. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  297. package/src/scheduled-stuck.ts +219 -0
  298. package/src/scheduled-tasks-http.test.ts +679 -0
  299. package/src/scheduled-tasks.ts +959 -0
  300. package/src/scheduled-work-outcome-http.test.ts +154 -0
  301. package/src/scheduled-work-outcome.ts +50 -0
  302. package/src/scoped-secrets.ts +139 -0
  303. package/src/send-dedup-request-id.test.ts +229 -0
  304. package/src/send-reply-agent-warning.test.ts +202 -0
  305. package/src/send-reply-alias-optional.test.ts +131 -0
  306. package/src/send-reply-attachments.test.ts +458 -0
  307. package/src/send_dedup.test.ts +54 -0
  308. package/src/send_dedup.ts +52 -6
  309. package/src/serve-error.test.ts +38 -0
  310. package/src/serve-error.ts +27 -0
  311. package/src/server.ts +5997 -0
  312. package/src/session-task-on-dispatch.ts +14 -0
  313. package/src/session-token-ownership-http.test.ts +122 -0
  314. package/src/shared/codex-inventory.ts +41 -0
  315. package/src/shared/daemon-provider-login.ts +31 -0
  316. package/src/shared/daemon-provider-snapshot.ts +52 -0
  317. package/src/shared/external-schedule-contract.ts +60 -0
  318. package/src/shared/node-name.test.ts +62 -0
  319. package/src/shared/node-name.ts +161 -0
  320. package/src/shared/provider-application.ts +29 -0
  321. package/src/shared/provider-collection.ts +14 -0
  322. package/src/shared/provider-initialization.ts +8 -0
  323. package/src/shared/reserved-env-drift.test.ts +10 -0
  324. package/src/shared/scoped-secret-contract.ts +5 -0
  325. package/src/shared/task-content-limit-drift.test.ts +28 -0
  326. package/src/shared/task-content-limit.ts +25 -0
  327. package/src/side-thread-command-transport.test.ts +312 -0
  328. package/src/side-thread-command-transport.ts +318 -0
  329. package/src/side-thread-http-integration.test.ts +233 -0
  330. package/src/side-thread-http.ts +504 -0
  331. package/src/side-thread-production.test.ts +72 -0
  332. package/src/side-thread-production.ts +118 -0
  333. package/src/side-thread.test.ts +1067 -0
  334. package/src/side-thread.ts +2499 -0
  335. package/src/skillhub-http.test.ts +108 -0
  336. package/src/sqlite-close-checkpoint.test.ts +78 -0
  337. package/src/start-node.test.ts +264 -0
  338. package/src/status-alias-filter-http.test.ts +106 -0
  339. package/src/status-alias-resolver-http.test.ts +163 -0
  340. package/src/status-alias-resolver.ts +19 -0
  341. package/src/status-node-id-filter-http.test.ts +161 -0
  342. package/src/status-read-cache-http.test.ts +229 -0
  343. package/src/status-read-cache.ts +122 -0
  344. package/src/stop-delete-node.test.ts +567 -1
  345. package/src/task-access-http.test.ts +402 -0
  346. package/src/task-access.ts +420 -0
  347. package/src/task-activity.ts +60 -0
  348. package/src/task-auth-origin-http.test.ts +93 -0
  349. package/src/task-auth-origin.test.ts +24 -0
  350. package/src/task-auth-origin.ts +7 -0
  351. package/src/task-consumption.test.ts +482 -0
  352. package/src/task-diagnostic-http.test.ts +149 -0
  353. package/src/task-diagnostic.test.ts +115 -0
  354. package/src/task-diagnostic.ts +118 -0
  355. package/src/task-expiry-notice-http.test.ts +287 -0
  356. package/src/task-expiry-notice.ts +315 -0
  357. package/src/task-idempotency-mcp.test.ts +142 -0
  358. package/src/task-idempotency.test.ts +76 -0
  359. package/src/task-idempotency.ts +81 -0
  360. package/src/task-late-replies.ts +54 -0
  361. package/src/task-late-reply-http.test.ts +152 -0
  362. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  363. package/src/task-lifecycle-watcher.test.ts +204 -0
  364. package/src/task-lifecycle-watcher.ts +109 -0
  365. package/src/task-network-resolution-http.test.ts +140 -0
  366. package/src/task-offline-delivery-2668.test.ts +119 -0
  367. package/src/task-offline-delivery.ts +81 -0
  368. package/src/task-orphan-http.test.ts +287 -0
  369. package/src/task-orphan.ts +119 -0
  370. package/src/task-queue-ahead-http.test.ts +309 -0
  371. package/src/task-queue-ahead-scale.test.ts +236 -0
  372. package/src/task-queue-ahead.ts +186 -0
  373. package/src/task-rejection-log-http.test.ts +160 -0
  374. package/src/task-rejection-log.ts +49 -0
  375. package/src/task-sender-http.test.ts +143 -0
  376. package/src/task-stale-open-http.test.ts +290 -0
  377. package/src/task-stale-open.ts +103 -0
  378. package/src/tasks-pagination-http.test.ts +141 -0
  379. package/src/team-rules-status-http.test.ts +90 -0
  380. package/src/team-rules-status.test.ts +59 -0
  381. package/src/team-rules-status.ts +72 -0
  382. package/src/tool-audience-http.test.ts +230 -0
  383. package/src/tool-audience.ts +120 -0
  384. package/src/tools-list-json-schema.test.ts +94 -0
  385. package/src/tools.ts +4212 -404
  386. package/src/upload-early-reject-guard.test.ts +155 -0
  387. package/src/uploads-http.test.ts +97 -15
  388. package/src/uploads.ts +103 -6
  389. package/src/user-avatar-http.test.ts +74 -0
  390. package/src/user-avatar-image.ts +160 -0
  391. package/src/user-avatar-migration.test.ts +25 -0
  392. package/src/user-avatar-upload-http.test.ts +348 -0
  393. package/src/user-inbox-by-agent-http.test.ts +161 -0
  394. package/src/user-inbox-netid-notnull.test.ts +122 -0
  395. package/src/user-inbox-read-http.test.ts +223 -0
  396. package/src/user-inbox-schema.test.ts +54 -0
  397. package/src/version-stats.test.ts +66 -0
  398. package/src/version-stats.ts +109 -0
@@ -0,0 +1,266 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-rest-columns-"));
7
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
8
+
9
+ let db: typeof import("./db.js").db;
10
+ let server: ReturnType<typeof Bun.serve>;
11
+ let base = "";
12
+ let token = "";
13
+ let networkId = "";
14
+
15
+ const INTERNAL_SENTINEL = "future_internal_only";
16
+ const sortedKeys = (value: Record<string, unknown>): string[] => Object.keys(value).sort();
17
+ const sorted = (values: readonly string[]): string[] => [...values].sort();
18
+
19
+ // Independent wire-contract golden. Do not derive these expectations from
20
+ // rest-projections.ts: doing so makes a deleted projection column disappear
21
+ // from both the response and the expected value, producing a false green.
22
+ const GOLDEN_RESPONSE_KEYS = {
23
+ networkList: [
24
+ "network_id", "network_name", "owner_id", "description", "settings",
25
+ "created_at", "updated_at", "visibility", "max_members", "member_role", "name",
26
+ ],
27
+ // 🔴 #1097:GET /api/auth/me 走的是 auth.ts 的 getUserAllNetworks(),
28
+ // 与 GET /api/networks 的 admin 分支**不是同一条查询**。
29
+ // server.ts:985 直接返回原始行,没有 :1166 那个 withNetworkNameAlias,
30
+ // 所以比 networkList 少一个 "name"。这里逐字写死,不从 rest-projections.ts 推导
31
+ // —— 理由见本文件顶部:从投影推导会让被删掉的列同时从响应和期望里消失,产生假绿。
32
+ authMeNetwork: [
33
+ "network_id", "network_name", "owner_id", "description", "settings",
34
+ "created_at", "updated_at", "visibility", "max_members", "member_role", "agent_access", "task_access",
35
+ // RFC-040(#455):不是列,是每次请求现算的「我负责的部门 + 全部下级」(department-heads.ts)。
36
+ "managed_department_ids",
37
+ ],
38
+ networkDetail: [
39
+ "network_id", "network_name", "owner_id", "description", "settings",
40
+ "created_at", "updated_at", "visibility", "max_members",
41
+ ],
42
+ statusSession: [
43
+ "resume_id", "alias", "tmux_name", "server", "ip", "hostname", "agent",
44
+ "project_dir", "version", "status", "task", "output", "progress", "score",
45
+ "cpu_load_1min", "cpu_cores", "mem_total_gb", "mem_used_gb", "mem_avail_gb",
46
+ "disk_total_gb", "disk_used_gb", "disk_avail_gb", "process_rss_bytes",
47
+ "process_rss_mb", "process_cpu_pct", "process_uptime_seconds",
48
+ "process_in_flight_count", "network_id", "registered_at", "updated_at",
49
+ "node_id", "session_id", "config_path", "channels", "last_seen_at", "model",
50
+ "external_schedules", "rules_file_capable", "skills_capable", "files_capable", "logs_capable", "runtime", "host", "process_telemetry",
51
+ // #448 — layered node health (memory-only; null when not reported or stale).
52
+ "health", "health_observed_ms_ago",
53
+ // #500 step 2 — open tasks on that node (task-queue-ahead.ts); full projection only.
54
+ "queue_depth",
55
+ ],
56
+ task: [
57
+ "task_id", "from_node_id", "from_name", "to_node_id", "to_name", "priority",
58
+ "status", "content", "result", "in_reply_to", "requires_response", "scope",
59
+ "created_at", "delivered_at", "started_at", "runtime_submitted_at", "consumed_at",
60
+ "completed_at", "expires_at", "network_id", "parent_task_id", "meta_json",
61
+ "thread_id", "turn_id", "late_replies",
62
+ ],
63
+ audit: [
64
+ "id", "user_id", "username", "action", "target_type", "target_id", "detail",
65
+ "ip", "network_id", "created_at",
66
+ ],
67
+ taskEvent: [
68
+ "id", "task_id", "from_status", "to_status", "event_type", "actor", "detail",
69
+ "created_at", "network_id",
70
+ ],
71
+ completion: [
72
+ "id", "session_name", "task", "result", "artifacts", "score",
73
+ "duration_minutes", "network_id", "completed_at",
74
+ ],
75
+ scheduledTask: [
76
+ "schedule_id", "network_id", "name", "target_node_id", "target_alias",
77
+ "task_content", "priority", "schedule_type", "timezone", "overlap_policy",
78
+ "misfire_policy", "status", "next_run_at", "last_run_at", "revision",
79
+ "created_at", "updated_at", "schedule", "watchers", "is_watcher", "can_edit", "can_manage_watchers",
80
+ ],
81
+ } as const;
82
+
83
+ async function api(path: string): Promise<any> {
84
+ const response = await fetch(`${base}${path}`, {
85
+ headers: { Authorization: `Bearer ${token}` },
86
+ });
87
+ expect(response.status).toBe(200);
88
+ return response.json();
89
+ }
90
+
91
+ // 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
92
+ // 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
93
+ // (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
94
+ // 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
95
+ beforeAll(async () => {
96
+ ({ db } = await import("./db.js"));
97
+ const { register } = await import("./auth.js");
98
+ const auth = register(`rest_shape_${Date.now()}`, "RestShape-Strong-1!", undefined, "rest-shape");
99
+ expect(auth.ok).toBe(true);
100
+ token = auth.token!;
101
+ networkId = auth.network_id!;
102
+
103
+ // Simulate future migrations. Any REST SELECT * silently broadcasts these
104
+ // columns; every endpoint below must keep them private without needing a
105
+ // code change when the table grows.
106
+ for (const table of ["networks", "sessions", "audit_log", "task_events", "tasks", "completions", "scheduled_tasks"]) {
107
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${INTERNAL_SENTINEL} TEXT`);
108
+ }
109
+
110
+ db.run(
111
+ `INSERT INTO sessions (resume_id, alias, status, agent, model, network_id, external_schedules)
112
+ VALUES ('resume-rest-shape', 'rest-shape-node', 'idle', 'agent-node:codex', 'gpt-shape', ?1, ?2)`,
113
+ [networkId, JSON.stringify({ observed_at: "2026-08-10T02:00:00.000Z", schedules: [] })],
114
+ );
115
+ db.run(
116
+ `INSERT INTO tasks (task_id, from_name, to_name, status, content, priority, network_id, parent_task_id, meta_json)
117
+ VALUES ('task-rest-shape', 'sender', 'rest-shape-node', 'delivered', 'shape', 'normal', ?1, 'parent-shape', '{"attachment":true}')`,
118
+ [networkId],
119
+ );
120
+ db.run(
121
+ `INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
122
+ VALUES ('task-rest-shape', 'created', 'delivered', 'shape-test', 'shape', ?1)`,
123
+ [networkId],
124
+ );
125
+ db.run(
126
+ `INSERT INTO completions (id, session_name, task, result, network_id)
127
+ VALUES ('completion-rest-shape', 'rest-shape-node', 'shape', 'done', ?1)`,
128
+ [networkId],
129
+ );
130
+ db.run(
131
+ `INSERT INTO audit_log (user_id, username, action, target_type, target_id, detail, ip, network_id)
132
+ VALUES ((SELECT owner_id FROM networks WHERE network_id = ?1), 'shape-user', 'shape_action', 'shape', 'shape-id', 'shape', '127.0.0.1', ?1)`,
133
+ [networkId],
134
+ );
135
+ db.run(
136
+ `INSERT INTO scheduled_tasks
137
+ (schedule_id, network_id, created_by, name, target_node_id, target_alias,
138
+ task_content, schedule_type, schedule_json, timezone, next_run_at)
139
+ VALUES ('schedule-rest-shape', ?1, 'private-user-id', 'shape schedule',
140
+ 'node-rest-shape', 'rest-shape-node', 'shape task', 'interval',
141
+ '{"type":"interval","every_seconds":3600}', 'UTC', '2099-01-01T00:00:00.000Z')`,
142
+ [networkId],
143
+ );
144
+
145
+ const mod = await import("./server.js");
146
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
147
+ base = `http://127.0.0.1:${server.port}`;
148
+ }, 30_000);
149
+
150
+ afterAll(() => {
151
+ try { server?.stop(true); } catch {}
152
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
153
+ });
154
+
155
+ describe("#311 REST response projections are stable across future ALTER TABLE", () => {
156
+ test("network list and detail preserve their existing public keys", async () => {
157
+ const list = await api("/api/networks");
158
+ const row = list.networks.find((item: any) => item.network_id === networkId);
159
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.networkList));
160
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
161
+
162
+ const detail = await api(`/api/networks/${networkId}`);
163
+ expect(sortedKeys(detail.network)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.networkDetail));
164
+ expect(detail.network[INTERNAL_SENTINEL]).toBeUndefined();
165
+ });
166
+
167
+ // 🔴 #1097:这条补的是 test647 抓到的一个**真覆盖洞**。
168
+ // tests/test647-rest-explicit-columns 的 L3b 变异把 auth.ts 的
169
+ // `SELECT ${sqlColumns(NETWORK_REST_COLUMNS, "n")}, nm.role as member_role`
170
+ // 改成 `SELECT n.*, …`,而**整套测试仍然全绿** —— 因为 getUserAllNetworks()
171
+ // 只在两处可达:server.ts:985(GET /api/auth/me) 与 server.ts:1165
172
+ // (GET /api/networks 的三元 **else** 分支),而上面那条测试打的是 /api/networks
173
+ // 且它的用户走 **if** 分支(:1156-1162 的内联查询)⇒ 两条可达路径一条都没覆盖。
174
+ test("auth/me networks come from an explicit column list, not SELECT *", async () => {
175
+ const me = await api("/api/auth/me");
176
+ const row = me.networks.find((item: any) => item.network_id === networkId);
177
+ expect(row).toBeDefined();
178
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.authMeNetwork));
179
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
180
+ });
181
+
182
+ test("full status preserves telemetry compatibility without storage drift", async () => {
183
+ const body = await api(`/api/status?network_id=${networkId}`);
184
+ const row = body.sessions.find((item: any) => item.alias === "rest-shape-node");
185
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.statusSession));
186
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
187
+ expect(row.external_schedules).toEqual({ observed_at: "2026-08-10T02:00:00.000Z", schedules: [] });
188
+ });
189
+
190
+ test("task list and task detail expose the same explicit contract", async () => {
191
+ const list = await api(`/api/tasks?network_id=${networkId}&task_id=task-rest-shape&skip_stats=1`);
192
+ expect(sortedKeys(list.tasks[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.task));
193
+ expect(list.tasks[0][INTERNAL_SENTINEL]).toBeUndefined();
194
+
195
+ const detail = await api(`/api/tasks/task-rest-shape?network_id=${networkId}`);
196
+ expect(sortedKeys(detail.task)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.task));
197
+ expect(detail.task[INTERNAL_SENTINEL]).toBeUndefined();
198
+ });
199
+
200
+ // #2884 —— 共享会话忙的失败:任务详情/列表要把「排队」与「会话等待」分开报。
201
+ // 现场那条 412 分钟的任务**不是排程任务**(scheduled_task_runs 里没有它),
202
+ // 所以投影必须落在任务读端点,不能只改排程 run。
203
+ test("#2884 busy failures expose queue vs session-wait split (non-scheduled tasks too)", async () => {
204
+ const BUSY = "[n] opencode 任务未提交:共享会话在 30 分钟 内一直处于忙碌状态,本任务没有发出";
205
+ // 时间用 JS 算再传参:`datetime('now','-N minutes')` 是 SQLite 方言,
206
+ // PG ladder 里会直接报错 (#2884)。completed_at 留空表示「现在」,由断言侧不需要它。
207
+ const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString().replace("T", " ").replace(/\..+/, "");
208
+ const nowTs = minutesAgo(0);
209
+ db.run(
210
+ `INSERT INTO tasks (task_id, from_name, to_name, status, content, priority, result,
211
+ created_at, started_at, completed_at, network_id)
212
+ VALUES ('task-busy-shape', 'sender', 'rest-shape-node', 'failed', 'busy', 'normal', ?1, ?2, ?3, ?4, ?5)`,
213
+ [BUSY, minutesAgo(412), minutesAgo(30), nowTs, networkId],
214
+ );
215
+ // 对照组:同一形状但原因不是会话忙 ⇒ 不能被加拆解
216
+ db.run(
217
+ `INSERT INTO tasks (task_id, from_name, to_name, status, content, priority, result,
218
+ created_at, started_at, completed_at, network_id)
219
+ VALUES ('task-plain-fail', 'sender', 'rest-shape-node', 'failed', 'plain', 'normal',
220
+ '执行出错: upstream refused', ?1, ?2, ?3, ?4)`,
221
+ [minutesAgo(400), minutesAgo(370), nowTs, networkId],
222
+ );
223
+
224
+ const detail = await api(`/api/tasks/task-busy-shape?network_id=${networkId}`);
225
+ expect(detail.task.status).toBe("failed");
226
+ expect(detail.task.result).toContain("共享会话");
227
+ expect(detail.task.result).toContain("排队 382 分钟");
228
+ expect(detail.task.result).toContain("会话等待 30 分钟");
229
+ expect(detail.task.result).toContain("不代表总共等了多久");
230
+ // 幂等:再读一次不重复追加
231
+ const again = await api(`/api/tasks/task-busy-shape?network_id=${networkId}`);
232
+ expect(again.task.result.match(/实测总耗时/g)?.length).toBe(1);
233
+
234
+ const plain = await api(`/api/tasks/task-plain-fail?network_id=${networkId}`);
235
+ expect(plain.task.result).not.toContain("排队");
236
+
237
+ // 列表端点走同一条投影
238
+ const list = await api(`/api/tasks?network_id=${networkId}&task_id=task-busy-shape&skip_stats=1`);
239
+ expect(list.tasks[0].result).toContain("排队 382 分钟");
240
+ // 响应键不变(不新增字段)
241
+ expect(sortedKeys(list.tasks[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.task));
242
+ });
243
+
244
+ test("audit, task-event, and completion rows are explicit", async () => {
245
+ const audit = await api("/api/audit-log?action=shape_action");
246
+ expect(sortedKeys(audit.logs[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.audit));
247
+ expect(audit.logs[0][INTERNAL_SENTINEL]).toBeUndefined();
248
+
249
+ const events = await api(`/api/task_events?network_id=${networkId}&task_id=task-rest-shape`);
250
+ expect(sortedKeys(events.events[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.taskEvent));
251
+ expect(events.events[0][INTERNAL_SENTINEL]).toBeUndefined();
252
+
253
+ const completions = await api(`/api/completions?network_id=${networkId}&since=2000-01-01T00:00:00.000Z`);
254
+ expect(sortedKeys(completions.completions[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.completion));
255
+ expect(completions.completions[0][INTERNAL_SENTINEL]).toBeUndefined();
256
+ });
257
+
258
+ test("scheduled-task decoding keeps storage-only identity and JSON private", async () => {
259
+ const body = await api(`/api/scheduled-tasks?network_id=${networkId}`);
260
+ const row = body.schedules.find((item: any) => item.schedule_id === "schedule-rest-shape");
261
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.scheduledTask));
262
+ expect(row.created_by).toBeUndefined();
263
+ expect(row.schedule_json).toBeUndefined();
264
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
265
+ });
266
+ });
@@ -0,0 +1,130 @@
1
+ // REST from_session identity binding.
2
+ //
3
+ // Run: COMMHUB_DB=/tmp/rest-identity-test.db bun test src/rest-identity.test.ts
4
+ // (COMMHUB_DB must be set explicitly — unset defaults to the production DB.)
5
+ //
6
+ // Assertion discipline: results are compared with toEqual against the whole
7
+ // object, so a widened accepted-set fails instead of silently passing.
8
+
9
+ import { describe, expect, test } from "bun:test";
10
+ import { nodeAliasForToken, resolveRestFromSession } from "./rest-identity.js";
11
+
12
+ const NTOK = "ntok_abc123";
13
+ const UTOK = "utok_abc123";
14
+
15
+ describe("REST from_session identity binding", () => {
16
+ test("node token claiming another node's alias is refused", () => {
17
+ expect(resolveRestFromSession({
18
+ token: NTOK,
19
+ tokenName: "node:通信IM牛",
20
+ requestedFrom: "通信龙",
21
+ })).toEqual({
22
+ ok: false,
23
+ error: "from_session_identity_mismatch",
24
+ message: "network token from_session does not match token-bound node alias",
25
+ tokenAlias: "通信IM牛",
26
+ requestedFromSession: "通信龙",
27
+ });
28
+ });
29
+
30
+ test("node token omitting from is bound to its own alias, not 'api'", () => {
31
+ expect(resolveRestFromSession({
32
+ token: NTOK,
33
+ tokenName: "node:通信IM牛",
34
+ requestedFrom: undefined,
35
+ })).toEqual({ ok: true, fromSession: "通信IM牛" });
36
+ });
37
+
38
+ test("node token claiming its own alias is accepted", () => {
39
+ expect(resolveRestFromSession({
40
+ token: NTOK,
41
+ tokenName: "node:通信IM牛",
42
+ requestedFrom: "通信IM牛",
43
+ })).toEqual({ ok: true, fromSession: "通信IM牛" });
44
+ });
45
+
46
+ test("whitespace padding does not defeat the comparison", () => {
47
+ expect(resolveRestFromSession({
48
+ token: NTOK,
49
+ tokenName: "node:通信IM牛",
50
+ requestedFrom: " 通信IM牛 ",
51
+ })).toEqual({ ok: true, fromSession: "通信IM牛" });
52
+ });
53
+
54
+ // The Dashboard posts as its logged-in user; this path must not change.
55
+ test("user token explicitly naming the authenticated username is accepted", () => {
56
+ expect(resolveRestFromSession({
57
+ token: UTOK,
58
+ tokenName: "dashboard",
59
+ authenticatedUsername: "admin",
60
+ requestedFrom: "admin",
61
+ })).toEqual({ ok: true, fromSession: "admin" });
62
+ });
63
+
64
+ test("user token with no from defaults to the authenticated username", () => {
65
+ expect(resolveRestFromSession({
66
+ token: UTOK,
67
+ tokenName: null,
68
+ authenticatedUsername: "admin",
69
+ requestedFrom: undefined,
70
+ })).toEqual({ ok: true, fromSession: "admin" });
71
+ });
72
+
73
+ test("legacy user auth without a username still falls back to 'api'", () => {
74
+ expect(resolveRestFromSession({
75
+ token: UTOK,
76
+ tokenName: null,
77
+ requestedFrom: undefined,
78
+ })).toEqual({ ok: true, fromSession: "api" });
79
+ });
80
+
81
+ // A non-string `from` must not be coerced into an identity.
82
+ test("non-string from is not treated as a claim", () => {
83
+ expect(resolveRestFromSession({
84
+ token: NTOK,
85
+ tokenName: "node:通信IM牛",
86
+ requestedFrom: { toString: () => "通信龙" },
87
+ })).toEqual({ ok: true, fromSession: "通信IM牛" });
88
+ });
89
+
90
+ // A network-bound token we cannot resolve to an alias must not be able to
91
+ // call itself anything. Found by independent review of this change.
92
+ describe("ntok_ with an unresolvable alias fails closed", () => {
93
+ for (const tokenName of ["node:", "node: ", "dashboard", null, undefined]) {
94
+ test(`claim is refused when tokenName is ${JSON.stringify(tokenName)}`, () => {
95
+ expect(resolveRestFromSession({
96
+ token: NTOK,
97
+ tokenName,
98
+ requestedFrom: "通信龙",
99
+ })).toEqual({
100
+ ok: false,
101
+ error: "from_session_identity_mismatch",
102
+ message: "network token has no resolvable node alias and may not claim a from_session",
103
+ tokenAlias: "",
104
+ requestedFromSession: "通信龙",
105
+ });
106
+ });
107
+ }
108
+
109
+ test("no claim at all still resolves to 'api'", () => {
110
+ expect(resolveRestFromSession({
111
+ token: NTOK,
112
+ tokenName: "node:",
113
+ requestedFrom: undefined,
114
+ })).toEqual({ ok: true, fromSession: "api" });
115
+ });
116
+ });
117
+
118
+ describe("nodeAliasForToken", () => {
119
+ test("only ntok_ + node: prefix yields an alias", () => {
120
+ expect(nodeAliasForToken(NTOK, "node:X")).toBe("X");
121
+ // A user token whose name merely looks node-shaped must not bind.
122
+ expect(nodeAliasForToken(UTOK, "node:X")).toBeNull();
123
+ // A node token whose name is not node-scoped must not bind.
124
+ expect(nodeAliasForToken(NTOK, "dashboard")).toBeNull();
125
+ expect(nodeAliasForToken(NTOK, null)).toBeNull();
126
+ // `node:` with nothing after it is not an identity.
127
+ expect(nodeAliasForToken(NTOK, "node: ")).toBeNull();
128
+ });
129
+ });
130
+ });
@@ -0,0 +1,141 @@
1
+ // REST from_session identity binding.
2
+ //
3
+ // Both transports resolve the same `api_tokens` row through resolveToken, and
4
+ // auth.ts already states the invariant:
5
+ //
6
+ // "Network-bound node tokens are an identity boundary: they must not spoof
7
+ // another node via from_session."
8
+ //
9
+ // tools.ts enforced it for MCP (defaultFrom + fromIdentityMismatchReply).
10
+ // POST /api/task did not — it took `body.from` verbatim, so any node holding
11
+ // its own ntok_ could claim another node's alias. That value is stored on the
12
+ // task row and, once sender labels reach the copresence TUIs, rendered to a
13
+ // human as an attribution.
14
+ //
15
+ // Production network tokens pass tokenId and resolve through resolveNodeCaller.
16
+ // A token whose name is not `node:` (not_a_node_token, the registration token
17
+ // before report_status) falls back to nodeAliasForToken, same as main.
18
+ // tokenId omitted keeps the name-only shape used by the unit cases below.
19
+
20
+ import { resolveNodeCaller } from "./create-node.js";
21
+
22
+ export interface RestIdentityInput {
23
+ /** Raw bearer token, only its prefix matters (`ntok_` = network-bound). */
24
+ token: string;
25
+ /** `api_tokens.name`; for node tokens it is `node:<alias>`. */
26
+ tokenName: string | null | undefined;
27
+ /** Set on the production path. Network tokens then ignore tokenName as authority. */
28
+ tokenId?: string | null;
29
+ /** Username resolved from the authenticated token. */
30
+ authenticatedUsername?: string | null;
31
+ /** Caller-supplied `body.from`. */
32
+ requestedFrom: unknown;
33
+ }
34
+
35
+ export type RestIdentityResult =
36
+ | { ok: true; fromSession: string; nodeId?: string | null }
37
+ | {
38
+ ok: false;
39
+ error: "from_session_identity_mismatch";
40
+ message: string;
41
+ tokenAlias: string;
42
+ requestedFromSession: string;
43
+ };
44
+
45
+ /** Alias a token is bound to, or null when it is not node-scoped. */
46
+ export function nodeAliasForToken(token: string, tokenName: string | null | undefined): string | null {
47
+ if (!token.startsWith("ntok_")) return null;
48
+ if (typeof tokenName !== "string" || !tokenName.startsWith("node:")) return null;
49
+ const alias = tokenName.slice("node:".length).trim();
50
+ return alias || null;
51
+ }
52
+
53
+ /** Human dispatches use the authenticated username; node credentials represent nodes. */
54
+ export function resolveUserTaskFromSession(username: string | null | undefined, requestedFrom: unknown): RestIdentityResult {
55
+ const fromSession = username?.trim() || "api";
56
+ const requested = typeof requestedFrom === "string" ? requestedFrom.trim() : "";
57
+ if (requested && requested !== fromSession) {
58
+ return {
59
+ ok: false,
60
+ error: "from_session_identity_mismatch",
61
+ message: "user token task sender must match the authenticated username",
62
+ tokenAlias: fromSession,
63
+ requestedFromSession: requested,
64
+ };
65
+ }
66
+ return { ok: true, fromSession };
67
+ }
68
+
69
+ export function resolveRestFromSession(input: RestIdentityInput): RestIdentityResult {
70
+ const requested = typeof input.requestedFrom === "string" ? input.requestedFrom.trim() : "";
71
+ let alias: string | null;
72
+ let nodeId: string | null = null;
73
+ if (input.token.startsWith("ntok_") && input.tokenId) {
74
+ const resolved = resolveNodeCaller(input.tokenId);
75
+ if (resolved.ok) {
76
+ alias = resolved.alias;
77
+ nodeId = resolved.kind === "node" ? resolved.nodeId : null;
78
+ } else if (resolved.reason === "not_a_node_token") { // board679-plain-ntok-rest
79
+ // Name is not `node:` yet. Main signs that as api, and refuses a claim.
80
+ // not_owner / bound_node_missing / ambiguous stay the hard reject.
81
+ alias = nodeAliasForToken(input.token, input.tokenName);
82
+ } else {
83
+ return {
84
+ ok: false,
85
+ error: "from_session_identity_mismatch",
86
+ message: "network token from_session does not match token-bound node alias",
87
+ tokenAlias: "",
88
+ requestedFromSession: requested,
89
+ };
90
+ }
91
+ } else {
92
+ alias = nodeAliasForToken(input.token, input.tokenName);
93
+ }
94
+
95
+ // A network-bound token whose name we cannot resolve to an alias (`node:`,
96
+ // `node: `, or a name that was never node-scoped) is the degenerate case.
97
+ // We know it IS a node credential; we just cannot tell WHICH node. Letting it
98
+ // claim anything is the worst available option, so refuse the claim outright
99
+ // rather than falling through to the unbound path.
100
+ //
101
+ // Production always writes `node:${nodeName}`, so this costs nothing real —
102
+ // but "we couldn't identify you, so you may call yourself anything" is
103
+ // exactly the fail-open shape this change exists to remove.
104
+ if (!alias && input.token.startsWith("ntok_")) {
105
+ if (requested) {
106
+ return {
107
+ ok: false,
108
+ error: "from_session_identity_mismatch",
109
+ message: "network token has no resolvable node alias and may not claim a from_session",
110
+ tokenAlias: "",
111
+ requestedFromSession: requested,
112
+ };
113
+ }
114
+ return { ok: true, fromSession: "api" };
115
+ }
116
+
117
+ // Authenticated human callers are always represented by their username.
118
+ // Keep the unscoped development / legacy transport path separate.
119
+ if (!alias) {
120
+ const authenticatedUsername = typeof input.authenticatedUsername === "string"
121
+ ? input.authenticatedUsername.trim()
122
+ : "";
123
+ if (authenticatedUsername) return resolveUserTaskFromSession(authenticatedUsername, input.requestedFrom);
124
+ return { ok: true, fromSession: requested || "api" };
125
+ }
126
+
127
+ // Node token claiming somebody else — refuse rather than silently rewrite,
128
+ // so a misconfigured caller is visible instead of quietly relabelled.
129
+ if (requested && requested !== alias) {
130
+ return {
131
+ ok: false,
132
+ error: "from_session_identity_mismatch",
133
+ message: "network token from_session does not match token-bound node alias",
134
+ tokenAlias: alias,
135
+ requestedFromSession: requested,
136
+ };
137
+ }
138
+
139
+ // Node token, no claim or a matching one: bind to the token's own alias.
140
+ return { ok: true, fromSession: alias, ...(input.tokenId ? { nodeId } : {}) };
141
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Stable REST row projections.
3
+ *
4
+ * These lists deliberately mirror the fields already exposed by the public
5
+ * endpoints before #311. Keeping them in one place makes the wire contract
6
+ * independent from future ALTER TABLE migrations: adding a storage-only
7
+ * column must never silently add a REST response key.
8
+ */
9
+ export const NETWORK_REST_COLUMNS = [
10
+ "network_id", "network_name", "owner_id", "description", "settings",
11
+ "created_at", "updated_at", "visibility", "max_members",
12
+ ] as const;
13
+
14
+ export const SESSION_REST_COLUMNS = [
15
+ "resume_id", "alias", "tmux_name", "server", "ip", "hostname", "agent",
16
+ "project_dir", "version", "status", "task", "output", "progress", "score",
17
+ "cpu_load_1min", "cpu_cores", "mem_total_gb", "mem_used_gb", "mem_avail_gb",
18
+ "disk_total_gb", "disk_used_gb", "disk_avail_gb", "process_rss_bytes",
19
+ "process_rss_mb", "process_cpu_pct", "process_uptime_seconds",
20
+ "process_in_flight_count", "network_id", "registered_at", "updated_at",
21
+ "node_id", "session_id", "config_path", "channels", "last_seen_at", "model",
22
+ "external_schedules", "rules_file_capable", "skills_capable", "files_capable",
23
+ "logs_capable",
24
+ // #2211 — the node's last team-rules outcome (see team-rules-status.ts).
25
+ "team_rules_revision", "team_rules_status", "team_rules_at", "team_rules_reason",
26
+ ] as const;
27
+
28
+ export const AUDIT_LOG_REST_COLUMNS = [
29
+ "id", "user_id", "username", "action", "target_type", "target_id", "detail",
30
+ "ip", "network_id", "created_at",
31
+ ] as const;
32
+
33
+ export const TASK_EVENT_REST_COLUMNS = [
34
+ "id", "task_id", "from_status", "to_status", "event_type", "actor", "detail",
35
+ "created_at", "network_id",
36
+ ] as const;
37
+
38
+ export const TASK_REST_COLUMNS = [
39
+ "task_id", "from_node_id", "from_name", "to_node_id", "to_name", "priority",
40
+ "status", "content", "result", "in_reply_to", "requires_response", "scope",
41
+ "created_at", "delivered_at", "started_at", "runtime_submitted_at", "consumed_at", "completed_at", "expires_at",
42
+ "network_id", "parent_task_id", "meta_json", "thread_id", "turn_id",
43
+ ] as const;
44
+
45
+ export const COMPLETION_REST_COLUMNS = [
46
+ "id", "session_name", "task", "result", "artifacts", "score",
47
+ "duration_minutes", "network_id", "completed_at",
48
+ ] as const;
49
+
50
+ // Storage projection for scheduled-task rows. `created_by` and
51
+ // `schedule_json` are intentionally selected for server-side auth/decoding,
52
+ // then removed by decodeRow before the REST response is serialized.
53
+ export const SCHEDULED_TASK_STORAGE_COLUMNS = [
54
+ "schedule_id", "network_id", "created_by", "created_by_node_id", "name", "target_node_id",
55
+ "target_alias", "task_content", "priority", "schedule_type", "schedule_json",
56
+ "timezone", "overlap_policy", "misfire_policy", "status", "next_run_at",
57
+ "last_run_at", "revision", "created_at", "updated_at",
58
+ "no_change_backoff", "backoff_streak", "backoff_effective_seconds", "backoff_last_run_id",
59
+ "requirement_wake_json", "requirement_wake_cursor", "requirement_wake_last_event_id",
60
+ ] as const;
61
+
62
+ export function sqlColumns(columns: readonly string[], qualifier?: string): string {
63
+ return columns.map((column) => qualifier ? `${qualifier}.${column}` : column).join(", ");
64
+ }
65
+
66
+ export const NETWORK_REST_SELECT = sqlColumns(NETWORK_REST_COLUMNS);
67
+ export const SESSION_REST_SELECT = sqlColumns(SESSION_REST_COLUMNS);
68
+ export const AUDIT_LOG_REST_SELECT = sqlColumns(AUDIT_LOG_REST_COLUMNS);
69
+ export const TASK_EVENT_REST_SELECT = sqlColumns(TASK_EVENT_REST_COLUMNS);
70
+ export const TASK_REST_SELECT = sqlColumns(TASK_REST_COLUMNS);
71
+ export const COMPLETION_REST_SELECT = sqlColumns(COMPLETION_REST_COLUMNS);
72
+ export const SCHEDULED_TASK_STORAGE_SELECT = sqlColumns(SCHEDULED_TASK_STORAGE_COLUMNS);