@yuriai/web 0.2.40-beta.4 → 0.2.40-beta.5
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.
- package/dist/assets/{AgentAvatar-BmT_6apW.js → AgentAvatar-B7KbxN8Y.js} +1 -1
- package/dist/assets/AssistantConversationSurface-BnK_KTBO.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-C34eOGCL.js → AssistantUnreadBadge-vu4ZhTft.js} +1 -1
- package/dist/assets/{AssistantView-0nXkM9VG.js → AssistantView-CEfEWUIr.js} +1 -1
- package/dist/assets/DiagramView-Dlzr08J_.js +1 -0
- package/dist/assets/{FadeInOnReveal-CCVdl9Vt.js → FadeInOnReveal-DMRmNsau.js} +1 -1
- package/dist/assets/{GuiPluginPage-BMt5AMqg.js → GuiPluginPage-DVug4z_p.js} +1 -1
- package/dist/assets/GuiPluginSurface-L43o6Xv8.js +1 -0
- package/dist/assets/{GuiPluginWindow-BVvzrnp1.js → GuiPluginWindow-tHXkS18H.js} +1 -1
- package/dist/assets/{Icon-B5nBc6dO.js → Icon-DizeYahT.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-Bv5mmf2U.js → ImageLoadingPlaceholder-BZC5m_km.js} +1 -1
- package/dist/assets/LoadingImage-Csw4L-Dr.js +1 -0
- package/dist/assets/MarkdownRenderer-D_0iKhQN.js +2 -0
- package/dist/assets/MarkdownRendererImpl-BZ0XgjS0.js +10 -0
- package/dist/assets/MarkstreamRendererImpl-DBd6Glg9.js +3 -0
- package/dist/assets/MobileDetailNavigation-xgwvsQuR.js +1 -0
- package/dist/assets/{MobileResizableSheet-D5PcZMuI.js → MobileResizableSheet-CQQ7O-2X.js} +1 -1
- package/dist/assets/MobileShareBridge-IO45gM2G.js +3 -0
- package/dist/assets/MobileSurface-DmYgZONB.js +2 -0
- package/dist/assets/{MultiRunWindow-rMqP99ID.js → MultiRunWindow-fJ3XfntS.js} +1 -1
- package/dist/assets/OnboardingScreen-MJS5T5rL.js +1 -0
- package/dist/assets/{OverlayScrollbar-Byx2H3pc.js → OverlayScrollbar-jtMYTn1y.js} +1 -1
- package/dist/assets/SettingsView-ZWFLpPSI.js +29 -0
- package/dist/assets/{SettingsWindow-U-RDDOS7.js → SettingsWindow-DGRmrIWz.js} +1 -1
- package/dist/assets/SetupTourDialog-BYbAubwA.js +1 -0
- package/dist/assets/TerminalView-CoJ6_9P1.js +8 -0
- package/dist/assets/ToolOutputDialog-5xBwOJ6a.js +16 -0
- package/dist/assets/VoiceSettings-CN33koSc.js +2 -0
- package/dist/assets/{YuriLogo-B58GIl2v.js → YuriLogo-CvyJy_R9.js} +1 -1
- package/dist/assets/YuriWordmark-DnFAS-Ko.js +1 -0
- package/dist/assets/{assistant-attachment-cache-Cmzt4xXE.js → assistant-attachment-cache-D-LmCflm.js} +1 -1
- package/dist/assets/bootstrap-eLlfzqAI.js +1 -0
- package/dist/assets/{capgoAdapter-B5NImlKh.js → capgoAdapter-CCLtBZL1.js} +1 -1
- package/dist/assets/{checkbox-Bdj4n5cI.js → checkbox-rOV6DjeG.js} +1 -1
- package/dist/assets/client-uz8O6TPX.js +7 -0
- package/dist/assets/{collapsible-D1JZOgJZ.js → collapsible-CKswuqAw.js} +1 -1
- package/dist/assets/{context-menu-DDX0ZFhc.js → context-menu-B4njwT_M.js} +1 -1
- package/dist/assets/{desktopHosts-DovfbQPm.js → desktopHosts-135cuRCE.js} +1 -1
- package/dist/assets/{desktopRelayRestore-D4pbpNKN.js → desktopRelayRestore-1aUztDPU.js} +1 -1
- package/dist/assets/{device-DNG0cNwQ.js → device-QL8KNSLM.js} +1 -1
- package/dist/assets/{diagram-C72TQWfh.js → diagram-BppQ_USn.js} +1 -1
- package/dist/assets/{dialog-CIKJalI5.js → dialog-Bg8MJnOV.js} +1 -1
- package/dist/assets/{es-D0Q_CV0t.js → es-Ba3NUCtE.js} +3 -3
- package/dist/assets/{fileMentionTouchSelection-tnd9RDDh.js → fileMentionTouchSelection-D-AdTJVr.js} +1 -1
- package/dist/assets/fileReferenceActions-cYqdsXFz.js +1 -0
- package/dist/assets/{fr-DrO5SAKl.js → fr-CRhp3hyT.js} +3 -3
- package/dist/assets/{gitApi-BI8OG_ts.js → gitApi-DVx_V1x6.js} +11 -7
- package/dist/assets/gitApiHttp-DvTBxvX8.js +3 -0
- package/dist/assets/historyImportQueries-D_9RlrLp.js +1 -0
- package/dist/assets/host-DrGjjO6K.js +1 -0
- package/dist/assets/{i18n-UaLestuf.js → i18n-RH7UieOS.js} +1 -1
- package/dist/assets/image-loading-DBqnxgDH.js +1 -0
- package/dist/assets/{input-gVHSS0EB.js → input-DRjuZMeA.js} +1 -1
- package/dist/assets/input-store-CjUOfpyA.js +1 -0
- package/dist/assets/insertionBoundaries-DZtQt2Ah.js +1 -0
- package/dist/assets/{ja-BNeP9_GU.js → ja-D-UPjDY2.js} +3 -3
- package/dist/assets/{ko-DRRFD_7l.js → ko-x-z9J5z7.js} +3 -3
- package/dist/assets/main-BMFY9mtb.js +2 -0
- package/dist/assets/main-D2s9J_jN.js +169 -0
- package/dist/assets/{markdownHeightCache-B-FoaQ1U.js → markdownHeightCache-BL99DlhC.js} +1 -1
- package/dist/assets/{markdownTheme-CHNl6tUv.js → markdownTheme-DFDWa8Gh.js} +1 -1
- package/dist/assets/mcpQueries-HzYMEVWd.js +1 -0
- package/dist/assets/miniChat-BbJ0GKpk.js +2 -0
- package/dist/assets/mobile-_zUth69Z.js +2 -0
- package/dist/assets/mobileBackNavigation--ZdrI-Yj.js +1 -0
- package/dist/assets/mobileConnections-C3eGEOPy.js +2 -0
- package/dist/assets/multirun-CDYNyLBH.js +3 -0
- package/dist/assets/{native-config-DqDXViVx.js → native-config-DOawZfln.js} +1 -1
- package/dist/assets/navigation-Ibk_Pw-q.js +2 -0
- package/dist/assets/{pl-BnW5wJrl.js → pl-Cqo1FJwM.js} +3 -3
- package/dist/assets/platform-wF65ZFgV.js +1 -0
- package/dist/assets/project-preview-2H-TmJkd.js +1 -0
- package/dist/assets/projectActions-50e_f9dI.js +1 -0
- package/dist/assets/projectMeta-D1Ytss9U.js +1 -0
- package/dist/assets/prompt-attachment-upload-BNhDXymd.js +1 -0
- package/dist/assets/{pt-BR-fZW8CCVQ.js → pt-BR-C930XU1k.js} +3 -3
- package/dist/assets/pwa-CXupOTsD.js +2 -0
- package/dist/assets/queue-abort-optimistic-CQXpIlq6.js +1 -0
- package/dist/assets/{react-DeB-Vc_L.js → react-CgRToPwO.js} +1 -1
- package/dist/assets/{readiness-CIlvQ-aQ.js → readiness-BfuZm6Yw.js} +2 -2
- package/dist/assets/relay-preview-frame-src-BPyz3nXA.js +1 -0
- package/dist/assets/remote-input-store-BOdCWpQY.js +1 -0
- package/dist/assets/remoteProjectQueries-CkxdZNw4.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-pJ59iC34.js +2 -0
- package/dist/assets/renderMobileApp-BQFC-gOA.js +29 -0
- package/dist/assets/{runtime-file-download-DMY1k1af.js → runtime-file-download-D11Nnedg.js} +1 -1
- package/dist/assets/runtime-file-resource-CuLP3xp7.js +6 -0
- package/dist/assets/runtimeConfig-tHm7o_0I.js +2 -0
- package/dist/assets/{runtimeEndpointReset-BOdd_mJM.css → runtimeEndpointReset-BUGfn7y0.css} +1 -1
- package/dist/assets/runtimeEndpointReset-BhHWFNvo.js +150 -0
- package/dist/assets/safeStorage-DTOhKN0V.js +1 -0
- package/dist/assets/scheduledTaskNavigation-BIDtQ4wN.js +1 -0
- package/dist/assets/{select-BwCKwnTH.js → select-B1On-Y4Z.js} +1 -1
- package/dist/assets/sessionLookup-RcyTTDOy.js +1 -0
- package/dist/assets/sortable-tabs-strip-nD1Me06z.js +1 -0
- package/dist/assets/{speechSettingsQueries-C5mPRWIv.js → speechSettingsQueries-BYhNpzDJ.js} +1 -1
- package/dist/assets/src-BZCFf9_1.css +2 -0
- package/dist/assets/{store-CzVMz42v.js → store-DunGyOfe.js} +4 -4
- package/dist/assets/terminalApi-madXrfqA.js +1 -0
- package/dist/assets/{textarea-CaTDyZrS.js → textarea-Qt06OhhX.js} +1 -1
- package/dist/assets/{tooltip-BvZzoiqg.js → tooltip-D382RCy1.js} +1 -1
- package/dist/assets/tour-CQMBn8gJ.js +1 -0
- package/dist/assets/{types-Bm8kDgSv.js → types-CHszLAS3.js} +1 -1
- package/dist/assets/{uk-C4OKsNRv.js → uk-OXQSdzuT.js} +3 -3
- package/dist/assets/{useAppFontEffects-C9IaiJgF.js → useAppFontEffects-CqXrCJVt.js} +63 -58
- package/dist/assets/useAppFontEffects-K31q-1OV.css +1 -0
- package/dist/assets/useAssistantUIStore-jOKVcBK8.js +1 -0
- package/dist/assets/useDesktopWindowControlsLayout-KH4UP7Gj.js +1 -0
- package/dist/assets/{useDictation-Sk20Gi0T.js → useDictation-Bs7TWO9r.js} +1 -1
- package/dist/assets/useEffectiveDirectory-CCKRdyK9.js +1 -0
- package/dist/assets/useFontPreferences-CPrl1_3z.js +1 -0
- package/dist/assets/{useMobileHtmlPreviewStore-C03uVLfX.js → useMobileHtmlPreviewStore-EOAzZiAy.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BNtVrnSw.js +13 -0
- package/dist/assets/usePluginsStore-bMuGciUE.js +1 -0
- package/dist/assets/useProjectRuntimeAPIs-BFCXBu2J.js +1 -0
- package/dist/assets/{useStreamingTextThrottle-CeKHHK13.js → useStreamingTextThrottle-C8xAqcgP.js} +1 -1
- package/dist/assets/{useThemeSystem-CNzUUkFn.js → useThemeSystem-C57Z9mV2.js} +1 -1
- package/dist/assets/useUIStore-Cfmg-aDQ.js +1 -0
- package/dist/assets/uuid-D-SDZijH.js +1 -0
- package/dist/assets/{vendor-base-ui-CzHs0bHY.js → vendor-base-ui-z2M4boRm.js} +1 -1
- package/dist/assets/{vendor-cmdk-C_tivUtr.js → vendor-cmdk-BgHvMv5l.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-accessibility-BOtnpZt5.js → vendor-dnd-kit-accessibility-gVi9ga0x.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-core-DK4OoOTr.js → vendor-dnd-kit-core-Dd5yS2-T.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-Cv69eQm1.js → vendor-dnd-kit-sortable-CV-SGi8y.js} +1 -1
- package/dist/assets/{vendor-framer-motion-DDMKlXiP.js → vendor-framer-motion-CF9BQLta.js} +1 -1
- package/dist/assets/{vendor-markstream-react-6zxyQLCD.js → vendor-markstream-react-TwEpkgfP.js} +3 -3
- package/dist/assets/vendor-motion-Dv27UnOI.js +1 -0
- package/dist/assets/{vendor-pierre-diffs-BFiZ3IhI.js → vendor-pierre-diffs-tqo4Z3TC.js} +1 -1
- package/dist/assets/{vendor-react-DlzBev0S.js → vendor-react-P8wFrkcT.js} +1 -1
- package/dist/assets/{vendor-react-drawio-Dyg1-39Q.js → vendor-react-drawio-CQW1YP2l.js} +1 -1
- package/dist/assets/vendor-reactuses-core-Dyjw5sZR.js +1 -0
- package/dist/assets/{vendor-sonner-BEHGipm5.js → vendor-sonner-B5HgJenP.js} +1 -1
- package/dist/assets/{vendor-stream-diffs-wcQxoPZk.js → vendor-stream-diffs-DCMtZcS3.js} +2 -2
- package/dist/assets/vendor-tanstack-query-core-BSjXNgF_.js +1 -0
- package/dist/assets/vendor-tanstack-react-query-B-KblYBV.js +1 -0
- package/dist/assets/{vendor-tanstack-react-virtual-DSFNK3qc.js → vendor-tanstack-react-virtual-BkuqzrEV.js} +1 -1
- package/dist/assets/{vendor-zustand-vDaAPGfl.js → vendor-zustand-Cwko4FG1.js} +1 -1
- package/dist/assets/{zh-CN-ieAs59w6.js → zh-CN-B5X8yCZV.js} +3 -3
- package/dist/assets/{zh-TW-WWTW1fkP.js → zh-TW-CF6zr1fk.js} +3 -3
- package/dist/index.html +32 -27
- package/dist/mini-chat.html +32 -27
- package/dist/mobile.html +2 -2
- package/package.json +3 -2
- package/server/index.d.ts +19 -0
- package/server/index.js +35 -5
- package/server/lib/client-auth/remote-clients.js +11 -0
- package/server/lib/content-search/DOCUMENTATION.md +5 -0
- package/server/lib/content-search/routes.js +4 -0
- package/server/lib/content-search/routes.test.js +10 -0
- package/server/lib/event-stream/DOCUMENTATION.md +5 -0
- package/server/lib/event-stream/runtime.js +3 -0
- package/server/lib/event-stream/upstream-reader.js +1 -1
- package/server/lib/gui-customization/skill/references/remote-connections.md +11 -0
- package/server/lib/message-queue/DOCUMENTATION.md +4 -0
- package/server/lib/message-queue/service.js +2 -1
- package/server/lib/message-queue/service.test.js +11 -0
- package/server/lib/notifications/emitter-runtime.js +5 -0
- package/server/lib/opencode/DOCUMENTATION.md +28 -0
- package/server/lib/opencode/core-routes.js +14 -2
- package/server/lib/opencode/core-routes.test.js +28 -0
- package/server/lib/opencode/feature-routes-runtime.js +6 -1
- package/server/lib/opencode/proxy.js +1 -0
- package/server/lib/opencode/routes.js +18 -4
- package/server/lib/opencode/routes.test.js +22 -0
- package/server/lib/opencode/settings-helpers.js +26 -0
- package/server/lib/opencode/settings-helpers.test.js +20 -0
- package/server/lib/opencode/settings-runtime.js +5 -3
- package/server/lib/opencode/settings-runtime.test.js +35 -0
- package/server/lib/preview/DOCUMENTATION.md +73 -0
- package/server/lib/preview/file-preview-path.js +37 -0
- package/server/lib/preview/file-target.js +38 -0
- package/server/lib/preview/file-target.test.js +111 -0
- package/server/lib/preview/proxy-runtime.js +110 -17
- package/server/lib/projects/DOCUMENTATION.md +6 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/remote-hosts/DOCUMENTATION.md +269 -0
- package/server/lib/remote-hosts/configuration.js +15 -0
- package/server/lib/remote-hosts/deadline.js +22 -0
- package/server/lib/remote-hosts/deadline.test.js +64 -0
- package/server/lib/remote-hosts/fixtures/settings-server.mjs +26 -0
- package/server/lib/remote-hosts/gateway.js +644 -0
- package/server/lib/remote-hosts/json-lifecycle.test.js +55 -0
- package/server/lib/remote-hosts/preview-scope.js +23 -0
- package/server/lib/remote-hosts/relay-client.ts +3 -0
- package/server/lib/remote-hosts/routes.js +432 -0
- package/server/lib/remote-hosts/routes.test.js +1176 -0
- package/server/lib/remote-hosts/settings-production.test.js +145 -0
- package/server/lib/remote-hosts/store.js +110 -0
- package/server/lib/remote-hosts/store.test.js +33 -0
- package/server/lib/remote-hosts/transport.js +113 -0
- package/server/lib/session-folders/routes.js +1 -0
- package/server/lib/transcript-cache/DOCUMENTATION.md +4 -0
- package/server/lib/transcript-cache/routes.js +3 -0
- package/server/lib/transcript-cache/service.js +15 -0
- package/server/lib/transcript-cache/service.test.js +13 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +18 -0
- package/server/lib/ui-auth/ui-auth.js +30 -2
- package/server/lib/ui-auth/ui-auth.test.js +46 -1
- package/dist/assets/AssistantConversationSurface-B-D-mLgs.js +0 -3
- package/dist/assets/DiagramView-BU6jWxKJ.js +0 -1
- package/dist/assets/GuiPluginSurface-kxAcgmf1.js +0 -1
- package/dist/assets/LoadingImage-BzBw_1lI.js +0 -1
- package/dist/assets/MarkdownRenderer-CoMohPOZ.js +0 -2
- package/dist/assets/MarkdownRendererImpl-DoZW1UKH.js +0 -10
- package/dist/assets/MarkstreamRendererImpl-B3zd5x2O.js +0 -3
- package/dist/assets/MobileDetailNavigation-bEZ_NA03.js +0 -1
- package/dist/assets/MobileShareBridge-Cjukxazk.js +0 -3
- package/dist/assets/MobileTabPageHeader-Da1maXx-.js +0 -2
- package/dist/assets/OnboardingScreen-CZhqHzAj.js +0 -1
- package/dist/assets/SettingsView-7Bea2DvF.js +0 -29
- package/dist/assets/SetupTourDialog-CKec5tUy.js +0 -1
- package/dist/assets/TerminalView-CS1oSAuY.js +0 -8
- package/dist/assets/ToolOutputDialog-BWhrFvvI.js +0 -10
- package/dist/assets/VoiceSettings-7aFmJq9Z.js +0 -2
- package/dist/assets/YuriWordmark--S-QEpRp.js +0 -1
- package/dist/assets/appThemeRegistry-LyWTE-mT.js +0 -1
- package/dist/assets/bootstrap-BhC95qVC.js +0 -1
- package/dist/assets/fileQueries-D9l0crnM.js +0 -1
- package/dist/assets/fileReferenceActions-BmquJskG.js +0 -1
- package/dist/assets/gitApiHttp-D4d-rgcR.js +0 -9
- package/dist/assets/historyImportQueries-DkB2_92i.js +0 -1
- package/dist/assets/host-kMLXU0hK.js +0 -1
- package/dist/assets/image-loading-BrDob6MW.js +0 -1
- package/dist/assets/insertionBoundaries-B-yZI6iY.js +0 -1
- package/dist/assets/main-BfAN93rT.js +0 -169
- package/dist/assets/main-DYWwmI_W.js +0 -2
- package/dist/assets/mcpQueries-CehWHIB1.js +0 -1
- package/dist/assets/miniChat-BlkcLQBr.js +0 -2
- package/dist/assets/mobile-I3Xe5NtO.js +0 -2
- package/dist/assets/mobileBackNavigation-BFUH-c-G.js +0 -1
- package/dist/assets/mobileConnections-BFvtbJXX.js +0 -2
- package/dist/assets/multirun-DdEjp77z.js +0 -3
- package/dist/assets/pathNormalization-ewtPqJWn.js +0 -1
- package/dist/assets/platform-DMsFWy1a.js +0 -1
- package/dist/assets/projectActions-C-9Z8R7y.js +0 -1
- package/dist/assets/projectMeta-BKgum5WN.js +0 -1
- package/dist/assets/pwa-BvKUY4Hk.js +0 -2
- package/dist/assets/queue-abort-optimistic-BcbiNk8t.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-DIjWdFHu.js +0 -2
- package/dist/assets/renderMobileApp-CE0QyOH0.js +0 -29
- package/dist/assets/runtime-file-resource-CL7EVzOG.js +0 -2
- package/dist/assets/runtimeConfig-uhjQn4kK.js +0 -2
- package/dist/assets/runtimeEndpointReset-DezNESKT.js +0 -149
- package/dist/assets/scheduledTaskNavigation-FMDNRUnX.js +0 -1
- package/dist/assets/sessionLookup-DzKZsy-W.js +0 -1
- package/dist/assets/sortable-tabs-strip-m5JQrTx4.js +0 -1
- package/dist/assets/src-HgtAe3Q4.css +0 -2
- package/dist/assets/terminalApi-DK4KmfFn.js +0 -1
- package/dist/assets/touch-gestures-CErgaXZ7.js +0 -1
- package/dist/assets/tour-DDI0Zg7l.js +0 -1
- package/dist/assets/useAppFontEffects-RpgNbjA4.css +0 -1
- package/dist/assets/useAssistantUIStore-nNYL140o.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-C3M12PjJ.js +0 -1
- package/dist/assets/useEffectiveDirectory-Do4UqfZR.js +0 -1
- package/dist/assets/useFontPreferences-DxzruDDQ.js +0 -1
- package/dist/assets/useMobileNavigationStore-InwdmuDX.js +0 -17
- package/dist/assets/usePluginsStore-BH4-CNcj.js +0 -1
- package/dist/assets/useUIStore-vvNwcOk3.js +0 -1
- package/dist/assets/useWorkerHighlightedLines-0XahwAbS.js +0 -7
- package/dist/assets/vendor-motion-C9oiAdx-.js +0 -1
- package/dist/assets/vendor-reactuses-core-CuTmqEMK.js +0 -1
- package/dist/assets/vendor-tanstack-query-core-Y_YoRHtC.js +0 -1
- package/dist/assets/vendor-tanstack-react-query-B-Wpqq5J.js +0 -1
|
@@ -0,0 +1,1176 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import fs from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
import { once } from 'node:events';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
10
|
+
import { WebSocket, WebSocketServer } from 'ws';
|
|
11
|
+
import { createPrivateRelayServer } from '../../../../relay-server/src/index.js';
|
|
12
|
+
import { startRelayHost } from '../relay/host-client.js';
|
|
13
|
+
import { exportPublicKeyJwk, generateEcdhKeyPair } from '../relay/e2ee.js';
|
|
14
|
+
import { createPreviewProxyRuntime } from '../preview/proxy-runtime.js';
|
|
15
|
+
import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
|
|
16
|
+
import { registerCommonRequestMiddleware } from '../opencode/core-routes.js';
|
|
17
|
+
import { createUiAuth } from '../ui-auth/ui-auth.js';
|
|
18
|
+
import { createRemoteClientAuthRuntime } from '../client-auth/remote-clients.js';
|
|
19
|
+
import { createGlobalUiEventBroadcaster } from '../event-stream/runtime.js';
|
|
20
|
+
import { createRemoteHostStore } from './store.js';
|
|
21
|
+
import { createRemoteHostGateway } from './gateway.js';
|
|
22
|
+
import { registerRemoteHostRoutes } from './routes.js';
|
|
23
|
+
import { registerTranscriptCacheRoutes } from '../transcript-cache/routes.js';
|
|
24
|
+
import { registerFsRoutes } from '../fs/routes.js';
|
|
25
|
+
import { createTerminalRuntime } from '../terminal/runtime.js';
|
|
26
|
+
import { readTerminalWsControlFrame, createTerminalWsControlFrame } from '../terminal/terminal-ws-protocol.js';
|
|
27
|
+
import { createTranscriptCacheService } from '../transcript-cache/service.js';
|
|
28
|
+
|
|
29
|
+
const require = createRequire(import.meta.url);
|
|
30
|
+
const disposers = [];
|
|
31
|
+
afterEach(async () => { for (const dispose of disposers.splice(0).reverse()) await dispose(); });
|
|
32
|
+
const wait = async (test) => { await vi.waitFor(test, { timeout: 5000, interval: 10 }); };
|
|
33
|
+
|
|
34
|
+
async function host({ adapter = null, supportedRemote = true, failHubWrite = false, requestTimeoutMs = 500,
|
|
35
|
+
operationTimeoutMs = requestTimeoutMs, indexStats, requireClientAuth = false, productionTerminal = false, terminalFrames = [] } = {}) {
|
|
36
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-remote-host-test-'));
|
|
37
|
+
const clients = createRemoteClientAuthRuntime({ fsPromises: fs, path, crypto, storePath: path.join(directory, 'clients.json') });
|
|
38
|
+
const issued = await clients.createClient({ clientKind: 'desktop-local', authMethod: 'pairing', pairingId: 'test-pairing' });
|
|
39
|
+
const auth = createUiAuth({ password: null, requireClientAuth, clientAuthController: clients, readSettingsFromDiskMigrated: async () => ({}) });
|
|
40
|
+
const app = express();
|
|
41
|
+
registerCommonRequestMiddleware(app, { express });
|
|
42
|
+
const server = http.createServer(app);
|
|
43
|
+
const sockets = new Set();
|
|
44
|
+
server.on('connection', (socket) => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
|
|
45
|
+
const store = createRemoteHostStore(path.join(directory, 'remote-hosts.sqlite'));
|
|
46
|
+
let fail = failHubWrite;
|
|
47
|
+
if (failHubWrite) {
|
|
48
|
+
const save = store.saveProject;
|
|
49
|
+
store.saveProject = (...args) => { if (fail) { fail = false; throw new Error('injected disk failure'); } return save(...args); };
|
|
50
|
+
}
|
|
51
|
+
const sseClients = new Set();
|
|
52
|
+
const broadcast = createGlobalUiEventBroadcaster({ sseClients, wsClients: new Set(),
|
|
53
|
+
writeSseEvent: (res, payload) => res.write(`data: ${JSON.stringify(payload)}\n\n`) });
|
|
54
|
+
const eventSubscribers = new Set();
|
|
55
|
+
const globalEventHub = { subscribeEvent(listener) { eventSubscribers.add(listener); return () => eventSubscribers.delete(listener); } };
|
|
56
|
+
let runtime;
|
|
57
|
+
const gateway = createRemoteHostGateway({ store, indexDbPath: path.join(directory, 'session-index.sqlite'), adapter,
|
|
58
|
+
broadcast: (payload, options) => broadcast(payload, { ...options,
|
|
59
|
+
targetFilter: (resource) => runtime?.canReceiveHostEvents(resource) === true }), requestTimeoutMs, operationTimeoutMs });
|
|
60
|
+
let settings = { projects: [] };
|
|
61
|
+
let requests = 0;
|
|
62
|
+
let capabilityGate = Promise.resolve();
|
|
63
|
+
let capabilityRequests = 0;
|
|
64
|
+
let worktrees = [];
|
|
65
|
+
let worktreeFailure = false;
|
|
66
|
+
let worktreeRequests = 0;
|
|
67
|
+
app.use((_req, _res, next) => { requests++; next(); });
|
|
68
|
+
app.use(async (req, _res, next) => {
|
|
69
|
+
if (req.path === '/api/hosts/capabilities') { capabilityRequests++; await capabilityGate; }
|
|
70
|
+
next();
|
|
71
|
+
});
|
|
72
|
+
app.get('/auth/session', auth.handleSessionStatus);
|
|
73
|
+
app.post('/auth/url-token', auth.handleUrlAuthToken);
|
|
74
|
+
app.use('/api', auth.requireAuth);
|
|
75
|
+
runtime = registerRemoteHostRoutes(app, { gateway, getAuth: () => auth, server,
|
|
76
|
+
isRequestOriginAllowed: () => true, remoteClientAuthRuntime: clients,
|
|
77
|
+
readSettings: async () => settings,
|
|
78
|
+
persistSettings: async (update) => { settings = { ...settings, ...update(settings) }; return settings; },
|
|
79
|
+
validateDirectoryPath: async (value) => typeof value === 'string' && value.startsWith('/')
|
|
80
|
+
? { ok: true, directory: value } : { ok: false, error: 'invalid path' },
|
|
81
|
+
globalEventHub, broadcaster: broadcast, supportedRemote, version: 'test-version' });
|
|
82
|
+
app.get('/api/global/event', (req, res) => {
|
|
83
|
+
res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); res.flushHeaders();
|
|
84
|
+
sseClients.add(res); res.once('close', () => sseClients.delete(res)); res.write(': ready\n\n');
|
|
85
|
+
});
|
|
86
|
+
const content = new Set();
|
|
87
|
+
const terminalRuntime = productionTerminal ? createTerminalRuntime({ app, server, express, fs: require('node:fs'), path,
|
|
88
|
+
uiAuthController: auth, buildAugmentedPath: () => process.env.PATH || '', searchPathFor: () => null, isExecutable: () => false,
|
|
89
|
+
isRequestOriginAllowed: async () => true, rejectWebSocketUpgrade: (socket) => socket.destroy(),
|
|
90
|
+
TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS: 30000, TERMINAL_INPUT_WS_REBIND_WINDOW_MS: 1000,
|
|
91
|
+
TERMINAL_INPUT_WS_MAX_REBINDS_PER_WINDOW: 3 }) : null;
|
|
92
|
+
const terminal = new WebSocketServer({ noServer: true });
|
|
93
|
+
server.on('upgrade', async (req, socket, head) => {
|
|
94
|
+
if (productionTerminal) return;
|
|
95
|
+
if (new URL(req.url, 'http://local.invalid').pathname !== '/api/terminal/ws') return;
|
|
96
|
+
const token = await auth.ensureSessionToken(req, null);
|
|
97
|
+
if (!token) return socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
|
98
|
+
terminal.handleUpgrade(req, socket, head, (ws) => {
|
|
99
|
+
for (const frame of terminalFrames) ws.send(frame);
|
|
100
|
+
ws.on('message', (data, binary) => ws.send(data, { binary }));
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
app.get('/api/event', (_req, res) => {
|
|
104
|
+
res.set({ 'Content-Type': 'text/event-stream' }); res.flushHeaders(); content.add(res);
|
|
105
|
+
res.once('close', () => content.delete(res)); res.write(': ready\n\n');
|
|
106
|
+
});
|
|
107
|
+
let summaries = { directories: [], pinnedSessionIds: [] };
|
|
108
|
+
let indexGate = Promise.resolve();
|
|
109
|
+
let indexRequests = 0;
|
|
110
|
+
let indexActive = 0;
|
|
111
|
+
let indexMax = 0;
|
|
112
|
+
const indexSyncRequests = [];
|
|
113
|
+
app.post('/api/yuri/session-index/sync', express.json(), (req, res) => {
|
|
114
|
+
indexSyncRequests.push(req.body.directories);
|
|
115
|
+
for (const directory of req.body.directories || []) if (!summaries.directories.some((entry) => entry.directory === directory)) {
|
|
116
|
+
summaries.directories.push({ directory, sessions: [], hasMore: false });
|
|
117
|
+
}
|
|
118
|
+
res.status(202).json(summaries);
|
|
119
|
+
});
|
|
120
|
+
app.get('/api/yuri/session-index', async (_req, res) => {
|
|
121
|
+
indexRequests++; indexActive++; indexMax = Math.max(indexMax, indexActive);
|
|
122
|
+
if (indexStats) { indexStats.active++; indexStats.max = Math.max(indexStats.max, indexStats.active); }
|
|
123
|
+
res.once('close', () => { indexActive--; if (indexStats) indexStats.active--; });
|
|
124
|
+
await indexGate;
|
|
125
|
+
if (!res.destroyed) res.json(summaries);
|
|
126
|
+
});
|
|
127
|
+
app.get('/api/yuri/session-unread', (_req, res) => res.json({ revision: 0, sessions: {} }));
|
|
128
|
+
app.get('/api/git/worktrees', (_req, res) => {
|
|
129
|
+
worktreeRequests++;
|
|
130
|
+
if (worktreeFailure) return res.status(503).json({ code: 'worktree_catalog_unavailable' });
|
|
131
|
+
res.json(worktrees);
|
|
132
|
+
});
|
|
133
|
+
app.get('/api/session-folders', (_req, res) => res.json({ version: 1, foldersMap: {}, collapsedFolderIds: [] }));
|
|
134
|
+
app.get('/api/session-folders/order', (_req, res) => res.json({ revision: 0, sessionOrderByScope: {}, sessionOrderActivityByScope: {} }));
|
|
135
|
+
let messageHeaders;
|
|
136
|
+
app.post('/api/session/:id/message', express.json(), (req, res) => {
|
|
137
|
+
messageHeaders = req.headers;
|
|
138
|
+
res.json({ received: req.body });
|
|
139
|
+
});
|
|
140
|
+
app.get('/api/fs/raw', (_req, res) => res.type('text/plain').send('remote file body'));
|
|
141
|
+
const previewRuntime = createPreviewProxyRuntime({ crypto, URL, createProxyMiddleware, responseInterceptor });
|
|
142
|
+
previewRuntime.attach(app, { server, express, uiAuthController: auth, isRequestOriginAllowed: () => true,
|
|
143
|
+
rejectWebSocketUpgrade: (socket) => socket.destroy() });
|
|
144
|
+
const transcript = createTranscriptCacheService({ dbPath: path.join(directory, 'transcript-cache.sqlite') });
|
|
145
|
+
registerTranscriptCacheRoutes(app, { transcriptCacheService: transcript });
|
|
146
|
+
server.listen(0, '127.0.0.1'); await once(server, 'listening');
|
|
147
|
+
const url = `http://127.0.0.1:${server.address().port}`;
|
|
148
|
+
const headers = { Authorization: `Bearer ${issued.token}`, 'Content-Type': 'application/json' };
|
|
149
|
+
disposers.push(async () => {
|
|
150
|
+
runtime.stop(); terminal.close(); transcript.close(); auth.dispose();
|
|
151
|
+
await terminalRuntime?.shutdown();
|
|
152
|
+
for (const socket of sockets) socket.destroy();
|
|
153
|
+
await new Promise((resolve) => server.close(resolve));
|
|
154
|
+
await fs.rm(directory, { recursive: true, force: true });
|
|
155
|
+
});
|
|
156
|
+
return { app, server, store, gateway, url, headers, clients, issued, directory, content, auth,
|
|
157
|
+
emit(payload, scope = '/same/path') { for (const listener of eventSubscribers) listener({ payload, directory: scope }); },
|
|
158
|
+
setSummaries(value) { summaries = value; }, get projects() { return settings.projects; },
|
|
159
|
+
get requests() { return requests; }, get statusStreams() { return eventSubscribers.size; },
|
|
160
|
+
get liveClients() { return sseClients.size; }, broadcast,
|
|
161
|
+
get capabilityRequests() { return capabilityRequests; },
|
|
162
|
+
get messageHeaders() { return messageHeaders; },
|
|
163
|
+
setCapabilityGate(promise) { capabilityGate = promise; },
|
|
164
|
+
get indexRequests() { return indexRequests; }, get indexActive() { return indexActive; }, get indexMax() { return indexMax; },
|
|
165
|
+
setIndexGate(promise) { indexGate = promise; },
|
|
166
|
+
setWorktrees(paths) { worktrees = paths.map((path) => ({ path })); },
|
|
167
|
+
setWorktreeFailure(value) { worktreeFailure = value; },
|
|
168
|
+
get worktreeRequests() { return worktreeRequests; },
|
|
169
|
+
get indexSyncRequests() { return indexSyncRequests; },
|
|
170
|
+
call(route, method = 'GET', body) { return fetch(`${url}${route}`, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); },
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function aggregate(options = {}) {
|
|
175
|
+
const remote = await host({ requireClientAuth: options.requireClientAuth, productionTerminal: options.productionTerminal,
|
|
176
|
+
terminalFrames: options.terminalFrames });
|
|
177
|
+
let hosts = [{ id: 'remote-1', label: 'Remote', source: 'direct', apiUrl: remote.url, clientToken: remote.issued.token }];
|
|
178
|
+
const listeners = new Set();
|
|
179
|
+
const adapter = { listHosts: async () => hosts, subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); } };
|
|
180
|
+
const hub = await host({ adapter, ...options });
|
|
181
|
+
return { hub, remote, setHosts(next) { hosts = next; for (const fn of listeners) fn(); } };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
describe('Remote Host production HTTP contract', () => {
|
|
185
|
+
it('forwards worktree dialog GitHub reads and prompt templates without allowing machine mutations', async () => {
|
|
186
|
+
const { hub, remote } = await aggregate();
|
|
187
|
+
const reads = ['/api/github/auth/status', '/api/github/issues/list', '/api/github/pulls/list',
|
|
188
|
+
'/api/github/issues/get', '/api/github/issues/comments', '/api/github/pulls/context', '/api/magic-prompts'];
|
|
189
|
+
for (const route of reads) {
|
|
190
|
+
remote.app.get(route, (req, res) => res.json({ source: 'remote', route, directory: req.query.directory }));
|
|
191
|
+
const response = await hub.call(`/api/hosts/remote-1${route}?directory=%2Fremote%2Frepo`);
|
|
192
|
+
expect(response.status, route).toBe(200);
|
|
193
|
+
expect(await response.json()).toEqual({ source: 'remote', route, directory: '/remote/repo' });
|
|
194
|
+
}
|
|
195
|
+
const before = remote.requests;
|
|
196
|
+
for (const [route, method] of [
|
|
197
|
+
['/api/github/auth/start', 'POST'], ['/api/github/auth/logout', 'POST'],
|
|
198
|
+
['/api/github/auth/status', 'POST'], ['/api/github/issues/list', 'POST'],
|
|
199
|
+
['/api/github/auth/unknown', 'GET'], ['/api/magic-prompts', 'PUT'],
|
|
200
|
+
['/api/magic-prompts', 'POST'], ['/api/magic-prompts', 'DELETE'],
|
|
201
|
+
]) {
|
|
202
|
+
const response = await hub.call(`/api/hosts/remote-1${route}`, method);
|
|
203
|
+
expect(response.status, `${method} ${route}`).toBe(403);
|
|
204
|
+
expect(await response.json()).toMatchObject({ code: 'remote_scope_forbidden' });
|
|
205
|
+
}
|
|
206
|
+
expect(remote.requests).toBe(before);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it('preserves the production terminal greeting while downstream authorization is completing', async () => {
|
|
210
|
+
const { hub, remote } = await aggregate({ requireClientAuth: true, productionTerminal: true });
|
|
211
|
+
const directFrames = [];
|
|
212
|
+
const direct = new WebSocket(`${remote.url.replace('http:', 'ws:')}/api/terminal/ws`, { headers: remote.headers });
|
|
213
|
+
disposers.push(() => direct.terminate());
|
|
214
|
+
direct.on('message', (data) => directFrames.push(readTerminalWsControlFrame(data)));
|
|
215
|
+
await wait(() => expect(directFrames).toContainEqual({ t: 'ok', v: 2 }));
|
|
216
|
+
direct.close();
|
|
217
|
+
const authorize = hub.auth.resolveAuthContext;
|
|
218
|
+
let upgrades = 0;
|
|
219
|
+
hub.auth.resolveAuthContext = async (...args) => {
|
|
220
|
+
const result = await authorize(...args);
|
|
221
|
+
if (args[0].headers.upgrade === 'websocket' && ++upgrades === 2) await new Promise((resolve) => setTimeout(resolve, 30));
|
|
222
|
+
return result;
|
|
223
|
+
};
|
|
224
|
+
const frames = [];
|
|
225
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
226
|
+
disposers.push(() => socket.terminate());
|
|
227
|
+
socket.on('message', (data) => frames.push(readTerminalWsControlFrame(data)));
|
|
228
|
+
await once(socket, 'open');
|
|
229
|
+
await vi.waitFor(() => expect(frames).toContainEqual({ t: 'ok', v: 2 }), { timeout: 300 });
|
|
230
|
+
socket.send(createTerminalWsControlFrame({ t: 'b', s: 'missing-session' }));
|
|
231
|
+
await wait(() => expect(frames).toContainEqual({ t: 'e', c: 'SESSION_NOT_FOUND', f: false }));
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it.each(['bytes', 'frames', 'revoked'])('rejects admission without forwarding early frames when %s exceeds its boundary', async (boundary) => {
|
|
235
|
+
const terminalFrames = boundary === 'bytes' ? [Buffer.alloc(1024 * 1024 + 1)]
|
|
236
|
+
: boundary === 'frames' ? Array.from({ length: 257 }, () => '') : ['must-not-leak'];
|
|
237
|
+
const { hub } = await aggregate({ requireClientAuth: true, terminalFrames });
|
|
238
|
+
const authorize = hub.auth.resolveAuthContext;
|
|
239
|
+
let upgrades = 0;
|
|
240
|
+
hub.auth.resolveAuthContext = async (...args) => {
|
|
241
|
+
if (args[0].headers.upgrade === 'websocket' && ++upgrades === 2) {
|
|
242
|
+
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
243
|
+
if (boundary === 'revoked') await hub.clients.revokeClient(hub.issued.client.id);
|
|
244
|
+
}
|
|
245
|
+
return authorize(...args);
|
|
246
|
+
};
|
|
247
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
248
|
+
disposers.push(() => socket.terminate());
|
|
249
|
+
const opened = vi.fn();
|
|
250
|
+
const message = vi.fn();
|
|
251
|
+
socket.on('open', opened);
|
|
252
|
+
socket.on('message', message);
|
|
253
|
+
socket.on('error', () => {});
|
|
254
|
+
await new Promise((resolve) => socket.once('close', resolve));
|
|
255
|
+
expect(opened).not.toHaveBeenCalled();
|
|
256
|
+
expect(message).not.toHaveBeenCalled();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it('preserves the order and text/binary types of frames sent before downstream admission', async () => {
|
|
260
|
+
const { hub } = await aggregate({ terminalFrames: ['first', Buffer.from([0, 255, 1]), 'last'], requireClientAuth: true });
|
|
261
|
+
const authorize = hub.auth.resolveAuthContext;
|
|
262
|
+
let upgrades = 0;
|
|
263
|
+
hub.auth.resolveAuthContext = async (...args) => {
|
|
264
|
+
const result = await authorize(...args);
|
|
265
|
+
if (args[0].headers.upgrade === 'websocket' && ++upgrades === 2) await new Promise((resolve) => setTimeout(resolve, 30));
|
|
266
|
+
return result;
|
|
267
|
+
};
|
|
268
|
+
const frames = [];
|
|
269
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
270
|
+
disposers.push(() => socket.terminate());
|
|
271
|
+
socket.on('message', (data, binary) => frames.push({ data: binary ? [...data] : data.toString(), binary }));
|
|
272
|
+
await once(socket, 'open');
|
|
273
|
+
socket.send('after-admission');
|
|
274
|
+
await wait(() => expect(frames).toEqual([
|
|
275
|
+
{ data: 'first', binary: false }, { data: [0, 255, 1], binary: true },
|
|
276
|
+
{ data: 'last', binary: false }, { data: 'after-admission', binary: false },
|
|
277
|
+
]));
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
it('keeps the scope generation across short discovery connections without retaining unreferenced transports', async () => {
|
|
281
|
+
const { hub, remote } = await aggregate({ requireClientAuth: true });
|
|
282
|
+
const before = await (await hub.call('/api/hosts')).json();
|
|
283
|
+
const scope = before.hosts[0].scopeGeneration;
|
|
284
|
+
expect(scope).toEqual(expect.any(String));
|
|
285
|
+
expect(remote.requests).toBe(0);
|
|
286
|
+
const abort = new AbortController();
|
|
287
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
288
|
+
const wires = new Set();
|
|
289
|
+
try {
|
|
290
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
291
|
+
const response = await hub.call('/api/hosts/remote-1/connect', 'POST');
|
|
292
|
+
expect(response.status).toBe(200);
|
|
293
|
+
const { host: connected } = await response.json();
|
|
294
|
+
expect(connected.scopeGeneration).toBe(scope);
|
|
295
|
+
wires.add(connected.generation);
|
|
296
|
+
await wait(async () => expect((await hub.gateway.list()).hosts[0].state).toBe('idle'));
|
|
297
|
+
expect(await (await hub.call('/api/hosts/remote-1/api/fs/raw')).text()).toBe('remote file body');
|
|
298
|
+
const after = await (await hub.call('/api/hosts')).json();
|
|
299
|
+
expect(after.hosts[0]).toMatchObject({ state: 'idle', scopeGeneration: scope });
|
|
300
|
+
expect(after.hosts[0].generation).toBeUndefined();
|
|
301
|
+
}
|
|
302
|
+
expect(wires.size).toBe(3);
|
|
303
|
+
expect(remote.statusStreams).toBe(0);
|
|
304
|
+
expect(remote.indexRequests).toBe(0);
|
|
305
|
+
expect(remote.indexSyncRequests).toEqual([]);
|
|
306
|
+
} finally { abort.abort(); await stream.body.cancel().catch(() => {}); }
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it('retires scope generations on credential changes and host removal without ABA reuse', async () => {
|
|
310
|
+
const { hub, remote, setHosts } = await aggregate({ requireClientAuth: true });
|
|
311
|
+
const descriptor = { id: 'remote-1', label: 'Remote', source: 'direct', apiUrl: remote.url, clientToken: remote.issued.token };
|
|
312
|
+
const scope = async () => (await (await hub.call('/api/hosts')).json()).hosts[0]?.scopeGeneration;
|
|
313
|
+
const first = await scope();
|
|
314
|
+
expect(first).toEqual(expect.any(String));
|
|
315
|
+
const issued = await remote.clients.createClient({ clientKind: 'desktop-local', authMethod: 'pairing', pairingId: 'rotated' });
|
|
316
|
+
setHosts([{ ...descriptor, clientToken: issued.token }]);
|
|
317
|
+
const rotated = await scope();
|
|
318
|
+
setHosts([descriptor]);
|
|
319
|
+
const restoredCredential = await scope();
|
|
320
|
+
setHosts([]);
|
|
321
|
+
expect(await scope()).toBeUndefined();
|
|
322
|
+
setHosts([descriptor]);
|
|
323
|
+
const restoredHost = await scope();
|
|
324
|
+
setHosts([]);
|
|
325
|
+
setHosts([descriptor]);
|
|
326
|
+
const rapidReadd = await scope();
|
|
327
|
+
expect(new Set([first, rotated, restoredCredential, restoredHost, rapidReadd]).size).toBe(5);
|
|
328
|
+
expect(remote.requests).toBe(0);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it('rejects a late physical response when credentials rotate and return to their original value', async () => {
|
|
332
|
+
const { hub, remote, setHosts } = await aggregate({ requireClientAuth: true });
|
|
333
|
+
let reached;
|
|
334
|
+
const entered = new Promise((resolve) => { reached = resolve; });
|
|
335
|
+
let release;
|
|
336
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
337
|
+
remote.app.get('/api/fs/late-scope', async (_req, res) => {
|
|
338
|
+
reached();
|
|
339
|
+
await gate;
|
|
340
|
+
if (!res.destroyed) res.json({ stale: true });
|
|
341
|
+
});
|
|
342
|
+
const descriptor = { id: 'remote-1', label: 'Remote', source: 'direct', apiUrl: remote.url, clientToken: remote.issued.token };
|
|
343
|
+
const initial = (await (await hub.call('/api/hosts')).json()).hosts[0].scopeGeneration;
|
|
344
|
+
const pending = hub.call('/api/hosts/remote-1/api/fs/late-scope');
|
|
345
|
+
try {
|
|
346
|
+
await entered;
|
|
347
|
+
const issued = await remote.clients.createClient({ clientKind: 'desktop-local', authMethod: 'pairing', pairingId: 'rotated' });
|
|
348
|
+
setHosts([{ ...descriptor, clientToken: issued.token }]);
|
|
349
|
+
setHosts([descriptor]);
|
|
350
|
+
await hub.gateway.reconcile();
|
|
351
|
+
const current = (await (await hub.call('/api/hosts')).json()).hosts[0].scopeGeneration;
|
|
352
|
+
expect(current).not.toBe(initial);
|
|
353
|
+
release();
|
|
354
|
+
const old = await pending;
|
|
355
|
+
expect([409, 503]).toContain(old.status);
|
|
356
|
+
expect(await old.json()).not.toHaveProperty('stale');
|
|
357
|
+
expect(await (await hub.call('/api/hosts/remote-1/api/fs/raw')).text()).toBe('remote file body');
|
|
358
|
+
expect(remote.statusStreams).toBe(0);
|
|
359
|
+
} finally { release(); }
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('preserves authoritative optional file existence through the Hub for present, empty and missing files', async () => {
|
|
363
|
+
const { hub, remote } = await aggregate({ requireClientAuth: true });
|
|
364
|
+
registerFsRoutes(remote.app, { os, path, fsPromises: fs, crypto,
|
|
365
|
+
normalizeDirectoryPath: (value) => value, yuriDataDir: remote.directory });
|
|
366
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: remote.directory });
|
|
367
|
+
for (const [name, content, exists] of [
|
|
368
|
+
['present.txt', 'remote file contents', true], ['empty.txt', '', true], ['missing.txt', '', false],
|
|
369
|
+
]) {
|
|
370
|
+
const file = path.join(remote.directory, name);
|
|
371
|
+
if (exists) await fs.writeFile(file, content);
|
|
372
|
+
const route = `/api/fs/read?${new URLSearchParams({ path: file, optional: 'true', directory: remote.directory })}`;
|
|
373
|
+
const authoritative = await remote.call(route);
|
|
374
|
+
expect(authoritative.status).toBe(200);
|
|
375
|
+
expect(authoritative.headers.get('x-yuri-file-exists')).toBe(String(exists));
|
|
376
|
+
const forwarded = await hub.call(`/api/hosts/remote-1${route}`);
|
|
377
|
+
expect(forwarded.status).toBe(200);
|
|
378
|
+
expect.soft(forwarded.headers.get('x-yuri-file-exists'), name).toBe(String(exists));
|
|
379
|
+
expect(await forwarded.text()).toBe(await authoritative.text());
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
it('streams attachment bytes and integrity headers to remote storage without forwarding client credentials', async () => {
|
|
384
|
+
const { hub, remote } = await aggregate({ requireClientAuth: true });
|
|
385
|
+
registerFsRoutes(remote.app, { os, path, fsPromises: fs, crypto,
|
|
386
|
+
normalizeDirectoryPath: (value) => value, yuriDataDir: remote.directory });
|
|
387
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: remote.directory });
|
|
388
|
+
const received = [];
|
|
389
|
+
const capture = (req) => {
|
|
390
|
+
if (req.url.startsWith('/api/fs/prompt-attachments/')) received.push(req.headers);
|
|
391
|
+
};
|
|
392
|
+
remote.server.prependListener('request', capture);
|
|
393
|
+
try {
|
|
394
|
+
for (const [name, mime, bytes] of [
|
|
395
|
+
['文件.bin', 'application/octet-stream', Buffer.from([0, 255, 128, 13, 10])],
|
|
396
|
+
['data.json', 'application/json', Buffer.from('{ "keep": true }\n')],
|
|
397
|
+
]) {
|
|
398
|
+
const digest = crypto.createHash('sha256').update(bytes).digest('hex');
|
|
399
|
+
const headers = { ...hub.headers, 'content-type': mime,
|
|
400
|
+
'x-yuri-content-length': String(bytes.length), 'x-yuri-sha256': digest,
|
|
401
|
+
'x-yuri-mime': mime, 'x-yuri-filename': encodeURIComponent(name),
|
|
402
|
+
'x-opencode-directory': remote.directory, cookie: 'hub-only=value', 'x-unrelated': 'not-forwarded' };
|
|
403
|
+
const route = `${hub.url}/api/hosts/remote-1/api/fs/prompt-attachments/att-bytes?storage=temporary`;
|
|
404
|
+
const response = await fetch(route, { method: 'PUT', headers, body: bytes });
|
|
405
|
+
expect(response.status).toBe(200);
|
|
406
|
+
const stored = await response.json();
|
|
407
|
+
disposers.push(() => fs.rm(path.dirname(stored.path), { recursive: true, force: true }));
|
|
408
|
+
expect(stored).toMatchObject({ success: true, size: bytes.length, sha256: digest, mime });
|
|
409
|
+
expect(path.basename(stored.path)).toBe(name);
|
|
410
|
+
expect(await fs.readFile(stored.path)).toEqual(bytes);
|
|
411
|
+
const upstream = received.at(-1);
|
|
412
|
+
expect(upstream.authorization === remote.headers.Authorization).toBe(true);
|
|
413
|
+
expect(upstream.cookie).toBeUndefined();
|
|
414
|
+
expect(upstream['x-unrelated']).toBeUndefined();
|
|
415
|
+
const invalid = await fetch(route, { method: 'PUT', headers: { ...headers, 'x-yuri-sha256': '0'.repeat(64) }, body: bytes });
|
|
416
|
+
expect(invalid.status).toBe(400);
|
|
417
|
+
expect(await invalid.json()).toEqual({ error: 'Attachment digest mismatch' });
|
|
418
|
+
}
|
|
419
|
+
} finally { remote.server.off('request', capture); }
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it('does not resurrect a reference deleted while the remote project catalog refresh was in flight', async () => {
|
|
423
|
+
const { hub, remote } = await aggregate();
|
|
424
|
+
const first = await (await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' })).json();
|
|
425
|
+
const second = await (await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/another/path' })).json();
|
|
426
|
+
let reached;
|
|
427
|
+
const reachedCatalog = new Promise(resolve => { reached = resolve; });
|
|
428
|
+
let release;
|
|
429
|
+
const gate = new Promise(resolve => { release = resolve; });
|
|
430
|
+
const holdCatalog = (req, res) => {
|
|
431
|
+
if (req.method !== 'GET' || new URL(req.url, remote.url).pathname !== '/api/projects') return;
|
|
432
|
+
const end = res.end;
|
|
433
|
+
res.end = function (...args) { reached(); void gate.then(() => { if (!res.destroyed) end.apply(res, args); }); return res; };
|
|
434
|
+
};
|
|
435
|
+
remote.server.prependListener('request', holdCatalog);
|
|
436
|
+
const abort = new AbortController();
|
|
437
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
438
|
+
try {
|
|
439
|
+
await reachedCatalog;
|
|
440
|
+
expect((await hub.call(`/api/hosts/remote-1/projects/${first.project.id}`, 'DELETE')).status).toBe(204);
|
|
441
|
+
release();
|
|
442
|
+
await wait(() => expect(hub.store.receipt('remote-1').lastSyncedAt).toBeTruthy());
|
|
443
|
+
expect(hub.store.projects().map(project => project.id)).toEqual([second.project.id]);
|
|
444
|
+
expect((await hub.call(`/api/hosts/remote-1/projects/${second.project.id}`, 'DELETE')).status).toBe(204);
|
|
445
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
446
|
+
} finally { release(); abort.abort(); await stream.body.cancel().catch(() => {}); remote.server.off('request', holdCatalog); }
|
|
447
|
+
});
|
|
448
|
+
it('does not restore a Hub reference deleted while a metadata PATCH is completing remotely', async () => {
|
|
449
|
+
const { hub, remote } = await aggregate();
|
|
450
|
+
const { project } = await (await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' })).json();
|
|
451
|
+
const send = hub.gateway.json;
|
|
452
|
+
let completed;
|
|
453
|
+
const completion = new Promise(resolve => { completed = resolve; });
|
|
454
|
+
let release;
|
|
455
|
+
const gate = new Promise(resolve => { release = resolve; });
|
|
456
|
+
hub.gateway.json = async (...args) => {
|
|
457
|
+
const result = await send(...args);
|
|
458
|
+
if (args[2]?.method === 'PATCH') { completed(); await gate; }
|
|
459
|
+
return result;
|
|
460
|
+
};
|
|
461
|
+
const patch = hub.call(`/api/hosts/remote-1/projects/${project.id}`, 'PATCH', { label: 'remote committed' });
|
|
462
|
+
try {
|
|
463
|
+
await completion;
|
|
464
|
+
expect((await hub.call(`/api/hosts/remote-1/projects/${project.id}`, 'DELETE')).status).toBe(204);
|
|
465
|
+
release();
|
|
466
|
+
expect((await patch).status).toBe(404);
|
|
467
|
+
expect(hub.store.hasProjects()).toBe(false);
|
|
468
|
+
expect(remote.projects[0].label).toBe('remote committed');
|
|
469
|
+
} finally { release(); hub.gateway.json = send; }
|
|
470
|
+
});
|
|
471
|
+
it('authorizes file targets against the authoritative root, strips Hub path credentials and revokes through the Host', async () => {
|
|
472
|
+
const { hub, remote } = await aggregate({ requireClientAuth: true });
|
|
473
|
+
const root = path.join(remote.directory, 'file-project');
|
|
474
|
+
await fs.mkdir(path.join(root, 'nested'), { recursive: true });
|
|
475
|
+
await fs.writeFile(path.join(root, 'index.html'), '<link rel="stylesheet" href="style.css"><p>remote file</p>');
|
|
476
|
+
await fs.writeFile(path.join(root, 'style.css'), 'body { color: red; }');
|
|
477
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: root });
|
|
478
|
+
const received = [];
|
|
479
|
+
const capture = (req) => received.push({ method: req.method, url: req.url,
|
|
480
|
+
usesRemoteCredential: req.headers.authorization === `Bearer ${remote.issued.token}` });
|
|
481
|
+
remote.server.prependListener('request', capture);
|
|
482
|
+
const created = await hub.call('/api/hosts/remote-1/api/preview/targets', 'POST', {
|
|
483
|
+
kind: 'file', directory: path.join(root, 'nested'), path: path.join(root, 'index.html'),
|
|
484
|
+
});
|
|
485
|
+
expect(created.status).toBe(200);
|
|
486
|
+
const target = await created.json();
|
|
487
|
+
expect(target.kind).toBe('file');
|
|
488
|
+
const tokenResponse = await (await hub.call('/auth/url-token', 'POST', {})).json();
|
|
489
|
+
const hubToken = tokenResponse.token;
|
|
490
|
+
expect(typeof hubToken).toBe('string');
|
|
491
|
+
const route = `${target.proxyBasePath}/_file/${target.previewToken}/${hubToken}${target.entryPath}`;
|
|
492
|
+
const document = await fetch(hub.url + route);
|
|
493
|
+
expect(document.status).toBe(200);
|
|
494
|
+
expect(document.headers.get('referrer-policy')).toBe('no-referrer');
|
|
495
|
+
expect(document.headers.get('cache-control')).toContain('no-store');
|
|
496
|
+
expect(await document.text()).toContain('remote file');
|
|
497
|
+
const asset = await fetch(new URL('style.css', hub.url + route));
|
|
498
|
+
expect(asset.status).toBe(200); expect(await asset.text()).toContain('color: red');
|
|
499
|
+
const forwarded = received.filter(req => req.url.includes('/_file/'));
|
|
500
|
+
expect(forwarded.length).toBe(2);
|
|
501
|
+
expect(forwarded.every(req => !req.url.includes(hubToken) && req.url.includes(`/${target.previewToken}/-/`) && req.usesRemoteCredential)).toBe(true);
|
|
502
|
+
const beforeDenied = received.length;
|
|
503
|
+
for (const directory of ['/not-referenced', `${root}/../outside`, `${root}/./nested`]) {
|
|
504
|
+
expect((await hub.call('/api/hosts/remote-1/api/preview/targets', 'POST', {
|
|
505
|
+
kind: 'file', directory, path: path.join(root, 'index.html'),
|
|
506
|
+
})).status).toBe(404);
|
|
507
|
+
}
|
|
508
|
+
expect(received.length).toBe(beforeDenied);
|
|
509
|
+
const ws = new WebSocket(`${hub.url.replace('http:', 'ws:')}${route}`, { headers: hub.headers });
|
|
510
|
+
await new Promise(resolve => { ws.on('error', resolve); ws.on('unexpected-response', (_req, response) => { response.resume(); resolve(); }); });
|
|
511
|
+
expect(ws.readyState).not.toBe(WebSocket.OPEN); ws.terminate();
|
|
512
|
+
expect((await fetch(`${hub.url}/api/hosts/remote-1/api/preview/targets?yuri_url_token=${hubToken}`, {
|
|
513
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
514
|
+
body: JSON.stringify({ kind: 'file', directory: root, path: path.join(root, 'index.html') }),
|
|
515
|
+
})).status).toBe(401);
|
|
516
|
+
expect((await fetch(`${hub.url}/api/hosts/remote-1/api/preview/targets/${target.id}?yuri_url_token=${hubToken}`, {
|
|
517
|
+
method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ previewToken: target.previewToken }),
|
|
518
|
+
})).status).toBe(401);
|
|
519
|
+
expect((await hub.call(`/api/hosts/remote-1/api/preview/targets/${target.id}`, 'DELETE', { previewToken: target.previewToken })).status).toBe(204);
|
|
520
|
+
expect((await hub.call(route)).status).toBe(404);
|
|
521
|
+
remote.server.off('request', capture);
|
|
522
|
+
});
|
|
523
|
+
it('releases the last project status stream while the authorized Hub window stays online', async () => {
|
|
524
|
+
const { hub, remote } = await aggregate();
|
|
525
|
+
const first = await (await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' })).json();
|
|
526
|
+
const second = await (await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/another/path' })).json();
|
|
527
|
+
const abort = new AbortController();
|
|
528
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
529
|
+
try {
|
|
530
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
531
|
+
expect((await hub.call(`/api/hosts/remote-1/projects/${first.project.id}`, 'DELETE')).status).toBe(204);
|
|
532
|
+
expect(remote.statusStreams).toBe(1);
|
|
533
|
+
expect((await hub.call(`/api/hosts/remote-1/projects/${second.project.id}`, 'DELETE')).status).toBe(204);
|
|
534
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
535
|
+
expect(hub.liveClients).toBe(1);
|
|
536
|
+
expect(remote.projects).toHaveLength(2);
|
|
537
|
+
} finally { abort.abort(); await stream.body.cancel().catch(() => {}); }
|
|
538
|
+
});
|
|
539
|
+
it('asks the remote scheduler to discover summaries without requiring a remote UI window', async () => {
|
|
540
|
+
const { hub, remote } = await aggregate();
|
|
541
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
542
|
+
expect(remote.indexSyncRequests).toEqual([]);
|
|
543
|
+
const abort = new AbortController();
|
|
544
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
545
|
+
try {
|
|
546
|
+
await wait(() => expect(remote.indexSyncRequests).toEqual([['/same/path']]));
|
|
547
|
+
await wait(async () => expect((await (await hub.call('/api/hosts/remote-1/summaries')).json()).directories)
|
|
548
|
+
.toHaveLength(1));
|
|
549
|
+
const before = remote.indexRequests;
|
|
550
|
+
remote.emit({ type: 'yuri:session-index-changed', properties: { cause: 'change' } });
|
|
551
|
+
await wait(() => expect(remote.indexRequests).toBeGreaterThan(before));
|
|
552
|
+
expect(remote.indexSyncRequests).toHaveLength(1);
|
|
553
|
+
} finally { abort.abort(); await stream.body.cancel().catch(() => {}); }
|
|
554
|
+
});
|
|
555
|
+
it('forwards scoped form reads and replies to the remote authority', async () => {
|
|
556
|
+
const { hub, remote } = await aggregate();
|
|
557
|
+
remote.app.get('/api/form', (_req, res) => res.json([{ id: 'remote-form', sessionID: 'remote-session' }]));
|
|
558
|
+
remote.app.post('/api/form/:id/reply', express.json(), (req, res) => res.json({ id: req.params.id, reply: req.body }));
|
|
559
|
+
expect(await (await hub.call('/api/hosts/remote-1/api/form')).json()).toEqual([{ id: 'remote-form', sessionID: 'remote-session' }]);
|
|
560
|
+
expect(await (await hub.call('/api/hosts/remote-1/api/form/remote-form/reply', 'POST', { answers: ['yes'] })).json())
|
|
561
|
+
.toEqual({ id: 'remote-form', reply: { answers: ['yes'] } });
|
|
562
|
+
});
|
|
563
|
+
it('does not revive persisted busy status merely because a reconnect opened its status stream', async () => {
|
|
564
|
+
const { hub, remote } = await aggregate();
|
|
565
|
+
remote.setSummaries({ directories: [{ directory: '/same/path', hasMore: false, sessions: [{
|
|
566
|
+
id: 'busy-session', directory: '/same/path', title: 'Busy', time: { created: 1, updated: 2 },
|
|
567
|
+
metadata: { yuri: { sessionStatus: { type: 'busy', changedAt: Date.now() } } },
|
|
568
|
+
}] }] });
|
|
569
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
570
|
+
const firstAbort = new AbortController();
|
|
571
|
+
const first = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: firstAbort.signal });
|
|
572
|
+
const snapshot = async () => (await hub.call('/api/hosts/remote-1/summaries')).json();
|
|
573
|
+
await wait(async () => expect((await snapshot()).stale).toBe(false));
|
|
574
|
+
firstAbort.abort(); await first.body.cancel().catch(() => {});
|
|
575
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
576
|
+
let resume;
|
|
577
|
+
remote.setIndexGate(new Promise((resolve) => { resume = resolve; }));
|
|
578
|
+
const before = remote.indexRequests;
|
|
579
|
+
const secondAbort = new AbortController();
|
|
580
|
+
const second = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: secondAbort.signal });
|
|
581
|
+
try {
|
|
582
|
+
await wait(() => expect(remote.indexRequests).toBeGreaterThan(before));
|
|
583
|
+
const pending = await snapshot();
|
|
584
|
+
expect(pending.stale).toBe(true);
|
|
585
|
+
expect(pending.directories[0].sessions[0].metadata.yuri.sessionStatus.type).toBe('unknown');
|
|
586
|
+
resume();
|
|
587
|
+
await wait(async () => expect((await snapshot()).stale).toBe(false));
|
|
588
|
+
} finally { resume(); secondAbort.abort(); await second.body.cancel().catch(() => {}); }
|
|
589
|
+
});
|
|
590
|
+
it('keeps external worktree summaries and content under their authoritative remote project', async () => {
|
|
591
|
+
const { hub, remote } = await aggregate();
|
|
592
|
+
remote.setWorktrees(['/same/path', '/outside/branch']);
|
|
593
|
+
remote.setSummaries({ directories: ['/same/path', '/same/path/nested', '/outside/branch', '/unrelated'].map((directory, i) => ({
|
|
594
|
+
directory, sessions: [{ id: `session-${i}`, directory, title: directory, time: { created: 1, updated: 2 } }], hasMore: false,
|
|
595
|
+
})) });
|
|
596
|
+
expect((await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' })).status).toBe(200);
|
|
597
|
+
const abort = new AbortController();
|
|
598
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
599
|
+
const snapshot = async () => (await hub.call('/api/hosts/remote-1/summaries')).json();
|
|
600
|
+
try {
|
|
601
|
+
await wait(async () => expect((await snapshot()).directories.map((row) => row.directory).sort())
|
|
602
|
+
.toEqual(['/outside/branch', '/same/path', '/same/path/nested']));
|
|
603
|
+
expect((await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/outside/branch', sessionId: 'session-2' })).status).toBe(200);
|
|
604
|
+
expect((await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/unrelated', sessionId: 'session-3' })).status).toBe(404);
|
|
605
|
+
const reopened = createRemoteHostStore(path.join(hub.directory, 'remote-hosts.sqlite'));
|
|
606
|
+
try { expect(reopened.organization('remote-1').worktrees.projectDirectories['/same/path']).toEqual(['/same/path', '/outside/branch']); }
|
|
607
|
+
finally { reopened.close(); }
|
|
608
|
+
const worktreeRequests = remote.worktreeRequests;
|
|
609
|
+
const indexRequests = remote.indexRequests;
|
|
610
|
+
remote.emit({ type: 'yuri:session-index-changed', properties: { cause: 'change' } });
|
|
611
|
+
await wait(() => expect(remote.indexRequests).toBeGreaterThan(indexRequests));
|
|
612
|
+
await wait(async () => expect((await snapshot()).lastSyncedAt).toBeGreaterThan(0));
|
|
613
|
+
expect(remote.worktreeRequests).toBe(worktreeRequests);
|
|
614
|
+
remote.setWorktreeFailure(true);
|
|
615
|
+
remote.emit({ type: 'yuri:worktree-topology-changed', properties: { projectDirectory: '/same/path', directory: '/outside/branch', operation: 'removed' } });
|
|
616
|
+
await wait(async () => expect((await snapshot()).worktrees.staleProjectDirectories).toEqual(['/same/path']));
|
|
617
|
+
expect((await snapshot()).directories.some((row) => row.directory === '/outside/branch')).toBe(true);
|
|
618
|
+
remote.setWorktreeFailure(false);
|
|
619
|
+
remote.setWorktrees(['/same/path']);
|
|
620
|
+
remote.emit({ type: 'yuri:worktree-topology-changed', properties: { projectDirectory: '/same/path', directory: '/outside/branch', operation: 'removed' } });
|
|
621
|
+
await wait(async () => expect((await snapshot()).directories.some((row) => row.directory === '/outside/branch')).toBe(false));
|
|
622
|
+
expect((await snapshot()).worktrees.staleProjectDirectories).toEqual([]);
|
|
623
|
+
} finally {
|
|
624
|
+
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
it('maps only the effective nested source directory into each authoritative worktree', async () => {
|
|
628
|
+
const { hub, remote } = await aggregate();
|
|
629
|
+
remote.setWorktrees(['/repo', '/outside/branch']);
|
|
630
|
+
remote.setSummaries({ directories: ['/repo', '/repo/src', '/outside/branch', '/outside/branch/src', '/outside/branch/docs'].map((directory) => ({
|
|
631
|
+
directory, sessions: [], hasMore: false,
|
|
632
|
+
})) });
|
|
633
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/repo/src' });
|
|
634
|
+
const abort = new AbortController();
|
|
635
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
636
|
+
try {
|
|
637
|
+
await wait(async () => expect((await (await hub.call('/api/hosts/remote-1/summaries')).json()).directories.map((row) => row.directory).sort())
|
|
638
|
+
.toEqual(['/outside/branch/src', '/repo/src']));
|
|
639
|
+
expect((await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/outside/branch' })).status).toBe(404);
|
|
640
|
+
expect((await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/outside/branch/docs' })).status).toBe(404);
|
|
641
|
+
expect((await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/repo/src/../docs' })).status).toBe(404);
|
|
642
|
+
expect((await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/outside/branch/src' })).status).toBe(200);
|
|
643
|
+
const snapshot = await (await hub.call('/api/hosts/remote-1/summaries')).json();
|
|
644
|
+
expect(snapshot.worktrees.projectDirectories['/repo/src']).toEqual(['/repo/src', '/outside/branch/src']);
|
|
645
|
+
} finally { abort.abort(); await stream.body.cancel().catch(() => {}); }
|
|
646
|
+
});
|
|
647
|
+
it('keeps local-only startup at zero upstream requests/subscriptions and never exposes host credentials', async () => {
|
|
648
|
+
const { hub, remote } = await aggregate();
|
|
649
|
+
expect(remote.requests).toBe(0);
|
|
650
|
+
const response = await hub.call('/api/hosts');
|
|
651
|
+
const list = await response.json();
|
|
652
|
+
expect(list.hosts[0]).toMatchObject({ id: 'remote-1', source: 'direct', state: 'idle' });
|
|
653
|
+
expect(JSON.stringify(list)).not.toContain(remote.issued.token);
|
|
654
|
+
expect(JSON.stringify(list)).not.toContain(remote.url);
|
|
655
|
+
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
656
|
+
expect(remote.requests).toBe(0);
|
|
657
|
+
expect(remote.statusStreams).toBe(0);
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
it('rejects passwordless browsers, arbitrary cookies, unpaired clients and missing hosts', async () => {
|
|
661
|
+
const { hub } = await aggregate();
|
|
662
|
+
expect((await fetch(`${hub.url}/api/hosts`)).status).toBe(401);
|
|
663
|
+
expect((await fetch(`${hub.url}/api/hosts`, { headers: { Cookie: 'yuri_ui_session=forged' } })).status).toBe(401);
|
|
664
|
+
const ordinary = await hub.clients.createClient({ clientKind: 'mobile', authMethod: 'password' });
|
|
665
|
+
expect((await fetch(`${hub.url}/api/hosts`, { headers: { Authorization: `Bearer ${ordinary.token}` } })).status).toBe(403);
|
|
666
|
+
expect((await hub.call('/api/hosts/absent/api/fs/raw')).status).toBe(404);
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
it('creates remote first; retries a Hub disk failure by association without duplicating or deleting remote data', async () => {
|
|
670
|
+
const { hub, remote } = await aggregate({ failHubWrite: true });
|
|
671
|
+
const route = '/api/hosts/remote-1/projects';
|
|
672
|
+
expect((await hub.call(route, 'POST', { path: '/same/path', label: 'Remote project' })).status).toBe(503);
|
|
673
|
+
expect(remote.projects).toHaveLength(1);
|
|
674
|
+
const first = await (await hub.call(route, 'POST', { path: '/same/path' })).json();
|
|
675
|
+
expect(first.project).toMatchObject({ hostId: 'remote-1', path: '/same/path', remoteState: 'ok' });
|
|
676
|
+
const again = await (await hub.call(route, 'POST', { path: '/same/path' })).json();
|
|
677
|
+
expect(again.project.id).toBe(first.project.id);
|
|
678
|
+
expect(remote.projects).toHaveLength(1);
|
|
679
|
+
expect((await hub.call(`${route}/${first.project.id}`, 'PATCH', { label: 'Changed', color: 'blue' })).status).toBe(200);
|
|
680
|
+
expect(remote.projects[0].label).toBe('Changed');
|
|
681
|
+
expect((await hub.call(`${route}/${first.project.id}`, 'DELETE')).status).toBe(204);
|
|
682
|
+
expect(remote.projects).toHaveLength(1);
|
|
683
|
+
expect(hub.store.projects()).toHaveLength(0);
|
|
684
|
+
expect(remote.statusStreams).toBe(0);
|
|
685
|
+
expect(remote.indexRequests).toBe(0);
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
it('multiplexes one lightweight status stream, retains SQLite summaries offline and releases all streams on revoke', async () => {
|
|
689
|
+
const { hub, remote } = await aggregate();
|
|
690
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
691
|
+
remote.setSummaries({ directories: [{ directory: '/same/path', sessions: [{ id: 'same-session', title: 'Remote title',
|
|
692
|
+
directory: '/same/path', time: { created: 1, updated: 2 }, metadata: { yuri: { sessionStatus: { type: 'busy' } } } }], hasMore: false }] });
|
|
693
|
+
const abort = new AbortController();
|
|
694
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
695
|
+
const reader = stream.body.getReader();
|
|
696
|
+
const events = [];
|
|
697
|
+
const read = (async () => { try {
|
|
698
|
+
for (;;) { const value = await reader.read(); if (value.done) break; events.push(new TextDecoder().decode(value.value)); }
|
|
699
|
+
} catch { /* revoke/abort closes the stream */ } })();
|
|
700
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
701
|
+
await wait(async () => expect((await (await hub.call('/api/hosts/remote-1/summaries')).json()).directories[0]?.sessions[0]?.title).toBe('Remote title'));
|
|
702
|
+
remote.emit({ type: 'session.renamed', data: { sessionID: 'same-session', title: 'Renamed' }, created: Date.now() });
|
|
703
|
+
await wait(() => expect(events.join('')).toContain('Renamed'));
|
|
704
|
+
remote.emit({ type: 'message.part.delta', properties: { sessionID: 'same-session', delta: 'SECRET_BODY' } });
|
|
705
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
706
|
+
expect(events.join('')).not.toContain('SECRET_BODY');
|
|
707
|
+
await hub.clients.revokeClient(hub.issued.client.id);
|
|
708
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
709
|
+
await wait(() => expect(hub.liveClients).toBe(0));
|
|
710
|
+
abort.abort(); await read;
|
|
711
|
+
const snapshot = hub.gateway.summaries('remote-1');
|
|
712
|
+
expect(snapshot.stale).toBe(true);
|
|
713
|
+
expect(snapshot.directories[0].sessions[0].title).toBe('Renamed');
|
|
714
|
+
expect(snapshot.directories[0].sessions[0].metadata.yuri.sessionStatus.type).toBe('unknown');
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
it('preserves failed metadata writes and marks remote removal without deleting the Hub reference', async () => {
|
|
718
|
+
const { hub, remote } = await aggregate();
|
|
719
|
+
const route = '/api/hosts/remote-1/projects';
|
|
720
|
+
const { project } = await (await hub.call(route, 'POST', { path: '/same/path', label: 'Original' })).json();
|
|
721
|
+
remote.projects.splice(0);
|
|
722
|
+
const failed = await hub.call(`${route}/${project.id}`, 'PATCH', { label: 'Not committed' });
|
|
723
|
+
expect(failed.status).toBe(404);
|
|
724
|
+
expect(hub.store.projects()[0].label).toBe('Original');
|
|
725
|
+
const abort = new AbortController();
|
|
726
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
727
|
+
await wait(() => expect(hub.store.projects()[0].remoteState).toBe('remote-removed'));
|
|
728
|
+
expect(hub.store.projects()[0].id).toBe(project.id);
|
|
729
|
+
const restored = await (await hub.call(route, 'POST', { path: '/same/path', label: 'Restored' })).json();
|
|
730
|
+
expect(restored.project).toMatchObject({ id: project.id, label: 'Restored', remoteState: 'ok' });
|
|
731
|
+
expect(remote.projects).toHaveLength(1);
|
|
732
|
+
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
it('proxies content without Hub cache writes or client credentials and rejects machine mutations/recursive aggregation', async () => {
|
|
736
|
+
const { hub, remote } = await aggregate();
|
|
737
|
+
const response = await fetch(`${hub.url}/api/hosts/remote-1/api/session/s1/message?directory=%2Fsame%2Fpath`, {
|
|
738
|
+
method: 'POST', headers: { ...hub.headers, Cookie: 'private=hub-cookie' }, body: JSON.stringify({ text: 'UNIQUE_TRANSCRIPT_MARKER' }),
|
|
739
|
+
});
|
|
740
|
+
const payload = await response.json();
|
|
741
|
+
expect(payload.received.text).toBe('UNIQUE_TRANSCRIPT_MARKER');
|
|
742
|
+
expect(remote.messageHeaders.authorization).toBe(`Bearer ${remote.issued.token}`);
|
|
743
|
+
expect(remote.messageHeaders.cookie).toBeUndefined();
|
|
744
|
+
expect(JSON.stringify(payload)).not.toContain(remote.issued.token);
|
|
745
|
+
for (const route of ['api/config', 'api/hosts', 'api/yuri/transcript-cache/session', 'api/system/update']) {
|
|
746
|
+
expect((await hub.call(`/api/hosts/remote-1/${route}`, 'POST', {})).status).toBe(403);
|
|
747
|
+
}
|
|
748
|
+
expect((await hub.call('/api/yuri/transcript-cache/session?hostId=remote-1&transport=remote:hub:host&generation=0&directory=/same/path&sessionID=s1')).status).toBe(403);
|
|
749
|
+
for (const name of ['remote-hosts.sqlite', 'session-index.sqlite', 'transcript-cache.sqlite']) {
|
|
750
|
+
const bytes = await fs.readFile(path.join(hub.directory, name)).catch((error) => {
|
|
751
|
+
if (error.code === 'ENOENT') return Buffer.alloc(0); throw error;
|
|
752
|
+
});
|
|
753
|
+
expect(bytes.includes(Buffer.from('UNIQUE_TRANSCRIPT_MARKER'))).toBe(false);
|
|
754
|
+
}
|
|
755
|
+
const Database = require('better-sqlite3');
|
|
756
|
+
const db = new Database(path.join(hub.directory, 'transcript-cache.sqlite'));
|
|
757
|
+
expect(db.prepare('SELECT count(*) AS n FROM transcript_cache_content').get().n).toBe(0);
|
|
758
|
+
db.close();
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
it('shares content leases across clients and refuses a ninth active subscription instead of evicting readers', async () => {
|
|
762
|
+
const { hub, remote } = await aggregate();
|
|
763
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
764
|
+
const abort = new AbortController();
|
|
765
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
766
|
+
const lease = async (sessionId) => hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/same/path', sessionId });
|
|
767
|
+
const a = await (await lease('s0')).json();
|
|
768
|
+
const b = await (await lease('s0')).json();
|
|
769
|
+
await wait(() => expect(remote.content.size).toBe(1));
|
|
770
|
+
await hub.call(`/api/hosts/remote-1/subscriptions/${a.id}`, 'DELETE');
|
|
771
|
+
expect(remote.content.size).toBe(1);
|
|
772
|
+
for (let i = 1; i < 8; i++) expect((await lease(`s${i}`)).status).toBe(200);
|
|
773
|
+
expect((await lease('s9')).status).toBe(429);
|
|
774
|
+
expect(remote.content.size).toBeLessThanOrEqual(8);
|
|
775
|
+
await hub.call(`/api/hosts/remote-1/subscriptions/${b.id}`, 'DELETE');
|
|
776
|
+
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
777
|
+
await wait(() => expect(remote.content.size).toBe(0));
|
|
778
|
+
});
|
|
779
|
+
|
|
780
|
+
it('routes terminal WebSocket upgrades through the host prefix with real credentials', async () => {
|
|
781
|
+
const { hub } = await aggregate();
|
|
782
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
783
|
+
await once(socket, 'open');
|
|
784
|
+
const reply = once(socket, 'message'); socket.send('terminal input');
|
|
785
|
+
expect((await reply)[0].toString()).toBe('terminal input');
|
|
786
|
+
socket.close(); await once(socket, 'close');
|
|
787
|
+
});
|
|
788
|
+
|
|
789
|
+
it('shares one delayed SSH preparation and transport across simultaneous cold HTTP requests', async () => {
|
|
790
|
+
const remote = await host();
|
|
791
|
+
const descriptor = { id: 'ssh-cold', source: 'ssh', apiUrl: remote.url, clientToken: remote.issued.token };
|
|
792
|
+
let release;
|
|
793
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
794
|
+
const prepareHost = vi.fn(async () => { await gate; return descriptor; });
|
|
795
|
+
const hub = await host({ adapter: { listHosts: async () => [descriptor], prepareHost } });
|
|
796
|
+
const requests = Array.from({ length: 5 }, async () => {
|
|
797
|
+
const response = await hub.call('/api/hosts/ssh-cold/api/fs/raw');
|
|
798
|
+
return { status: response.status, body: await response.text() };
|
|
799
|
+
});
|
|
800
|
+
await wait(() => expect(prepareHost).toHaveBeenCalledTimes(1));
|
|
801
|
+
release();
|
|
802
|
+
expect(await Promise.all(requests)).toEqual(Array.from({ length: 5 }, () => ({ status: 200, body: 'remote file body' })));
|
|
803
|
+
expect(prepareHost).toHaveBeenCalledTimes(1);
|
|
804
|
+
expect(remote.capabilityRequests).toBe(1);
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
it('explicit connect waits through SSH preparation and remote admission without starting directory or status reads', async () => {
|
|
808
|
+
const remote = await host();
|
|
809
|
+
const descriptor = { id: 'ssh-cold', source: 'ssh', apiUrl: remote.url, clientToken: remote.issued.token };
|
|
810
|
+
let sshReady;
|
|
811
|
+
let serviceReady;
|
|
812
|
+
const sshGate = new Promise((resolve) => { sshReady = resolve; });
|
|
813
|
+
remote.setCapabilityGate(new Promise((resolve) => { serviceReady = resolve; }));
|
|
814
|
+
const prepareHost = vi.fn(async () => { await sshGate; return descriptor; });
|
|
815
|
+
const hub = await host({ adapter: { listHosts: async () => [descriptor], prepareHost }, requestTimeoutMs: 5000 });
|
|
816
|
+
let completed = false;
|
|
817
|
+
const connection = hub.call('/api/hosts/ssh-cold/connect', 'POST').then((response) => { completed = true; return response; });
|
|
818
|
+
try {
|
|
819
|
+
await wait(() => expect(prepareHost).toHaveBeenCalledOnce());
|
|
820
|
+
expect(completed).toBe(false);
|
|
821
|
+
expect(remote.requests).toBe(0);
|
|
822
|
+
sshReady();
|
|
823
|
+
await wait(() => expect(remote.capabilityRequests).toBe(1));
|
|
824
|
+
expect(completed).toBe(false);
|
|
825
|
+
serviceReady();
|
|
826
|
+
const response = await connection;
|
|
827
|
+
expect(response.status).toBe(200);
|
|
828
|
+
expect((await response.json()).host).toMatchObject({ id: 'ssh-cold', version: 'test-version' });
|
|
829
|
+
expect(remote.requests).toBe(1);
|
|
830
|
+
expect(remote.statusStreams).toBe(0);
|
|
831
|
+
expect(remote.indexRequests).toBe(0);
|
|
832
|
+
} finally {
|
|
833
|
+
sshReady(); serviceReady();
|
|
834
|
+
await connection;
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
it('isolates colliding host/session paths, keeps offline partitions and fairly bounds refresh work with a stalled host', async () => {
|
|
839
|
+
const stats = { active: 0, max: 0 };
|
|
840
|
+
const remotes = await Promise.all(Array.from({ length: 3 }, () => host({ indexStats: stats })));
|
|
841
|
+
const descriptors = remotes.map((remote, index) => ({ id: `host-${index}`, name: `Host ${index}`, source: 'direct',
|
|
842
|
+
apiUrl: remote.url, clientToken: remote.issued.token }));
|
|
843
|
+
const hub = await host({ adapter: { listHosts: async () => descriptors }, requestTimeoutMs: 2000 });
|
|
844
|
+
const summary = (title) => ({ directories: [{ directory: '/same/path', sessions: [{ id: 'same-id', title,
|
|
845
|
+
directory: '/same/path', time: { created: 1, updated: Date.now() } }], hasMore: false }] });
|
|
846
|
+
for (let index = 0; index < 3; index++) {
|
|
847
|
+
remotes[index].setSummaries(summary(`Title ${index}`));
|
|
848
|
+
expect((await hub.call(`/api/hosts/host-${index}/projects`, 'POST', { path: '/same/path' })).status).toBe(200);
|
|
849
|
+
}
|
|
850
|
+
expect(new Set(hub.store.projects().map((project) => project.id)).size).toBe(3);
|
|
851
|
+
const abort = new AbortController();
|
|
852
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
853
|
+
for (let index = 0; index < 3; index++) await wait(async () => {
|
|
854
|
+
const snapshot = await (await hub.call(`/api/hosts/host-${index}/summaries`)).json();
|
|
855
|
+
expect(snapshot.directories[0]?.sessions[0]?.title).toBe(`Title ${index}`);
|
|
856
|
+
});
|
|
857
|
+
let release;
|
|
858
|
+
remotes[0].setIndexGate(new Promise((resolve) => { release = resolve; }));
|
|
859
|
+
for (let index = 0; index < 3; index++) {
|
|
860
|
+
remotes[index].setSummaries(summary(`New ${index}`));
|
|
861
|
+
remotes[index].broadcast({ type: 'yuri:session-index-changed', properties: { cause: 'change' } });
|
|
862
|
+
}
|
|
863
|
+
for (const index of [1, 2]) await wait(async () => {
|
|
864
|
+
const snapshot = await (await hub.call(`/api/hosts/host-${index}/summaries`)).json();
|
|
865
|
+
expect(snapshot.directories[0]?.sessions[0]?.title).toBe(`New ${index}`);
|
|
866
|
+
});
|
|
867
|
+
expect(remotes[0].indexActive).toBe(1);
|
|
868
|
+
expect(stats.max).toBeLessThanOrEqual(2);
|
|
869
|
+
expect(remotes.every((remote) => remote.indexMax === 1)).toBe(true);
|
|
870
|
+
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
871
|
+
await wait(() => expect(remotes.every((remote) => remote.statusStreams === 0)).toBe(true));
|
|
872
|
+
await wait(() => expect(remotes[0].indexActive).toBe(0));
|
|
873
|
+
release();
|
|
874
|
+
const reopened = createRemoteHostStore(path.join(hub.directory, 'remote-hosts.sqlite'));
|
|
875
|
+
const offline = createRemoteHostGateway({ store: reopened, indexDbPath: path.join(hub.directory, 'session-index.sqlite') });
|
|
876
|
+
expect(reopened.hubId).toBe(hub.store.hubId);
|
|
877
|
+
expect(offline.summaries('host-0').directories[0].sessions[0].title).toBe('Title 0');
|
|
878
|
+
expect(offline.summaries('host-1').directories[0].sessions[0].title).toBe('New 1');
|
|
879
|
+
expect(offline.summaries('host-2').directories[0].sessions[0].title).toBe('New 2');
|
|
880
|
+
offline.stop();
|
|
881
|
+
});
|
|
882
|
+
|
|
883
|
+
it('never sends host content to anonymous or unpaired global-stream consumers', async () => {
|
|
884
|
+
const { hub, remote } = await aggregate();
|
|
885
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
886
|
+
const aborts = [new AbortController(), new AbortController()];
|
|
887
|
+
const authorized = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: aborts[0].signal });
|
|
888
|
+
const unauthorized = await fetch(`${hub.url}/api/global/event`, { signal: aborts[1].signal });
|
|
889
|
+
const text = ['', ''];
|
|
890
|
+
const reads = [authorized, unauthorized].map(async (response, index) => {
|
|
891
|
+
try { for await (const chunk of response.body) text[index] += new TextDecoder().decode(chunk); } catch { /* Stream disposal. */ }
|
|
892
|
+
});
|
|
893
|
+
await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/same/path', sessionId: 's1' });
|
|
894
|
+
await wait(() => expect(remote.content.size).toBe(1));
|
|
895
|
+
for (const res of remote.content) res.write(`data: ${JSON.stringify({ type: 'message.part.delta', properties: { sessionID: 's1', delta: 'AUTHORIZED_REMOTE_CONTENT' } })}\n\n`);
|
|
896
|
+
await wait(() => expect(text[0]).toContain('AUTHORIZED_REMOTE_CONTENT'));
|
|
897
|
+
expect(text[1]).not.toContain('yuri:host-');
|
|
898
|
+
expect(text[1]).not.toContain('AUTHORIZED_REMOTE_CONTENT');
|
|
899
|
+
for (const abort of aborts) abort.abort(); await Promise.all(reads);
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
it('closes direct terminal sockets when the saved host or credential is removed', async () => {
|
|
903
|
+
const { hub, setHosts } = await aggregate();
|
|
904
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
905
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
906
|
+
await once(socket, 'open');
|
|
907
|
+
const closed = once(socket, 'close');
|
|
908
|
+
setHosts([]);
|
|
909
|
+
await closed;
|
|
910
|
+
const list = await (await hub.call('/api/hosts')).json();
|
|
911
|
+
expect(list.projects[0].remoteState).toBe('host-unavailable');
|
|
912
|
+
expect(list.hosts[0]).toMatchObject({ id: 'remote-1', available: false, state: 'offline' });
|
|
913
|
+
});
|
|
914
|
+
|
|
915
|
+
it('does not resurrect a content lease if its owner is revoked while the host is connecting', async () => {
|
|
916
|
+
const { hub, remote } = await aggregate();
|
|
917
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
918
|
+
let release;
|
|
919
|
+
remote.setCapabilityGate(new Promise((resolve) => { release = resolve; }));
|
|
920
|
+
const before = remote.capabilityRequests;
|
|
921
|
+
const pending = hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/same/path', sessionId: 'pending' });
|
|
922
|
+
await wait(() => expect(remote.capabilityRequests).toBeGreaterThan(before));
|
|
923
|
+
await hub.clients.revokeClient(hub.issued.client.id);
|
|
924
|
+
release();
|
|
925
|
+
expect((await pending).status).toBe(401);
|
|
926
|
+
expect(remote.content.size).toBe(0);
|
|
927
|
+
});
|
|
928
|
+
|
|
929
|
+
it('closes existing direct terminal sockets when the issuing Hub client is revoked', async () => {
|
|
930
|
+
const { hub } = await aggregate();
|
|
931
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
932
|
+
await once(socket, 'open');
|
|
933
|
+
const closed = once(socket, 'close');
|
|
934
|
+
await hub.clients.revokeClient(hub.issued.client.id);
|
|
935
|
+
await closed;
|
|
936
|
+
expect((await hub.call('/api/hosts')).status).toBe(401);
|
|
937
|
+
});
|
|
938
|
+
|
|
939
|
+
it('rejects a terminal upgrade if its client is revoked during the upstream handshake', async () => {
|
|
940
|
+
const { hub, remote } = await aggregate();
|
|
941
|
+
let admit;
|
|
942
|
+
remote.setCapabilityGate(new Promise((resolve) => { admit = resolve; }));
|
|
943
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
944
|
+
let opened = false;
|
|
945
|
+
socket.on('open', () => { opened = true; });
|
|
946
|
+
socket.on('error', () => {});
|
|
947
|
+
try {
|
|
948
|
+
await wait(() => expect(remote.capabilityRequests).toBeGreaterThan(0));
|
|
949
|
+
await hub.clients.revokeClient(hub.issued.client.id);
|
|
950
|
+
admit();
|
|
951
|
+
await wait(() => expect(socket.readyState).toBe(WebSocket.CLOSED));
|
|
952
|
+
expect(opened).toBe(false);
|
|
953
|
+
} finally {
|
|
954
|
+
admit();
|
|
955
|
+
socket.terminate();
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
|
|
959
|
+
it('bounds response-header waits even for the streaming HTTP proxy', async () => {
|
|
960
|
+
const { hub, remote } = await aggregate({ requestTimeoutMs: 200 });
|
|
961
|
+
remote.app.get('/api/session/stall', (_req, _res) => {});
|
|
962
|
+
const controller = new AbortController();
|
|
963
|
+
let status;
|
|
964
|
+
const request = fetch(`${hub.url}/api/hosts/remote-1/api/session/stall`, {
|
|
965
|
+
headers: hub.headers, signal: controller.signal,
|
|
966
|
+
}).then((response) => { status = response.status; }, () => {});
|
|
967
|
+
try {
|
|
968
|
+
await wait(() => expect(status).toBe(503));
|
|
969
|
+
} finally {
|
|
970
|
+
controller.abort();
|
|
971
|
+
await request;
|
|
972
|
+
}
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
it('continues another hosts refresh while an interactive response body is still streaming', async () => {
|
|
976
|
+
const slow = await host();
|
|
977
|
+
const fast = await host();
|
|
978
|
+
const hub = await host({ adapter: { listHosts: async () => [
|
|
979
|
+
{ id: 'slow', source: 'direct', apiUrl: slow.url, clientToken: slow.issued.token },
|
|
980
|
+
{ id: 'fast', source: 'direct', apiUrl: fast.url, clientToken: fast.issued.token },
|
|
981
|
+
] } });
|
|
982
|
+
for (const id of ['slow', 'fast']) await hub.call(`/api/hosts/${id}/projects`, 'POST', { path: '/same/path' });
|
|
983
|
+
const streams = new AbortController();
|
|
984
|
+
const globalStream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: streams.signal });
|
|
985
|
+
const requestAbort = new AbortController();
|
|
986
|
+
let response;
|
|
987
|
+
try {
|
|
988
|
+
await wait(() => expect(fast.statusStreams).toBe(1));
|
|
989
|
+
await wait(async () => expect((await (await hub.call('/api/hosts/fast/summaries')).json()).lastSyncedAt).toBeGreaterThan(0));
|
|
990
|
+
slow.app.get('/api/session/stream', (_req, res) => {
|
|
991
|
+
res.type('application/json'); res.flushHeaders(); res.write('{');
|
|
992
|
+
});
|
|
993
|
+
response = await fetch(`${hub.url}/api/hosts/slow/api/session/stream`, {
|
|
994
|
+
headers: hub.headers, signal: requestAbort.signal,
|
|
995
|
+
});
|
|
996
|
+
const previous = fast.indexRequests;
|
|
997
|
+
fast.emit({ type: 'yuri:session-index-changed', properties: { cause: 'change' } });
|
|
998
|
+
await wait(() => expect(fast.indexRequests).toBeGreaterThan(previous));
|
|
999
|
+
} finally {
|
|
1000
|
+
requestAbort.abort(); streams.abort();
|
|
1001
|
+
await response?.body?.cancel().catch(() => {});
|
|
1002
|
+
await globalStream.body.cancel().catch(() => {});
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
it('times out incomplete session JSON but allows a file body to outlive that deadline', async () => {
|
|
1007
|
+
const { hub, remote } = await aggregate({ requestTimeoutMs: 200 });
|
|
1008
|
+
remote.app.get('/api/session/incomplete', (_req, res) => {
|
|
1009
|
+
res.type('application/json'); res.flushHeaders(); res.write('{');
|
|
1010
|
+
});
|
|
1011
|
+
const controller = new AbortController();
|
|
1012
|
+
const incomplete = await fetch(`${hub.url}/api/hosts/remote-1/api/session/incomplete`, {
|
|
1013
|
+
headers: hub.headers, signal: controller.signal,
|
|
1014
|
+
});
|
|
1015
|
+
let rejected = false;
|
|
1016
|
+
const body = incomplete.text().catch(() => { rejected = true; });
|
|
1017
|
+
try {
|
|
1018
|
+
await wait(() => expect(rejected).toBe(true));
|
|
1019
|
+
} finally {
|
|
1020
|
+
controller.abort(); await body;
|
|
1021
|
+
}
|
|
1022
|
+
let release;
|
|
1023
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
1024
|
+
remote.app.get('/api/fs/serve/large', async (_req, res) => {
|
|
1025
|
+
res.type('application/octet-stream'); res.flushHeaders(); res.write('first-');
|
|
1026
|
+
await gate;
|
|
1027
|
+
res.end('last');
|
|
1028
|
+
});
|
|
1029
|
+
const file = await hub.call('/api/hosts/remote-1/api/fs/serve/large');
|
|
1030
|
+
const content = file.text();
|
|
1031
|
+
try {
|
|
1032
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
1033
|
+
release();
|
|
1034
|
+
expect(await content).toBe('first-last');
|
|
1035
|
+
} finally {
|
|
1036
|
+
release();
|
|
1037
|
+
}
|
|
1038
|
+
});
|
|
1039
|
+
|
|
1040
|
+
it('does not apply the short snapshot timeout to a synchronous shell operation', async () => {
|
|
1041
|
+
const { hub, remote } = await aggregate({ requestTimeoutMs: 100, operationTimeoutMs: 2000 });
|
|
1042
|
+
remote.app.post('/api/session/task/shell', async (_req, res) => {
|
|
1043
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1044
|
+
res.json({ complete: true });
|
|
1045
|
+
});
|
|
1046
|
+
const response = await hub.call('/api/hosts/remote-1/api/session/task/shell', 'POST', { command: 'fixture' });
|
|
1047
|
+
expect(response.status).toBe(200);
|
|
1048
|
+
expect(await response.json()).toEqual({ complete: true });
|
|
1049
|
+
});
|
|
1050
|
+
|
|
1051
|
+
it('closes direct terminal sockets after the target revokes its saved credential', async () => {
|
|
1052
|
+
const { hub, remote } = await aggregate();
|
|
1053
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
1054
|
+
const abort = new AbortController();
|
|
1055
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
1056
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
1057
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/remote-1/api/terminal/ws`, { headers: hub.headers });
|
|
1058
|
+
await once(socket, 'open');
|
|
1059
|
+
const closed = once(socket, 'close');
|
|
1060
|
+
await remote.clients.revokeClient(remote.issued.client.id);
|
|
1061
|
+
await closed;
|
|
1062
|
+
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
1063
|
+
});
|
|
1064
|
+
|
|
1065
|
+
it('sends ready for each shared lease and changes ready generation after content reconnect', async () => {
|
|
1066
|
+
const { hub, remote } = await aggregate();
|
|
1067
|
+
await hub.call('/api/hosts/remote-1/projects', 'POST', { path: '/same/path' });
|
|
1068
|
+
const abort = new AbortController();
|
|
1069
|
+
const response = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
1070
|
+
let text = '';
|
|
1071
|
+
const read = (async () => { try { for await (const chunk of response.body) text += new TextDecoder().decode(chunk); } catch { /* Stream disposal. */ } })();
|
|
1072
|
+
const first = await (await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/same/path', sessionId: 'shared' })).json();
|
|
1073
|
+
await wait(() => expect(text).toContain(first.id));
|
|
1074
|
+
const second = await (await hub.call('/api/hosts/remote-1/subscriptions', 'POST', { directory: '/same/path', sessionId: 'shared' })).json();
|
|
1075
|
+
expect(second.channelId).toBe(first.channelId);
|
|
1076
|
+
await wait(() => expect(text).toContain(second.id));
|
|
1077
|
+
const generations = () => [...text.matchAll(/"readyGeneration":"([^"]+)"/g)].map((match) => match[1]);
|
|
1078
|
+
const initial = generations()[0];
|
|
1079
|
+
await hub.call(`/api/hosts/remote-1/subscriptions/${first.id}`, 'DELETE');
|
|
1080
|
+
for (const res of remote.content) res.end();
|
|
1081
|
+
await wait(() => expect(new Set(generations()).size).toBeGreaterThan(1));
|
|
1082
|
+
expect(generations().at(-1)).not.toBe(initial);
|
|
1083
|
+
abort.abort(); await read;
|
|
1084
|
+
});
|
|
1085
|
+
|
|
1086
|
+
it('keeps preview registration, HTML subresources and redirects on the selected host without forwarding Hub URL tokens', async () => {
|
|
1087
|
+
const { hub } = await aggregate();
|
|
1088
|
+
const target = http.createServer((req, res) => {
|
|
1089
|
+
if (req.url === '/asset.css') { res.writeHead(200, { 'Content-Type': 'text/css' }); res.end('body{color:red}'); return; }
|
|
1090
|
+
if (req.url === '/redirect') { res.writeHead(302, { Location: '/next' }); res.end(); return; }
|
|
1091
|
+
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><link rel="stylesheet" href="/asset.css"><body>Remote preview</body>');
|
|
1092
|
+
});
|
|
1093
|
+
target.listen(0, '127.0.0.1'); await once(target, 'listening');
|
|
1094
|
+
disposers.push(() => new Promise((resolve) => target.close(resolve)));
|
|
1095
|
+
const registration = await (await hub.call('/api/hosts/remote-1/api/preview/targets', 'POST', {
|
|
1096
|
+
url: `http://127.0.0.1:${target.address().port}`,
|
|
1097
|
+
})).json();
|
|
1098
|
+
expect(registration.proxyBasePath).toMatch(/^\/api\/hosts\/remote-1\/api\/preview\/proxy\//);
|
|
1099
|
+
const authResponse = await hub.call('/auth/url-token', 'POST');
|
|
1100
|
+
const token = (await authResponse.json()).token;
|
|
1101
|
+
const previewUrl = `${hub.url}${registration.proxyBasePath}/?yuri_preview_token=${registration.previewToken}&yuri_url_token=${token}`;
|
|
1102
|
+
const html = await (await fetch(previewUrl)).text();
|
|
1103
|
+
expect(html).toContain('/api/hosts/remote-1/api/preview/proxy/');
|
|
1104
|
+
expect(html).not.toContain('__YURI_HUB_URL_AUTH__');
|
|
1105
|
+
const assetMatch = html.match(/href="([^"]*asset\.css[^"]*)"/);
|
|
1106
|
+
expect(assetMatch).not.toBeNull();
|
|
1107
|
+
expect((await fetch(`${hub.url}${assetMatch[1].replaceAll('&', '&')}`)).status).toBe(200);
|
|
1108
|
+
const redirect = await fetch(`${hub.url}${registration.proxyBasePath}/redirect?yuri_preview_token=${registration.previewToken}&yuri_url_token=${token}`, { redirect: 'manual' });
|
|
1109
|
+
expect(redirect.status).toBe(302);
|
|
1110
|
+
expect(redirect.headers.get('location')).toContain(`${registration.proxyBasePath}/next`);
|
|
1111
|
+
});
|
|
1112
|
+
|
|
1113
|
+
it.each([0, 1, 2])('uses the real E2EE Relay client for Relay-only hosts, including terminal forwarding (%i)', async (iteration) => {
|
|
1114
|
+
const productionTerminal = iteration === 2;
|
|
1115
|
+
const remote = await host({ requireClientAuth: true, productionTerminal });
|
|
1116
|
+
const relay = createPrivateRelayServer({ host: '127.0.0.1', port: 0 });
|
|
1117
|
+
await relay.start();
|
|
1118
|
+
const encryption = await generateEcdhKeyPair();
|
|
1119
|
+
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
|
1120
|
+
const jwk = publicKey.export({ format: 'jwk' });
|
|
1121
|
+
const canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
|
|
1122
|
+
const serverId = crypto.createHash('sha256').update(canonical).digest('base64url');
|
|
1123
|
+
const identity = { serverId, hostEncPubJwk: await exportPublicKeyJwk(encryption.publicKey), hostEncPrivateKey: encryption.privateKey,
|
|
1124
|
+
signRelayAuth(role, connectionId) {
|
|
1125
|
+
const ts = Date.now();
|
|
1126
|
+
return { ts, sig: crypto.sign('SHA256', Buffer.from(`${ts}.${serverId}.${role}.${connectionId || ''}`),
|
|
1127
|
+
{ key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url'), pk: Buffer.from(canonical).toString('base64url') };
|
|
1128
|
+
} };
|
|
1129
|
+
const relayUrl = relay.wsUrl;
|
|
1130
|
+
const relayHost = startRelayHost({ relayUrl, identity, getLocalPort: () => remote.server.address().port,
|
|
1131
|
+
authorizeRequest: remote.auth.authorizeRelayRequest, onStatus: () => {}, logger: { info() {}, warn() {} } });
|
|
1132
|
+
disposers.push(async () => { relayHost.stop(); await relay.stop(); });
|
|
1133
|
+
const paired = await remote.clients.createClient({ clientKind: 'desktop', authMethod: 'pairing', pairingId: 'relay-pair', usesRelay: true });
|
|
1134
|
+
const descriptor = { id: 'relay-only', name: 'Relay Host', source: 'relay', clientToken: paired.token,
|
|
1135
|
+
relay: { relayUrl, serverId, hostEncPubJwk: identity.hostEncPubJwk } };
|
|
1136
|
+
const hub = await host({ adapter: { listHosts: async () => [descriptor] }, requestTimeoutMs: 5000 });
|
|
1137
|
+
if (productionTerminal) {
|
|
1138
|
+
const authorize = hub.auth.resolveAuthContext;
|
|
1139
|
+
let upgrades = 0;
|
|
1140
|
+
hub.auth.resolveAuthContext = async (...args) => {
|
|
1141
|
+
const result = await authorize(...args);
|
|
1142
|
+
if (args[0].headers.upgrade === 'websocket' && ++upgrades === 2) await new Promise((resolve) => setTimeout(resolve, 30));
|
|
1143
|
+
return result;
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
const reads = await Promise.all(Array.from({ length: 5 }, async () => {
|
|
1147
|
+
const response = await hub.call('/api/hosts/relay-only/api/fs/raw');
|
|
1148
|
+
return { status: response.status, body: await response.text() };
|
|
1149
|
+
}));
|
|
1150
|
+
expect(reads).toEqual(Array.from({ length: 5 }, () => ({ status: 200, body: 'remote file body' })));
|
|
1151
|
+
const abort = new AbortController();
|
|
1152
|
+
const stream = await fetch(`${hub.url}/api/global/event`, { headers: hub.headers, signal: abort.signal });
|
|
1153
|
+
const created = await hub.call('/api/hosts/relay-only/projects', 'POST', { path: '/same/path' });
|
|
1154
|
+
expect({ status: created.status, body: await created.json() }).toMatchObject({ status: 200,
|
|
1155
|
+
body: { project: { hostId: 'relay-only', path: '/same/path' } } });
|
|
1156
|
+
await wait(() => expect(remote.statusStreams).toBe(1));
|
|
1157
|
+
const socket = new WebSocket(`${hub.url.replace('http:', 'ws:')}/api/hosts/relay-only/api/terminal/ws`, { headers: hub.headers });
|
|
1158
|
+
disposers.push(() => socket.terminate());
|
|
1159
|
+
const frames = [];
|
|
1160
|
+
if (productionTerminal) socket.on('message', (data) => frames.push(readTerminalWsControlFrame(data)));
|
|
1161
|
+
await once(socket, 'open');
|
|
1162
|
+
if (productionTerminal) {
|
|
1163
|
+
await wait(() => expect(frames).toContainEqual({ t: 'ok', v: 2 }));
|
|
1164
|
+
socket.send(createTerminalWsControlFrame({ t: 'p' }));
|
|
1165
|
+
await wait(() => expect(frames).toContainEqual({ t: 'po', v: 2 }));
|
|
1166
|
+
socket.send(createTerminalWsControlFrame({ t: 'b', s: 'missing-session' }));
|
|
1167
|
+
await wait(() => expect(frames).toContainEqual({ t: 'e', c: 'SESSION_NOT_FOUND', f: false }));
|
|
1168
|
+
} else {
|
|
1169
|
+
const reply = once(socket, 'message'); socket.send('encrypted terminal');
|
|
1170
|
+
expect((await reply)[0].toString()).toBe('encrypted terminal');
|
|
1171
|
+
}
|
|
1172
|
+
socket.close(); await once(socket, 'close');
|
|
1173
|
+
abort.abort(); await stream.body.cancel().catch(() => {});
|
|
1174
|
+
await wait(() => expect(remote.statusStreams).toBe(0));
|
|
1175
|
+
}, 20000);
|
|
1176
|
+
});
|