From 78274c7b78bfbaaa9f35703aad014228a994024a Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 02:22:03 +0800 Subject: [PATCH] =?UTF-8?q?fix(sidebar):=20/sidebar/*=20=E4=BC=A0=E8=BE=93?= =?UTF-8?q?=E6=8C=89=E9=A1=B5=E9=9D=A2=E5=89=8D=E7=BC=80=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=EF=BC=8C=E5=8F=8D=E4=BB=A3=E5=AD=90=E8=B7=AF=E5=BE=84=E4=B8=8B?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E7=94=A9=E6=8E=89=E5=89=8D=E7=BC=80=EF=BC=88?= =?UTF-8?q?#584=20=E7=A7=BB=E6=A4=8D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 贡献者 PR #584(fix: preserve reverse-proxy base paths,head 1ca99d8)的改动面在 dev 上仍然需要——JSON API / upload / file / html / bundle 与两条 WebSocket 都还是 源站绝对路径(带前导斜杠 → 反代子路径下 404 / 1006),目标 issue #753 仍 OPEN, docs/plans/2026-10-04-issue-triage.md 也把 #584 记为优先合入项。但它不能机械解冲突, 故按 dev 现有结构重写。 复用(PR 的可复用部分): - 新增 src/client/host-route-url.ts:hostRouteUrl() / hostWebSocketUrl() 先去前导 斜杠,再按注入基底解析;基底去 search/hash 并强制目录尾斜杠——launch token 查询串 与「缺尾斜杠的前缀」都不会吃掉路径最后一段。 改写(dev 侧已经变掉的东西): - 基底来源并进 dev 的 2718725:desktop-env.ts 的 sidebarWebSocketBase() 泛化为 hostTransportBase()(__DSH_TRANSPORT__.streamBaseUrl 优先,回落 document.baseURI), HTTP 与 WS 从此共用一个基底权威,而不是另起一套。丢弃 PR 的 hostDocumentBase() 「取 document.baseURI 与 location.href 中更长者」启发式:它会顶掉刚落地的桌面壳修复 (dsh-app://app/ 下 location.href 会重新拼出不可达的 ws://app/…),而基线 0.2.0-rc.1 的宿主产物里没有 (PR 自己的 e2e 也只采集、从不断言它)。 最终解析式与宿主 dsh-api-gateway 逐字同形(去前导斜杠 + 壳注入基底优先)。 - 丢弃 src/client/TerminalView.tsx 的改动:该文件在 dev 已删除(终端已交还宿主), 其覆盖的 WS 语义改由 dev 现存的两条调用点承担,并补齐 PR 文件清单里漏掉的 src/client/use-dir-watch.ts(fs-watch socket)。 调用点(一律相对路径 + 前缀解析):api.ts 的 JSON API / upload / file / html / archive、chunk-loader.ts 的 CHUNK_URL、markdown-images.ts 与 MarkdownHtml / TextEditor / DiffPane 的媒体改写(原 window.location.origin 在桌面壳下是 dsh-app://app,媒体同样不可达)、use-host-feeds.ts 与 use-dir-watch.ts 的两条 WebSocket。archiveDownloadUrl 是 PR 漏掉的同类调用点(FileTree 用它 fetch zip 字节), 一并纳入;open-in-app.ts 打的是宿主路由 /open-in-app/*,与 PR 明确不碰的宿主 /api 同类,不纳入。 消费插件契约(指南「接入 API 即文档」): - BetterSidebarService 新增 hostRouteUrl(path)(features 'hostRouteUrl'), docs/external-plugin-guide.md §6 / §7 / §15 的 fetch('/sidebar/api/…') 示例改为 经它解析,并写明「绝不写前导斜杠」。 验证:pnpm typecheck / pnpm exec vitest run(161 files / 1812 passed / 13 skipped)/ eslint 全绿。tests/base-path.spec.ts 钉前缀保留与基底优先级,并在真实调用点上断言 (api fetch 的 URL、chunk 注入的 script src、jsdom 下 fs-watch 的 socket URL); PR 自带的 base-path e2e 在 page.evaluate 里复制实现后自证,回归守不住,故不引入该 lane。 Refs #584 Co-authored-by: idoall <6040958+idoall@users.noreply.github.com> --- docs/external-plugin-guide.md | 33 +++++-- src/client/MarkdownHtml.tsx | 9 +- src/client/TextEditor.tsx | 5 +- src/client/api.ts | 22 +++-- src/client/changes/DiffPane.tsx | 3 +- src/client/chunk-loader.ts | 4 +- src/client/desktop-env.ts | 27 ++++-- src/client/host-route-url.ts | 57 +++++++++++ src/client/markdown-images.ts | 30 +++--- src/client/service.ts | 14 +++ src/client/sidebar/use-host-feeds.ts | 5 +- src/client/use-dir-watch.ts | 5 +- tests/archive-client.spec.ts | 7 +- tests/base-path.spec.ts | 138 +++++++++++++++++++++++++++ tests/browser-globals.ts | 4 + tests/chunk-loader.spec.ts | 34 ++++++- tests/file-tree-dir-watch.spec.tsx | 20 ++++ tests/markdown-html-render.spec.tsx | 12 +-- tests/open-external-client.spec.ts | 3 +- tests/paths.spec.ts | 7 +- tests/sandbox-views.spec.tsx | 6 +- tests/zip.spec.ts | 3 +- 22 files changed, 371 insertions(+), 77 deletions(-) create mode 100644 src/client/host-route-url.ts create mode 100644 tests/base-path.spec.ts diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index a325d8d1..5eda3369 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -2,7 +2,7 @@ > 面向 **消费插件开发者**:如何让你的插件向 better-sidebar 注册新的侧边栏页面(tab)和文件类型预览器。 > -> 适用版本:**v0.4.0+**(`ctx.betterSidebar` 服务);声明式设置 **v0.4.1+**;text/number 设置行 **v0.11.0+**;badge/生命周期/定向打开/插件设置/版本探测 **v0.12.0+**;select 设置行(`settingSelect`)与外链认领(`urlTarget`)**v0.13.0+**;统一 `@deepseek-ai/cordis` 类型基底 **v0.15.2+**。当前版本 **v0.24.0**(peer 下限 `^0.2.0-rc.1`,仅支持 DSH **0.2.0-rc.1+**;0.1.7 线请用 v0.23.0——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 会被 0.2.0 宿主的启动预检静默禁用)。**v0.19.0 移除了自绘右侧面板与自由窗口**(见 §0、§11);**自 v0.20.0 开发线起**(**注意:0.20.0 从未发布到 npm,这些变更全部落在 v0.21.1**)插件**移除了自带的终端**(宿主 0.1.6 的 `ui-sidebar-terminal` 取代,见 §4.4)、**移除了终端固定(pin)**,并在 0.1.7 上**把浏览器视图与只读文件预览整体让给宿主**(`ui-sidebar-browser` / `ui-sidebar-documentpreview`,见 §4.4、§5.4)、**收敛了外链接管**(见 §4.1)、**重写了设置接入面**(`SettingsForms`,见 §8.2)、**给文件树加了实时刷新**(见 §10);同时**删除了轮尾产物行接管**(DSH 0.1.6 把 `conversation.chat.turnTail` 从 chain 改成只能追加的 list,替换语义不复存在)。 +> 适用版本:**v0.4.0+**(`ctx.betterSidebar` 服务);声明式设置 **v0.4.1+**;text/number 设置行 **v0.11.0+**;badge/生命周期/定向打开/插件设置/版本探测 **v0.12.0+**;select 设置行(`settingSelect`)与外链认领(`urlTarget`)**v0.13.0+**;统一 `@deepseek-ai/cordis` 类型基底 **v0.15.2+**;路由前缀安全解析(`hostRouteUrl`)**v0.25.0+**。当前版本 **v0.24.0**(peer 下限 `^0.2.0-rc.1`,仅支持 DSH **0.2.0-rc.1+**;0.1.7 线请用 v0.23.0——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 会被 0.2.0 宿主的启动预检静默禁用)。**v0.19.0 移除了自绘右侧面板与自由窗口**(见 §0、§11);**自 v0.20.0 开发线起**(**注意:0.20.0 从未发布到 npm,这些变更全部落在 v0.21.1**)插件**移除了自带的终端**(宿主 0.1.6 的 `ui-sidebar-terminal` 取代,见 §4.4)、**移除了终端固定(pin)**,并在 0.1.7 上**把浏览器视图与只读文件预览整体让给宿主**(`ui-sidebar-browser` / `ui-sidebar-documentpreview`,见 §4.4、§5.4)、**收敛了外链接管**(见 §4.1)、**重写了设置接入面**(`SettingsForms`,见 §8.2)、**给文件树加了实时刷新**(见 §10);同时**删除了轮尾产物行接管**(DSH 0.1.6 把 `conversation.chat.turnTail` 从 chain 改成只能追加的 list,替换语义不复存在)。 > 权威代码:`src/client/service.ts`(服务实现)、`src/client/builtins/`(内置 5 tab + 3 viewer 参考实现)、`lib/types/client/service.d.ts`(类型声明)。 > 仓库开发规则(硬约束 / CI / 发版)见 [AGENTS.md](../AGENTS.md)。 @@ -596,7 +596,8 @@ ctx.effect(() => ```ts // POST /sidebar/api/,body 带 sessionId + cwd(可选) -const res = await fetch('/sidebar/api/fs.read', { +// 路由经 ctx.betterSidebar.hostRouteUrl() 解析(v0.25.0+):不要写前导斜杠 +const res = await fetch(ctx.betterSidebar.hostRouteUrl('sidebar/api/fs.read'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: scope.sessionId, path }), @@ -604,6 +605,8 @@ const res = await fetch('/sidebar/api/fs.read', { const { value } = await res.json() // 错误时 { ok: false, error: { code, message } } ``` +> **绝不写前导斜杠**(v0.25.0+,issue #753):`fetch('/sidebar/api/…')` 与 `new URL('/sidebar/ws/…', base)` 会把请求钉在**源站根**。反代把 GUI 挂在子路径时(如 `https://host/dataops/proxy/3080/`),请求会甩掉前缀 → JSON API 404、懒加载 chunk 加载不出来、媒体/HTML 预览空白、WebSocket 1006;桌面壳下 `dsh-app://app/` 更是直接不可达。`hostRouteUrl()` 用宿主同款的传输基底(壳注入的 `__DSH_TRANSPORT__.streamBaseUrl` 优先,回落 `document.baseURI`)解析相对路径,并把前缀原样保留;`features` 含 `'hostRouteUrl'` 时可用,旧版本回退到自查 `document.baseURI`(但拿不到桌面壳的真实基底)。你自己的 HTTP/WS 路由同理:一律**相对路径 + 页面前缀**。 + 常用方法(完整清单见 `src/client/api.ts`): | 方法 | 说明 | @@ -624,21 +627,24 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me 把若干文件/目录打成 ZIP 下载,并且**有进度可看**:选择项在 `archive.build` 里一次性收集(与 `fs.tree` 同一套词法解析——**无包含检查**,目录递归、符号链接跳过、同名条目用父目录消歧),打包在后台进行,客户端轮询进度、完成后取字节。 ```ts +// 路由助手同 §6:相对路径交给 hostRouteUrl,别写前导斜杠 +const route = (path: string): string => ctx.betterSidebar.hostRouteUrl(path) + // 1) 启动:paths 是会话命名空间里的绝对路径(与 fs.tree 的行 path 同形) -const build = await fetch('/sidebar/api/archive.build', { +const build = await fetch(route('sidebar/api/archive.build'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId, cwd, paths: ['/w/src', '/w/notes.md'], name: '报告.zip' }), }).then(r => r.json()) // → { ok: true, value: { id: 'ar-…', entries: 5 } } // 2) 轮询:state 为 building | ready | error;done/total 是条目进度,bytes 是已读未压缩字节 -const status = await fetch('/sidebar/api/archive.status', { +const status = await fetch(route('sidebar/api/archive.status'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: build.value.id, sessionId }), }).then(r => r.json()) // 3) 下载(仅 ready 时):同一 id 只能取一次,取完即释放 -const url = `/sidebar/archive?${new URLSearchParams({ sessionId, id: build.value.id })}` +const url = route(`sidebar/archive?${new URLSearchParams({ sessionId, id: build.value.id })}`) ``` 约束与状态码:任务表最多 **4 个并发构建**(超出时 `archive.build` 回 `bad-request`,HTTP 409),完成/失败后保留 **5 分钟**(过期即消失);`id` 只对**创建它的 session** 可用(其他 session 读是 `forbidden` 403);`/sidebar/archive` 在构建中回 **409**、构建失败回 **410**(消息即失败原因)、未知/过期/已下载回 **404**。响应头为 `content-type: application/zip` + `content-disposition: attachment; filename=""; filename*=UTF-8''<百分号编码>`(非 latin1 文件名走 RFC 5987,ASCII 档位对旧客户端生效)。上限沿用 `src/zip.ts` 的 `ZIP_MAX_ENTRIES = 10_000` 与 `ZIP_MAX_BYTES = 256 MiB`(未压缩总量)。 @@ -647,10 +653,12 @@ const url = `/sidebar/archive?${new URLSearchParams({ sessionId, id: build.value ```ts // 媒体 URL(图片等直接 ):/sidebar/file?sessionId=...&path=... -const url = `/sidebar/file?${new URLSearchParams({ sessionId: scope.sessionId, path })}` +const url = ctx.betterSidebar.hostRouteUrl( + `sidebar/file?${new URLSearchParams({ sessionId: scope.sessionId, path })}` +) ``` -> 注:内置的 `api.ts` 是 better-sidebar 内部模块,外部插件 **不要** value-import 它(构建纯度门会挡);按上表模式自己 fetch 即可。所有路由带与 `/api` 相同的 Host 头信任围栏,浏览器同源访问天然通过。 +> 注:内置的 `api.ts` 是 better-sidebar 内部模块,外部插件 **不要** value-import 它(构建纯度门会挡);按上表模式自己 fetch 即可,路由一律经 `hostRouteUrl()`(或等价的「相对路径 + 页面前缀」解析)。所有路由带与 `/api` 相同的 Host 头信任围栏,浏览器同源访问天然通过。 --- @@ -729,7 +737,7 @@ interface BetterSidebarService { /** 能力清单(只增不删,唯一例外:v0.19.0 删除了 'floatWindows'): * 'badge' | 'tabLifecycle' | 'updateTab' | 'openFile' | 'targetedOpen' | * 'stateSubscription' | 'tabMeta' | 'pluginSettings' | 'urlTarget' | - * 'settingSelect' | 'fileIcons' | 'rightActions' + * 'settingSelect' | 'fileIcons' | 'rightActions' | 'hostRouteUrl' * ——用 `features.includes('xxx')` 按能力 gate。 */ readonly features: readonly string[] /** 当前快照:激活 sessionId + 其状态(面板几何/打开的 tabs/展开集)+ prefs。 @@ -750,6 +758,11 @@ interface BetterSidebarService { * 注意:path 派生 id 只对 openFile/openSidebarFile 成立;editorExplorer 合并模式的 * 原地切换经 updateTab 重写 path/title,tab id 保持稳定、不再对应 path。 */ openFile(scope: SessionScope, path: string, title?: string): void + /** 把插件自有 host 路由(如 `'sidebar/api/fs.read'`)解析成绝对 URL, + * 保留反代子路径前缀(v0.25.0+,features 含 'hostRouteUrl')。前导斜杠会被 + * 去掉——带着它就会甩掉前缀、钉到源站根;桌面壳的真实基底也由它给出。 + * 详见 §6 的前缀安全说明。 */ + hostRouteUrl(path: string): string } /** openTab 的 seed(v0.12.0 起导出命名类型)。 */ @@ -1098,7 +1111,7 @@ interface SettingsDescriptor { } ``` -**`my-plugin/src/client/index.tsx`**(CSV viewer 的 `custom` load 直取 `/sidebar/api/fs.read`,注意响应 envelope 是 `{ value }`): +**`my-plugin/src/client/index.tsx`**(CSV viewer 的 `custom` load 直取 `/sidebar/api/fs.read`,注意响应 envelope 是 `{ value }`,且路由经 `hostRouteUrl()` 解析——见 §6 的前导斜杠禁忌): ```tsx import { createElement } from 'react' @@ -1126,7 +1139,7 @@ export function apply(ctx: Context): void { exts: ['csv'], fetchStrategy: 'custom', load: async (path, scope) => { - const res = await fetch('/sidebar/api/fs.read', { + const res = await fetch(ctx.betterSidebar.hostRouteUrl('sidebar/api/fs.read'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: scope.sessionId, path }), diff --git a/src/client/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index 251c51a7..6d945701 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -40,7 +40,8 @@ import { LazyMermaidMarkdown } from './mermaid-lazy.tsx' export interface MarkdownHtmlMedia { scope: SessionScope path: string - origin: string + /** The injected transport base, reverse-proxy prefix included. */ + baseUrl: string } /** Tag-like text in a rendered text node — the inline pass gate. */ @@ -77,7 +78,7 @@ function postProcessSanitized(root: Element, media: MarkdownHtmlMedia): void { for (const element of root.querySelectorAll('img, video, audio, source')) { const src = element.getAttribute('src') if (src === null) continue - element.setAttribute('src', resolveLocalMediaDest(src, media.scope, media.path, media.origin)) + element.setAttribute('src', resolveLocalMediaDest(src, media.scope, media.path, media.baseUrl)) } } @@ -298,7 +299,7 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr // stance), so rewrite local ones into /sidebar/file media URLs first — // the same trust fence the sanitized HTML leaves below go through. // Idempotent: already-absolute media URLs pass through untouched. - const text = rewriteLocalImageUrls(raw, media.scope, media.path, media.origin) + const text = rewriteLocalImageUrls(raw, media.scope, media.path, media.baseUrl) return { kind: 'markdown', text, @@ -336,7 +337,7 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr } return { kind: 'html', parts } // `media` is a memoized object in the host (TextEditor); identity tracks - // scope/path/origin changes so sanitization re-runs exactly when needed. + // scope/path/baseUrl changes so sanitization re-runs exactly when needed. }), [info, media]) const nodes: ReactNode[] = [] diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index d28b969a..20f348fc 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -23,6 +23,7 @@ import { openSearchPanel } from '@codemirror/search' import { IconCheckOutlineRegular, IconSearchOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' import { markdownTextProps } from './markdown-labels.tsx' import { api, htmlUrl, SidebarApiError } from './api.ts' +import { hostTransportBase } from './desktop-env.ts' import { markdownPreviewSource } from './markdown-frontmatter.ts' import { rewriteLocalImageUrls } from './markdown-images.ts' import { languageForPath } from './lang.ts' @@ -433,7 +434,7 @@ export function TextEditor(props: FileViewerProps) { /** The preview source with local image destinations rewritten to absolute * media URLs (see {@link rewriteLocalImageUrls}). */ const previewText = markdown - ? rewriteLocalImageUrls(previewMdText, scope, path, window.location.origin) + ? rewriteLocalImageUrls(previewMdText, scope, path, hostTransportBase()) : previewMdText /** md/mermaid block split for the preview (mermaid fences lift out). Split * only in preview mode: edit-mode keystrokes must not re-scan the source. */ @@ -462,7 +463,7 @@ export function TextEditor(props: FileViewerProps) { * `media` identity, so a fresh object per render would re-sanitize every * keystroke. */ const htmlMedia = useMemo( - () => ({ scope, path, origin: window.location.origin }), + () => ({ scope, path, baseUrl: hostTransportBase() }), // eslint-disable-next-line react-hooks/exhaustive-deps [scope.sessionId, scope.cwd, path], ) diff --git a/src/client/api.ts b/src/client/api.ts index 3455e9cd..25cbd8a7 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -1,12 +1,14 @@ /** - * Typed fetch wrapper over the /sidebar JSON API. Every call posts to - * `/sidebar/api/` with the sessionId and — when known — the session's - * cwd from the client's own list summary. The host prefers its attached - * session header and uses the summary cwd only while the session is still - * hydrating at page load (a detached session would otherwise fail the + * Typed fetch wrapper over the /sidebar JSON API. Every call posts through + * {@link hostRouteUrl} to `/sidebar/api/` with the sessionId and — + * when known — the session's cwd from the client's own list summary (the + * route keeps a reverse-proxy prefix; see host-route-url.ts). The host prefers + * its attached session header and uses the summary cwd only while the session + * is still hydrating at page load (a detached session would otherwise fail the * request). Failures surface as {@link SidebarApiError} with the wire code. */ import { encodeHtmlUrl } from '../html-route.ts' +import { hostRouteUrl } from './host-route-url.ts' import { resolveSidebarPath } from './paths.ts' import type { SidechatLiveEvent, SidechatLogEvent, SidechatThreadInfo } from '../sidechat-core.ts' import type { @@ -142,7 +144,7 @@ async function readEnvelope(response: Response): Promise { async function call(method: string, payload: Record, signal?: AbortSignal): Promise { let response: Response try { - response = await fetch(`/sidebar/api/${method}`, { + response = await fetch(hostRouteUrl(`sidebar/api/${method}`).href, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload), @@ -195,7 +197,7 @@ async function fetchUpload( if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd) let response: Response try { - response = await fetch(`/sidebar/upload?${params.toString()}`, { + response = await fetch(hostRouteUrl(`sidebar/upload?${params.toString()}`).href, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body, @@ -492,7 +494,7 @@ export function archiveStatus(scope: SessionScope, id: string): Promise (mdOp && reading && readingSrc !== '' && target.kind === 'op' - ? rewriteLocalImageUrls(readingSrc, scope, target.path, window.location.origin) + ? rewriteLocalImageUrls(readingSrc, scope, target.path, hostTransportBase()) : ''), [mdOp, reading, readingSrc, scope, target], ) diff --git a/src/client/chunk-loader.ts b/src/client/chunk-loader.ts index bd33b558..8055dd41 100644 --- a/src/client/chunk-loader.ts +++ b/src/client/chunk-loader.ts @@ -50,6 +50,8 @@ * client.js); an edit that does land while a core HMR happens is caught by * the ETag comparison on the next activation. */ +import { hostRouteUrl } from './host-route-url.ts' + export type ChunkName = 'editor' | 'mermaid' | 'locale' /** The module exports a chunk factory provides (namespace-ish record). */ @@ -80,7 +82,7 @@ export const CHUNK_EXTERNALS: readonly string[] = [ ] /** Chunk script endpoint served by the plugin host half (src/bundle-route.ts). */ -const CHUNK_URL = (name: ChunkName): string => `/sidebar/bundle/${name}.js` +const CHUNK_URL = (name: ChunkName): string => hostRouteUrl(`sidebar/bundle/${name}.js`).href /** Bound on the revalidation HEAD round-trip. A timeout fails open (drop + * re-fetch on the next open) so a stuck bundle route can never wedge lazy diff --git a/src/client/desktop-env.ts b/src/client/desktop-env.ts index c2b2ccb2..2c04f014 100644 --- a/src/client/desktop-env.ts +++ b/src/client/desktop-env.ts @@ -67,22 +67,29 @@ function parseTitlebarInset(raw: string | null): number { } /** - * Absolute base for the plugin's own WebSocket routes. + * Absolute base for the plugin's own host transports — the HTTP routes + * (`/sidebar/api/*`, `/sidebar/file`, `/sidebar/bundle/*`, …) and the + * WebSockets (`/sidebar/ws/*`) resolve through the same source + * (see `host-route-url.ts`). * * A desktop shell may serve the GUI from a custom scheme: the official Electron * shell uses `dsh-app://app/`, whose `location.host` is the literal string - * `app`. Resolving `/sidebar/ws/*` against that origin produces `ws://app/...`, - * which can never complete a DNS lookup — every socket the sidebar opens then - * fails with a connection error. The shell publishes the Host's real base - * through `__DSH_TRANSPORT__.streamBaseUrl`, the same source DSH's own downlink - * mux resolves through (`stream-client.ts` in `@deepseek-ai/dsh-api-gateway`), - * so prefer it and fall back to `document.baseURI` for ordinary http(s) pages. - * @returns A URL string usable as the base argument of `new URL`. + * `app`. Resolving a route against that origin produces `ws://app/...`, which + * can never complete a DNS lookup — every socket the sidebar opens then fails + * with a connection error. The shell publishes the Host's real base through + * `__DSH_TRANSPORT__.streamBaseUrl`, the same source DSH's own downlink mux + * resolves through (`stream-client.ts` in `@deepseek-ai/dsh-api-gateway`), so + * prefer it and fall back to `document.baseURI` for ordinary http(s) pages — + * that base is also what carries a reverse-proxy directory prefix. + * @returns A URL string usable as the base argument of `new URL`, or '' when + * neither source exists (non-DOM specs); route resolution then substitutes a + * placeholder origin it never actually requests. */ -export function sidebarWebSocketBase(): string { +export function hostTransportBase(): string { const transport = (globalThis as { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }).__DSH_TRANSPORT__ const base = transport?.streamBaseUrl - return base !== undefined && base !== '' ? base : document.baseURI + if (base !== undefined && base !== '') return base + return typeof document !== 'undefined' && typeof document.baseURI === 'string' ? document.baseURI : '' } /** Test hook: drop the memo so the next parse re-reads the URL/globals. */ diff --git a/src/client/host-route-url.ts b/src/client/host-route-url.ts new file mode 100644 index 00000000..bfd57c55 --- /dev/null +++ b/src/client/host-route-url.ts @@ -0,0 +1,57 @@ +/** + * Prefix-safe resolution of the plugin's own host routes (HTTP and WebSocket). + * + * The client half talks to the Host at `/sidebar/*`. Built with a leading + * slash those URLs pin themselves to the ORIGIN ROOT, so a GUI served under a + * reverse-proxy directory (`https://host/dataops/proxy/3080/`) sends every + * request OUTSIDE the prefix: the JSON API answers 404, lazy chunks never + * load, media and HTML previews stay blank, and the WebSockets close with + * 1006. Resolving a RELATIVE path against the injected transport base keeps + * the request under the page's own directory — the same shape DSH's own client + * uses (`new URL(REMOTE_STREAM_MUX_PATH.slice(1), __DSH_TRANSPORT__?.streamBaseUrl + * ?? document.baseURI)` in `@deepseek-ai/dsh-api-gateway`). + * + * The base is normalized to a directory first (search/hash dropped, trailing + * slash forced) so a launch-token query cannot leak into the route and a + * prefix written without its final slash cannot eat the last path segment. + */ +import { hostTransportBase } from './desktop-env.ts' + +/** Placeholder origin for the non-DOM case (specs / SSR): resolution needs an + * absolute base, but the caller never issues the resulting request. */ +const PLACEHOLDER_ORIGIN = 'http://dsh.internal/' + +/** + * Resolve one host route against the injected base. Leading slashes are + * stripped on purpose — keeping one would discard a reverse-proxy prefix. + * @param path - The route, with or without a leading slash + * (`sidebar/api/fs.tree`, `sidebar/ws/fs-watch`). + * @param baseUrl - Override for the shared transport base; specs pass a static + * prefix so resolution stays pure. + * @returns The absolute route URL (the base's origin + any prefix included). + */ +export function hostRouteUrl(path: string, baseUrl: string = hostTransportBase()): URL { + return new URL(path.replace(/^\/+/, ''), directoryBase(baseUrl)) +} + +/** {@link hostRouteUrl} with the `ws:`/`wss:` scheme `WebSocket` requires. */ +export function hostWebSocketUrl(path: string, baseUrl: string = hostTransportBase()): URL { + const url = hostRouteUrl(path, baseUrl) + url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' + return url +} + +/** + * Turn any transport base into a directory base: drop the query (the launch + * token rides there) and the hash, then force a trailing slash. DSH serves the + * GUI from a directory, so a base without the final slash is the same prefix + * with the browser's own trailing-slash elision — resolving against it + * verbatim would replace its last segment instead of appending to it. + */ +function directoryBase(baseUrl: string): string { + const url = new URL(baseUrl === '' ? PLACEHOLDER_ORIGIN : baseUrl, PLACEHOLDER_ORIGIN) + url.search = '' + url.hash = '' + if (!url.pathname.endsWith('/')) url.pathname += '/' + return url.href +} diff --git a/src/client/markdown-images.ts b/src/client/markdown-images.ts index c246b19f..b3a1b977 100644 --- a/src/client/markdown-images.ts +++ b/src/client/markdown-images.ts @@ -5,12 +5,13 @@ * a previewed `.md` (`![alt](./img.png)`, an absolute `/cwd/img.png`, or a * reference definition) would otherwise fall back to its alt text. This * dependency-free helper rewrites those destinations into absolute - * `/sidebar/file` media URLs (prefixed with the GUI's own origin) so - * `MarkdownText` accepts them; the host media route then serves the bytes, - * still restricted to files under the session cwd. + * `/sidebar/file` media URLs, resolved against the injected transport base so + * a reverse-proxy prefix survives; `MarkdownText` accepts them because they are + * absolute http(s), and the host media route then serves the bytes. */ import type { SessionScope } from './api.ts' +import { hostRouteUrl } from './host-route-url.ts' import { isAbsolutePath } from './paths.ts' /** @@ -61,16 +62,16 @@ function normalizeLocalPath(path: string): string { * @param text - The raw markdown source (inline + reference images). * @param scope - The session scope (sessionId + cwd) for the media route. * @param filePath - The absolute path of the opened `.md` file. - * @param origin - The GUI's own origin (`window.location.origin`); injected - * so the core rewrite stays pure and unit-testable. + * @param baseUrl - The injected transport base (`hostTransportBase()` in the + * renderers); injected so the core rewrite stays pure and unit-testable. * @returns The markdown with local image destinations rewritten in place. */ /** * Resolve one media destination against the session's media route: local - * (relative or absolute) paths become absolute `/sidebar/file` URLs (prefixed - * with the GUI's own origin so the shared MarkdownText http(s) allowlist - * accepts them), while remote URLs, `#`-anchors and empty destinations are - * returned untouched. Shared by the markdown image rewriter below and by the + * (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved + * through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them + * AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and + * empty destinations are returned untouched. Shared by the markdown image rewriter below and by the * preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same * allowlist when rendering `` inside HTML blocks). */ @@ -78,7 +79,7 @@ export function resolveLocalMediaDest( dest: string, scope: SessionScope, filePath: string, - origin: string, + baseUrl: string, ): string { const trimmed = dest.trim() if (trimmed === '' || trimmed.startsWith('#')) return dest @@ -87,19 +88,20 @@ export function resolveLocalMediaDest( const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1) const candidate = isAbsolutePath(trimmed) ? trimmed : directory + trimmed // Mirrors api.ts fileUrl/mediaUrl for the /sidebar/file media route, made - // absolute so the shared MarkdownText http(s) allowlist accepts it. + // absolute (and prefix-preserving) so the shared MarkdownText http(s) + // allowlist accepts it. const params = new URLSearchParams({ sessionId: scope.sessionId, path: normalizeLocalPath(candidate) }) if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd) - return `${origin}/sidebar/file?${params.toString()}` + return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href } export function rewriteLocalImageUrls( text: string, scope: SessionScope, filePath: string, - origin: string, + baseUrl: string, ): string { - const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, origin) + const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, baseUrl) // Mask fenced code blocks and inline code spans so image-looking text // inside documentation examples is never rewritten. The sentinel uses a diff --git a/src/client/service.ts b/src/client/service.ts index d65dab6d..3f61fd56 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -27,6 +27,7 @@ import { type SidebarSnapshot, type SidebarState, type SidebarStore, type SidebarTab, type TabType, } from './state.ts' import { baseName, extOf } from './paths.ts' +import { hostRouteUrl as resolveHostRoute } from './host-route-url.ts' import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx' import type { SessionScope } from './api.ts' import type { SidebarPrefs } from '../prefs-shared.ts' @@ -634,6 +635,17 @@ export interface BetterSidebarService { activateTab(tabId: string, scope?: SessionScope): void /** Open a file in the sidebar editor of `scope`'s session (title defaults to the file name). */ openFile(scope: SessionScope, path: string, title?: string): void + /** + * Resolve one of the plugin's own host routes (`sidebar/api/fs.read`) into + * an absolute URL the page can fetch even when the GUI is served under a + * reverse-proxy directory (v0.25.0+; `features` contains 'hostRouteUrl'). + * + * Never build these URLs with a leading slash yourself: that pins the + * request to the ORIGIN ROOT, so `/proxy//sidebar/api/…` leaves the + * prefix and 404s (and a desktop shell's `dsh-app://` origin is not + * reachable at all). `path` is taken with or without a leading slash. + */ + hostRouteUrl(path: string): string /** * Install (or clear) the native right-Sidebar write face. * @internal Called once by the client half; not part of the consumer API. @@ -717,6 +729,7 @@ export const SIDEBAR_FEATURES = [ 'settingSelect', 'fileIcons', 'rightActions', + 'hostRouteUrl', ] as const /** Run one plugin callback; a throw is logged and never breaks the caller. */ @@ -1240,6 +1253,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe updateTab, activateTab, openFile, + hostRouteUrl: (path: string): string => resolveHostRoute(path).href, setSurface: (next: SidebarSurface | undefined) => { surface = next }, } } diff --git a/src/client/sidebar/use-host-feeds.ts b/src/client/sidebar/use-host-feeds.ts index fbc30b1d..68f71a37 100644 --- a/src/client/sidebar/use-host-feeds.ts +++ b/src/client/sidebar/use-host-feeds.ts @@ -9,7 +9,7 @@ import { useEffect, useRef } from 'react' import type { Context, SidebarJobView, SidebarSessionList } from '../../context-types.ts' import type { SidebarStore } from '../state.ts' import { isNarrowWidth } from '../breakpoints.ts' -import { sidebarWebSocketBase } from '../desktop-env.ts' +import { hostWebSocketUrl } from '../host-route-url.ts' import { detectNewDirectSubagent } from '../subagent-detect.ts' import { detectNewJob } from '../subagent-jobs.ts' import { clientJobs, useJobsSnapshot } from '../jobs-client.ts' @@ -113,8 +113,7 @@ export function useHostFeeds(feeds: { let failures = 0 const connect = (): void => { if (closed) return - const url = new URL('/sidebar/ws/agent-opens', sidebarWebSocketBase()) - url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' + const url = hostWebSocketUrl('sidebar/ws/agent-opens') url.search = new URLSearchParams({ sessionId }).toString() socket = new WebSocket(url.toString()) socket.onmessage = (event) => { diff --git a/src/client/use-dir-watch.ts b/src/client/use-dir-watch.ts index 6878e2b3..6194ab05 100644 --- a/src/client/use-dir-watch.ts +++ b/src/client/use-dir-watch.ts @@ -14,7 +14,7 @@ * un-watched, so a long session does not accumulate handles. */ import { useEffect, useMemo, useRef } from 'react' -import { sidebarWebSocketBase } from './desktop-env.ts' +import { hostWebSocketUrl } from './host-route-url.ts' /** One server frame: a stale directory, a watch verdict, or a refusal. */ interface FsWatchFrame { @@ -97,8 +97,7 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void { const connect = (): void => { if (closed) return - const url = new URL('/sidebar/ws/fs-watch', sidebarWebSocketBase()) - url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' + const url = hostWebSocketUrl('sidebar/ws/fs-watch') url.search = new URLSearchParams({ sessionId }).toString() socket = new WebSocket(url.toString()) socket.onopen = () => { diff --git a/tests/archive-client.spec.ts b/tests/archive-client.spec.ts index 3de1dfe2..c48f4829 100644 --- a/tests/archive-client.spec.ts +++ b/tests/archive-client.spec.ts @@ -10,6 +10,7 @@ * These cases run the real module against a stubbed `fetch` and assert the * request bodies, including the session scope on every archive call. */ +import './browser-globals.ts' import { afterEach, describe, expect, it, vi } from 'vitest' import { archiveBuild, archiveDownloadUrl, archiveStatus, type SessionScope } from '../src/client/api.ts' @@ -42,21 +43,21 @@ describe('archive client payloads', () => { it('posts the session scope on archive.status (the host requires BOTH keys)', async () => { const posted = stubFetch({ state: 'ready', done: 1, total: 1, bytes: 8 }) await expect(archiveStatus(scope, 'job-1')).resolves.toEqual({ state: 'ready', done: 1, total: 1, bytes: 8 }) - expect(posted).toEqual([{ url: '/sidebar/api/archive.status', body: { sessionId: 's1', cwd: '/w', id: 'job-1' } }]) + expect(posted).toEqual([{ url: 'http://localhost/sidebar/api/archive.status', body: { sessionId: 's1', cwd: '/w', id: 'job-1' } }]) }) it('carries the scope on archive.build, plus the selection and the name', async () => { const posted = stubFetch({ id: 'job-2', entries: 2 }) await expect(archiveBuild(scope, ['/w/a.ts', '/w/b.ts'], 'archive.zip')).resolves.toEqual({ id: 'job-2', entries: 2 }) expect(posted).toEqual([{ - url: '/sidebar/api/archive.build', + url: 'http://localhost/sidebar/api/archive.build', body: { sessionId: 's1', cwd: '/w', paths: ['/w/a.ts', '/w/b.ts'], name: 'archive.zip' }, }]) }) it('puts the session on the download URL (it answers only the session that built it)', () => { // A session without a cwd keeps the URL scoped and free of an empty cwd. - expect(archiveDownloadUrl({ sessionId: 's9' }, 'job-9')).toBe('/sidebar/archive?sessionId=s9&id=job-9') + expect(archiveDownloadUrl({ sessionId: 's9' }, 'job-9')).toBe('http://localhost/sidebar/archive?sessionId=s9&id=job-9') }) it('omits an empty cwd but never the sessionId', async () => { diff --git a/tests/base-path.spec.ts b/tests/base-path.spec.ts new file mode 100644 index 00000000..babec038 --- /dev/null +++ b/tests/base-path.spec.ts @@ -0,0 +1,138 @@ +/** + * Reverse-proxy base paths (issue #753). + * + * The plugin's client half talks to the Host at `/sidebar/*`. Every one of + * those URLs used to be built with a LEADING SLASH — `fetch('/sidebar/api/…')`, + * `new URL('/sidebar/ws/…', base)`, `` `${origin}/sidebar/file?…` `` — which + * pins the request to the ORIGIN ROOT. Behind a reverse proxy that serves the + * GUI at `https://host/dataops/proxy/3080/`, the browser therefore asks + * `https://host/sidebar/…`: the JSON API 404s, lazy chunks never load, media + * and HTML previews stay blank, and the WebSockets close with 1006. + * + * These cases pin the resolver's contract (relative path + page prefix), the + * single base authority (`__DSH_TRANSPORT__` first — the desktop shell's + * `dsh-app://` origin is unreachable, see desktop-env.ts), and the URLs the + * REAL call sites produce under a prefix. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import './browser-globals.ts' +import { hostRouteUrl, hostWebSocketUrl } from '../src/client/host-route-url.ts' +import { archiveDownloadUrl, downloadUrl, htmlUrl, mediaUrl, type SessionScope } from '../src/client/api.ts' +import { createBetterSidebarService } from '../src/client/service.ts' +import { createSidebarStore } from '../src/client/state.ts' + +/** A code-server-style prefix: a directory path, behind https. */ +const PROXY = 'https://host.example.test/dataops/proxy/3080/' +const scope: SessionScope = { sessionId: 's1', cwd: '/ws' } + +/** Run `body` with the page served under `base` — the one input the resolver + * reads when the shell injected no transport. */ +async function withPageBase(base: string, body: () => void | Promise): Promise { + const document = globalThis.document as { baseURI?: string } + const previous = document.baseURI + Object.defineProperty(document, 'baseURI', { value: base, configurable: true, writable: true }) + try { + await body() + } finally { + Object.defineProperty(document, 'baseURI', { value: previous, configurable: true, writable: true }) + } +} + +afterEach(() => { + vi.unstubAllGlobals() + delete (globalThis as { __DSH_TRANSPORT__?: unknown }).__DSH_TRANSPORT__ +}) + +describe('hostRouteUrl / hostWebSocketUrl', () => { + it('keeps the page prefix for every HTTP route family', () => { + expect(hostRouteUrl('sidebar/api/fs.tree', PROXY).href) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/api/fs.tree') + expect(hostRouteUrl('sidebar/upload?sessionId=s', PROXY).href) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/upload?sessionId=s') + expect(hostRouteUrl('sidebar/file?sessionId=s&path=%2Fws%2Fa.png', PROXY).href) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/file?sessionId=s&path=%2Fws%2Fa.png') + expect(hostRouteUrl('sidebar/html/s/ws/index.html', PROXY).href) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/html/s/ws/index.html') + expect(hostRouteUrl('sidebar/bundle/editor.js', PROXY).href) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/bundle/editor.js') + expect(hostRouteUrl('sidebar/archive?sessionId=s&id=a', PROXY).href) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/archive?sessionId=s&id=a') + }) + + it('accepts the route with or without its leading slash and never keeps it', () => { + // A leading slash is the bug itself: it replaces the whole prefix. + expect(hostRouteUrl('/sidebar/api/fs.tree', PROXY).href) + .toBe(hostRouteUrl('sidebar/api/fs.tree', PROXY).href) + expect(hostRouteUrl('///sidebar/api/fs.tree', PROXY).pathname) + .toBe('/dataops/proxy/3080/sidebar/api/fs.tree') + }) + + it('upgrades the WebSocket scheme and keeps the prefix', () => { + expect(hostWebSocketUrl('sidebar/ws/fs-watch', PROXY).href) + .toBe('wss://host.example.test/dataops/proxy/3080/sidebar/ws/fs-watch') + expect(hostWebSocketUrl('sidebar/ws/agent-opens', 'http://127.0.0.1:4199/app/').href) + .toBe('ws://127.0.0.1:4199/app/sidebar/ws/agent-opens') + }) + + it('treats a launch-token query and a missing trailing slash as a directory prefix', () => { + expect(hostRouteUrl('sidebar/api/fs.tree', 'https://host.test/dataops/proxy/3080?token=abc').href) + .toBe('https://host.test/dataops/proxy/3080/sidebar/api/fs.tree') + expect(hostRouteUrl('sidebar/bundle/editor.js', 'https://host.test/dataops/proxy/3080#frag').href) + .toBe('https://host.test/dataops/proxy/3080/sidebar/bundle/editor.js') + // The launch URL's own token must never ride along into the route. + expect(hostRouteUrl('sidebar/api/fs.tree', 'https://host.test/?token=abc').href) + .toBe('https://host.test/sidebar/api/fs.tree') + }) + + it('prefers the shell transport base over the document base (desktop shell)', () => { + // 2718725: the Electron shell serves the GUI from `dsh-app://app/`, whose + // host is the literal string `app` — resolving against it never connects. + vi.stubGlobal('__DSH_TRANSPORT__', { streamBaseUrl: 'http://127.0.0.1:4199/' }) + // The default parameter is exercised on purpose (undefined = "read it"). + expect(hostRouteUrl('sidebar/api/fs.tree', undefined).href) + .toBe('http://127.0.0.1:4199/sidebar/api/fs.tree') + expect(hostWebSocketUrl('sidebar/ws/fs-watch', undefined).href) + .toBe('ws://127.0.0.1:4199/sidebar/ws/fs-watch') + }) +}) + +describe('the real call sites resolve through the page prefix', () => { + it('builds the media, download, HTML and archive URLs under the prefix', async () => { + await withPageBase(PROXY, () => { + expect(mediaUrl(scope, '/ws/img/a.png')) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fimg%2Fa.png&cwd=%2Fws') + expect(downloadUrl(scope, '/ws/img/a.png')) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fimg%2Fa.png&cwd=%2Fws&download=1') + expect(htmlUrl({ sessionId: 's1' }, '/ws/index.html')) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/html/s1/ws/index.html') + expect(archiveDownloadUrl({ sessionId: 's1' }, 'job-1')) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/archive?sessionId=s1&id=job-1') + }) + }) + + it('posts the JSON API under the prefix', async () => { + const urls: string[] = [] + vi.stubGlobal('fetch', vi.fn(async (url: string) => { + urls.push(url) + return { ok: true, status: 200, json: async () => ({ ok: true, value: {} }) } as unknown as Response + })) + await withPageBase(PROXY, async () => { + const { api } = await import('../src/client/api.ts') + await api.settingsGet() + await api.fsTree(scope, '/ws') + }) + expect(urls).toEqual([ + 'https://host.example.test/dataops/proxy/3080/sidebar/api/settings.get', + 'https://host.example.test/dataops/proxy/3080/sidebar/api/fs.tree', + ]) + }) + + it('exposes the same resolution to consumer plugins through the service', async () => { + await withPageBase(PROXY, () => { + const service = createBetterSidebarService(createSidebarStore()) + expect(service.features).toContain('hostRouteUrl') + expect(service.hostRouteUrl('/sidebar/api/fs.read')) + .toBe('https://host.example.test/dataops/proxy/3080/sidebar/api/fs.read') + }) + }) +}) diff --git a/tests/browser-globals.ts b/tests/browser-globals.ts index 3a6961a1..0a7e4f87 100644 --- a/tests/browser-globals.ts +++ b/tests/browser-globals.ts @@ -28,6 +28,10 @@ const elementStub = (): Record => ({ if (g.document === undefined) { g.document = { + // desktop-env.ts's hostTransportBase() falls back to `document.baseURI` + // when the shell injected no __DSH_TRANSPORT__; the plugin's /sidebar/* + // URLs resolve against it, so specs pin one stable page base. + baseURI: 'http://localhost/', createElement: () => elementStub(), createDocumentFragment: () => elementStub(), addEventListener: () => {}, diff --git a/tests/chunk-loader.spec.ts b/tests/chunk-loader.spec.ts index 82193ef9..1a39ca6f 100644 --- a/tests/chunk-loader.spec.ts +++ b/tests/chunk-loader.spec.ts @@ -83,6 +83,34 @@ describe('test-registry path (vitest / jsdom-less environments)', () => { }) describe('production path (script injection + global registry + externals require)', () => { + it('injects the chunk script under the page prefix (reverse proxy, issue #753)', async () => { + installModuleSystem() + // The loader's fire-and-forget ETag HEAD rides along; stub it so no real + // request to the fake prefix host outlives this case. + vi.stubGlobal('fetch', vi.fn(async () => ({ headers: { get: () => null } }) as unknown as Response)) + const loaded: string[] = [] + setChunkScriptLoaderForTests(async (src) => { + loaded.push(src) + simulateScript('editor', () => ({ TextEditor: 'editor-view' })) + }) + // The GUI served at `/dataops/proxy/3080/`: a leading-slash bundle URL + // would ask the origin root, where the proxy serves nothing → 404 and a + // chunk that never materializes. + const document = globalThis.document as { baseURI?: string } + const previous = document.baseURI + Object.defineProperty(document, 'baseURI', { + value: 'https://host.test/dataops/proxy/3080/', + configurable: true, + writable: true, + }) + try { + await loadChunk('editor') + } finally { + Object.defineProperty(document, 'baseURI', { value: previous, configurable: true, writable: true }) + } + expect(loaded).toEqual(['https://host.test/dataops/proxy/3080/sidebar/bundle/editor.js']) + }) + it('resolves externals through an injected ctx.modules system (rc.8 — no page global)', async () => { const modules = installModuleSystem() const loaded: string[] = [] @@ -91,7 +119,7 @@ describe('production path (script injection + global registry + externals requir simulateScript('editor', (require) => ({ TextEditor: `view:${String(require('react'))}` })) }) const exports = await loadChunk('editor') - expect(loaded).toEqual(['/sidebar/bundle/editor.js']) + expect(loaded).toEqual(['http://localhost/sidebar/bundle/editor.js']) expect(exports).toEqual({ TextEditor: 'view:[object Object]' }) expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length) // The injection also lands on a plugin-owned global so chunk-bundle @@ -116,7 +144,7 @@ describe('production path (script injection + global registry + externals requir simulateScript('editor', (require) => ({ TextEditor: `view:${String(require('react'))}` })) }) const exports = await loadChunk('editor') - expect(loaded).toEqual(['/sidebar/bundle/editor.js']) + expect(loaded).toEqual(['http://localhost/sidebar/bundle/editor.js']) expect(exports).toEqual({ TextEditor: 'view:[object Object]' }) // Externals resolved through the module system's seed branch, once. expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length) @@ -135,7 +163,7 @@ describe('production path (script injection + global registry + externals requir }) await loadChunk('locale') await loadChunk('editor') - expect(seen).toEqual(['/sidebar/bundle/locale.js', '/sidebar/bundle/editor.js']) + expect(seen).toEqual(['http://localhost/sidebar/bundle/locale.js', 'http://localhost/sidebar/bundle/editor.js']) expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length) }) diff --git a/tests/file-tree-dir-watch.spec.tsx b/tests/file-tree-dir-watch.spec.tsx index 88106048..af10dda3 100644 --- a/tests/file-tree-dir-watch.spec.tsx +++ b/tests/file-tree-dir-watch.spec.tsx @@ -103,6 +103,26 @@ describe('useDirectoryWatch', () => { harness.unmount() }) + it('opens the socket under the page prefix (reverse proxy, issue #753)', () => { + // The prefix is part of the page's own base: a leading-slash route leaves + // it, and the proxy never forwards the handshake to the host (1006). + const page = document as { baseURI?: string } + const previous = page.baseURI + Object.defineProperty(page, 'baseURI', { + value: 'https://host.test/dataops/proxy/3080/', + configurable: true, + writable: true, + }) + try { + const harness = mountProbe(() => {}) + expect(harness.socket().url) + .toBe('wss://host.test/dataops/proxy/3080/sidebar/ws/fs-watch?sessionId=s1') + harness.unmount() + } finally { + Object.defineProperty(page, 'baseURI', { value: previous, configurable: true, writable: true }) + } + }) + it('sends nothing when a re-render repeats the same directories in a fresh array', () => { const harness = mountProbe(() => {}) const socket = harness.socket() diff --git a/tests/markdown-html-render.spec.tsx b/tests/markdown-html-render.spec.tsx index 78da0c0d..258e3c95 100644 --- a/tests/markdown-html-render.spec.tsx +++ b/tests/markdown-html-render.spec.tsx @@ -21,7 +21,7 @@ setupReactAct() const media: MarkdownHtmlMedia = { scope: { sessionId: 's1', cwd: '/ws' }, path: '/ws/docs/README.md', - origin: 'http://gui.origin', + baseUrl: 'http://gui.origin/proxy/3080/', } const codeLabels = { copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines', @@ -86,7 +86,7 @@ describe('MarkdownDocument (HTML leaves)', () => { it('rewrites local media sources through the /sidebar/file route', async () => { const { container, root } = await renderDocument('shot') const img = container.querySelector('img') - expect(img?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws') + expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws') await unmount(root) }) }) @@ -334,9 +334,9 @@ describe('MarkdownDocument (local markdown images)', () => { ].join('\n')) const imgs = [...container.querySelectorAll('img')] expect(imgs.length, 'both local images must render as , not alt fallback').toBe(2) - expect(imgs[0]?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fassets%2Ficon.svg&cwd=%2Fws') + expect(imgs[0]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fassets%2Ficon.svg&cwd=%2Fws') expect(imgs[0]?.getAttribute('alt')).toBe('icon') - expect(imgs[1]?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Flogo.png&cwd=%2Fws') + expect(imgs[1]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Flogo.png&cwd=%2Fws') expect(imgs[1]?.getAttribute('alt')).toBe('logo') await unmount(root) }) @@ -349,7 +349,7 @@ describe('MarkdownDocument (local markdown images)', () => { ].join('\n')) const img = container.querySelector('img') expect(img, 'the markdown-syntax image after an HTML run must render').not.toBeNull() - expect(img?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws') + expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws') await unmount(root) }) @@ -361,7 +361,7 @@ describe('MarkdownDocument (local markdown images)', () => { }) it('is idempotent for already-rewritten media URLs', async () => { - const url = 'http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws' + const url = 'http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws' const { container, root } = await renderDocument(`![a](${url})`) const img = container.querySelector('img') expect(img?.getAttribute('src')).toBe(url) diff --git a/tests/open-external-client.spec.ts b/tests/open-external-client.spec.ts index 714233f5..ed2b8d6f 100644 --- a/tests/open-external-client.spec.ts +++ b/tests/open-external-client.spec.ts @@ -3,6 +3,7 @@ * VSCode-family SSH URLs must launch on the browser machine, while local * editor URLs and reveal actions keep using the DSH host opener. */ +import './browser-globals.ts' import { afterEach, describe, expect, it, vi } from 'vitest' import { api } from '../src/client/api.ts' @@ -64,7 +65,7 @@ describe('api.openExternal', () => { expect(assign).not.toHaveBeenCalled() expect(fetchMock).toHaveBeenCalledOnce() - expect(fetchMock.mock.calls[0]?.[0]).toBe('/sidebar/api/open.external') + expect(String(fetchMock.mock.calls[0]?.[0])).toBe('http://localhost/sidebar/api/open.external') }) it('keeps reveal actions and http(s) lookalikes on the host opener', async () => { diff --git a/tests/paths.spec.ts b/tests/paths.spec.ts index 5e761462..9d87425f 100644 --- a/tests/paths.spec.ts +++ b/tests/paths.spec.ts @@ -1,3 +1,4 @@ +import './browser-globals.ts' import { describe, expect, it } from 'vitest' import { decodeHtmlUrl } from '../src/html-route.ts' import { isAbsolutePath, relativeTo, workspaceRelativePath } from '../src/client/paths.ts' @@ -69,11 +70,11 @@ describe('path helpers', () => { // The marker is platform-neutral now: the host resolves the decoded // '//server/share/...' form per-platform, so no cwd/OS signal is needed. expect(htmlUrl({ sessionId: 's' }, '\\\\server\\share\\proj\\a.html')) - .toBe('/sidebar/html/s//server/share/proj/a.html') + .toBe('http://localhost/sidebar/html/s//server/share/proj/a.html') expect(htmlUrl({ sessionId: 's', cwd: '/home/me' }, '//server/share/a.html')) - .toBe('/sidebar/html/s//server/share/a.html') + .toBe('http://localhost/sidebar/html/s//server/share/a.html') expect(htmlUrl({ sessionId: 's', cwd: '/home/me' }, '/home/me/index.html')) - .toBe('/sidebar/html/s/home/me/index.html') + .toBe('http://localhost/sidebar/html/s/home/me/index.html') }) }) diff --git a/tests/sandbox-views.spec.tsx b/tests/sandbox-views.spec.tsx index 96078609..abf3fd57 100644 --- a/tests/sandbox-views.spec.tsx +++ b/tests/sandbox-views.spec.tsx @@ -51,7 +51,7 @@ describe('HTML preview iframe sandbox', () => { expect(HTML_IFRAME_SANDBOX).not.toContain('allow-same-origin') expect(HTML_IFRAME_SANDBOX).not.toContain('allow-top-navigation') // Cross-origin framing by construction: route-src (never srcdoc). - expect(iframe).toContain('src="/sidebar/html/s1/p/a/index.html"') + expect(iframe).toContain('src="http://localhost/sidebar/html/s1/p/a/index.html"') expect(iframe).not.toContain('srcdoc=') // Referrer + permissions policy stay locked even when sandboxed. // (React SSR renders the referrerPolicy prop camelCase as written.) @@ -135,7 +135,9 @@ describe('changes tab HTML render preview sandbox', () => { expect(iframe).toContain(`sandbox="${HTML_IFRAME_SANDBOX}"`) expect(HTML_IFRAME_SANDBOX).not.toContain('allow-same-origin') expect(HTML_IFRAME_SANDBOX).not.toContain('allow-top-navigation') - // Cross-origin framing by construction: route-src (never srcdoc). + // Cross-origin framing by construction: route-src (never srcdoc). The src + // here is the caller's literal (DiffPane passes htmlUrl(...)); this surface + // only frames what it is given. expect(iframe).toContain('src="/sidebar/html/s1/p/a/index.html"') expect(iframe).not.toContain('srcdoc=') expect(iframe).toContain('referrerPolicy="no-referrer"') diff --git a/tests/zip.spec.ts b/tests/zip.spec.ts index 8ff3fce8..303e3c05 100644 --- a/tests/zip.spec.ts +++ b/tests/zip.spec.ts @@ -11,6 +11,7 @@ * workspace, covering the fence, the parameter guards and a full * directory walk. */ +import './browser-globals.ts' import { afterEach, describe, expect, it, vi } from 'vitest' import { spawnSync } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' @@ -538,7 +539,7 @@ describe('disambiguateArchiveNames', () => { describe('archive task flow (build → status → download)', () => { it('archive client helpers build the frozen request/URL shapes', () => { expect(archiveDownloadUrl({ sessionId: 's-1' }, 'ar-9')) - .toBe('/sidebar/archive?sessionId=s-1&id=ar-9') + .toBe('http://localhost/sidebar/archive?sessionId=s-1&id=ar-9') }) it('zips a selected file and a selected directory, walking it recursively', async () => {