Files
apes-sidebar/tests/base-path.spec.ts
T
Menghuan1918andidoall 78274c7b78 fix(sidebar): /sidebar/* 传输按页面前缀解析,反代子路径下不再甩掉前缀(#584 移植)
贡献者 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 的宿主产物里没有 <base href>(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>
2026-10-05 02:22:03 +08:00

139 lines
7.1 KiB
TypeScript

/**
* 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<void>): Promise<void> {
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')
})
})
})