@myrialabs/clopen 0.4.47 → 0.4.49

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 (390) hide show
  1. package/README.md +11 -11
  2. package/backend/artifacts/project/sources.ts +1 -1
  3. package/backend/auth/auth-service.ts +52 -358
  4. package/backend/auth/onboarding.test.ts +2 -3
  5. package/backend/auth/permissions.test.ts +10 -20
  6. package/backend/auth/permissions.ts +4 -290
  7. package/backend/auth/rate-limiter.test.ts +8 -9
  8. package/backend/auth/rate-limiter.ts +0 -2
  9. package/backend/auth/tokens.ts +1 -8
  10. package/backend/bootstrap.ts +7 -0
  11. package/backend/chat/attachments.test.ts +88 -0
  12. package/backend/chat/attachments.ts +159 -0
  13. package/backend/chat/engine-handoff.test.ts +0 -2
  14. package/backend/chat/message-pages.test.ts +163 -0
  15. package/backend/chat/message-pages.ts +233 -0
  16. package/backend/chat/stream-manager.ts +91 -67
  17. package/backend/chat/turn-answer.test.ts +64 -0
  18. package/backend/chat/turn-answer.ts +125 -0
  19. package/backend/chat-apps/awaiting.test.ts +39 -0
  20. package/backend/chat-apps/awaiting.ts +49 -0
  21. package/backend/chat-apps/conversation.ts +746 -0
  22. package/backend/chat-apps/inbound.ts +324 -0
  23. package/backend/chat-apps/index.ts +309 -0
  24. package/backend/chat-apps/link-events.ts +20 -0
  25. package/backend/chat-apps/media.test.ts +62 -0
  26. package/backend/chat-apps/media.ts +208 -0
  27. package/backend/chat-apps/messages.test.ts +229 -0
  28. package/backend/chat-apps/messages.ts +365 -0
  29. package/backend/chat-apps/outbound.ts +243 -0
  30. package/backend/chat-apps/pairing.test.ts +45 -0
  31. package/backend/chat-apps/pairing.ts +74 -0
  32. package/backend/chat-apps/platforms/index.ts +20 -0
  33. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  34. package/backend/chat-apps/platforms/telegram.ts +191 -0
  35. package/backend/chat-apps/platforms/types.ts +114 -0
  36. package/backend/chat-apps/questions.ts +133 -0
  37. package/backend/chat-apps/runtime.ts +572 -0
  38. package/backend/chat-apps/storage.test.ts +201 -0
  39. package/backend/chat-apps/turns.test.ts +45 -0
  40. package/backend/chat-apps/turns.ts +208 -0
  41. package/backend/containers/pty.ts +3 -11
  42. package/backend/control/actions/accounts.ts +89 -0
  43. package/backend/control/actions/files.ts +116 -0
  44. package/backend/control/actions/models.ts +188 -0
  45. package/backend/control/actions/projects.ts +272 -0
  46. package/backend/control/actions/sessions.ts +280 -0
  47. package/backend/control/actions/skills.ts +111 -0
  48. package/backend/control/control.test.ts +169 -0
  49. package/backend/control/define.ts +20 -0
  50. package/backend/control/folders.test.ts +67 -0
  51. package/backend/control/index.ts +213 -0
  52. package/backend/control/invoke.ts +44 -0
  53. package/backend/control/links.ts +35 -0
  54. package/backend/control/paging.ts +26 -0
  55. package/backend/control/types.ts +117 -0
  56. package/backend/control/workspace.ts +127 -0
  57. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  58. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  59. package/backend/database/migrations/086_single_owner.ts +418 -0
  60. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  61. package/backend/database/migrations/index.ts +28 -0
  62. package/backend/database/queries/auth-queries.ts +7 -85
  63. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  64. package/backend/database/queries/channel-queries.ts +270 -0
  65. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  66. package/backend/database/queries/file-share-queries.ts +5 -23
  67. package/backend/database/queries/git-identity-queries.ts +31 -42
  68. package/backend/database/queries/graph-queries.ts +1 -1
  69. package/backend/database/queries/index.ts +15 -1
  70. package/backend/database/queries/message-queries.test.ts +146 -0
  71. package/backend/database/queries/message-queries.ts +42 -1
  72. package/backend/database/queries/permission-set-queries.ts +1 -1
  73. package/backend/database/queries/profile-queries.ts +1 -1
  74. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  75. package/backend/database/queries/project-queries.ts +50 -63
  76. package/backend/database/queries/session-queries.ts +28 -56
  77. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  78. package/backend/db-client/env/diff.ts +9 -33
  79. package/backend/db-client/env/env.test.ts +8 -8
  80. package/backend/db-client/env/service.ts +1 -1
  81. package/backend/db-client/integrations/projector.ts +0 -5
  82. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  83. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  84. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  85. package/backend/engine/adapters/cline/stream.ts +11 -15
  86. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  87. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  88. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  89. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  90. package/backend/engine/adapters/opencode/stream.ts +11 -0
  91. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  92. package/backend/engine/adapters/parent-scope.ts +44 -0
  93. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  94. package/backend/engine/adapters/pi/stream.ts +4 -5
  95. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  96. package/backend/engine/bootstrap-default-engine.ts +2 -2
  97. package/backend/engine/docs/adapter-contract.md +8 -1
  98. package/backend/engine/install-runner.ts +8 -17
  99. package/backend/files/file-shares.ts +20 -44
  100. package/backend/files/file-size-limit.ts +3 -3
  101. package/backend/files/file-watcher.ts +19 -0
  102. package/backend/files/image-processing.ts +1 -1
  103. package/backend/files/os-clipboard.ts +2 -2
  104. package/backend/git/contributors.test.ts +35 -0
  105. package/backend/git/contributors.ts +46 -0
  106. package/backend/git/git-executor.ts +25 -5
  107. package/backend/git/git-service.ts +420 -19
  108. package/backend/git/identity/credential-helper.test.ts +2 -7
  109. package/backend/git/identity/import-local.test.ts +11 -16
  110. package/backend/git/identity/import-local.ts +12 -12
  111. package/backend/git/identity/index.ts +10 -24
  112. package/backend/git/identity/resolve.ts +13 -14
  113. package/backend/git/identity/scope-config.ts +33 -28
  114. package/backend/git/identity/service.ts +44 -47
  115. package/backend/git/op-lock.test.ts +111 -0
  116. package/backend/git/op-lock.ts +180 -0
  117. package/backend/git/remote-sync.test.ts +249 -0
  118. package/backend/host/metrics.ts +1 -1
  119. package/backend/http/bearer-auth.ts +1 -2
  120. package/backend/http/files-download.test.ts +8 -9
  121. package/backend/http/files-download.ts +2 -2
  122. package/backend/http/files-shared.test.ts +62 -89
  123. package/backend/http/files-shared.ts +2 -2
  124. package/backend/http/files-upload.test.ts +3 -7
  125. package/backend/http/files-upload.ts +3 -3
  126. package/backend/http/notes-images.test.ts +15 -38
  127. package/backend/http/notes-images.ts +6 -8
  128. package/backend/http/ssh-sftp.ts +5 -10
  129. package/backend/http/static-assets.test.ts +78 -0
  130. package/backend/http/static-assets.ts +104 -0
  131. package/backend/index.ts +32 -16
  132. package/backend/integrations/accounts.ts +61 -3
  133. package/backend/integrations/index.ts +2 -2
  134. package/backend/integrations/registry/define.ts +15 -0
  135. package/backend/integrations/registry/index.ts +2 -0
  136. package/backend/integrations/registry/providers/telegram.ts +54 -0
  137. package/backend/integrations/registry/types.ts +21 -1
  138. package/backend/integrations/webhooks/gateway.ts +7 -6
  139. package/backend/integrations/webhooks/verify.test.ts +30 -0
  140. package/backend/integrations/webhooks/verify.ts +4 -0
  141. package/backend/mcp/external/project.ts +1 -1
  142. package/backend/mcp/internal/remote-server.test.ts +1 -3
  143. package/backend/mcp/internal/remote-server.ts +4 -4
  144. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  145. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  146. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  147. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  148. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  149. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  150. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  151. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  152. package/backend/memory/redact.ts +1 -1
  153. package/backend/notes/access.test.ts +28 -29
  154. package/backend/notes/access.ts +6 -11
  155. package/backend/permissions/service.ts +1 -1
  156. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  157. package/backend/preview/browser/browser-clipboard.ts +67 -0
  158. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  159. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  160. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  161. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  162. package/backend/preview/browser/browser-pool.ts +67 -6
  163. package/backend/preview/browser/browser-preview-service.ts +383 -29
  164. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  165. package/backend/preview/browser/browser-video-capture.ts +92 -5
  166. package/backend/preview/browser/element-locator.ts +190 -17
  167. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  168. package/backend/preview/browser/keyboard-chords.ts +132 -0
  169. package/backend/preview/browser/paste.ts +81 -0
  170. package/backend/preview/browser/process-usage.ts +142 -0
  171. package/backend/preview/browser/profile-lock.ts +209 -0
  172. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  173. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  174. package/backend/preview/browser/types.ts +40 -2
  175. package/backend/preview/browser/viewport.test.ts +45 -0
  176. package/backend/preview/browser/viewport.ts +96 -0
  177. package/backend/profiles/service.ts +2 -2
  178. package/backend/project/status-manager.ts +43 -172
  179. package/backend/projects/home.ts +61 -0
  180. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  181. package/backend/projects/project-cleanup.ts +0 -8
  182. package/backend/skills/service.ts +2 -3
  183. package/backend/snapshot/blob-store.ts +9 -1
  184. package/backend/snapshot/helpers.ts +3 -11
  185. package/backend/snapshot/line-stats.test.ts +80 -0
  186. package/backend/snapshot/line-stats.ts +64 -0
  187. package/backend/snapshot/restore.ts +252 -0
  188. package/backend/snapshot/snapshot-service.ts +14 -27
  189. package/backend/snapshot/turn-changes.test.ts +10 -5
  190. package/backend/snapshot/turn-changes.ts +78 -40
  191. package/backend/ssh/ptykit.ts +1 -2
  192. package/backend/terminal/ptykit.ts +10 -8
  193. package/backend/tunnel/public-origin.ts +31 -20
  194. package/backend/utils/user-helpers.ts +0 -55
  195. package/backend/utils/ws-wire.test.ts +87 -0
  196. package/backend/utils/ws-wire.ts +189 -0
  197. package/backend/utils/ws.ts +101 -192
  198. package/backend/worktrees/branching/engine.ts +3 -16
  199. package/backend/worktrees/branching/index.ts +1 -1
  200. package/backend/worktrees/branching/projector.ts +1 -1
  201. package/backend/worktrees/branching/service.ts +13 -25
  202. package/backend/ws/access.ts +12 -21
  203. package/backend/ws/artifacts/generate.ts +2 -2
  204. package/backend/ws/auth/device.ts +16 -71
  205. package/backend/ws/auth/index.ts +4 -22
  206. package/backend/ws/auth/login.test.ts +14 -60
  207. package/backend/ws/auth/login.ts +24 -124
  208. package/backend/ws/auth/status.ts +0 -1
  209. package/backend/ws/chat/composer.ts +118 -118
  210. package/backend/ws/chat/stream.ts +105 -57
  211. package/backend/ws/chat-apps/index.ts +117 -0
  212. package/backend/ws/containers/actions.ts +11 -25
  213. package/backend/ws/containers/index.ts +3 -4
  214. package/backend/ws/containers/list.ts +10 -36
  215. package/backend/ws/containers/logs.ts +2 -2
  216. package/backend/ws/containers/tunnel.ts +1 -2
  217. package/backend/ws/db-client/access.ts +2 -16
  218. package/backend/ws/db-client/accounts.ts +5 -15
  219. package/backend/ws/db-client/connections.ts +17 -25
  220. package/backend/ws/db-client/context.ts +1 -1
  221. package/backend/ws/db-client/env.ts +7 -10
  222. package/backend/ws/db-client/index.ts +2 -2
  223. package/backend/ws/db-client/io.ts +5 -5
  224. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  225. package/backend/ws/db-client/query.ts +18 -17
  226. package/backend/ws/db-client/schema.ts +13 -13
  227. package/backend/ws/db-client/structure.ts +35 -35
  228. package/backend/ws/db-client/supabase.ts +4 -21
  229. package/backend/ws/deployments/context.ts +1 -1
  230. package/backend/ws/deployments/crud.ts +0 -5
  231. package/backend/ws/engine/access.ts +7 -20
  232. package/backend/ws/engine/claude/accounts.ts +4 -4
  233. package/backend/ws/engine/cline/accounts.ts +5 -5
  234. package/backend/ws/engine/codex/accounts.ts +3 -3
  235. package/backend/ws/engine/pi/accounts.ts +5 -5
  236. package/backend/ws/files/clipboard.ts +8 -27
  237. package/backend/ws/files/image-edit.ts +6 -6
  238. package/backend/ws/files/index.ts +1 -1
  239. package/backend/ws/files/path-access.test.ts +32 -131
  240. package/backend/ws/files/path-access.ts +8 -87
  241. package/backend/ws/files/read.ts +45 -19
  242. package/backend/ws/files/reveal.ts +3 -3
  243. package/backend/ws/files/search.ts +7 -7
  244. package/backend/ws/files/share.ts +9 -13
  245. package/backend/ws/files/state.ts +9 -12
  246. package/backend/ws/files/watch.ts +3 -3
  247. package/backend/ws/files/write.ts +30 -31
  248. package/backend/ws/git/branch.ts +80 -59
  249. package/backend/ws/git/commit.ts +63 -44
  250. package/backend/ws/git/conflict.ts +16 -18
  251. package/backend/ws/git/identity-context.ts +8 -17
  252. package/backend/ws/git/identity.ts +17 -27
  253. package/backend/ws/git/index.ts +3 -1
  254. package/backend/ws/git/log.ts +52 -0
  255. package/backend/ws/git/op-state.ts +139 -0
  256. package/backend/ws/git/remote.ts +241 -141
  257. package/backend/ws/git/repo-context.ts +67 -0
  258. package/backend/ws/git/staging.ts +18 -28
  259. package/backend/ws/git/status.ts +5 -2
  260. package/backend/ws/index.ts +5 -1
  261. package/backend/ws/instructions/crud.ts +1 -1
  262. package/backend/ws/integrations/crud.ts +1 -3
  263. package/backend/ws/mcp/crud.ts +3 -5
  264. package/backend/ws/mcp/tools.ts +1 -1
  265. package/backend/ws/memory/crud.ts +14 -46
  266. package/backend/ws/memory/index.ts +2 -2
  267. package/backend/ws/messages/crud.ts +78 -8
  268. package/backend/ws/notes/index.ts +33 -39
  269. package/backend/ws/permissions/crud.ts +3 -4
  270. package/backend/ws/ports/index.ts +1 -2
  271. package/backend/ws/ports/kill.ts +5 -10
  272. package/backend/ws/ports/list.ts +4 -10
  273. package/backend/ws/preview/access.ts +1 -1
  274. package/backend/ws/preview/browser/interact.ts +52 -79
  275. package/backend/ws/preview/browser/native-ui.ts +24 -0
  276. package/backend/ws/preview/browser/stats.ts +98 -1
  277. package/backend/ws/preview/browser/tab-info.ts +15 -0
  278. package/backend/ws/preview/browser/tab.ts +19 -4
  279. package/backend/ws/preview/index.ts +29 -0
  280. package/backend/ws/preview/watchers.ts +84 -0
  281. package/backend/ws/profiles/crud.ts +6 -8
  282. package/backend/ws/project-artifacts/index.ts +30 -31
  283. package/backend/ws/projects/crud.ts +33 -35
  284. package/backend/ws/projects/index.ts +3 -8
  285. package/backend/ws/projects/info.ts +3 -3
  286. package/backend/ws/projects/overview.ts +19 -30
  287. package/backend/ws/projects/status.ts +17 -57
  288. package/backend/ws/sessions/crud.ts +42 -57
  289. package/backend/ws/sessions/index.ts +1 -1
  290. package/backend/ws/settings/crud.ts +1 -1
  291. package/backend/ws/skills/crud.ts +3 -4
  292. package/backend/ws/skills/index.ts +1 -1
  293. package/backend/ws/snapshot/changes.ts +12 -13
  294. package/backend/ws/snapshot/restore.ts +11 -295
  295. package/backend/ws/snapshot/timeline.ts +2 -4
  296. package/backend/ws/ssh/access.ts +6 -21
  297. package/backend/ws/ssh/connections.ts +21 -31
  298. package/backend/ws/ssh/forwards.ts +12 -12
  299. package/backend/ws/ssh/sftp.ts +34 -34
  300. package/backend/ws/ssh/tunnel.ts +1 -2
  301. package/backend/ws/stack/install.ts +7 -17
  302. package/backend/ws/subagents/crud.ts +1 -1
  303. package/backend/ws/terminal/tunnel.ts +2 -2
  304. package/backend/ws/tunnel/share.ts +0 -2
  305. package/backend/ws/user/crud.ts +1 -59
  306. package/backend/ws/user/index.ts +1 -1
  307. package/backend/ws/work/context.ts +1 -1
  308. package/backend/ws/work/crud.ts +0 -5
  309. package/backend/ws/workspace/state.ts +10 -13
  310. package/backend/ws/worktrees/branching.ts +7 -36
  311. package/backend/ws/worktrees/crud.ts +2 -2
  312. package/bin/clopen.ts +46 -41
  313. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  314. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  315. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  316. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  317. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  318. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  319. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  320. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  321. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  322. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  323. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  324. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  325. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  326. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  327. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  328. package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
  329. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  330. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  331. package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
  332. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  333. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  334. package/dist/assets/main-D2_TmcwQ.js +1240 -0
  335. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  336. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  337. package/dist/assets/main-Yucigcmf.css +1 -0
  338. package/dist/assets/main-Yucigcmf.css.br +0 -0
  339. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  340. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  341. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  342. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  343. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  344. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  345. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  346. package/dist/fonts/dm-sans.css.br +0 -0
  347. package/dist/fonts/dm-sans.css.gz +0 -0
  348. package/dist/index.html +2 -2
  349. package/dist/index.html.br +0 -0
  350. package/dist/index.html.gz +0 -0
  351. package/dist/sw.js.br +0 -0
  352. package/dist/sw.js.gz +0 -0
  353. package/package.json +3 -3
  354. package/shared/constants/attachments.ts +14 -0
  355. package/shared/constants/engine-tools.ts +1 -1
  356. package/shared/constants/preview.test.ts +259 -0
  357. package/shared/constants/preview.ts +1018 -57
  358. package/shared/constants/tool-icons.ts +5 -0
  359. package/shared/types/containers/container.ts +1 -1
  360. package/shared/types/database/schema.ts +9 -6
  361. package/shared/types/git-identity.ts +1 -1
  362. package/shared/types/git.ts +116 -0
  363. package/shared/types/integrations.ts +7 -0
  364. package/shared/types/stores/settings.ts +1 -1
  365. package/shared/types/unified/index.ts +1 -1
  366. package/shared/types/unified/message.ts +0 -7
  367. package/shared/types/unified/stream.ts +13 -5
  368. package/shared/types/unified/tool.ts +15 -1
  369. package/shared/utils/ask-user-question.test.ts +319 -0
  370. package/shared/utils/ask-user-question.ts +154 -0
  371. package/shared/utils/diff-calculator.test.ts +178 -41
  372. package/shared/utils/diff-calculator.ts +383 -100
  373. package/shared/utils/home-project.ts +25 -0
  374. package/shared/utils/logger.ts +2 -0
  375. package/shared/utils/process-supervisor.test.ts +172 -0
  376. package/shared/utils/process-supervisor.ts +251 -0
  377. package/shared/utils/ws-chunk.test.ts +33 -0
  378. package/shared/utils/ws-chunk.ts +73 -0
  379. package/shared/utils/ws-client-chunks.test.ts +45 -0
  380. package/shared/utils/ws-client.ts +43 -0
  381. package/shared/utils/ws-server.ts +49 -21
  382. package/backend/auth/session-invalidation.test.ts +0 -112
  383. package/backend/auth/session-invalidation.ts +0 -77
  384. package/backend/project/status-manager.test.ts +0 -32
  385. package/backend/ws/auth/invites.ts +0 -94
  386. package/backend/ws/auth/users.ts +0 -112
  387. package/backend/ws/projects/presence.ts +0 -46
  388. package/backend/ws/stack/access.ts +0 -31
  389. package/dist/assets/main-BiDNMWb3.css +0 -1
  390. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -14,6 +14,7 @@ import type { Elysia } from 'elysia';
14
14
  import { t, type TSchema, type Static } from 'elysia';
15
15
  import { Value } from '@sinclair/typebox/value';
16
16
  import { debug } from './logger';
17
+ import { sendBinary, sendReply, sendText } from '$backend/utils/ws-wire';
17
18
 
18
19
  // ============================================================================
19
20
  // Singleton Encoders (Performance Optimization)
@@ -321,18 +322,14 @@ export class WSRouter<
321
322
  const { ws: wsServer } = await import('$backend/utils/ws');
322
323
  const { projectQueries } = await import('$backend/database/queries');
323
324
 
324
- // userId is set exclusively by auth handlers (auth:login, auth:setup, auth:accept-invite)
325
+ // userId is set exclusively by auth handlers (auth:login, auth:setup, auth:claim-device-code)
325
326
  // ws:set-context only handles projectId
326
327
  if (data.projectId !== undefined) {
327
328
  if (data.projectId !== null) {
328
- const state = wsServer.getConnectionState(conn);
329
- const userId = state?.userId;
330
- if (!userId) {
329
+ if (!wsServer.getConnectionState(conn)?.userId) {
331
330
  throw new Error('Authentication required');
332
331
  }
333
-
334
- const hasProjectAccess = projectQueries.userHasProject(userId, data.projectId);
335
- if (!hasProjectAccess) {
332
+ if (!projectQueries.isListed(data.projectId)) {
336
333
  throw new Error('Project not found');
337
334
  }
338
335
  }
@@ -514,6 +511,35 @@ export class WSRouter<
514
511
  return this as any;
515
512
  }
516
513
 
514
+ /**
515
+ * Run a route in-process for a connection, through the same auth gate and
516
+ * request validation as a message from a browser — and return what the
517
+ * handler returned instead of sending it. The rate limiter is skipped: an
518
+ * in-process caller is not a flood, and it pays its own limits upstream.
519
+ *
520
+ * This is what lets the control catalog (`backend/control/`) drive
521
+ * everything the web UI can, with the web UI's own permission rules,
522
+ * without a second implementation of any of it.
523
+ */
524
+ async invoke(conn: WSConnection, action: string, data: unknown = {}): Promise<unknown> {
525
+ if (this.authMiddleware) {
526
+ const auth = await this.authMiddleware(conn, action);
527
+ if (!auth.allowed) throw new Error(auth.error || 'Access denied');
528
+ }
529
+ const httpRoute = this.httpRoutes.get(action);
530
+ const route = httpRoute ?? this.routes.get(action);
531
+ if (!route || action === 'ws:set-context') throw new Error(`Unknown action: ${action}`);
532
+ let validated: unknown = {};
533
+ if (route.dataSchema) {
534
+ try {
535
+ validated = Value.Decode(route.dataSchema, data ?? {});
536
+ } catch (err) {
537
+ throw new Error(`Request validation failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
538
+ }
539
+ }
540
+ return route.handler({ conn, data: validated } as any);
541
+ }
542
+
517
543
  /**
518
544
  * Handle HTTP-like request-response message
519
545
  * @internal
@@ -581,13 +607,13 @@ export class WSRouter<
581
607
  if (isBinaryAction(responseAction, validatedResponse)) {
582
608
  // For binary responses, wrap in success envelope with requestId
583
609
  const wrappedResponse = { success: true, data: validatedResponse, requestId };
584
- const binaryMessage = encodeBinaryMessage(responseAction, wrappedResponse);
585
- conn.send(Buffer.from(binaryMessage));
610
+ sendBinary(conn, responseAction, encodeBinaryMessage(responseAction, wrappedResponse));
586
611
  debug.log('websocket', 'HTTP success (binary):', action);
587
612
  } else {
588
- // For JSON responses, wrap in success envelope with requestId
613
+ // For JSON responses, wrap in success envelope with requestId. Large
614
+ // replies leave in chunks (see sendReply).
589
615
  const wrappedResponse = { success: true, data: validatedResponse, requestId };
590
- conn.send(JSON.stringify({ action: responseAction, payload: wrappedResponse }));
616
+ await sendReply(conn, responseAction, requestId, JSON.stringify({ action: responseAction, payload: wrappedResponse }));
591
617
  debug.log('websocket', 'HTTP success (JSON):', action);
592
618
  }
593
619
  } catch (err) {
@@ -595,7 +621,11 @@ export class WSRouter<
595
621
  const errorMessage = err instanceof Error ? err.message : String(err);
596
622
 
597
623
  const errorResponse = { success: false, error: errorMessage, requestId };
598
- conn.send(JSON.stringify({ action: responseAction, payload: errorResponse }));
624
+ try {
625
+ sendText(conn, responseAction, JSON.stringify({ action: responseAction, payload: errorResponse }));
626
+ } catch {
627
+ // Connection may be closed
628
+ }
599
629
  debug.error('websocket', `HTTP error [${action}]:`, errorMessage);
600
630
  }
601
631
  }
@@ -643,12 +673,12 @@ export class WSRouter<
643
673
  // so ws.http() on the client receives it instead of timing out
644
674
  if (this.httpRoutes.has(action)) {
645
675
  const requestId = payload?.requestId;
646
- conn.send(JSON.stringify({
676
+ sendText(conn, `${action}:response`, JSON.stringify({
647
677
  action: `${action}:response`,
648
678
  payload: { success: false, error: authResult.error, requestId }
649
679
  }));
650
680
  } else {
651
- conn.send(JSON.stringify({
681
+ sendText(conn, 'auth:error', JSON.stringify({
652
682
  action: 'auth:error',
653
683
  payload: { error: authResult.error, blockedAction: action }
654
684
  }));
@@ -684,7 +714,7 @@ export class WSRouter<
684
714
  // have no requestId and still just drop.
685
715
  if (isRequest) {
686
716
  try {
687
- conn.send(JSON.stringify({
717
+ sendText(conn, `${action}:response`, JSON.stringify({
688
718
  action: `${action}:response`,
689
719
  payload: {
690
720
  success: false,
@@ -734,13 +764,11 @@ export class WSRouter<
734
764
  */
735
765
  asPlugin(path: string = '/ws') {
736
766
  return (app: Elysia) => {
767
+ // Socket limits (payload size, idle timeout, compression) are NOT set
768
+ // here: Elysia ignores them on a `.ws()` route and only passes the
769
+ // app-level `websocket` config to Bun.serve — see WS_SERVER_OPTIONS
770
+ // in backend/utils/ws-wire.ts.
737
771
  return app.ws(path, {
738
- // Allow large binary frames (file uploads, zip extracts).
739
- // Bun/uWS default is 16MB which trips EPIPE on the dev proxy
740
- // long before the configurable per-file limit kicks in.
741
- maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
742
- // Disable inactivity disconnects during long binary transfers.
743
- idleTimeout: 960, // seconds (max allowed by uWS)
744
772
  message: (conn, message) => {
745
773
  this.handleMessage(conn, message);
746
774
  },
@@ -1,112 +0,0 @@
1
- import { describe, expect, test, mock, beforeEach } from 'bun:test';
2
- import { invalidateUserSessions, getActiveSessionCountForUser } from './session-invalidation';
3
-
4
- const mockGetConnectionsForUser = mock(() => [] as any[]);
5
- const mockClearAuthForConnections = mock(() => 0);
6
- const mockGetProjectChatSessions = mock(() => new Map());
7
- const mockEmitUser = mock(() => {});
8
-
9
- const mockKillSession = mock(() => {});
10
- const mockList = mock((_namespace: string) => [] as Array<{ sessionId: string }>);
11
-
12
- mock.module('$backend/utils/ws', () => ({
13
- ws: {
14
- getConnectionsForUser: mockGetConnectionsForUser,
15
- clearAuthForConnections: mockClearAuthForConnections,
16
- getProjectChatSessions: mockGetProjectChatSessions,
17
- emit: {
18
- user: mockEmitUser
19
- }
20
- }
21
- }));
22
-
23
- mock.module('$backend/terminal/ptykit', () => ({
24
- ptyKitManager: {
25
- list: mockList,
26
- killSession: mockKillSession
27
- }
28
- }));
29
-
30
- describe('invalidateUserSessions', () => {
31
- beforeEach(() => {
32
- mockGetConnectionsForUser.mockClear();
33
- mockClearAuthForConnections.mockClear();
34
- mockGetProjectChatSessions.mockClear();
35
- mockEmitUser.mockClear();
36
- mockKillSession.mockClear();
37
- mockList.mockClear();
38
- });
39
-
40
- test('clears auth on all connections for a user', () => {
41
- mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2', 'conn3']);
42
- mockClearAuthForConnections.mockReturnValue(3);
43
-
44
- const cleared = invalidateUserSessions('user-123');
45
-
46
- expect(cleared).toBe(3);
47
- expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-123');
48
- expect(mockClearAuthForConnections).toHaveBeenCalledWith(['conn1', 'conn2', 'conn3']);
49
- expect(mockEmitUser).toHaveBeenCalledWith('user-123', 'auth:force-logout-user', { reason: 'Project access revoked' });
50
- });
51
-
52
- test('returns 0 when user has no active connections', () => {
53
- mockGetConnectionsForUser.mockReturnValue([]);
54
- mockClearAuthForConnections.mockReturnValue(0);
55
-
56
- const cleared = invalidateUserSessions('user-456');
57
-
58
- expect(cleared).toBe(0);
59
- });
60
-
61
- test('kills all PTY sessions in the project namespace on access revocation', () => {
62
- mockGetConnectionsForUser.mockReturnValue(['conn1']);
63
- mockClearAuthForConnections.mockReturnValue(1);
64
- // PtyKit lists sessions by namespace (= projectId); collaborative terminals
65
- // are project-scoped, so all of proj-1's sessions are torn down.
66
- mockList.mockReturnValue([
67
- { sessionId: 'session-a' },
68
- { sessionId: 'session-b' }
69
- ]);
70
-
71
- invalidateUserSessions('bob', 'proj-1');
72
-
73
- expect(mockList).toHaveBeenCalledWith('proj-1');
74
- expect(mockKillSession).toHaveBeenCalledTimes(2);
75
- expect(mockKillSession).toHaveBeenCalledWith('session-a', 'SIGKILL');
76
- expect(mockKillSession).toHaveBeenCalledWith('session-b', 'SIGKILL');
77
- });
78
-
79
- test('kills PTY sessions when user has no websocket connections but project access was revoked', () => {
80
- mockGetConnectionsForUser.mockReturnValue([]);
81
- mockList.mockReturnValue([{ sessionId: 'session-a' }]);
82
-
83
- const cleared = invalidateUserSessions('bob', 'proj-1');
84
-
85
- expect(cleared).toBe(0);
86
- expect(mockKillSession).toHaveBeenCalledTimes(1);
87
- expect(mockKillSession).toHaveBeenCalledWith('session-a', 'SIGKILL');
88
- });
89
- });
90
-
91
- describe('getActiveSessionCountForUser', () => {
92
- beforeEach(() => {
93
- mockGetConnectionsForUser.mockClear();
94
- });
95
-
96
- test('returns count of active connections for user', () => {
97
- mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2']);
98
-
99
- const count = getActiveSessionCountForUser('user-789');
100
-
101
- expect(count).toBe(2);
102
- expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-789');
103
- });
104
-
105
- test('returns 0 when user has no connections', () => {
106
- mockGetConnectionsForUser.mockReturnValue([]);
107
-
108
- const count = getActiveSessionCountForUser('user-none');
109
-
110
- expect(count).toBe(0);
111
- });
112
- });
@@ -1,77 +0,0 @@
1
- /**
2
- * Session Invalidation
3
- *
4
- * Provides functions to invalidate user sessions when project access changes
5
- * or other security-relevant events occur.
6
- */
7
-
8
- import { ws } from '$backend/utils/ws';
9
- import { debug } from '$shared/utils/logger';
10
- import { ptyKitManager } from '$backend/terminal/ptykit';
11
-
12
- /**
13
- * Invalidate all active WebSocket sessions for a specific user.
14
- * This clears their in-memory auth state and triggers a force-logout
15
- * event so the frontend knows to disconnect and re-authenticate.
16
- *
17
- * Also kills any PTY terminal sessions belonging to the specified
18
- * project to prevent orphaned processes from continuing to run
19
- * after access is revoked.
20
- *
21
- * @param userId - The user whose sessions should be invalidated
22
- * @param projectId - Optional project ID to scope PTY cleanup
23
- * @returns The number of connections that were cleared
24
- */
25
- export function invalidateUserSessions(userId: string, projectId?: string): number {
26
- const connections = ws.getConnectionsForUser(userId);
27
- if (connections.length === 0) {
28
- debug.log('auth', `No active sessions to invalidate for user ${userId}`);
29
- if (projectId) {
30
- killUserPtySessionsForProject(userId, projectId);
31
- }
32
- return 0;
33
- }
34
-
35
- const cleared = ws.clearAuthForConnections(connections);
36
- debug.log('auth', `Invalidated ${cleared} session(s) for user ${userId}`);
37
-
38
- // Notify only this user's active connections to force logout.
39
- ws.emit.user(userId, 'auth:force-logout-user', { reason: 'Project access revoked' });
40
-
41
- if (projectId) {
42
- killUserPtySessionsForProject(userId, projectId);
43
- }
44
-
45
- return cleared;
46
- }
47
-
48
- /**
49
- * Kill PTY terminal sessions in a project when a user's access is revoked.
50
- * Prevents orphaned shell processes from continuing to run. Terminals are
51
- * collaborative and project-scoped (PtyKit keys sessions by namespace =
52
- * projectId), so revoking access tears down that project's terminals.
53
- */
54
- function killUserPtySessionsForProject(userId: string, projectId: string): void {
55
- let killedCount = 0;
56
-
57
- for (const session of ptyKitManager.list(projectId)) {
58
- debug.log('auth', `Killing PTY session ${session.sessionId} (project ${projectId} access revoked for user ${userId})`);
59
- ptyKitManager.killSession(session.sessionId, 'SIGKILL');
60
- killedCount++;
61
- }
62
-
63
- if (killedCount > 0) {
64
- debug.log('auth', `Killed ${killedCount} PTY session(s) in project ${projectId}`);
65
- }
66
- }
67
-
68
- /**
69
- * Get the number of active WebSocket connections for a user.
70
- * Useful for logging and debugging.
71
- *
72
- * @param userId - The user to check
73
- * @returns Number of active connections
74
- */
75
- export function getActiveSessionCountForUser(userId: string): number {
76
- return ws.getConnectionsForUser(userId).length;
77
- }
@@ -1,32 +0,0 @@
1
- import { describe, expect, test } from 'bun:test';
2
- import {
3
- clearProjectPresence,
4
- getProjectStatusData,
5
- updateUserPresence
6
- } from './status-manager';
7
-
8
- async function getSingleProjectStatus(projectId: string) {
9
- const status = await getProjectStatusData(projectId);
10
- if (Array.isArray(status)) {
11
- throw new Error('expected single-project status payload');
12
- }
13
- return status;
14
- }
15
-
16
- describe('clearProjectPresence', () => {
17
- test('removes active users for the project from status data', async () => {
18
- updateUserPresence('proj-presence', 'user-1', 'Alice', 'join');
19
-
20
- const before = await getSingleProjectStatus('proj-presence');
21
- expect(before.activeUsers).toHaveLength(1);
22
-
23
- clearProjectPresence('proj-presence');
24
-
25
- const after = await getSingleProjectStatus('proj-presence');
26
- expect(after.activeUsers).toEqual([]);
27
- });
28
-
29
- test('is a no-op when the project has no presence entry', () => {
30
- expect(() => clearProjectPresence('proj-never-seen')).not.toThrow();
31
- });
32
- });
@@ -1,94 +0,0 @@
1
- import { t } from 'elysia';
2
- import { createRouter } from '$shared/utils/ws-server';
3
- import { createInvite, listInvites, revokeInvite } from '$backend/auth/auth-service';
4
- import { ws } from '$backend/utils/ws';
5
-
6
- export const inviteHandler = createRouter()
7
- // Create invite token (admin only — enforced by auth gate)
8
- .http('auth:create-invite', {
9
- data: t.Object({
10
- label: t.Optional(t.String()),
11
- maxUses: t.Optional(t.Number({ minimum: 0 })),
12
- expiresInMinutes: t.Optional(t.Number({ minimum: 1 })),
13
- projectIds: t.Optional(t.Array(t.String()))
14
- }),
15
- response: t.Object({
16
- inviteToken: t.String(),
17
- invite: t.Object({
18
- id: t.String(),
19
- role: t.String(),
20
- label: t.Union([t.String(), t.Null()]),
21
- max_uses: t.Number(),
22
- use_count: t.Number(),
23
- expires_at: t.Union([t.String(), t.Null()]),
24
- created_at: t.String(),
25
- project_ids: t.Union([t.String(), t.Null()])
26
- })
27
- })
28
- }, async ({ data, conn }) => {
29
- const userId = ws.getUserId(conn);
30
- const result = createInvite(userId, {
31
- label: data.label,
32
- maxUses: data.maxUses,
33
- expiresInMinutes: data.expiresInMinutes,
34
- projectIds: data.projectIds
35
- });
36
-
37
- // Broadcast so every admin's invite list (Team) stays in sync.
38
- ws.emit.global('remote-access:changed', { kind: 'invite-created' });
39
-
40
- return {
41
- inviteToken: result.inviteToken,
42
- invite: {
43
- id: result.invite!.id,
44
- role: result.invite!.role,
45
- label: result.invite!.label,
46
- max_uses: result.invite!.max_uses,
47
- use_count: result.invite!.use_count,
48
- expires_at: result.invite!.expires_at,
49
- created_at: result.invite!.created_at,
50
- project_ids: result.invite!.project_ids
51
- }
52
- };
53
- })
54
-
55
- // List all invites (admin only)
56
- .http('auth:list-invites', {
57
- data: t.Object({}),
58
- response: t.Array(t.Object({
59
- id: t.String(),
60
- role: t.String(),
61
- label: t.Union([t.String(), t.Null()]),
62
- max_uses: t.Number(),
63
- use_count: t.Number(),
64
- expires_at: t.Union([t.String(), t.Null()]),
65
- created_at: t.String(),
66
- project_ids: t.Union([t.String(), t.Null()])
67
- }))
68
- }, async () => {
69
- const invites = listInvites();
70
- return invites.map(inv => ({
71
- id: inv.id,
72
- role: inv.role,
73
- label: inv.label,
74
- max_uses: inv.max_uses,
75
- use_count: inv.use_count,
76
- expires_at: inv.expires_at,
77
- created_at: inv.created_at,
78
- project_ids: inv.project_ids
79
- }));
80
- })
81
-
82
- // Revoke invite (admin only)
83
- .http('auth:revoke-invite', {
84
- data: t.Object({
85
- id: t.String({ minLength: 1 })
86
- }),
87
- response: t.Object({
88
- success: t.Boolean()
89
- })
90
- }, async ({ data }) => {
91
- revokeInvite(data.id);
92
- ws.emit.global('remote-access:changed', { kind: 'invite-revoked' });
93
- return { success: true };
94
- });
@@ -1,112 +0,0 @@
1
- import { t } from 'elysia';
2
- import { createRouter } from '$shared/utils/ws-server';
3
- import {
4
- listUsers,
5
- removeUser,
6
- listUserProjects,
7
- assignProjectToUser,
8
- unassignProjectFromUser
9
- } from '$backend/auth/auth-service';
10
- import { invalidateUserSessions } from '$backend/auth/session-invalidation';
11
- import { auditLogQueries } from '$backend/database/queries';
12
- import { ws } from '$backend/utils/ws';
13
- import { clientIpFromConnection } from '$backend/utils/client-ip';
14
-
15
- export const usersHandler = createRouter()
16
- // List all users (admin only — enforced by auth gate)
17
- .http('auth:list-users', {
18
- data: t.Object({}),
19
- response: t.Array(t.Object({
20
- id: t.String(),
21
- name: t.String(),
22
- role: t.Union([t.Literal('admin'), t.Literal('member')]),
23
- color: t.String(),
24
- avatar: t.String(),
25
- createdAt: t.String()
26
- }))
27
- }, async () => {
28
- return listUsers();
29
- })
30
-
31
- // Remove user (admin only)
32
- .http('auth:remove-user', {
33
- data: t.Object({
34
- userId: t.String({ minLength: 1 })
35
- }),
36
- response: t.Object({
37
- success: t.Boolean()
38
- })
39
- }, async ({ data }) => {
40
- removeUser(data.userId);
41
- ws.emit.global('auth:users-changed', { type: 'removed', userId: data.userId });
42
- return { success: true };
43
- })
44
-
45
- // List projects assigned to a specific user (admin only)
46
- .http('auth:list-user-projects', {
47
- data: t.Object({
48
- userId: t.String({ minLength: 1 })
49
- }),
50
- response: t.Array(t.Any())
51
- }, async ({ data }) => {
52
- return listUserProjects(data.userId);
53
- })
54
-
55
- // Assign a project to a user (admin only)
56
- .http('auth:assign-project', {
57
- data: t.Object({
58
- userId: t.String({ minLength: 1 }),
59
- projectId: t.String({ minLength: 1 })
60
- }),
61
- response: t.Object({
62
- added: t.Boolean()
63
- })
64
- }, async ({ data, conn }) => {
65
- const actorUserId = ws.getUserId(conn);
66
- const added = assignProjectToUser(data.userId, data.projectId);
67
- if (added) {
68
- auditLogQueries.logEvent({
69
- userId: data.userId,
70
- actorUserId,
71
- eventType: 'project:assigned',
72
- eventDetails: `Project ${data.projectId} assigned to user ${data.userId}`,
73
- ipAddress: clientIpFromConnection(conn)
74
- });
75
- ws.emit.global('auth:user-projects-changed', {
76
- type: 'assigned',
77
- userId: data.userId,
78
- projectId: data.projectId
79
- });
80
- }
81
- return { added };
82
- })
83
-
84
- // Revoke a user's access to a project (admin only)
85
- .http('auth:unassign-project', {
86
- data: t.Object({
87
- userId: t.String({ minLength: 1 }),
88
- projectId: t.String({ minLength: 1 })
89
- }),
90
- response: t.Object({
91
- removed: t.Boolean()
92
- })
93
- }, async ({ data, conn }) => {
94
- const actorUserId = ws.getUserId(conn);
95
- const removed = unassignProjectFromUser(data.userId, data.projectId);
96
- if (removed) {
97
- invalidateUserSessions(data.userId, data.projectId);
98
- auditLogQueries.logEvent({
99
- userId: data.userId,
100
- actorUserId,
101
- eventType: 'project:unassigned',
102
- eventDetails: `Project ${data.projectId} unassigned from user ${data.userId}`,
103
- ipAddress: clientIpFromConnection(conn)
104
- });
105
- ws.emit.global('auth:user-projects-changed', {
106
- type: 'unassigned',
107
- userId: data.userId,
108
- projectId: data.projectId
109
- });
110
- }
111
- return { removed };
112
- });
@@ -1,46 +0,0 @@
1
- /**
2
- * Projects Presence Management
3
- *
4
- * Handles user presence updates:
5
- * - projects:update-presence (HTTP) - Update user presence with broadcast
6
- *
7
- * Uses `projects:presence-updated` event (declared in status.ts)
8
- */
9
-
10
- import { t } from 'elysia';
11
- import { createRouter } from '$shared/utils/ws-server';
12
- import { updateUserPresence, getProjectStatusData } from '../../project/status-manager';
13
- import { streamManager } from '../../chat/stream-manager';
14
- import { ws } from '$backend/utils/ws';
15
- import { debug } from '$shared/utils/logger';
16
-
17
- export const presenceHandler = createRouter()
18
- .http('projects:update-presence', {
19
- data: t.Object({
20
- userName: t.String({ minLength: 1 }),
21
- action: t.Optional(t.String())
22
- }),
23
- response: t.Any()
24
- }, async ({ data, conn }) => {
25
- const projectId = ws.getProjectId(conn);
26
- const userId = ws.getUserId(conn);
27
- const { userName, action } = data;
28
-
29
- updateUserPresence(projectId, userId, userName, action || 'join');
30
-
31
- try {
32
- streamManager.cleanupProjectStreams(projectId);
33
- } catch (cleanupError) {
34
- debug.error('project', 'Error cleaning up project streams:', cleanupError);
35
- }
36
-
37
- // Broadcast full presence to all clients
38
- const allStatuses = await getProjectStatusData();
39
- ws.emit.global('projects:presence-updated', {
40
- type: 'presence-updated',
41
- timestamp: Date.now(),
42
- data: allStatuses
43
- });
44
-
45
- return await getProjectStatusData(projectId);
46
- });
@@ -1,31 +0,0 @@
1
- /**
2
- * Stack access guards.
3
- *
4
- * Install sessions are global (one runner per backend) but each session has
5
- * an owning user. Handlers must isolate sessions across users so admin A
6
- * cannot drive admin B's install. The router-level admin gate covers
7
- * authentication; this guard covers per-session ownership.
8
- */
9
-
10
- import type { WSConnection } from '$shared/utils/ws-server';
11
- import { ws } from '$backend/utils/ws';
12
- import { getSession, getSessionOwner, SYSTEM_INSTALL_USER } from '$backend/engine/install-runner';
13
-
14
- type InstallSession = NonNullable<ReturnType<typeof getSession>>;
15
-
16
- /**
17
- * Throw if the install session exists but is owned by another user.
18
- * Returns the session if accessible, or `null` if it doesn't exist
19
- * (mirrors the existing handler behaviour for `install-cancel`).
20
- */
21
- export function requireInstallSessionAccess(conn: WSConnection, sessionId: string): InstallSession | null {
22
- const userId = ws.getUserId(conn);
23
- const owner = getSessionOwner(sessionId);
24
- // Installs clopen starts itself belong to no user; any admin reaching this
25
- // guard may watch or cancel them, otherwise a startup repair would show up
26
- // in Settings → Stack as a running session nobody is allowed to touch.
27
- if (owner && owner !== SYSTEM_INSTALL_USER && owner !== userId) {
28
- throw new Error('Install session not found');
29
- }
30
- return getSession(sessionId);
31
- }