gitspace 0.2.0-rc.20 → 0.2.0-rc.21

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 (474) hide show
  1. package/package.json +11 -6
  2. package/.claude/settings.local.json +0 -10
  3. package/.gitspace/bundle.json +0 -50
  4. package/.gitspace/events.json +0 -11
  5. package/.gitspace/processes.json +0 -23
  6. package/.gitspace/scripts/select/01-status.sh +0 -39
  7. package/.gitspace/scripts/setup/01-install-deps.sh +0 -12
  8. package/.gitspace/scripts/setup/02-typecheck.sh +0 -16
  9. package/AGENTS.md +0 -469
  10. package/CLAUDE.md +0 -1
  11. package/bun.lock +0 -794
  12. package/docs/CONNECTION.md +0 -623
  13. package/docs/GATEWAY-WORKER.md +0 -319
  14. package/docs/GETTING-STARTED.md +0 -448
  15. package/docs/GITSPACE-PLATFORM.md +0 -1819
  16. package/docs/INFRASTRUCTURE.md +0 -1347
  17. package/docs/PROTOCOL.md +0 -619
  18. package/docs/QUICKSTART.md +0 -183
  19. package/docs/RELAY.md +0 -327
  20. package/docs/REMOTE-DESIGN.md +0 -554
  21. package/docs/ROADMAP.md +0 -564
  22. package/docs/SITE_DOCS_FIGMA_MAKE.md +0 -1176
  23. package/docs/STACK-DESIGN.md +0 -588
  24. package/docs/UNIFIED_ARCHITECTURE.md +0 -138
  25. package/experiments/pty-benchmark.ts +0 -148
  26. package/experiments/pty-latency.ts +0 -100
  27. package/experiments/router/client.ts +0 -199
  28. package/experiments/router/protocol.ts +0 -74
  29. package/experiments/router/router.ts +0 -217
  30. package/experiments/router/session.ts +0 -180
  31. package/experiments/router/test.ts +0 -133
  32. package/experiments/socket-bandwidth.ts +0 -77
  33. package/homebrew/gitspace.rb +0 -45
  34. package/landing-page/ATTRIBUTIONS.md +0 -3
  35. package/landing-page/README.md +0 -11
  36. package/landing-page/bun.lock +0 -801
  37. package/landing-page/guidelines/Guidelines.md +0 -61
  38. package/landing-page/index.html +0 -37
  39. package/landing-page/package.json +0 -90
  40. package/landing-page/postcss.config.mjs +0 -15
  41. package/landing-page/public/_redirects +0 -1
  42. package/landing-page/public/favicon.png +0 -0
  43. package/landing-page/src/app/App.tsx +0 -53
  44. package/landing-page/src/app/components/figma/ImageWithFallback.tsx +0 -27
  45. package/landing-page/src/app/components/ui/accordion.tsx +0 -66
  46. package/landing-page/src/app/components/ui/alert-dialog.tsx +0 -157
  47. package/landing-page/src/app/components/ui/alert.tsx +0 -66
  48. package/landing-page/src/app/components/ui/aspect-ratio.tsx +0 -11
  49. package/landing-page/src/app/components/ui/avatar.tsx +0 -53
  50. package/landing-page/src/app/components/ui/badge.tsx +0 -46
  51. package/landing-page/src/app/components/ui/breadcrumb.tsx +0 -109
  52. package/landing-page/src/app/components/ui/button.tsx +0 -57
  53. package/landing-page/src/app/components/ui/calendar.tsx +0 -75
  54. package/landing-page/src/app/components/ui/card.tsx +0 -92
  55. package/landing-page/src/app/components/ui/carousel.tsx +0 -241
  56. package/landing-page/src/app/components/ui/chart.tsx +0 -353
  57. package/landing-page/src/app/components/ui/checkbox.tsx +0 -32
  58. package/landing-page/src/app/components/ui/collapsible.tsx +0 -33
  59. package/landing-page/src/app/components/ui/command.tsx +0 -177
  60. package/landing-page/src/app/components/ui/context-menu.tsx +0 -252
  61. package/landing-page/src/app/components/ui/dialog.tsx +0 -135
  62. package/landing-page/src/app/components/ui/drawer.tsx +0 -132
  63. package/landing-page/src/app/components/ui/dropdown-menu.tsx +0 -257
  64. package/landing-page/src/app/components/ui/form.tsx +0 -168
  65. package/landing-page/src/app/components/ui/hover-card.tsx +0 -44
  66. package/landing-page/src/app/components/ui/input-otp.tsx +0 -77
  67. package/landing-page/src/app/components/ui/input.tsx +0 -21
  68. package/landing-page/src/app/components/ui/label.tsx +0 -24
  69. package/landing-page/src/app/components/ui/menubar.tsx +0 -276
  70. package/landing-page/src/app/components/ui/navigation-menu.tsx +0 -168
  71. package/landing-page/src/app/components/ui/pagination.tsx +0 -127
  72. package/landing-page/src/app/components/ui/popover.tsx +0 -48
  73. package/landing-page/src/app/components/ui/progress.tsx +0 -31
  74. package/landing-page/src/app/components/ui/radio-group.tsx +0 -45
  75. package/landing-page/src/app/components/ui/resizable.tsx +0 -56
  76. package/landing-page/src/app/components/ui/scroll-area.tsx +0 -58
  77. package/landing-page/src/app/components/ui/select.tsx +0 -189
  78. package/landing-page/src/app/components/ui/separator.tsx +0 -28
  79. package/landing-page/src/app/components/ui/sheet.tsx +0 -139
  80. package/landing-page/src/app/components/ui/sidebar.tsx +0 -726
  81. package/landing-page/src/app/components/ui/skeleton.tsx +0 -13
  82. package/landing-page/src/app/components/ui/slider.tsx +0 -63
  83. package/landing-page/src/app/components/ui/sonner.tsx +0 -25
  84. package/landing-page/src/app/components/ui/switch.tsx +0 -31
  85. package/landing-page/src/app/components/ui/table.tsx +0 -116
  86. package/landing-page/src/app/components/ui/tabs.tsx +0 -66
  87. package/landing-page/src/app/components/ui/textarea.tsx +0 -18
  88. package/landing-page/src/app/components/ui/toggle-group.tsx +0 -73
  89. package/landing-page/src/app/components/ui/toggle.tsx +0 -47
  90. package/landing-page/src/app/components/ui/tooltip.tsx +0 -61
  91. package/landing-page/src/app/components/ui/use-mobile.ts +0 -21
  92. package/landing-page/src/app/components/ui/utils.ts +0 -6
  93. package/landing-page/src/components/docs/DocsContent.tsx +0 -801
  94. package/landing-page/src/components/docs/DocsSidebar.tsx +0 -90
  95. package/landing-page/src/components/landing/CTA.tsx +0 -59
  96. package/landing-page/src/components/landing/Comparison.tsx +0 -84
  97. package/landing-page/src/components/landing/FaultyTerminal.tsx +0 -424
  98. package/landing-page/src/components/landing/Features.tsx +0 -201
  99. package/landing-page/src/components/landing/Hero.tsx +0 -142
  100. package/landing-page/src/components/landing/Pricing.tsx +0 -140
  101. package/landing-page/src/components/landing/Roadmap.tsx +0 -86
  102. package/landing-page/src/components/landing/Security.tsx +0 -81
  103. package/landing-page/src/components/landing/TerminalWindow.tsx +0 -27
  104. package/landing-page/src/components/landing/UseCases.tsx +0 -55
  105. package/landing-page/src/components/landing/Workflow.tsx +0 -101
  106. package/landing-page/src/components/layout/DashboardNavbar.tsx +0 -37
  107. package/landing-page/src/components/layout/Footer.tsx +0 -55
  108. package/landing-page/src/components/layout/LandingNavbar.tsx +0 -82
  109. package/landing-page/src/components/ui/badge.tsx +0 -39
  110. package/landing-page/src/components/ui/breadcrumb.tsx +0 -115
  111. package/landing-page/src/components/ui/button.tsx +0 -57
  112. package/landing-page/src/components/ui/card.tsx +0 -79
  113. package/landing-page/src/components/ui/mock-terminal.tsx +0 -68
  114. package/landing-page/src/components/ui/separator.tsx +0 -28
  115. package/landing-page/src/lib/utils.ts +0 -6
  116. package/landing-page/src/main.tsx +0 -10
  117. package/landing-page/src/pages/Dashboard.tsx +0 -133
  118. package/landing-page/src/pages/DocsPage.tsx +0 -79
  119. package/landing-page/src/pages/LandingPage.tsx +0 -31
  120. package/landing-page/src/pages/TerminalView.tsx +0 -106
  121. package/landing-page/src/styles/fonts.css +0 -0
  122. package/landing-page/src/styles/index.css +0 -3
  123. package/landing-page/src/styles/tailwind.css +0 -4
  124. package/landing-page/src/styles/theme.css +0 -181
  125. package/landing-page/vite.config.ts +0 -19
  126. package/scripts/GHOSTTY_TAB_BUG.md +0 -106
  127. package/scripts/build.ts +0 -298
  128. package/scripts/migrate-secrets.ts +0 -77
  129. package/scripts/release.ts +0 -140
  130. package/scripts/sample-events.ts +0 -263
  131. package/scripts/test-tabs-minimal.ts +0 -68
  132. package/scripts/test-tabs-workaround.ts +0 -95
  133. package/scripts/test-tabs.ts +0 -171
  134. package/src/__tests__/test-utils.ts +0 -298
  135. package/src/app/input/__tests__/sessionCommands.test.ts +0 -40
  136. package/src/app/input/sessionCommands.ts +0 -94
  137. package/src/app/session/__tests__/useAttachController.test.ts +0 -229
  138. package/src/app/session/createSessionBackend.bun.ts +0 -76
  139. package/src/app/session/createSessionBackend.web.ts +0 -104
  140. package/src/app/session/types.ts +0 -16
  141. package/src/app/session/useAttachController.ts +0 -220
  142. package/src/app/session/useProcessActions.ts +0 -201
  143. package/src/app/session/useSessionClient.ts +0 -35
  144. package/src/app/session/useWorkspaceDeleteFlow.ts +0 -170
  145. package/src/app.tui.tsx +0 -2929
  146. package/src/app.web.tsx +0 -1454
  147. package/src/commands/__tests__/connect-key.test.ts +0 -10
  148. package/src/commands/__tests__/events.test.ts +0 -201
  149. package/src/commands/__tests__/notifications.test.ts +0 -349
  150. package/src/commands/__tests__/process.test.ts +0 -251
  151. package/src/commands/__tests__/serve-messages.test.ts +0 -190
  152. package/src/commands/__tests__/serve-process-hosting.test.ts +0 -63
  153. package/src/commands/access.ts +0 -298
  154. package/src/commands/add.ts +0 -455
  155. package/src/commands/auth.ts +0 -369
  156. package/src/commands/bundle.ts +0 -232
  157. package/src/commands/config.ts +0 -242
  158. package/src/commands/connect-key.ts +0 -1
  159. package/src/commands/connect.ts +0 -576
  160. package/src/commands/directory.ts +0 -16
  161. package/src/commands/events.ts +0 -157
  162. package/src/commands/host.ts +0 -566
  163. package/src/commands/identity.ts +0 -184
  164. package/src/commands/linear.ts +0 -717
  165. package/src/commands/list.ts +0 -181
  166. package/src/commands/migrate.ts +0 -52
  167. package/src/commands/notifications.ts +0 -351
  168. package/src/commands/process.ts +0 -104
  169. package/src/commands/relay.ts +0 -315
  170. package/src/commands/remove.ts +0 -279
  171. package/src/commands/review.ts +0 -787
  172. package/src/commands/serve.ts +0 -1946
  173. package/src/commands/share.ts +0 -451
  174. package/src/commands/status.ts +0 -125
  175. package/src/commands/switch.ts +0 -361
  176. package/src/commands/tmux.ts +0 -317
  177. package/src/components/DPad.web.tsx +0 -343
  178. package/src/components/DiffViewer.web.tsx +0 -1192
  179. package/src/components/Events.tsx +0 -137
  180. package/src/components/Events.tui.tsx +0 -129
  181. package/src/components/Events.web.tsx +0 -386
  182. package/src/components/FloatingControls.web.tsx +0 -112
  183. package/src/components/FloatingJogWheel.web.tsx +0 -240
  184. package/src/components/Flow.tsx +0 -458
  185. package/src/components/Flow.tui.tsx +0 -343
  186. package/src/components/Flow.web.tsx +0 -442
  187. package/src/components/Inbox.tsx +0 -448
  188. package/src/components/Inbox.tui.tsx +0 -262
  189. package/src/components/Inbox.web.tsx +0 -329
  190. package/src/components/MachineList.tsx +0 -187
  191. package/src/components/MachineList.tui.tsx +0 -161
  192. package/src/components/MachineList.web.tsx +0 -210
  193. package/src/components/NumPad.web.tsx +0 -270
  194. package/src/components/ProjectList.tsx +0 -175
  195. package/src/components/ProjectList.tui.tsx +0 -109
  196. package/src/components/ProjectList.web.tsx +0 -143
  197. package/src/components/ProjectOnboardingStep.ts +0 -23
  198. package/src/components/ProjectOnboardingStep.tui.tsx +0 -88
  199. package/src/components/ProjectOnboardingStep.web.tsx +0 -59
  200. package/src/components/RemoteMachineScreen.tui.tsx +0 -690
  201. package/src/components/ScriptTerminal.tui.tsx +0 -160
  202. package/src/components/ScriptTerminal.web.tsx +0 -89
  203. package/src/components/SessionTerminal.tui.tsx +0 -406
  204. package/src/components/SessionTerminal.web.tsx +0 -467
  205. package/src/components/SpacesBrowser.tsx +0 -540
  206. package/src/components/SpacesBrowser.tui.tsx +0 -258
  207. package/src/components/SpacesBrowser.web.tsx +0 -332
  208. package/src/components/TerminalControls.web.tsx +0 -464
  209. package/src/components/ThreadPanel.web.tsx +0 -798
  210. package/src/components/__tests__/SpacesBrowser.test.ts +0 -541
  211. package/src/components/__tests__/SpacesBrowser.tui.test.tsx +0 -249
  212. package/src/components/__tests__/script-terminal-buffer.tui.test.ts +0 -72
  213. package/src/components/index.ts +0 -105
  214. package/src/components/review-decision-colors.ts +0 -11
  215. package/src/components/script-terminal-buffer.tui.ts +0 -37
  216. package/src/components/session-terminal-page-navigation.ts +0 -48
  217. package/src/components/terminal-bracketed-paste.tui.test.ts +0 -43
  218. package/src/components/terminal-bracketed-paste.tui.ts +0 -46
  219. package/src/core/__tests__/access.test.ts +0 -240
  220. package/src/core/__tests__/bundle-refresh.test.ts +0 -567
  221. package/src/core/__tests__/bundle.test.ts +0 -209
  222. package/src/core/__tests__/github-review.test.ts +0 -781
  223. package/src/core/__tests__/project-lifecycle.test.ts +0 -137
  224. package/src/core/__tests__/workspace-lifecycle.test.ts +0 -159
  225. package/src/core/__tests__/workspace.test.ts +0 -149
  226. package/src/core/access.ts +0 -277
  227. package/src/core/bundle-refresh.ts +0 -1064
  228. package/src/core/bundle.ts +0 -326
  229. package/src/core/config.ts +0 -405
  230. package/src/core/git.ts +0 -768
  231. package/src/core/github-review.ts +0 -761
  232. package/src/core/github.ts +0 -151
  233. package/src/core/identity.ts +0 -631
  234. package/src/core/linear.ts +0 -403
  235. package/src/core/preferences-service.ts +0 -17
  236. package/src/core/project-catalog.ts +0 -52
  237. package/src/core/project-lifecycle.ts +0 -163
  238. package/src/core/review-executor.ts +0 -316
  239. package/src/core/review.ts +0 -407
  240. package/src/core/secret-runtime.ts +0 -167
  241. package/src/core/shell.ts +0 -117
  242. package/src/core/trusted-relays.ts +0 -315
  243. package/src/core/workspace-lifecycle.ts +0 -216
  244. package/src/core/workspace.ts +0 -363
  245. package/src/hooks/__tests__/useLocalSession.tui.test.ts +0 -557
  246. package/src/hooks/index.ts +0 -8
  247. package/src/hooks/index.tui.ts +0 -32
  248. package/src/hooks/useDaemonStatus.tui.ts +0 -174
  249. package/src/hooks/useLocalSession.tui.ts +0 -395
  250. package/src/hooks/useRelayConnection.web.ts +0 -54
  251. package/src/hooks/useRemoteMachines.tui.ts +0 -166
  252. package/src/hooks/useRemoteTerminal.tui.ts +0 -22
  253. package/src/hooks/useReview.web.ts +0 -248
  254. package/src/hooks/useTerminal.web.ts +0 -36
  255. package/src/hooks/useUserActivity.ts +0 -61
  256. package/src/hooks/useVisualViewport.web.ts +0 -104
  257. package/src/index.ts +0 -1376
  258. package/src/lib/events/__tests__/collector-filter.test.ts +0 -105
  259. package/src/lib/events/__tests__/store-query.test.ts +0 -103
  260. package/src/lib/events/collector.ts +0 -494
  261. package/src/lib/events/filters.ts +0 -26
  262. package/src/lib/events/index.ts +0 -11
  263. package/src/lib/events/indexer.ts +0 -14
  264. package/src/lib/events/paths.ts +0 -69
  265. package/src/lib/events/reader.ts +0 -212
  266. package/src/lib/events/store.ts +0 -141
  267. package/src/lib/invite.web.ts +0 -58
  268. package/src/lib/preferences-service.web.ts +0 -41
  269. package/src/lib/processes/__tests__/config.test.ts +0 -83
  270. package/src/lib/processes/__tests__/names.test.ts +0 -125
  271. package/src/lib/processes/__tests__/schema.test.ts +0 -208
  272. package/src/lib/processes/__tests__/watchdog.test.ts +0 -210
  273. package/src/lib/processes/autostart.ts +0 -16
  274. package/src/lib/processes/config.ts +0 -187
  275. package/src/lib/processes/control.ts +0 -53
  276. package/src/lib/processes/editor.ts +0 -32
  277. package/src/lib/processes/events-config.ts +0 -37
  278. package/src/lib/processes/index.ts +0 -14
  279. package/src/lib/processes/instances.ts +0 -20
  280. package/src/lib/processes/manager.ts +0 -131
  281. package/src/lib/processes/names.ts +0 -71
  282. package/src/lib/processes/registry.ts +0 -26
  283. package/src/lib/processes/runner.ts +0 -211
  284. package/src/lib/processes/scheduler.ts +0 -17
  285. package/src/lib/processes/schema.ts +0 -74
  286. package/src/lib/processes/session-list.ts +0 -15
  287. package/src/lib/processes/state.ts +0 -82
  288. package/src/lib/processes/watchdog.test.ts +0 -79
  289. package/src/lib/processes/watchdog.ts +0 -106
  290. package/src/lib/remote-session/__tests__/protocol.test.ts +0 -291
  291. package/src/lib/remote-session/index.ts +0 -7
  292. package/src/lib/remote-session/protocol.ts +0 -443
  293. package/src/lib/remote-session/session-handler.ts +0 -1298
  294. package/src/lib/remote-session/workspace-scanner.ts +0 -161
  295. package/src/lib/sonner.web.ts +0 -1
  296. package/src/lib/storage/identity-store.web.ts +0 -94
  297. package/src/lib/tmux-lite/README.md +0 -81
  298. package/src/lib/tmux-lite/cli.ts +0 -855
  299. package/src/lib/tmux-lite/crypto/__tests__/helpers/handshake-runner.ts +0 -349
  300. package/src/lib/tmux-lite/crypto/__tests__/helpers/mock-relay.ts +0 -291
  301. package/src/lib/tmux-lite/crypto/__tests__/helpers/test-identities.ts +0 -142
  302. package/src/lib/tmux-lite/crypto/__tests__/integration/authorization.integration.test.ts +0 -339
  303. package/src/lib/tmux-lite/crypto/__tests__/integration/e2e-communication.integration.test.ts +0 -477
  304. package/src/lib/tmux-lite/crypto/__tests__/integration/error-handling.integration.test.ts +0 -499
  305. package/src/lib/tmux-lite/crypto/__tests__/integration/handshake.integration.test.ts +0 -371
  306. package/src/lib/tmux-lite/crypto/__tests__/integration/security.integration.test.ts +0 -573
  307. package/src/lib/tmux-lite/crypto/access-control.test.ts +0 -512
  308. package/src/lib/tmux-lite/crypto/access-control.ts +0 -320
  309. package/src/lib/tmux-lite/crypto/frames.test.ts +0 -262
  310. package/src/lib/tmux-lite/crypto/frames.ts +0 -141
  311. package/src/lib/tmux-lite/crypto/handshake.ts +0 -894
  312. package/src/lib/tmux-lite/crypto/identity.test.ts +0 -220
  313. package/src/lib/tmux-lite/crypto/identity.ts +0 -286
  314. package/src/lib/tmux-lite/crypto/index.ts +0 -51
  315. package/src/lib/tmux-lite/crypto/invites.test.ts +0 -381
  316. package/src/lib/tmux-lite/crypto/invites.ts +0 -215
  317. package/src/lib/tmux-lite/crypto/keyexchange.ts +0 -435
  318. package/src/lib/tmux-lite/crypto/keys.test.ts +0 -58
  319. package/src/lib/tmux-lite/crypto/keys.ts +0 -47
  320. package/src/lib/tmux-lite/crypto/secretbox.test.ts +0 -169
  321. package/src/lib/tmux-lite/crypto/secretbox.ts +0 -124
  322. package/src/lib/tmux-lite/handshake-handler.ts +0 -451
  323. package/src/lib/tmux-lite/process-run.integration.test.ts +0 -266
  324. package/src/lib/tmux-lite/protocol.test.ts +0 -307
  325. package/src/lib/tmux-lite/protocol.ts +0 -291
  326. package/src/lib/tmux-lite/relay-client.ts +0 -506
  327. package/src/lib/tmux-lite/server-lifecycle.test.ts +0 -212
  328. package/src/lib/tmux-lite/server.ts +0 -1412
  329. package/src/lib/tmux-lite/shell-integration.sh +0 -37
  330. package/src/lib/tmux-lite/terminal-queries.test.ts +0 -54
  331. package/src/lib/tmux-lite/terminal-queries.ts +0 -49
  332. package/src/notifications/__tests__/useNotifications.test.ts +0 -739
  333. package/src/notifications/index.ts +0 -32
  334. package/src/notifications/policy.test.ts +0 -424
  335. package/src/notifications/policy.ts +0 -139
  336. package/src/notifications/types.ts +0 -82
  337. package/src/notifications/useNotifications.ts +0 -350
  338. package/src/pages/ReviewPage.web.tsx +0 -511
  339. package/src/preferences/index.ts +0 -1
  340. package/src/preferences/types.ts +0 -9
  341. package/src/relay/__tests__/e2e-flow.test.ts +0 -1284
  342. package/src/relay/__tests__/helpers/auth.ts +0 -354
  343. package/src/relay/__tests__/helpers/ports.ts +0 -51
  344. package/src/relay/__tests__/protocol-validation.test.ts +0 -265
  345. package/src/relay/authorization.ts +0 -303
  346. package/src/relay/embedded-assets.generated.d.ts +0 -15
  347. package/src/relay/identity.ts +0 -352
  348. package/src/relay/index.ts +0 -57
  349. package/src/relay/pipes.test.ts +0 -427
  350. package/src/relay/pipes.ts +0 -195
  351. package/src/relay/protocol.ts +0 -804
  352. package/src/relay/registries.test.ts +0 -437
  353. package/src/relay/registries.ts +0 -593
  354. package/src/relay/server.test.ts +0 -1323
  355. package/src/relay/server.ts +0 -1128
  356. package/src/relay/signing.ts +0 -238
  357. package/src/relay/types.ts +0 -69
  358. package/src/relay-client/__tests__/machine-directory-client.test.ts +0 -152
  359. package/src/relay-client/__tests__/useMachineDirectory.test.ts +0 -172
  360. package/src/relay-client/adapters/browser.ts +0 -27
  361. package/src/relay-client/adapters/node.ts +0 -29
  362. package/src/relay-client/index.ts +0 -33
  363. package/src/relay-client/machine-directory-client.ts +0 -244
  364. package/src/relay-client/useMachineDirectory.ts +0 -175
  365. package/src/serve/client-session-manager.ts +0 -635
  366. package/src/serve/daemon.ts +0 -497
  367. package/src/serve/pty-session.ts +0 -236
  368. package/src/serve/types.ts +0 -174
  369. package/src/session/__tests__/backend-manager.test.ts +0 -101
  370. package/src/session/__tests__/local-session-backend.test.ts +0 -1129
  371. package/src/session/__tests__/reducer.test.ts +0 -80
  372. package/src/session/__tests__/remote-session-backend.test.ts +0 -995
  373. package/src/session/__tests__/session-name.test.ts +0 -35
  374. package/src/session/__tests__/useBundleRefreshAttachFlow.test.ts +0 -431
  375. package/src/session/__tests__/useRemoteSessionClient.test.ts +0 -424
  376. package/src/session/__tests__/workspace-shell-hooks.integration.test.ts +0 -268
  377. package/src/session/__tests__/workspace-shell-hooks.test.ts +0 -24
  378. package/src/session/adapters/browser-remote.ts +0 -101
  379. package/src/session/adapters/node-remote.ts +0 -135
  380. package/src/session/backend-key.ts +0 -5
  381. package/src/session/backend-manager.ts +0 -80
  382. package/src/session/backend.ts +0 -93
  383. package/src/session/backends/local-session-backend.ts +0 -1119
  384. package/src/session/backends/remote-session-backend.ts +0 -1378
  385. package/src/session/crypto/__tests__/web-terminal.test.ts +0 -1158
  386. package/src/session/crypto/frames.web.ts +0 -205
  387. package/src/session/crypto/handshake.web.ts +0 -396
  388. package/src/session/crypto/identity.web.ts +0 -133
  389. package/src/session/crypto/keyexchange.web.ts +0 -246
  390. package/src/session/crypto/relay-signing.web.ts +0 -53
  391. package/src/session/events.ts +0 -38
  392. package/src/session/index.ts +0 -116
  393. package/src/session/reducer.ts +0 -274
  394. package/src/session/selectors.ts +0 -28
  395. package/src/session/session-name.ts +0 -50
  396. package/src/session/types.ts +0 -101
  397. package/src/session/useBundleRefreshAttachFlow.ts +0 -608
  398. package/src/session/useRemoteSessionClient.ts +0 -424
  399. package/src/session/useSessionEngine.ts +0 -432
  400. package/src/session/workspace-shell-hooks.ts +0 -35
  401. package/src/tui/__tests__/input-text.test.ts +0 -24
  402. package/src/tui/__tests__/local-terminal-sync.test.ts +0 -82
  403. package/src/tui/__tests__/session-terminal-page-navigation.test.ts +0 -94
  404. package/src/tui/app.tsx +0 -2
  405. package/src/tui/index.ts +0 -18
  406. package/src/tui/input-text.ts +0 -38
  407. package/src/tui/local-terminal-sync.ts +0 -41
  408. package/src/types/bundle-refresh.ts +0 -42
  409. package/src/types/bundle.ts +0 -130
  410. package/src/types/config.ts +0 -287
  411. package/src/types/errors.ts +0 -292
  412. package/src/types/events.ts +0 -91
  413. package/src/types/identity.ts +0 -284
  414. package/src/types/processes.ts +0 -45
  415. package/src/types/review.ts +0 -349
  416. package/src/types/script-phase.ts +0 -3
  417. package/src/types/workspace-fuzzy.ts +0 -49
  418. package/src/types/workspace.ts +0 -151
  419. package/src/utils/__tests__/onboarding.test.ts +0 -358
  420. package/src/utils/__tests__/run-scripts.test.ts +0 -535
  421. package/src/utils/__tests__/run-workspace-scripts.test.ts +0 -406
  422. package/src/utils/__tests__/workspace-setup.integration.test.ts +0 -633
  423. package/src/utils/__tests__/workspace-state.test.ts +0 -78
  424. package/src/utils/bun-socket-writer.ts +0 -80
  425. package/src/utils/clipboard.ts +0 -53
  426. package/src/utils/deps.test.ts +0 -31
  427. package/src/utils/deps.ts +0 -145
  428. package/src/utils/device.web.ts +0 -163
  429. package/src/utils/fuzzy-match.ts +0 -125
  430. package/src/utils/hostnames.ts +0 -43
  431. package/src/utils/hunk-header.ts +0 -17
  432. package/src/utils/id.ts +0 -9
  433. package/src/utils/logger.ts +0 -127
  434. package/src/utils/markdown.ts +0 -254
  435. package/src/utils/normalize-env-key.ts +0 -13
  436. package/src/utils/onboarding.ts +0 -279
  437. package/src/utils/prompts.ts +0 -176
  438. package/src/utils/run-commands.ts +0 -112
  439. package/src/utils/run-scripts.ts +0 -337
  440. package/src/utils/run-workspace-scripts.ts +0 -355
  441. package/src/utils/sanitize.test.ts +0 -149
  442. package/src/utils/sanitize.ts +0 -162
  443. package/src/utils/secrets.ts +0 -836
  444. package/src/utils/shell-escape.ts +0 -40
  445. package/src/utils/utf8.ts +0 -79
  446. package/src/utils/workspace-id.ts +0 -55
  447. package/src/utils/workspace-state.ts +0 -427
  448. package/src/version.generated.d.ts +0 -2
  449. package/todo-security.md +0 -92
  450. package/tsconfig.json +0 -29
  451. package/web/README.md +0 -73
  452. package/web/bun.lock +0 -675
  453. package/web/eslint.config.js +0 -23
  454. package/web/index.css +0 -249
  455. package/web/index.html +0 -16
  456. package/web/main.tsx +0 -10
  457. package/web/package.json +0 -39
  458. package/web/public/vite.svg +0 -1
  459. package/web/tsconfig.app.json +0 -35
  460. package/web/tsconfig.json +0 -7
  461. package/web/tsconfig.node.json +0 -26
  462. package/web/vite.config.ts +0 -39
  463. package/worker/bun.lock +0 -237
  464. package/worker/package.json +0 -22
  465. package/worker/schema.sql +0 -96
  466. package/worker/src/handlers/auth.ts +0 -451
  467. package/worker/src/handlers/subdomains.ts +0 -376
  468. package/worker/src/handlers/user.ts +0 -98
  469. package/worker/src/index.ts +0 -70
  470. package/worker/src/middleware/auth.ts +0 -152
  471. package/worker/src/services/cloudflare.ts +0 -609
  472. package/worker/src/types.ts +0 -96
  473. package/worker/tsconfig.json +0 -15
  474. package/worker/wrangler.toml +0 -26
@@ -1,1946 +0,0 @@
1
- /**
2
- * Serve command implementation
3
- *
4
- * Handles 'gssh serve' to start a machine-side daemon that accepts
5
- * remote connections, authenticates clients via X3DH, and spawns PTY sessions.
6
- *
7
- * Also handles gitspace.sh hosting via Cloudflare Tunnels when configured.
8
- *
9
- * Supports daemon mode with start/stop/status subcommands.
10
- */
11
-
12
- import { watch, appendFileSync, existsSync, writeFileSync, readdirSync } from 'fs';
13
- import { join } from 'path';
14
- import { createHash } from 'crypto';
15
- import { spawn, type Subprocess } from 'bun';
16
- import { logger } from '../utils/logger.js';
17
- import { promptPassword, promptConfirm } from '../utils/prompts.js';
18
- import { getSecret } from '../utils/secrets.js';
19
- import {
20
- isRelayTrusted,
21
- addTrustedRelay,
22
- getTrustedRelay,
23
- isLocalhost,
24
- computeRelayFingerprint,
25
- type RelayTrustStatus,
26
- } from '../core/trusted-relays.js';
27
- import {
28
- loadKeypair,
29
- keypairExists,
30
- readMachineIdentity,
31
- getPublicKeyWithoutPassword,
32
- writeRelayConfig,
33
- clearRelayConfig,
34
- } from '../core/identity.js';
35
- import { readAccessList, getAccessListPath } from '../core/access.js';
36
- import { AccessControlList } from '../lib/tmux-lite/crypto/access-control.js';
37
- import { ClientSessionManager } from '../serve/client-session-manager.js';
38
- import type { ServeEventHandler } from '../serve/types.js';
39
- import type { AccessEntry } from '../types/identity.js';
40
- import {
41
- NoIdentityError,
42
- SpacesError,
43
- } from '../types/errors.js';
44
- import { getServeTokenKey, readHostConfig, type HostConfig } from './host.js';
45
- import { createRelayServer } from '../relay/server.js';
46
- import { generateRelayIdentity } from '../relay/identity.js';
47
- import { signMessage } from '../relay/signing.js';
48
- import { PROTOCOL_VERSION } from '../relay/protocol.js';
49
- import { ed25519 } from '@noble/curves/ed25519.js';
50
- import {
51
- isServeRunning,
52
- getServePid,
53
- writeServePid,
54
- cleanupServeFiles,
55
- startStatusServer,
56
- stopStatusServer,
57
- setDaemonState,
58
- updateDaemonState,
59
- queryServeStatus,
60
- sendShutdownCommand,
61
- getServeLogFile,
62
- setAccessCommandHandler,
63
- ensureServeDaemonDir,
64
- getServeDaemonDir,
65
- type StatusResponse,
66
- } from '../serve/daemon.js';
67
- import { initializeSecretRuntime } from '../core/secret-runtime.js';
68
- import { listSessions } from '../lib/tmux-lite/cli.js';
69
- import { loadProcessesConfig } from '../lib/processes/config.js';
70
- import { parseProcessSessionName } from '../lib/processes/names.js';
71
- import { resolveWorkspaceRef } from '../lib/events/paths.js';
72
- import { getGitspaceDir } from '../core/config.js';
73
- import { buildProcessHostname, normalizeHostLabel } from '../utils/hostnames.js';
74
- import type { ProcessPortConfig } from '../types/processes.js';
75
-
76
- /** Package version for daemon status */
77
- const PACKAGE_VERSION = '1.0.0';
78
-
79
- /** Default relay URL */
80
- // No default relay - must use hosting or explicit --relay
81
-
82
- /** Local relay port for gitspace.sh hosting */
83
- const LOCAL_RELAY_PORT = 4480;
84
-
85
- /** Cloudflared process reference */
86
- let cloudflaredProcess: Subprocess | null = null;
87
- let cloudflaredSubdomain: string | null = null;
88
- let cloudflaredRestartAttempts = 0;
89
- const MAX_CLOUDFLARED_RESTARTS = 5;
90
- const CLOUDFLARED_RESTART_DELAY = 5000;
91
-
92
- // ============================================================================
93
- // Helper Functions
94
- // ============================================================================
95
-
96
- /**
97
- * Validate that an access entry has required keys
98
- * @param entry - Access entry to validate
99
- * @param logLabel - Label for logging if validation fails
100
- * @returns true if valid, false if missing required keys
101
- */
102
- function isValidAccessEntry(entry: AccessEntry, logLabel?: string): boolean {
103
- const label = logLabel || entry.label || entry.identityId.substring(0, 12) + '...';
104
-
105
- if (!entry.keyExchangePublicKey || entry.keyExchangePublicKey.length === 0) {
106
- logger.warning(`Skipping access entry with missing keyExchangePublicKey: ${label}`);
107
- return false;
108
- }
109
- if (!entry.signingPublicKey || entry.signingPublicKey.length === 0) {
110
- logger.warning(`Skipping access entry with missing signingPublicKey: ${label}`);
111
- return false;
112
- }
113
- return true;
114
- }
115
-
116
- /**
117
- * Create a ServeEventHandler that logs events
118
- * @param sessionManager - Session manager for tracking active sessions
119
- * @param isLocalRelay - Whether this is for a local relay (affects log messages)
120
- * @returns Event handler function
121
- */
122
- function createEventHandler(
123
- sessionManager: ClientSessionManager,
124
- isLocalRelay: boolean
125
- ): ServeEventHandler {
126
- const relayName = isLocalRelay ? 'local relay' : 'relay';
127
-
128
- return (event) => {
129
- const timestamp = new Date().toLocaleTimeString();
130
-
131
- switch (event.type) {
132
- case 'client_connected':
133
- logger.dim(`[${timestamp}] Client ${event.connectionId.substring(0, 12)}... connecting`);
134
- break;
135
-
136
- case 'client_authenticated':
137
- logger.success(`[${timestamp}] Client ${event.identityId.substring(0, 12)}... authenticated`);
138
- logger.dim(` Access: ${event.accessType === 'full' ? 'Full access' : `Session invite${event.sessionId ? ` (${event.sessionId})` : ''}`}`);
139
- updateSessionDisplay(sessionManager);
140
- break;
141
-
142
- case 'client_disconnected':
143
- logger.dim(`[${timestamp}] Client ${event.connectionId.substring(0, 12)}... disconnected: ${event.reason}`);
144
- updateSessionDisplay(sessionManager);
145
- break;
146
-
147
- case 'relay_connected':
148
- logger.success(isLocalRelay ? 'Machine registered with local relay' : 'Connected to relay');
149
- break;
150
-
151
- case 'relay_disconnected':
152
- logger.warning(`Disconnected from ${relayName}: ${event.code} ${event.reason}`);
153
- break;
154
-
155
- case 'relay_reconnecting':
156
- logger.dim(`Reconnecting to ${relayName} (attempt ${event.attempt})...`);
157
- break;
158
-
159
- case 'error':
160
- logger.error(`Error${event.connectionId ? ` (${event.connectionId.substring(0, 12)}...)` : ''}: ${event.error.message}`);
161
- break;
162
- }
163
- };
164
- }
165
-
166
- /**
167
- * Result of relay trust verification
168
- */
169
- type RelayTrustResult =
170
- | { trusted: true }
171
- | { trusted: false; reason: string };
172
-
173
- /**
174
- * Verify and establish trust with a relay
175
- *
176
- * @param relayUrl - The relay URL
177
- * @param relayPublicKey - The relay's public key
178
- * @param relayFingerprint - The relay's fingerprint
179
- * @param relayLabel - Optional relay label
180
- * @param explicitPubkey - Optional explicit public key to trust
181
- * @returns Result indicating if trust was established
182
- */
183
- async function verifyRelayTrust(
184
- relayUrl: string,
185
- relayPublicKey: string,
186
- relayFingerprint: string,
187
- relayLabel: string | undefined,
188
- explicitPubkey?: string
189
- ): Promise<RelayTrustResult> {
190
- const trustStatus = isRelayTrusted(relayUrl, relayPublicKey);
191
-
192
- if (trustStatus === 'mismatch') {
193
- // SECURITY: Relay key changed - HARD FAIL
194
- logger.log('');
195
- logger.error('SECURITY WARNING: Relay public key mismatch!');
196
- logger.error(`Expected: ${getTrustedRelay(relayUrl)?.fingerprint}`);
197
- logger.error(`Received: ${relayFingerprint}`);
198
- logger.log('');
199
- logger.error('The relay identity has changed. This could indicate a man-in-the-middle attack.');
200
- logger.error('If this is expected, remove the old trust with: gssh relay untrust ' + relayUrl);
201
- return { trusted: false, reason: 'Relay identity mismatch - possible security threat' };
202
- }
203
-
204
- if (trustStatus === 'unknown') {
205
- // Unknown relay - check if explicit trust was provided or auto-trust localhost
206
- if (isLocalhost(relayUrl)) {
207
- // Localhost auto-trust
208
- console.log('[serve] Localhost relay - auto-trusting');
209
- addTrustedRelay(relayUrl, relayPublicKey, relayLabel);
210
- } else if (explicitPubkey) {
211
- // Explicit trust provided via --relay-pubkey
212
- if (explicitPubkey === relayPublicKey) {
213
- console.log('[serve] Explicit trust match - trusting relay');
214
- addTrustedRelay(relayUrl, relayPublicKey, relayLabel);
215
- } else {
216
- logger.error('Relay public key does not match --relay-pubkey');
217
- logger.error(`Expected: ${computeRelayFingerprint(explicitPubkey)}`);
218
- logger.error(`Received: ${relayFingerprint}`);
219
- return { trusted: false, reason: 'Relay public key does not match --relay-pubkey' };
220
- }
221
- } else {
222
- // Unknown remote relay - prompt for confirmation
223
- logger.log('');
224
- logger.bold('Unknown Relay');
225
- logger.log(` URL: ${relayUrl}`);
226
- logger.log(` Fingerprint: ${relayFingerprint}`);
227
- if (relayLabel) {
228
- logger.log(` Label: ${relayLabel}`);
229
- }
230
- logger.log('');
231
-
232
- // Ask for confirmation
233
- const shouldTrust = await promptConfirm('Trust this relay?');
234
-
235
- if (!shouldTrust) {
236
- logger.info('Relay not trusted, aborting connection');
237
- return { trusted: false, reason: 'User declined to trust relay' };
238
- }
239
-
240
- // Save trust
241
- addTrustedRelay(relayUrl, relayPublicKey, relayLabel);
242
- logger.success('Relay trusted and saved');
243
- }
244
- }
245
-
246
- return { trusted: true };
247
- }
248
-
249
- /**
250
- * Sign a challenge and create registration message
251
- *
252
- * @param challenge - Base64 challenge from relay
253
- * @param signingPrivateKey - Private key for signing
254
- * @param machineId - Machine ID
255
- * @param publicIdentity - Public identity info
256
- * @returns Signed message data or null on error
257
- */
258
- function signChallengeAndCreateRegistration(
259
- challenge: string,
260
- signingPrivateKey: Uint8Array,
261
- machineId: string,
262
- publicIdentity: PublicIdentity
263
- ): { challengeResponse: string; message: object } | null {
264
- try {
265
- const nonceBytes = new Uint8Array(Buffer.from(challenge, 'base64'));
266
- const signature = ed25519.sign(nonceBytes, signingPrivateKey);
267
- const challengeResponse = Buffer.from(signature).toString('base64');
268
-
269
- return {
270
- challengeResponse,
271
- message: {
272
- type: 'register_machine',
273
- machineId,
274
- signingKey: publicIdentity.signingPublicKey,
275
- keyExchangeKey: publicIdentity.keyExchangePublicKey,
276
- label: publicIdentity.label,
277
- protocolVersion: PROTOCOL_VERSION,
278
- challengeResponse,
279
- },
280
- };
281
- } catch (err) {
282
- logger.error(`Failed to sign challenge: ${err instanceof Error ? err.message : String(err)}`);
283
- return null;
284
- }
285
- }
286
-
287
- /**
288
- * Create a data message for sending to a client via relay
289
- */
290
- function createDataMessage(connectionId: string, data: Uint8Array | Buffer): string {
291
- return JSON.stringify({
292
- type: 'data',
293
- connectionId,
294
- data: Buffer.from(data).toString('base64'),
295
- });
296
- }
297
-
298
- /**
299
- * Create a send callback for a client connection
300
- */
301
- function createSendCallback(
302
- ws: WebSocket,
303
- connectionId: string
304
- ): (data: Uint8Array | Buffer) => void {
305
- return (sendData) => {
306
- ws.send(createDataMessage(connectionId, sendData));
307
- };
308
- }
309
-
310
- // ============================================================================
311
- // Cloudflared Management
312
- // ============================================================================
313
-
314
- /**
315
- * Check if cloudflared is installed
316
- */
317
- async function isCloudflaredInstalled(): Promise<boolean> {
318
- try {
319
- const proc = spawn(['which', 'cloudflared'], { stdout: 'pipe', stderr: 'pipe' });
320
- const exitCode = await proc.exited;
321
- return exitCode === 0;
322
- } catch {
323
- return false;
324
- }
325
- }
326
-
327
- /**
328
- * Start cloudflared tunnel for a subdomain
329
- *
330
- * @param subdomain - The subdomain to tunnel (e.g., 'brad' for brad.gitspace.sh)
331
- * @returns true if started successfully
332
- */
333
- async function startCloudflared(subdomain: string): Promise<boolean> {
334
- // Get tunnel token from keychain
335
- const tunnelToken = await getSecret(`TUNNEL_TOKEN_${subdomain}`);
336
- if (!tunnelToken) {
337
- logger.warning(`No tunnel token found for ${subdomain}.gitspace.sh`);
338
- logger.dim('Run: gssh host reserve ' + subdomain + ' (to get token)');
339
- return false;
340
- }
341
-
342
- // Check if cloudflared is installed
343
- if (!await isCloudflaredInstalled()) {
344
- logger.warning('cloudflared is not installed');
345
- logger.dim('Install: brew install cloudflared (macOS) or see https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');
346
- return false;
347
- }
348
-
349
- cloudflaredSubdomain = subdomain;
350
-
351
- // Start cloudflared with tunnel token via TUNNEL_TOKEN env var to avoid argv exposure
352
- logger.info(`Starting tunnel for ${subdomain}.gitspace.sh...`);
353
-
354
- try {
355
- cloudflaredProcess = spawn(['cloudflared', 'tunnel', 'run'], {
356
- env: { ...process.env, TUNNEL_TOKEN: tunnelToken },
357
- stdin: 'ignore',
358
- stdout: 'pipe',
359
- stderr: 'pipe',
360
- });
361
-
362
- // Handle cloudflared output
363
- handleCloudflaredOutput(cloudflaredProcess);
364
-
365
- // Monitor process exit
366
- cloudflaredProcess.exited.then((exitCode) => {
367
- if (exitCode !== 0 && cloudflaredSubdomain) {
368
- logger.warning(`cloudflared exited with code ${exitCode}`);
369
- handleCloudflaredCrash();
370
- }
371
- });
372
-
373
- logger.success(`Tunnel active: https://${subdomain}.gitspace.sh`);
374
- logger.dim(` Wildcard: https://*.${subdomain}.gitspace.sh`);
375
- return true;
376
- } catch (error) {
377
- logger.error(`Failed to start cloudflared: ${error instanceof Error ? error.message : String(error)}`);
378
- return false;
379
- }
380
- }
381
-
382
- /**
383
- * Handle cloudflared stdout/stderr
384
- */
385
- function handleCloudflaredOutput(proc: Subprocess): void {
386
- // Read stdout
387
- const stdout = proc.stdout;
388
- if (stdout && typeof stdout !== 'number') {
389
- (async () => {
390
- const reader = stdout.getReader();
391
- try {
392
- while (true) {
393
- const { done, value } = await reader.read();
394
- if (done) break;
395
- const text = new TextDecoder().decode(value);
396
- // Only log important messages, skip routine output
397
- if (text.includes('ERR') || text.includes('error') || text.includes('failed')) {
398
- logger.dim(`[cloudflared] ${text.trim()}`);
399
- }
400
- }
401
- } catch {
402
- // Stream closed
403
- }
404
- })();
405
- }
406
-
407
- // Read stderr
408
- const stderr = proc.stderr;
409
- if (stderr && typeof stderr !== 'number') {
410
- (async () => {
411
- const reader = stderr.getReader();
412
- try {
413
- while (true) {
414
- const { done, value } = await reader.read();
415
- if (done) break;
416
- const text = new TextDecoder().decode(value);
417
- // cloudflared logs most output to stderr
418
- if (text.includes('ERR') || text.includes('error') || text.includes('failed')) {
419
- logger.warning(`[cloudflared] ${text.trim()}`);
420
- }
421
- }
422
- } catch {
423
- // Stream closed
424
- }
425
- })();
426
- }
427
- }
428
-
429
- /**
430
- * Handle cloudflared crash and restart
431
- */
432
- function handleCloudflaredCrash(): void {
433
- if (!cloudflaredSubdomain) return;
434
-
435
- cloudflaredRestartAttempts++;
436
-
437
- if (cloudflaredRestartAttempts > MAX_CLOUDFLARED_RESTARTS) {
438
- logger.error(`cloudflared crashed ${MAX_CLOUDFLARED_RESTARTS} times, giving up`);
439
- logger.dim('Check your tunnel token or network connection');
440
- cloudflaredSubdomain = null;
441
- return;
442
- }
443
-
444
- logger.info(`Restarting cloudflared (attempt ${cloudflaredRestartAttempts}/${MAX_CLOUDFLARED_RESTARTS})...`);
445
-
446
- setTimeout(async () => {
447
- if (cloudflaredSubdomain) {
448
- await startCloudflared(cloudflaredSubdomain);
449
- }
450
- }, CLOUDFLARED_RESTART_DELAY);
451
- }
452
-
453
- /**
454
- * Stop cloudflared process
455
- */
456
- function stopCloudflared(): void {
457
- if (cloudflaredProcess) {
458
- logger.dim('Stopping cloudflared...');
459
- cloudflaredProcess.kill();
460
- cloudflaredProcess = null;
461
- cloudflaredSubdomain = null;
462
- }
463
- }
464
-
465
- // ============================================================================
466
- // Process Hosting (Serve Tunnel)
467
- // ============================================================================
468
-
469
- export interface ProcessHostEntry {
470
- hostname: string;
471
- service: string;
472
- protocol: 'http' | 'tcp';
473
- workspaceId: string;
474
- processName: string;
475
- instance: number;
476
- port: number;
477
- portName?: string;
478
- }
479
-
480
- const SERVE_CONFIG_PATH = () => join(getServeDaemonDir(), 'serve-tunnel.yml');
481
- const SERVE_REFRESH_INTERVAL_MS = 5000;
482
- const SERVE_READY_TIMEOUT_MS = 5000;
483
- const MAX_WORKSPACE_PATH_CACHE_SIZE = 256;
484
-
485
- export function buildServeIngressConfig(entries: ProcessHostEntry[]): string {
486
- const lines = ['ingress:'];
487
- for (const entry of entries) {
488
- lines.push(` - hostname: ${entry.hostname}`);
489
- lines.push(` service: ${entry.service}`);
490
- }
491
- lines.push(' - service: http_status:404');
492
- return `${lines.join('\n')}\n`;
493
- }
494
-
495
- function hashConfig(config: string): string {
496
- return createHash('sha256').update(config).digest('hex');
497
- }
498
-
499
- function findWorkspacePathById(workspaceId: string): string | null {
500
- const spacesDir = getGitspaceDir();
501
- if (!existsSync(spacesDir)) {
502
- return null;
503
- }
504
- const entries = readdirSync(spacesDir, { withFileTypes: true });
505
- for (const entry of entries) {
506
- if (!entry.isDirectory()) continue;
507
- if (entry.name === 'app') continue;
508
- const candidate = join(spacesDir, entry.name, 'workspaces', workspaceId);
509
- if (existsSync(candidate)) {
510
- return candidate;
511
- }
512
- }
513
- return null;
514
- }
515
-
516
- async function waitForCloudflaredReady(proc: Subprocess): Promise<boolean> {
517
- const result = await Promise.race([
518
- proc.exited.then((code) => ({ code })),
519
- Bun.sleep(SERVE_READY_TIMEOUT_MS).then(() => ({ code: null })),
520
- ]);
521
- return result.code === null;
522
- }
523
-
524
- class ServeProcessHostManager {
525
- private serveDomain: string;
526
- private tunnelToken: string;
527
- private process: Subprocess | null = null;
528
- private configHash: string | null = null;
529
- private registry: ProcessHostEntry[] = [];
530
- private refreshPromise: Promise<void> | null = null;
531
- private restartAttempts = 0;
532
- private retryTimer: ReturnType<typeof setTimeout> | null = null;
533
- private workspacePathCache = new Map<string, string>();
534
-
535
- constructor(options: { serveDomain: string; tunnelToken: string }) {
536
- this.serveDomain = options.serveDomain;
537
- this.tunnelToken = options.tunnelToken;
538
- }
539
-
540
- get domain(): string {
541
- return this.serveDomain;
542
- }
543
-
544
- get entries(): ProcessHostEntry[] {
545
- return [...this.registry];
546
- }
547
-
548
- get isActive(): boolean {
549
- return this.process !== null;
550
- }
551
-
552
- async refresh(): Promise<void> {
553
- if (this.refreshPromise) {
554
- return this.refreshPromise;
555
- }
556
- this.refreshPromise = this.refreshInternal().finally(() => {
557
- this.refreshPromise = null;
558
- });
559
- return this.refreshPromise;
560
- }
561
-
562
- stop(): void {
563
- if (this.retryTimer) {
564
- clearTimeout(this.retryTimer);
565
- this.retryTimer = null;
566
- }
567
- if (this.process) {
568
- this.process.kill();
569
- this.process = null;
570
- }
571
- this.workspacePathCache.clear();
572
- }
573
-
574
- private async refreshInternal(): Promise<void> {
575
- const entries = await this.collectProcessHosts();
576
- const sorted = entries.sort((a, b) => a.hostname.localeCompare(b.hostname));
577
- const config = buildServeIngressConfig(sorted);
578
- const nextHash = hashConfig(config);
579
-
580
- if (this.configHash === nextHash && this.process) {
581
- this.registry = sorted;
582
- return;
583
- }
584
-
585
- ensureServeDaemonDir();
586
- const configPath = SERVE_CONFIG_PATH();
587
- writeFileSync(configPath, config, 'utf-8');
588
-
589
- const swapped = await this.swapProcess(configPath);
590
- if (swapped) {
591
- this.registry = sorted;
592
- this.configHash = nextHash;
593
- logger.dim(`Serve tunnel updated (${sorted.length} routes)`);
594
- return;
595
- }
596
-
597
- this.handleStartupFailure();
598
- }
599
-
600
- private async collectProcessHosts(): Promise<ProcessHostEntry[]> {
601
- let sessions: Awaited<ReturnType<typeof listSessions>> = [];
602
- try {
603
- sessions = await listSessions();
604
- } catch {
605
- return [];
606
- }
607
- const configCache = new Map<string, ReturnType<typeof loadProcessesConfig>>();
608
- const entries: ProcessHostEntry[] = [];
609
- const seenWorkspaceIds = new Set<string>();
610
-
611
- for (const session of sessions) {
612
- const parsed = parseProcessSessionName(session.name);
613
- const processName = parsed?.processName;
614
- if (!processName) continue;
615
- const instance = parsed?.instance ?? 1;
616
-
617
- let workspaceRef = resolveWorkspaceRef(session.cwd);
618
- if (!workspaceRef && parsed?.workspaceId) {
619
- const cached = this.workspacePathCache.get(parsed.workspaceId);
620
- const workspacePath = cached ?? findWorkspacePathById(parsed.workspaceId);
621
- if (workspacePath) {
622
- this.setCachedWorkspacePath(parsed.workspaceId, workspacePath);
623
- workspaceRef = resolveWorkspaceRef(workspacePath);
624
- seenWorkspaceIds.add(parsed.workspaceId);
625
- }
626
- }
627
- if (!workspaceRef) continue;
628
- seenWorkspaceIds.add(workspaceRef.workspaceId);
629
- if (parsed?.workspaceId) {
630
- seenWorkspaceIds.add(parsed.workspaceId);
631
- }
632
-
633
- const config = configCache.get(workspaceRef.workspacePath) ?? loadProcessesConfig(workspaceRef.workspacePath);
634
- configCache.set(workspaceRef.workspacePath, config);
635
- const definition = config.processes.find((process) => process.name === processName);
636
- const ports = (definition?.ports ?? []).filter((port): port is ProcessPortConfig => Boolean(port));
637
-
638
- for (const port of ports) {
639
- if (!Number.isInteger(port.port) || port.port <= 0) {
640
- continue;
641
- }
642
- const trimmedPortName = port.name?.trim();
643
- const portLabel = trimmedPortName && trimmedPortName.length > 0 ? trimmedPortName : String(port.port);
644
- const hostname = buildProcessHostname(
645
- this.serveDomain,
646
- workspaceRef.workspaceId,
647
- processName,
648
- instance,
649
- portLabel
650
- );
651
- const protocol = port.protocol === 'tcp' ? 'tcp' : 'http';
652
- const service = `${protocol}://127.0.0.1:${port.port}`;
653
- entries.push({
654
- hostname,
655
- service,
656
- protocol,
657
- workspaceId: workspaceRef.workspaceId,
658
- processName,
659
- instance,
660
- port: port.port,
661
- portName: port.name,
662
- });
663
- }
664
- }
665
-
666
- const deduped = new Map<string, ProcessHostEntry>();
667
- for (const entry of entries) {
668
- if (!deduped.has(entry.hostname)) {
669
- deduped.set(entry.hostname, entry);
670
- }
671
- }
672
- this.pruneWorkspacePathCache(seenWorkspaceIds);
673
- return Array.from(deduped.values());
674
- }
675
-
676
- private async swapProcess(configPath: string): Promise<boolean> {
677
- const nextProcess = this.spawnProcess(configPath);
678
- const ready = await waitForCloudflaredReady(nextProcess);
679
- if (!ready) {
680
- nextProcess.kill();
681
- return false;
682
- }
683
-
684
- const previous = this.process;
685
- this.process = nextProcess;
686
- this.restartAttempts = 0;
687
- if (this.retryTimer) {
688
- clearTimeout(this.retryTimer);
689
- this.retryTimer = null;
690
- }
691
- if (previous) {
692
- previous.kill();
693
- }
694
- return true;
695
- }
696
-
697
- private spawnProcess(configPath: string): Subprocess {
698
- const proc = spawn(['cloudflared', 'tunnel', '--config', configPath, 'run'], {
699
- env: { ...process.env, TUNNEL_TOKEN: this.tunnelToken },
700
- stdin: 'ignore',
701
- stdout: 'pipe',
702
- stderr: 'pipe',
703
- });
704
-
705
- handleCloudflaredOutput(proc);
706
-
707
- proc.exited.then((exitCode) => {
708
- if (exitCode !== 0 && this.process === proc) {
709
- this.handleCrash();
710
- }
711
- });
712
-
713
- return proc;
714
- }
715
-
716
- private handleCrash(): void {
717
- this.process = null;
718
- this.scheduleRetry('crashed');
719
- }
720
-
721
- private handleStartupFailure(): void {
722
- this.scheduleRetry('failed to start');
723
- }
724
-
725
- private scheduleRetry(reason: 'crashed' | 'failed to start'): void {
726
- if (this.retryTimer) {
727
- return;
728
- }
729
-
730
- this.restartAttempts += 1;
731
- if (this.restartAttempts > MAX_CLOUDFLARED_RESTARTS) {
732
- logger.error(`serve tunnel ${reason} ${MAX_CLOUDFLARED_RESTARTS} times, giving up`);
733
- return;
734
- }
735
-
736
- logger.info(`Restarting serve tunnel (${reason}) (attempt ${this.restartAttempts}/${MAX_CLOUDFLARED_RESTARTS})...`);
737
- this.retryTimer = setTimeout(() => {
738
- this.retryTimer = null;
739
- void this.refresh();
740
- }, CLOUDFLARED_RESTART_DELAY);
741
- }
742
-
743
- private setCachedWorkspacePath(workspaceId: string, workspacePath: string): void {
744
- if (this.workspacePathCache.has(workspaceId)) {
745
- this.workspacePathCache.delete(workspaceId);
746
- }
747
- this.workspacePathCache.set(workspaceId, workspacePath);
748
-
749
- while (this.workspacePathCache.size > MAX_WORKSPACE_PATH_CACHE_SIZE) {
750
- const oldest = this.workspacePathCache.keys().next().value;
751
- if (!oldest) {
752
- break;
753
- }
754
- this.workspacePathCache.delete(oldest);
755
- }
756
- }
757
-
758
- private pruneWorkspacePathCache(seenWorkspaceIds: Set<string>): void {
759
- for (const key of this.workspacePathCache.keys()) {
760
- if (!seenWorkspaceIds.has(key)) {
761
- this.workspacePathCache.delete(key);
762
- }
763
- }
764
- }
765
- }
766
-
767
- async function startServeProcessHosting(hostConfig: HostConfig): Promise<ServeProcessHostManager | null> {
768
- const serveSubdomain = hostConfig.serveSubdomain ?? `${hostConfig.subdomain}.serve`;
769
- const serveDomain = `${serveSubdomain}.gitspace.sh`;
770
- const tunnelToken = await getSecret(getServeTokenKey(hostConfig.subdomain));
771
-
772
- if (!tunnelToken) {
773
- logger.warning(`No serve tunnel token found for ${serveDomain}`);
774
- logger.dim(`Run: gssh host reserve ${hostConfig.subdomain} (to get token)`);
775
- return null;
776
- }
777
-
778
- if (!await isCloudflaredInstalled()) {
779
- logger.warning('cloudflared is not installed');
780
- return null;
781
- }
782
-
783
- const manager = new ServeProcessHostManager({ serveDomain, tunnelToken });
784
- await manager.refresh();
785
- if (manager.isActive) {
786
- logger.success(`Serve tunnel active: https://${serveDomain}`);
787
- logger.dim(` Wildcard: https://*.${serveDomain}`);
788
- } else {
789
- logger.warning(`Serve tunnel failed to start for https://${serveDomain}; retrying in background`);
790
- }
791
- return manager;
792
- }
793
-
794
- function stopServeProcessHosting(
795
- manager: ServeProcessHostManager | null,
796
- timer: ReturnType<typeof setInterval> | null
797
- ): void {
798
- if (timer) {
799
- clearInterval(timer);
800
- }
801
- manager?.stop();
802
- }
803
-
804
- // ============================================================================
805
- // Serve Command
806
- // ============================================================================
807
-
808
- /**
809
- * Start the serve daemon
810
- *
811
- * @param options - Command options
812
- */
813
- export async function serve(options: {
814
- relay?: string;
815
- relayPubkey?: string;
816
- ignoreKeychainAndSkipSecrets?: boolean;
817
- } = {}): Promise<void> {
818
- // Step 1: Load machine identity
819
- if (!keypairExists()) {
820
- throw new NoIdentityError();
821
- }
822
-
823
- const password = await promptPassword('Enter password to unlock identity:');
824
- if (!password) {
825
- logger.info('Cancelled');
826
- return;
827
- }
828
-
829
- const identity = await loadKeypair(password);
830
- if (!identity) {
831
- throw new SpacesError(
832
- 'Failed to unlock identity. Check your password.',
833
- 'USER_ERROR',
834
- 1
835
- );
836
- }
837
-
838
- // Extract signing private key for challenge-response
839
- // Ed25519 secret key is 64 bytes, but ed25519.sign() expects the 32-byte seed
840
- const signingPrivateKey = identity.signing.secretKey.slice(0, 32);
841
-
842
- // Get public identity for registration
843
- const publicIdentity = getPublicKeyWithoutPassword();
844
- if (!publicIdentity) {
845
- throw new SpacesError(
846
- 'Failed to read public identity',
847
- 'SYSTEM_ERROR',
848
- 2
849
- );
850
- }
851
-
852
- // Step 2: Load access control list
853
- const accessList = new AccessControlList();
854
- const entries = readAccessList();
855
- accessList.import(entries);
856
-
857
- await initializeSecretRuntime({
858
- ignoreKeychainAndSkipSecrets: options.ignoreKeychainAndSkipSecrets,
859
- });
860
-
861
- // Step 3: Check for gitspace.sh hosting or explicit relay
862
- const hostConfig = readHostConfig();
863
- const relayUrl = options.relay; // No default - must use hosting or explicit --relay
864
-
865
- // If no hosting config and no explicit relay, error out
866
- if (!hostConfig?.subdomain && !relayUrl) {
867
- throw new SpacesError(
868
- 'No relay configured.\n\n' +
869
- 'Either set up gitspace.sh hosting:\n' +
870
- ' gssh auth login\n' +
871
- ' gssh host reserve <subdomain>\n\n' +
872
- 'Or specify a relay explicitly:\n' +
873
- ' gssh serve start --relay ws://localhost:4480/ws',
874
- 'USER_ERROR'
875
- );
876
- }
877
-
878
- // Display info
879
- const machineIdentity = readMachineIdentity();
880
- const machineId = machineIdentity?.machineId ?? identity.id;
881
-
882
- logger.log('');
883
- logger.bold('Machine Identity:');
884
- logger.log(` ID: ${machineId}`);
885
- if (relayUrl) {
886
- logger.log(` Relay: ${relayUrl}`);
887
- }
888
- logger.log('');
889
- logger.dim(`Access list: ${entries.length} authorized ${entries.length === 1 ? 'client' : 'clients'}`);
890
- logger.log('');
891
- let localRelayServer: ReturnType<typeof createRelayServer> | null = null;
892
- let localRelayIdentity: ReturnType<typeof generateRelayIdentity> | null = null;
893
- let processHostManager: ServeProcessHostManager | null = null;
894
- let processHostRefreshTimer: ReturnType<typeof setInterval> | null = null;
895
-
896
- if (hostConfig?.subdomain) {
897
- logger.bold('gitspace.sh Hosting:');
898
-
899
- // Generate an ephemeral identity for local relay
900
- localRelayIdentity = generateRelayIdentity('local-relay');
901
-
902
- // Start local relay server with this machine pre-authorized
903
- try {
904
- localRelayServer = createRelayServer({
905
- port: LOCAL_RELAY_PORT,
906
- bind: '127.0.0.1', // Only listen locally, cloudflared handles external
907
- identity: localRelayIdentity,
908
- preAuthorizedMachines: [publicIdentity.signingPublicKey],
909
- });
910
- logger.success(`Local relay started on port ${LOCAL_RELAY_PORT}`);
911
- } catch (error) {
912
- logger.error(`Failed to start local relay: ${error instanceof Error ? error.message : String(error)}`);
913
- throw new SpacesError('Failed to start local relay server', 'SYSTEM_ERROR', 2);
914
- }
915
-
916
- // Start cloudflared tunnel
917
- const tunnelStarted = await startCloudflared(hostConfig.subdomain);
918
- if (tunnelStarted) {
919
- logger.log('');
920
- logger.dim(`Web terminal: https://${hostConfig.subdomain}.gitspace.sh`);
921
- logger.log('');
922
- } else {
923
- // Stop local relay if tunnel failed
924
- localRelayServer.stop();
925
- localRelayServer = null;
926
- logger.dim(' Hosting not active (tunnel token missing)');
927
- logger.log('');
928
- }
929
-
930
- processHostManager = await startServeProcessHosting(hostConfig);
931
- if (processHostManager) {
932
- processHostRefreshTimer = setInterval(() => {
933
- void processHostManager?.refresh();
934
- }, SERVE_REFRESH_INTERVAL_MS);
935
- }
936
- }
937
-
938
- const remoteSessionOptions = processHostManager
939
- ? {
940
- processHostDomain: processHostManager.domain,
941
- onProcessesChanged: () => processHostManager?.refresh(),
942
- }
943
- : undefined;
944
-
945
- // If gitspace.sh hosting is active, connect to local relay instead of external
946
- if (localRelayServer && localRelayIdentity) {
947
- // For local relay, we auto-authorize this machine (it's the same machine running both)
948
- // The relay identity was generated above; machine authenticates via challenge-response
949
- const localRelayUrl = `ws://127.0.0.1:${LOCAL_RELAY_PORT}/ws`;
950
-
951
- // Step 4: Create session manager for local relay
952
- const sessionManager = new ClientSessionManager({
953
- relay: localRelayUrl,
954
- identity,
955
- accessList,
956
- remoteSessionOptions,
957
- });
958
-
959
- // Initialize session manager (starts tmux-lite server)
960
- await sessionManager.initialize();
961
-
962
- // Set up event handling
963
- const eventHandler = createEventHandler(sessionManager, true);
964
- sessionManager.onEvent(eventHandler);
965
-
966
- // Connect to local relay (no token needed - uses challenge-response auth)
967
- logger.info('Registering with local relay...');
968
- try {
969
- await connectToRelay(localRelayUrl, machineId, publicIdentity, sessionManager, eventHandler, accessList, signingPrivateKey);
970
- } catch (error) {
971
- logger.error(`Failed to register with local relay: ${error instanceof Error ? error.message : String(error)}`);
972
- localRelayServer.stop();
973
- stopCloudflared();
974
- throw new SpacesError('Failed to register with local relay', 'SYSTEM_ERROR', 2);
975
- }
976
-
977
- logger.log('');
978
- logger.dim('Waiting for connections via gitspace.sh... (Ctrl+C to stop)');
979
- logger.log('');
980
-
981
- // Set up shutdown handler for gitspace.sh mode
982
- const shutdown = () => {
983
- logger.log('');
984
- logger.info('Shutting down...');
985
- stopCloudflared();
986
- stopServeProcessHosting(processHostManager, processHostRefreshTimer);
987
- sessionManager.cleanup();
988
- localRelayServer?.stop();
989
- process.exit(0);
990
- };
991
- process.on('SIGINT', shutdown);
992
- process.on('SIGTERM', shutdown);
993
-
994
- // Keep process alive
995
- await new Promise(() => {});
996
- return;
997
- }
998
-
999
- // If we get here, relayUrl must be defined (checked earlier)
1000
- if (!relayUrl) {
1001
- throw new SpacesError('No relay URL configured', 'USER_ERROR');
1002
- }
1003
-
1004
- // Step 4: Create session manager
1005
- const sessionManager = new ClientSessionManager({
1006
- relay: relayUrl,
1007
- identity,
1008
- accessList,
1009
- remoteSessionOptions,
1010
- });
1011
-
1012
- // Initialize session manager (starts tmux-lite server)
1013
- await sessionManager.initialize();
1014
-
1015
- // Set up event handling
1016
- const eventHandler = createEventHandler(sessionManager, false);
1017
- sessionManager.onEvent(eventHandler);
1018
-
1019
- // Step 5: Connect to relay
1020
- logger.info('Connecting to relay...');
1021
-
1022
- try {
1023
- await connectToRelay(relayUrl, machineId, publicIdentity, sessionManager, eventHandler, accessList, signingPrivateKey, options.relayPubkey);
1024
-
1025
- // Save relay config for share command
1026
- writeRelayConfig({
1027
- relayUrl,
1028
- machineId,
1029
- savedAt: Date.now(),
1030
- });
1031
- logger.dim('Relay config saved');
1032
- } catch (error) {
1033
- throw new SpacesError(
1034
- `Failed to connect to relay: ${error instanceof Error ? error.message : String(error)}`,
1035
- 'SYSTEM_ERROR',
1036
- 2
1037
- );
1038
- }
1039
-
1040
- logger.log('');
1041
- logger.dim('Waiting for connections... (Ctrl+C to stop)');
1042
- logger.log('');
1043
-
1044
- // Step 6: Handle shutdown
1045
- setupShutdownHandlers(sessionManager, false, () => stopServeProcessHosting(processHostManager, processHostRefreshTimer));
1046
-
1047
- // Keep process alive
1048
- await new Promise(() => {
1049
- // Never resolves - process stays alive until shutdown
1050
- });
1051
- }
1052
-
1053
- /**
1054
- * Public identity type for registration
1055
- */
1056
- interface PublicIdentity {
1057
- id: string;
1058
- signingPublicKey: string;
1059
- keyExchangePublicKey: string;
1060
- label?: string;
1061
- }
1062
-
1063
- /**
1064
- * Connect to relay WebSocket with protocol message support
1065
- */
1066
- async function connectToRelay(
1067
- relayUrl: string,
1068
- machineId: string,
1069
- publicIdentity: PublicIdentity,
1070
- sessionManager: ClientSessionManager,
1071
- eventHandler: ServeEventHandler,
1072
- accessList: AccessControlList,
1073
- signingPrivateKey?: Uint8Array,
1074
- relayPubkey?: string
1075
- ): Promise<void> {
1076
- // Build WebSocket URL with machine role (no token in URL - auth via challenge-response)
1077
- const url = new URL(relayUrl);
1078
- url.searchParams.set('role', 'machine');
1079
-
1080
- // Track current entries for diffing
1081
- let currentEntries = readAccessList();
1082
- let accessWatcher: ReturnType<typeof watch> | null = null;
1083
-
1084
- return new Promise((resolve, reject) => {
1085
- let reconnectAttempts = 0;
1086
- const maxReconnectAttempts = 10;
1087
- const baseReconnectDelay = 1000;
1088
- const maxReconnectDelay = 30000;
1089
- let resolved = false;
1090
- let currentWs: WebSocket | null = null;
1091
-
1092
- // Decode public key for message signing
1093
- const signingPublicKey = signingPrivateKey
1094
- ? new Uint8Array(Buffer.from(publicIdentity.signingPublicKey, 'base64'))
1095
- : null;
1096
-
1097
- // Helper to sign and send a message
1098
- const signAndSend = (ws: WebSocket, msg: object) => {
1099
- if (signingPrivateKey && signingPublicKey) {
1100
- const signed = signMessage(msg, signingPrivateKey, signingPublicKey);
1101
- ws.send(JSON.stringify(signed));
1102
- } else {
1103
- ws.send(JSON.stringify(msg));
1104
- }
1105
- };
1106
-
1107
- // Watch access list file for changes
1108
- const startAccessWatcher = () => {
1109
- const accessPath = getAccessListPath();
1110
-
1111
- // Create empty access list if it doesn't exist (watcher requires file to exist)
1112
- if (!existsSync(accessPath)) {
1113
- writeFileSync(accessPath, '[]', 'utf-8');
1114
- }
1115
-
1116
- // Debounce to avoid multiple triggers
1117
- let debounceTimeout: ReturnType<typeof setTimeout> | null = null;
1118
-
1119
- accessWatcher = watch(accessPath, (eventType) => {
1120
- if (eventType !== 'change') return;
1121
-
1122
- // Debounce
1123
- if (debounceTimeout) clearTimeout(debounceTimeout);
1124
- debounceTimeout = setTimeout(() => {
1125
- syncAccessList();
1126
- }, 100);
1127
- });
1128
-
1129
- logger.dim('Watching access list for changes');
1130
- };
1131
-
1132
- // Sync access list changes to relay
1133
- const syncAccessList = () => {
1134
- if (!currentWs || currentWs.readyState !== WebSocket.OPEN) return;
1135
-
1136
- try {
1137
- const newEntries = readAccessList();
1138
-
1139
- // Find added entries
1140
- const added = newEntries.filter(
1141
- (newEntry) => !currentEntries.find((e) => e.identityId === newEntry.identityId)
1142
- );
1143
-
1144
- // Find removed entries
1145
- const removed = currentEntries.filter(
1146
- (oldEntry) => !newEntries.find((e) => e.identityId === oldEntry.identityId)
1147
- );
1148
-
1149
- // Send authorize messages for new entries (signed)
1150
- for (const entry of added) {
1151
- // Validate entry before sending - skip entries with missing keys
1152
- if (!isValidAccessEntry(entry)) {
1153
- continue;
1154
- }
1155
-
1156
- signAndSend(currentWs, {
1157
- type: 'authorize_client',
1158
- machineId,
1159
- clientIdentityId: entry.identityId,
1160
- signingKey: entry.signingPublicKey,
1161
- keyExchangeKey: entry.keyExchangePublicKey,
1162
- accessType: entry.accessType,
1163
- sessionId: entry.sessionId,
1164
- });
1165
- logger.success(`Access granted: ${entry.label || entry.identityId.substring(0, 12)}...`);
1166
-
1167
- // Also update local access list
1168
- accessList.addEntry({
1169
- id: entry.identityId,
1170
- signingPublicKey: entry.signingPublicKey,
1171
- keyExchangePublicKey: entry.keyExchangePublicKey,
1172
- }, entry.accessType, entry.sessionId);
1173
- }
1174
-
1175
- // Send revoke messages for removed entries (signed)
1176
- for (const entry of removed) {
1177
- signAndSend(currentWs, {
1178
- type: 'revoke_client',
1179
- machineId,
1180
- clientIdentityId: entry.identityId,
1181
- });
1182
- logger.warning(`Access revoked: ${entry.label || entry.identityId.substring(0, 12)}...`);
1183
-
1184
- // Also update local access list
1185
- accessList.removeEntry(entry.identityId);
1186
- }
1187
-
1188
- // Update current entries
1189
- currentEntries = newEntries;
1190
- } catch (error) {
1191
- logger.error(`Failed to sync access list: ${error instanceof Error ? error.message : String(error)}`);
1192
- }
1193
- };
1194
-
1195
- const connect = () => {
1196
- console.log(`[serve] Connecting to relay: ${url.toString()}`);
1197
- const ws = new WebSocket(url.toString());
1198
- ws.binaryType = 'arraybuffer';
1199
- currentWs = ws;
1200
-
1201
- ws.onopen = () => {
1202
- console.log('[serve] WebSocket connected, waiting for relay identity...');
1203
- reconnectAttempts = 0;
1204
- // Don't send register_machine yet - wait for relay_identity message
1205
- };
1206
-
1207
- ws.onclose = (event) => {
1208
- console.log(`[serve] WebSocket closed: code=${event.code} reason=${event.reason || 'none'}`);
1209
- eventHandler({
1210
- type: 'relay_disconnected',
1211
- code: event.code,
1212
- reason: event.reason || 'Connection closed',
1213
- });
1214
-
1215
- // Clear relay config on disconnect
1216
- clearRelayConfig();
1217
-
1218
- // Attempt reconnection
1219
- if (reconnectAttempts < maxReconnectAttempts) {
1220
- reconnectAttempts++;
1221
- const delay = Math.min(
1222
- baseReconnectDelay * Math.pow(2, reconnectAttempts - 1) + Math.random() * 1000,
1223
- maxReconnectDelay
1224
- );
1225
- eventHandler({ type: 'relay_reconnecting', attempt: reconnectAttempts });
1226
- setTimeout(connect, delay);
1227
- }
1228
- };
1229
-
1230
- ws.onerror = (err) => {
1231
- console.log('[serve] WebSocket error:', err);
1232
- // Only reject on initial connection
1233
- if (!resolved && reconnectAttempts === 0) {
1234
- reject(new Error('WebSocket connection failed'));
1235
- }
1236
- };
1237
-
1238
- ws.onmessage = async (event) => {
1239
- try {
1240
- // Parse message
1241
- const data = event.data;
1242
- let msg: any;
1243
-
1244
- if (typeof data === 'string') {
1245
- msg = JSON.parse(data);
1246
- } else {
1247
- const str = new TextDecoder().decode(data as ArrayBuffer);
1248
- try {
1249
- msg = JSON.parse(str);
1250
- } catch {
1251
- logger.warning('Received binary data without JSON envelope');
1252
- return;
1253
- }
1254
- }
1255
-
1256
- // Handle protocol messages
1257
- switch (msg.type) {
1258
- case 'relay_identity': {
1259
- // Relay is identifying itself and providing a challenge
1260
- const { publicKey: relayPublicKey, fingerprint: relayFingerprint, label: relayLabel, challenge } = msg;
1261
-
1262
- console.log(`[serve] Received relay identity: ${relayFingerprint}${relayLabel ? ` (${relayLabel})` : ''}`);
1263
-
1264
- // Step 1: Verify relay trust
1265
- const trustResult = await verifyRelayTrust(
1266
- relayUrl,
1267
- relayPublicKey,
1268
- relayFingerprint,
1269
- relayLabel,
1270
- relayPubkey
1271
- );
1272
-
1273
- if (!trustResult.trusted) {
1274
- ws.close(1008, trustResult.reason);
1275
- if (!resolved) {
1276
- reject(new Error(trustResult.reason));
1277
- }
1278
- return;
1279
- }
1280
-
1281
- // Step 2: Sign the challenge and send register_machine
1282
- if (!signingPrivateKey) {
1283
- logger.error('No signing key available for challenge-response');
1284
- ws.close(1008, 'No signing key');
1285
- return;
1286
- }
1287
-
1288
- const registration = signChallengeAndCreateRegistration(
1289
- challenge,
1290
- signingPrivateKey,
1291
- machineId,
1292
- publicIdentity
1293
- );
1294
-
1295
- if (!registration) {
1296
- ws.close(1008, 'Challenge signing failed');
1297
- return;
1298
- }
1299
-
1300
- signAndSend(ws, registration.message);
1301
- console.log('[serve] Sent register_machine with challenge response');
1302
- break;
1303
- }
1304
-
1305
- case 'registered':
1306
- // Machine registered successfully
1307
- eventHandler({ type: 'relay_connected' });
1308
-
1309
- // Send initial access list entries to relay (signed)
1310
- for (const entry of currentEntries) {
1311
- // Validate entry before sending - skip entries with missing keys
1312
- if (!isValidAccessEntry(entry)) {
1313
- continue;
1314
- }
1315
-
1316
- signAndSend(ws, {
1317
- type: 'authorize_client',
1318
- machineId,
1319
- clientIdentityId: entry.identityId,
1320
- signingKey: entry.signingPublicKey,
1321
- keyExchangeKey: entry.keyExchangePublicKey,
1322
- accessType: entry.accessType,
1323
- sessionId: entry.sessionId,
1324
- });
1325
- logger.dim(`Synced access: ${entry.label || entry.identityId.substring(0, 12)}...`);
1326
- }
1327
-
1328
- // Start watching access list for changes
1329
- if (!accessWatcher) {
1330
- startAccessWatcher();
1331
- }
1332
-
1333
- // Register access command handler for CLI commands
1334
- setAccessCommandHandler({
1335
- async addAccess(entry) {
1336
- if (!currentWs || currentWs.readyState !== WebSocket.OPEN) {
1337
- return { success: false, error: 'Not connected to relay' };
1338
- }
1339
- try {
1340
- signAndSend(currentWs, {
1341
- type: 'add_global_access',
1342
- clientIdentityId: entry.clientIdentityId,
1343
- signingKey: entry.signingKey,
1344
- keyExchangeKey: entry.keyExchangeKey,
1345
- label: entry.label,
1346
- accessType: entry.accessType,
1347
- sessionId: entry.sessionId,
1348
- });
1349
- return { success: true };
1350
- } catch (err) {
1351
- return { success: false, error: err instanceof Error ? err.message : 'Send failed' };
1352
- }
1353
- },
1354
- async removeAccess(clientIdentityId) {
1355
- if (!currentWs || currentWs.readyState !== WebSocket.OPEN) {
1356
- return { success: false, error: 'Not connected to relay' };
1357
- }
1358
- try {
1359
- signAndSend(currentWs, {
1360
- type: 'remove_global_access',
1361
- clientIdentityId,
1362
- });
1363
- return { success: true };
1364
- } catch (err) {
1365
- return { success: false, error: err instanceof Error ? err.message : 'Send failed' };
1366
- }
1367
- },
1368
- });
1369
-
1370
- if (!resolved) {
1371
- resolved = true;
1372
- resolve();
1373
- }
1374
- break;
1375
-
1376
- case 'client_connected':
1377
- // New client connection
1378
- sessionManager.handleConnect(msg.connectionId);
1379
- // Set up send callback for this connection
1380
- sessionManager.setSendCallback(msg.connectionId, createSendCallback(ws, msg.connectionId));
1381
- break;
1382
-
1383
- case 'client_disconnected':
1384
- // Client disconnected
1385
- sessionManager.handleDisconnect(msg.connectionId, msg.reason || 'Client disconnected');
1386
- break;
1387
-
1388
- case 'data':
1389
- // Data from client - connectionId tells us which client
1390
- if (msg.data && msg.connectionId) {
1391
- const messageData = Buffer.from(msg.data, 'base64');
1392
-
1393
- // Ensure send callback is set
1394
- if (!sessionManager.getSession(msg.connectionId)) {
1395
- sessionManager.setSendCallback(msg.connectionId, createSendCallback(ws, msg.connectionId));
1396
- }
1397
-
1398
- const response = await sessionManager.handleMessage(
1399
- msg.connectionId,
1400
- messageData
1401
- );
1402
-
1403
- if (response) {
1404
- ws.send(createDataMessage(msg.connectionId, response));
1405
- }
1406
- }
1407
- break;
1408
-
1409
- case 'error':
1410
- logger.error(`Relay error: ${msg.message} (${msg.code})`);
1411
- if (!resolved) {
1412
- reject(new Error(msg.message));
1413
- }
1414
- break;
1415
-
1416
- case 'access_list':
1417
- // Full access list from relay - sync to local access list
1418
- logger.dim(`Received ${msg.entries?.length || 0} access entries from relay`);
1419
- if (msg.entries && Array.isArray(msg.entries)) {
1420
- for (const entry of msg.entries) {
1421
- accessList.addEntry({
1422
- id: entry.clientIdentityId,
1423
- signingPublicKey: entry.signingKey,
1424
- keyExchangePublicKey: entry.keyExchangeKey,
1425
- }, entry.accessType === 'full' ? 'full' : 'session-invite', entry.sessionId);
1426
- }
1427
- }
1428
- break;
1429
-
1430
- case 'access_update':
1431
- // Incremental access update from relay
1432
- if (msg.added && Array.isArray(msg.added)) {
1433
- for (const entry of msg.added) {
1434
- accessList.addEntry({
1435
- id: entry.clientIdentityId,
1436
- signingPublicKey: entry.signingKey,
1437
- keyExchangePublicKey: entry.keyExchangeKey,
1438
- }, entry.accessType === 'full' ? 'full' : 'session-invite', entry.sessionId);
1439
- logger.success(`Access granted (from relay): ${entry.label || entry.clientIdentityId.substring(0, 12)}...`);
1440
- }
1441
- }
1442
- if (msg.removed && Array.isArray(msg.removed)) {
1443
- for (const clientId of msg.removed) {
1444
- accessList.removeEntry(clientId);
1445
- logger.warning(`Access revoked (from relay): ${clientId.substring(0, 12)}...`);
1446
- }
1447
- }
1448
- break;
1449
-
1450
- case 'client_authorized':
1451
- // Acknowledgment that client authorization was registered with relay
1452
- // No action needed - the authorization was already applied locally
1453
- break;
1454
-
1455
- case 'client_revoked':
1456
- // Acknowledgment that client revocation was registered with relay
1457
- // No action needed - the revocation was already applied locally
1458
- break;
1459
-
1460
- default:
1461
- logger.dim(`Unknown message type: ${msg.type}`);
1462
- }
1463
- } catch (error) {
1464
- logger.error(`Message handling error: ${error instanceof Error ? error.message : String(error)}`);
1465
- }
1466
- };
1467
- };
1468
-
1469
- connect();
1470
- });
1471
- }
1472
-
1473
- /**
1474
- * Update session display
1475
- */
1476
- function updateSessionDisplay(sessionManager: ClientSessionManager): void {
1477
- const count = sessionManager.establishedSessionCount;
1478
- if (count > 0) {
1479
- logger.dim(`Active sessions: ${count}`);
1480
- }
1481
- }
1482
-
1483
- /**
1484
- * Set up shutdown handlers
1485
- */
1486
- function setupShutdownHandlers(
1487
- sessionManager: ClientSessionManager,
1488
- isDaemon: boolean = false,
1489
- cleanup?: () => void
1490
- ): void {
1491
- const shutdown = () => {
1492
- logger.log('');
1493
- logger.info('Shutting down...');
1494
-
1495
- // Stop cloudflared if running
1496
- stopCloudflared();
1497
- cleanup?.();
1498
-
1499
- clearRelayConfig();
1500
- sessionManager.cleanup();
1501
-
1502
- // Clean up daemon files if in daemon mode
1503
- if (isDaemon) {
1504
- stopStatusServer();
1505
- cleanupServeFiles();
1506
- }
1507
-
1508
- process.exit(0);
1509
- };
1510
-
1511
- process.on('SIGINT', shutdown);
1512
- process.on('SIGTERM', shutdown);
1513
- }
1514
-
1515
- // ============================================================================
1516
- // Daemon Commands
1517
- // ============================================================================
1518
-
1519
- /**
1520
- * Format uptime in human-readable format
1521
- */
1522
- function formatUptime(seconds: number): string {
1523
- if (seconds < 60) return `${seconds}s`;
1524
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
1525
- const hours = Math.floor(seconds / 3600);
1526
- const mins = Math.floor((seconds % 3600) / 60);
1527
- return `${hours}h ${mins}m`;
1528
- }
1529
-
1530
- /**
1531
- * Start serve daemon
1532
- */
1533
- export async function serveStart(options: {
1534
- relay?: string;
1535
- relayPubkey?: string;
1536
- passwordStdin?: boolean;
1537
- foreground?: boolean;
1538
- ignoreKeychainAndSkipSecrets?: boolean;
1539
- } = {}): Promise<void> {
1540
- // Check if already running
1541
- if (isServeRunning()) {
1542
- const pid = getServePid();
1543
- logger.info(`serve daemon already running${pid ? ` (pid ${pid})` : ''}`);
1544
- return;
1545
- }
1546
-
1547
- // Load identity (need password)
1548
- if (!keypairExists()) {
1549
- throw new NoIdentityError();
1550
- }
1551
-
1552
- let password: string | null = null;
1553
-
1554
- if (options.passwordStdin) {
1555
- // Read password from stdin
1556
- const reader = process.stdin;
1557
- const chunks: Buffer[] = [];
1558
-
1559
- const onData = (chunk: Buffer) => chunks.push(chunk);
1560
- reader.on('data', onData);
1561
-
1562
- await new Promise<void>((resolve, reject) => {
1563
- const timeoutId = setTimeout(() => reject(new Error('Timeout reading password from stdin')), 10000);
1564
- const onEnd = () => {
1565
- clearTimeout(timeoutId);
1566
- resolve();
1567
- };
1568
- const onError = (err: Error) => {
1569
- clearTimeout(timeoutId);
1570
- reject(err);
1571
- };
1572
- reader.once('end', onEnd);
1573
- reader.once('error', onError);
1574
- });
1575
-
1576
- // Clean up stdin to allow process to exit
1577
- reader.removeListener('data', onData);
1578
- reader.pause();
1579
-
1580
- password = Buffer.concat(chunks).toString().trim();
1581
- if (!password) {
1582
- throw new SpacesError('No password provided via stdin', 'USER_ERROR', 1);
1583
- }
1584
- } else {
1585
- // Interactive prompt
1586
- password = await promptPassword('Enter password to unlock identity:');
1587
- if (!password) {
1588
- logger.info('Cancelled');
1589
- return;
1590
- }
1591
- }
1592
-
1593
- // Validate password by loading keypair
1594
- const identity = await loadKeypair(password);
1595
- if (!identity) {
1596
- throw new SpacesError(
1597
- 'Failed to unlock identity. Check your password.',
1598
- 'USER_ERROR',
1599
- 1
1600
- );
1601
- }
1602
-
1603
- // Extract signing private key for challenge-response
1604
- const signingPrivateKey = identity.signing.secretKey.slice(0, 32);
1605
-
1606
- // If not foreground mode, fork to background
1607
- if (!options.foreground) {
1608
- logger.log('Starting serve daemon...');
1609
-
1610
- // Build args for background process
1611
- // Detect if we're running as a compiled binary vs dev mode
1612
- const isCompiled = !process.execPath.endsWith('bun');
1613
-
1614
- const serveArgs = ['serve', 'start', '--foreground'];
1615
- if (options.relay) serveArgs.push('--relay', options.relay);
1616
- if (options.relayPubkey) serveArgs.push('--relay-pubkey', options.relayPubkey);
1617
- if (options.ignoreKeychainAndSkipSecrets) {
1618
- serveArgs.push('--ignore-keychain-and-skip-secrets');
1619
- }
1620
- serveArgs.push('--password-stdin');
1621
-
1622
- // Build command: compiled binary runs directly, dev mode uses bun
1623
- const cmd = isCompiled
1624
- ? [process.execPath, ...serveArgs]
1625
- : ['bun', process.argv[1], ...serveArgs];
1626
-
1627
- // Write output to log file for debugging
1628
- const logFile = getServeLogFile();
1629
- ensureServeDaemonDir();
1630
-
1631
- // Truncate log file at start
1632
- await Bun.write(logFile, `[${new Date().toISOString()}] Starting serve daemon...\n`);
1633
-
1634
- const child = spawn({
1635
- cmd,
1636
- stdin: 'pipe',
1637
- stdout: Bun.file(logFile),
1638
- stderr: Bun.file(logFile),
1639
- env: process.env,
1640
- });
1641
-
1642
- // Send password via stdin
1643
- child.stdin.write(password);
1644
- child.stdin.end();
1645
-
1646
- // Wait a bit for process to start
1647
- await Bun.sleep(1000);
1648
-
1649
- // Check if it started
1650
- if (isServeRunning()) {
1651
- const pid = getServePid();
1652
- logger.success(`serve daemon started${pid ? ` (pid ${pid})` : ''}`);
1653
- // Force exit since inquirer prompts may keep event loop alive
1654
- process.exit(0);
1655
- } else {
1656
- // Read log file for error message
1657
- const logContent = await Bun.file(logFile).text();
1658
- logger.error('Daemon log:');
1659
- logger.log(logContent);
1660
- throw new SpacesError('Failed to start serve daemon. Check log above for details.', 'SYSTEM_ERROR', 2);
1661
- }
1662
- }
1663
-
1664
- // Foreground/daemon mode - write PID and start status server
1665
- writeServePid(process.pid);
1666
- startStatusServer();
1667
-
1668
- // Get public identity for registration
1669
- const publicIdentity = getPublicKeyWithoutPassword();
1670
- if (!publicIdentity) {
1671
- cleanupServeFiles();
1672
- throw new SpacesError('Failed to read public identity', 'SYSTEM_ERROR', 2);
1673
- }
1674
-
1675
- // Load access control list
1676
- const accessList = new AccessControlList();
1677
- const entries = readAccessList();
1678
- accessList.import(entries);
1679
-
1680
- try {
1681
- await initializeSecretRuntime({
1682
- ignoreKeychainAndSkipSecrets: options.ignoreKeychainAndSkipSecrets,
1683
- });
1684
- } catch (error) {
1685
- stopStatusServer();
1686
- cleanupServeFiles();
1687
- throw error;
1688
- }
1689
-
1690
- // Get config
1691
- const machineIdentity = readMachineIdentity();
1692
- const machineId = machineIdentity?.machineId ?? identity.id;
1693
-
1694
- // Check for gitspace.sh hosting
1695
- const hostConfig = readHostConfig();
1696
- const relayUrl = options.relay; // No default - must use hosting or explicit --relay
1697
-
1698
- // If no hosting config and no explicit relay, error out
1699
- if (!hostConfig?.subdomain && !relayUrl) {
1700
- cleanupServeFiles();
1701
- throw new SpacesError(
1702
- 'No relay configured.\n\n' +
1703
- 'Either set up gitspace.sh hosting:\n' +
1704
- ' gssh auth login\n' +
1705
- ' gssh host reserve <subdomain>\n\n' +
1706
- 'Or specify a relay explicitly:\n' +
1707
- ' gssh serve start --relay ws://localhost:4480/ws',
1708
- 'USER_ERROR'
1709
- );
1710
- }
1711
-
1712
- let localRelayServer: ReturnType<typeof createRelayServer> | null = null;
1713
- let localRelayIdentity: ReturnType<typeof generateRelayIdentity> | null = null;
1714
- let effectiveRelayUrl = relayUrl || '';
1715
- let processHostManager: ServeProcessHostManager | null = null;
1716
- let processHostRefreshTimer: ReturnType<typeof setInterval> | null = null;
1717
-
1718
- // Initialize daemon state
1719
- setDaemonState({
1720
- version: PACKAGE_VERSION,
1721
- startTime: Date.now(),
1722
- relay: {
1723
- url: effectiveRelayUrl,
1724
- status: 'connecting',
1725
- },
1726
- clients: 0,
1727
- hosting: hostConfig?.subdomain ? {
1728
- subdomain: hostConfig.subdomain,
1729
- tunnelActive: false,
1730
- } : undefined,
1731
- });
1732
-
1733
- if (hostConfig?.subdomain) {
1734
- // Generate an ephemeral identity for local relay
1735
- localRelayIdentity = generateRelayIdentity('local-relay');
1736
-
1737
- // Start local relay server with this machine pre-authorized
1738
- try {
1739
- localRelayServer = createRelayServer({
1740
- port: LOCAL_RELAY_PORT,
1741
- bind: '127.0.0.1',
1742
- identity: localRelayIdentity,
1743
- preAuthorizedMachines: [publicIdentity.signingPublicKey],
1744
- });
1745
- logger.success(`Local relay started on port ${LOCAL_RELAY_PORT}`);
1746
- } catch (error) {
1747
- cleanupServeFiles();
1748
- throw new SpacesError('Failed to start local relay server', 'SYSTEM_ERROR', 2);
1749
- }
1750
-
1751
- // Start cloudflared tunnel
1752
- const tunnelStarted = await startCloudflared(hostConfig.subdomain);
1753
- if (tunnelStarted) {
1754
- updateDaemonState({
1755
- hosting: {
1756
- subdomain: hostConfig.subdomain,
1757
- tunnelActive: true,
1758
- },
1759
- });
1760
- }
1761
-
1762
- processHostManager = await startServeProcessHosting(hostConfig);
1763
- if (processHostManager) {
1764
- processHostRefreshTimer = setInterval(() => {
1765
- void processHostManager?.refresh();
1766
- }, SERVE_REFRESH_INTERVAL_MS);
1767
- }
1768
-
1769
- // Use local relay (machine will authenticate via challenge-response)
1770
- effectiveRelayUrl = `ws://127.0.0.1:${LOCAL_RELAY_PORT}/ws`;
1771
- }
1772
-
1773
- const remoteSessionOptions = processHostManager
1774
- ? {
1775
- processHostDomain: processHostManager.domain,
1776
- onProcessesChanged: () => processHostManager?.refresh(),
1777
- }
1778
- : undefined;
1779
-
1780
- // Create session manager
1781
- const sessionManager = new ClientSessionManager({
1782
- relay: effectiveRelayUrl,
1783
- identity,
1784
- accessList,
1785
- remoteSessionOptions,
1786
- });
1787
-
1788
- // Initialize session manager (starts tmux-lite server)
1789
- await sessionManager.initialize();
1790
-
1791
- // Event handler - update daemon state
1792
- const eventHandler: ServeEventHandler = (event) => {
1793
- switch (event.type) {
1794
- case 'relay_connected':
1795
- updateDaemonState({ relay: { url: effectiveRelayUrl, status: 'connected' } });
1796
- break;
1797
- case 'relay_disconnected':
1798
- updateDaemonState({ relay: { url: effectiveRelayUrl, status: 'disconnected' } });
1799
- break;
1800
- case 'relay_reconnecting':
1801
- updateDaemonState({ relay: { url: effectiveRelayUrl, status: 'reconnecting' } });
1802
- break;
1803
- case 'client_authenticated':
1804
- case 'client_disconnected':
1805
- updateDaemonState({ clients: sessionManager.establishedSessionCount });
1806
- break;
1807
- }
1808
- };
1809
-
1810
- sessionManager.onEvent(eventHandler);
1811
-
1812
- // Connect to relay
1813
- try {
1814
- await connectToRelay(effectiveRelayUrl, machineId, publicIdentity, sessionManager, eventHandler, accessList, signingPrivateKey, options.relayPubkey);
1815
- updateDaemonState({ relay: { url: effectiveRelayUrl, status: 'connected' } });
1816
- } catch (error) {
1817
- localRelayServer?.stop();
1818
- stopCloudflared();
1819
- cleanupServeFiles();
1820
- throw new SpacesError(
1821
- `Failed to connect to relay: ${error instanceof Error ? error.message : String(error)}`,
1822
- 'SYSTEM_ERROR',
1823
- 2
1824
- );
1825
- }
1826
-
1827
- // Save relay config for share/access commands
1828
- writeRelayConfig({
1829
- relayUrl: effectiveRelayUrl,
1830
- machineId,
1831
- savedAt: Date.now(),
1832
- });
1833
-
1834
- // Set up shutdown handlers with daemon cleanup
1835
- setupShutdownHandlers(sessionManager, true, () => stopServeProcessHosting(processHostManager, processHostRefreshTimer));
1836
-
1837
- // Keep process alive
1838
- await new Promise(() => {});
1839
- }
1840
-
1841
- /**
1842
- * Stop serve daemon
1843
- */
1844
- export async function serveStop(): Promise<void> {
1845
- if (!isServeRunning()) {
1846
- logger.info('serve daemon not running');
1847
- return;
1848
- }
1849
-
1850
- logger.log('Stopping serve daemon...');
1851
-
1852
- // Try graceful shutdown via socket first
1853
- const success = await sendShutdownCommand();
1854
-
1855
- if (success) {
1856
- // Wait for process to exit
1857
- await Bun.sleep(1000);
1858
-
1859
- if (!isServeRunning()) {
1860
- logger.success('serve daemon stopped');
1861
- return;
1862
- }
1863
- }
1864
-
1865
- // Fallback: send SIGTERM directly
1866
- const pid = getServePid();
1867
- if (pid) {
1868
- try {
1869
- process.kill(pid, 'SIGTERM');
1870
- await Bun.sleep(1000);
1871
-
1872
- if (!isServeRunning()) {
1873
- logger.success('serve daemon stopped');
1874
- return;
1875
- }
1876
-
1877
- // Force kill
1878
- process.kill(pid, 'SIGKILL');
1879
- cleanupServeFiles();
1880
- logger.success('serve daemon stopped (forced)');
1881
- } catch {
1882
- cleanupServeFiles();
1883
- logger.success('serve daemon stopped');
1884
- }
1885
- }
1886
- }
1887
-
1888
- /**
1889
- * Show serve daemon status
1890
- */
1891
- export async function serveStatus(): Promise<void> {
1892
- // Build status output
1893
- const box = (lines: string[]) => {
1894
- const width = 44;
1895
- const top = '┌─ serve daemon ' + '─'.repeat(width - 16) + '┐';
1896
- const bottom = '└' + '─'.repeat(width) + '┘';
1897
- const padded = lines.map((l) => {
1898
- const visible = l.replace(/\x1b\[[0-9;]*m/g, ''); // Strip ANSI for length calc
1899
- const padding = width - visible.length;
1900
- return '│ ' + l + ' '.repeat(Math.max(0, padding - 1)) + '│';
1901
- });
1902
- return [top, ...padded, bottom].join('\n');
1903
- };
1904
-
1905
- if (!isServeRunning()) {
1906
- const lines = [
1907
- 'Status: \x1b[90m○ not running\x1b[0m',
1908
- '',
1909
- 'Run: \x1b[36mgssh serve start\x1b[0m',
1910
- ];
1911
- logger.log(box(lines));
1912
- return;
1913
- }
1914
-
1915
- // Query daemon for status
1916
- const status = await queryServeStatus();
1917
-
1918
- if (status) {
1919
- const statusIcon = status.relay.status === 'connected' ? '\x1b[32m●\x1b[0m' : '\x1b[33m●\x1b[0m';
1920
- const relayStatus = status.relay.status === 'connected' ? 'connected' : status.relay.status;
1921
-
1922
- const lines = [
1923
- `Status: ${statusIcon} running (pid ${status.pid})`,
1924
- `Version: ${status.version}`,
1925
- `Relay: ${status.relay.url}`,
1926
- ` ${relayStatus}`,
1927
- `Clients: ${status.clients} active`,
1928
- `Uptime: ${formatUptime(status.uptime)}`,
1929
- ];
1930
-
1931
- if (status.hosting) {
1932
- const tunnelIcon = status.hosting.tunnelActive ? '\x1b[32m●\x1b[0m' : '\x1b[31m●\x1b[0m';
1933
- lines.push(`Hosting: ${tunnelIcon} ${status.hosting.subdomain}.gitspace.sh`);
1934
- }
1935
-
1936
- logger.log(box(lines));
1937
- } else {
1938
- // Fallback if status query fails
1939
- const pid = getServePid();
1940
- const lines = [
1941
- `Status: \x1b[32m●\x1b[0m running${pid ? ` (pid ${pid})` : ''}`,
1942
- `Version: ${PACKAGE_VERSION}`,
1943
- ];
1944
- logger.log(box(lines));
1945
- }
1946
- }