Merge PR #797: fix(ws): WebSocket 路由改用壳注入的 transport base + 接受桌面壳页面 origin(0.2.0-rc.1 / v0.24.1 基线)
This commit is contained in:
commit
a749b20b68
5 files changed
+135
-6
No files matched your search
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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())
|
||||
|
||||
+21
-4
@@ -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 {
|
||||
|
||||
@@ -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<void>
|
||||
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<void>,
|
||||
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()
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user