From 27187256c9c81c31d3d12932654c42d564791918 Mon Sep 17 00:00:00 2001 From: MXY <393121069@qq.com> Date: Tue, 29 Sep 2026 01:51:46 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(client):=20WebSocket=20=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E6=94=B9=E7=94=A8=E5=A3=B3=E6=B3=A8=E5=85=A5=E7=9A=84?= =?UTF-8?q?=20transport=20base=EF=BC=880.2.0-rc.1=20/=20v0.24.1=20?= =?UTF-8?q?=E5=9F=BA=E7=BA=BF=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 桌面壳把页面放在 dsh-app://app/ 下,location.origin 的 host 是字面量 app,拼出的 ws://app/... 永远解析不了。改用 __DSH_TRANSPORT__.streamBaseUrl(壳经 DESKTOP_IPC.boot 注入);普通 http(s) 页面下与 location.origin 等价。 本 PR 是 #768 同一份修复在 0.24.1 上的重放:原 PR 基于 0.22.x,而 v0.24.0 起支持线已前移到 ^0.2.0-rc.1,旧基线无法合并,故新开。 --- src/client/desktop-env.ts | 19 +++++++++++++++++++ src/client/sidebar/use-host-feeds.ts | 3 ++- src/client/use-dir-watch.ts | 3 ++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/client/desktop-env.ts b/src/client/desktop-env.ts index 49ffdcb8..c2b2ccb2 100644 --- a/src/client/desktop-env.ts +++ b/src/client/desktop-env.ts @@ -66,6 +66,25 @@ function parseTitlebarInset(raw: string | null): number { return Math.min(120, Math.max(0, Math.round(parsed))) } +/** + * Absolute base for the plugin's own WebSocket routes. + * + * 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`. + */ +export function sidebarWebSocketBase(): string { + const transport = (globalThis as { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }).__DSH_TRANSPORT__ + const base = transport?.streamBaseUrl + return base !== undefined && base !== '' ? base : document.baseURI +} + /** Test hook: drop the memo so the next parse re-reads the URL/globals. */ export function resetDesktopEnvForTests(): void { cached = undefined diff --git a/src/client/sidebar/use-host-feeds.ts b/src/client/sidebar/use-host-feeds.ts index 3a9d6c75..fbc30b1d 100644 --- a/src/client/sidebar/use-host-feeds.ts +++ b/src/client/sidebar/use-host-feeds.ts @@ -9,6 +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 { detectNewDirectSubagent } from '../subagent-detect.ts' import { detectNewJob } from '../subagent-jobs.ts' import { clientJobs, useJobsSnapshot } from '../jobs-client.ts' @@ -112,7 +113,7 @@ export function useHostFeeds(feeds: { let failures = 0 const connect = (): void => { if (closed) return - const url = new URL('/sidebar/ws/agent-opens', location.origin) + const url = new URL('/sidebar/ws/agent-opens', sidebarWebSocketBase()) url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' url.search = new URLSearchParams({ sessionId }).toString() socket = new WebSocket(url.toString()) diff --git a/src/client/use-dir-watch.ts b/src/client/use-dir-watch.ts index 8f8c2f2a..6878e2b3 100644 --- a/src/client/use-dir-watch.ts +++ b/src/client/use-dir-watch.ts @@ -14,6 +14,7 @@ * un-watched, so a long session does not accumulate handles. */ import { useEffect, useMemo, useRef } from 'react' +import { sidebarWebSocketBase } from './desktop-env.ts' /** One server frame: a stale directory, a watch verdict, or a refusal. */ interface FsWatchFrame { @@ -96,7 +97,7 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void { const connect = (): void => { if (closed) return - const url = new URL('/sidebar/ws/fs-watch', location.origin) + const url = new URL('/sidebar/ws/fs-watch', sidebarWebSocketBase()) url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' url.search = new URLSearchParams({ sessionId }).toString() socket = new WebSocket(url.toString()) From e1c7ac349122b447e9ab496fbd86c30224c6a45d Mon Sep 17 00:00:00 2001 From: MXY <393121069@qq.com> Date: Thu, 1 Oct 2026 02:30:26 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(ws):=20fence=20=E6=8E=A5=E5=8F=97?= =?UTF-8?q?=E6=A1=8C=E9=9D=A2=E5=A3=B3=E9=A1=B5=E9=9D=A2=20origin=EF=BC=8C?= =?UTF-8?q?=E8=A1=A5=E5=85=A8=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=20WebSocket=20=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一个提交把 WebSocket 的 base 改到 `__DSH_TRANSPORT__.streamBaseUrl`,解决了 `ws://app` 解析不了的问题;但握手仍然失败。桌面壳页面位于 `dsh-app://app`, 它的 WebSocket 升级直连 Host 的 loopback 地址(壳的 `protocol.handle` 不承载 upgrade),Chromium 因此带上 `Origin: dsh-app://app`。fence 按 hostname 比较, 字面量 `app` 永远不等于 `127.0.0.1`,socket 在 `handleUpgrade` 之前就被销毁。 HTTP 路由不受影响,原因在壳自己:它转发前会删掉 origin 头,Host 侧看到的是 无 Origin 请求,fence 本就放行。所以同一个 fence 只在 WebSocket 路径上暴露。 改动:fence 在 Host 检查通过之后接受精确字符串 `dsh-app://app` —— 与壳自身 request forwarder 的信任集合(非 null 时只认这一个)逐字一致。同 scheme 的 其他 origin、跨站 origin 仍然拒绝;无 Origin 的请求本来就走放行分支,因此这 不是在既有信任面之外新增入口。 测试:`tests/trusted-hosts.spec.ts` 新增 4 例,其中两条是负向控制(Host 非 我方时仍拒、精确匹配而非前缀匹配)。两条新断言各做过一次变异验证:禁用该 分支只让「接受」一例变红,改成前缀匹配只让「精确」一例变红。 --- src/trust-fence.ts | 25 ++++++++-- tests/trusted-hosts.spec.ts | 91 +++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 4 deletions(-) diff --git a/src/trust-fence.ts b/src/trust-fence.ts index 431d6f5e..067cf120 100644 --- a/src/trust-fence.ts +++ b/src/trust-fence.ts @@ -1,10 +1,12 @@ /** - * Browser-trust fence for the sidebar routes, behaviorally identical to the - * /api gateway's fence in @deepseek-ai/dsh-client-connection + * Browser-trust fence for the sidebar routes, copied from the /api gateway's + * fence in @deepseek-ai/dsh-client-connection * (src/api-request-trust.ts + src/loopback-hostname.ts, BSD-3-Clause, * copied here because the package does not export these helpers and the - * plugin must not depend on its internals). Host-header loopback or a - * configured trusted authority passes; cross-site browser markers refuse. + * plugin must not depend on its internals) with one addition: the desktop + * shell's application origin, which reaches only the routes the shell does not + * forward. Host-header loopback or a configured trusted authority passes; + * cross-site browser markers refuse. * This is a DNS-rebinding / cross-site defense, not authentication. */ import type { IncomingHttpHeaders } from 'node:http' @@ -19,6 +21,18 @@ function header(headers: IncomingHttpHeaders, name: string): string | undefined return typeof value === 'string' ? value : undefined } +/** + * Origin of the Electron desktop shell's application page. The shell serves the + * GUI from the `dsh-app:` scheme, so a page-initiated WebSocket handshake + * carries this origin while the socket itself targets the Host's loopback + * authority — an authority match is impossible by construction. The shell's own + * request forwarder admits exactly this non-null origin and refuses every other + * one; WebSocket upgrades bypass that forwarder (the scheme handler does not + * carry them), which is why this fence is the first place the shell origin is + * ever compared against a request. + */ +const SHELL_APP_ORIGIN = 'dsh-app://app' + /** Normalized URL of a Host-header authority, or undefined when unparsable. */ function parseAuthority(authority: string): URL | undefined { try { @@ -76,6 +90,9 @@ export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: read // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused. const origin = header(request.headers, 'origin') if (origin === undefined) return true + // Checked only after the Host fence above bound the authority: the shell + // page's fixed origin is admitted as itself, never as an authority. + if (origin === SHELL_APP_ORIGIN) return true try { return new URL(origin).hostname === hostUrl.hostname } catch { diff --git a/tests/trusted-hosts.spec.ts b/tests/trusted-hosts.spec.ts index daa3df41..5abae259 100644 --- a/tests/trusted-hosts.spec.ts +++ b/tests/trusted-hosts.spec.ts @@ -8,6 +8,11 @@ * through the Loader (`entry.options.name === 'connection'`, which never * matched the row's module-specifier name), so trustedHosts stayed empty and * every remote /sidebar request was 403 "forbidden". + * + * A second group pins the one origin the fence admits without an authority + * match: the desktop shell's `dsh-app://app` page, whose WebSocket upgrades + * reach the Host directly and therefore carry an origin no Host authority can + * name. */ import { describe, expect, it } from 'vitest' import type { IncomingMessage, ServerResponse } from 'node:http' @@ -57,6 +62,7 @@ function req( /** Mount apply() against a fake context with a replaceable webRuntime trust list. */ function mount(initialTrustedHosts: readonly string[] = []): { api: (r: IncomingMessage, s: ServerResponse) => Promise + upgrade: (path: string) => SidebarWebUpgradeRoute['handler'] setTrustedHosts: (hosts: readonly string[]) => void cleanup: () => void } { @@ -86,6 +92,11 @@ function mount(initialTrustedHosts: readonly string[] = []): { if (api === undefined) throw new Error('test setup: /sidebar/api route not registered') return { api: api as (r: IncomingMessage, s: ServerResponse) => Promise, + upgrade: (path) => { + const handler = upgrades.find(route => route.path === path)?.handler + if (handler === undefined) throw new Error(`test setup: ${path} upgrade route not registered`) + return handler + }, setTrustedHosts: (hosts) => { runtime.trustedHosts = [...hosts] }, cleanup: () => { for (const cleanup of effects) cleanup() }, } @@ -232,3 +243,83 @@ describe('remote-access trust (webRuntime.trustedHosts)', () => { } }) }) + +/** + * The desktop shell serves the GUI from `dsh-app://app`, and its WebSocket + * upgrades reach the Host directly (the scheme handler does not carry + * upgrades), so a handshake carries an origin no Host authority can name. + * Refusing it destroys every /sidebar/ws socket — agent-opens pushes, fs-watch + * refreshes — while the forwarded HTTP routes keep working, because the shell + * strips the origin header before forwarding those. + */ +describe('desktop shell application origin', () => { + /** The shell page's own origin, as its handshakes and fetches present it. */ + const SHELL_ORIGIN = 'dsh-app://app' + + it('accepts the shell page origin on a loopback Host', async () => { + const { api, cleanup } = mount([]) + try { + const res = fakeRes() + await api(req('POST', '/sidebar/api/session.cwd', { + host: '127.0.0.1:19488', + origin: SHELL_ORIGIN, + }, '{"sessionId":"test-session"}'), res as unknown as ServerResponse) + expect(res.status).toBe(200) + } finally { + cleanup() + } + }) + + it('never carries the shell origin past the Host fence', async () => { + // The addition is an origin exception, not an authority: an untrusted Host + // must still refuse even when the request wears the shell's own origin. + const { api, cleanup } = mount([]) + try { + const res = fakeRes() + await api(req('POST', '/sidebar/api/session.cwd', { + host: 'evil.example', + origin: SHELL_ORIGIN, + }, '{"sessionId":"test-session"}'), res as unknown as ServerResponse) + expect(res.status).toBe(403) + } finally { + cleanup() + } + }) + + it('matches the shell origin exactly, not by scheme and not by suffix', async () => { + const { api, cleanup } = mount([]) + try { + for (const origin of ['dsh-app://evil', 'dsh-app://app.evil.example', 'http://evil.example']) { + const res = fakeRes() + await api(req('POST', '/sidebar/api/session.cwd', { + host: '127.0.0.1:19488', + origin, + }, '{"sessionId":"test-session"}'), res as unknown as ServerResponse) + expect(res.status, origin).toBe(403) + } + } finally { + cleanup() + } + }) + + it('destroys a cross-site handshake before the upgrade completes', async () => { + // The fence runs ahead of ws's own handshake handling, so its verdict on + // the upgrade path is observable as whether the socket gets destroyed. + const { upgrade, cleanup } = mount([]) + try { + const socket = { + destroyed: false, + destroy(): void { this.destroyed = true }, + } + await upgrade('/sidebar/ws/agent-opens')(req('GET', '/sidebar/ws/agent-opens?sessionId=test-session', { + host: '127.0.0.1:19488', + origin: 'http://evil.example', + connection: 'Upgrade', + upgrade: 'websocket', + }), socket, new Uint8Array()) + expect(socket.destroyed).toBe(true) + } finally { + cleanup() + } + }) +})