Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(dsh-tauri): adapt embedded admission for alpha.3 (#1086)

Hairy5e538137e630
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7a9a3dd4..a91bd679 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -90,6 +90,17 @@ jobs:
- name: Test iOS signing guards without credentials
run: python3 -m unittest discover -s .github/scripts -p 'test_ios_testflight.py' -v
+ - name: Install alpha.3 core for desktop admission regression
+ run: npm install --prefix "$RUNNER_TEMP/dsh-cli-admission" --no-audit --no-fund @deepseek-ai/[email protected]
+
+ - name: Test desktop admission against alpha.3 gateway
+ env:
+ DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli-admission/node_modules/@deepseek-ai/dsh/lib/bin.js
+ run: |
+ for seed in 301 302 303 304 305; do
+ node node_modules/vitest/vitest.mjs run --project unit packages/dsh-tauri/src/host/service/gate.runtime.test.ts --sequence.shuffle --sequence.seed="$seed" || exit $?
+ done
+
- name: Type check sources before generating declarations
run: pnpm run typecheck
diff --git a/packages/dsh-tauri/src/host/service/gate.runtime.test.ts b/packages/dsh-tauri/src/host/service/gate.runtime.test.ts
new file mode 100644
index 00000000..4139532d
--- /dev/null
+++ b/packages/dsh-tauri/src/host/service/gate.runtime.test.ts
@@ -0,0 +1,117 @@
+import type { Context as HostContext } from '@deepseek-ai/cordis'
+import type { HostConnectionService } from '@deepseek-ai/dsh-client-connection'
+import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
+import type { IncomingMessage } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import type { ConnectionHost } from '../types'
+import { createServer } from 'node:http'
+import { createRequire } from 'node:module'
+import process from 'node:process'
+import { pathToFileURL } from 'node:url'
+import { afterEach, expect, it, vi } from 'vitest'
+import { gate } from './gate'
+
+const require = createRequire(process.env.DSH_E2E_DSH_BIN ? pathToFileURL(process.env.DSH_E2E_DSH_BIN) : import.meta.url)
+const cleanups: Array<() => void | Promise<void>> = []
+afterEach(async () => {
+ try {
+ for (const cleanup of cleanups.splice(0).reverse())
+ await cleanup()
+ }
+ finally {
+ vi.unstubAllEnvs()
+ }
+})
+
+it('real core /api prefix admits its original peer only while the embedded gate is attached', async () => {
+ vi.stubEnv('DSH_TAURI_EMBEDDED', undefined)
+ const { Context } = await import(pathToFileURL(require.resolve('@deepseek-ai/cordis')).href) as typeof import('@deepseek-ai/cordis')
+ const connectionModule = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-client-connection')).href) as typeof import('@deepseek-ai/dsh-client-connection')
+ const context = new Context()
+ cleanups.push(() => context.fiber.dispose())
+ const routes: WebRoute[] = []
+ context.provide('webServer', {
+ protocol: 'http:',
+ host: '127.0.0.1',
+ register(route: WebRoute) {
+ routes.push(route)
+ return () => routes.splice(routes.indexOf(route), 1)
+ },
+ } as unknown as HostContext['webServer'])
+ context.provide('credentials', {
+ async modifyRecord(_key: string, update: (value: undefined) => Promise<unknown>) {
+ return update(undefined)
+ },
+ } as unknown as HostContext['credentials'])
+ await connectionModule.apply(context)
+ await vi.waitFor(() => expect(routes.map(route => route.path)).toContain('/api'))
+ const connection = context.connection as HostConnectionService & {
+ browserPeer?: { id: string, signal: AbortSignal, dispose: () => Promise<void> }
+ admitConnection?: (request: IncomingMessage) => { rejection: number } | { peer: unknown, release: () => Promise<void> }
+ }
+ const peer = connection.browserPeer ?? connection.operator
+ context.connection.rpc.intercept('/api', endpoint => endpoint === 'gate/probe', async (_endpoint, _payload, _signal, admitted) => ({ ok: true, value: { id: admitted.id } }))
+ const route = routes.find(route => route.path === '/api')!
+ const server = createServer((req, res) => {
+ const selected = routes.find(candidate => candidate.path === new URL(req.url!, 'http://localhost').pathname) ?? route
+ void Promise.resolve(selected.handler(req, res)).catch(error => res.destroy(error as Error))
+ })
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ cleanups.push(() => new Promise<void>((resolve, reject) => {
+ server.close(error => error ? reject(error) : resolve())
+ server.closeAllConnections()
+ }))
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+ const probe = (headers: Record<string, string> = {}) => fetch(`${base}/api/gate/probe`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...headers },
+ body: JSON.stringify({ type: 'client-request', rpcId: 'probe', method: 'gate/probe', payload: {} }),
+ })
+ expect((await probe()).status).toBe(401)
+ vi.stubEnv('DSH_TAURI_EMBEDDED', '1')
+ const detach = gate.attach(context as unknown as ConnectionHost)
+ cleanups.push(detach)
+ const allowed = await probe()
+ expect(allowed.status).toBe(200)
+ expect(await allowed.json()).toEqual({ type: 'server-response', rpcId: 'probe', result: { ok: true, value: { id: peer.id } } })
+ expect((await probe({ origin: 'http://evil.example' })).status).toBe(403)
+ const untrusted = { headers: { host: 'evil.example' } } as IncomingMessage
+ expect(connection.admit(untrusted)).toEqual({ rejection: 403 })
+ if (connection.admitConnection) {
+ const trusted = { headers: { host: new URL(base).host } } as IncomingMessage
+ const connectUrl = new URL(connection.authenticatedUrl(`${base}/`))
+ connectUrl.pathname = '/connect'
+ const credential = await fetch(connectUrl, { redirect: 'manual' })
+ expect(credential.status).toBe(302)
+ const cookie = credential.headers.get('set-cookie')!.split(';')[0]!
+ const apiAdmission = connection.admit({ headers: { ...trusted.headers, cookie } } as IncomingMessage)
+ expect(apiAdmission).toHaveProperty('peer')
+ if ('peer' in apiAdmission) {
+ expect(apiAdmission.peer).not.toBe(peer)
+ const api = await probe({ cookie })
+ expect(api.status).toBe(200)
+ expect(await api.json()).toEqual({ type: 'server-response', rpcId: 'probe', result: { ok: true, value: { id: apiAdmission.peer.id } } })
+ }
+ const upgrade = connection.admitConnection(trusted)
+ expect(upgrade).toMatchObject({ peer, release: expect.any(Function) })
+ if ('release' in upgrade)
+ await upgrade.release()
+ expect(connection.browserPeer!.signal.aborted).toBe(false)
+ expect(connection.admitConnection(untrusted)).toEqual({ rejection: 403 })
+ expect(connection.admitConnection({ headers: { ...trusted.headers, origin: 'http://evil.example' } } as IncomingMessage)).toEqual({ rejection: 403 })
+ detach()
+ cleanups.pop()
+ expect((await probe()).status).toBe(401)
+ cleanups.push(gate.attach(context as unknown as ConnectionHost))
+ Reflect.set(connection, 'disposed', true)
+ expect(connection.browserPeer!.signal.aborted).toBe(false)
+ expect((await probe()).status).toBe(401)
+ Reflect.set(connection, 'disposed', false)
+ await connection.browserPeer!.dispose()
+ expect(connection.admitConnection(trusted)).toEqual({ rejection: 401 })
+ expect(connection.requestRejection(trusted)).toBe(401)
+ expect((await probe()).status).toBe(401)
+ }
+ await cleanups.pop()!()
+ expect((await probe()).status).toBe(401)
+})
diff --git a/packages/dsh-tauri/src/host/service/gate.test.ts b/packages/dsh-tauri/src/host/service/gate.test.ts
index 9d7ca972..8f63b02c 100644
--- a/packages/dsh-tauri/src/host/service/gate.test.ts
+++ b/packages/dsh-tauri/src/host/service/gate.test.ts
@@ -1,8 +1,10 @@
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { ConnectionHost } from '../types'
+import { Context, Service } from '@deepseek-ai/cordis'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { gate } from './gate'
+const cleanups: Array<() => void | Promise<void>> = []
const request = {} as IncomingMessage
const response = {} as ServerResponse
let host: ConnectionHost
@@ -10,12 +12,12 @@ let host: ConnectionHost
/** 最小 connection 面:两道闸门都记账,用于断言是否调用了原实现。 */
function makeHost(rejection: 401 | 403 | undefined) {
const calls: string[] = []
- const connection: ConnectionHost['connection'] = {
- requestRejection: () => {
+ const connection = {
+ requestRejection: (_request: IncomingMessage) => {
calls.push('requestRejection')
return rejection
},
- authorizeIndex: () => {
+ authorizeIndex: (_request: IncomingMessage, _response: ServerResponse) => {
calls.push('authorizeIndex')
return false
},
@@ -28,12 +30,120 @@ beforeEach(() => {
vi.stubEnv('DSH_TAURI_EMBEDDED', undefined)
})
-afterEach(() => {
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse())
+ await cleanup()
+ vi.restoreAllMocks()
vi.stubEnv('DSH_TAURI_EMBEDDED', undefined)
vi.unstubAllEnvs()
})
+function modernService() {
+ const lifetime = new AbortController()
+ const browserPeer = { id: 'browser', signal: lifetime.signal }
+ const apiPeer = { id: 'api', signal: new AbortController().signal }
+ class Connection extends Service {
+ browserPeer = browserPeer
+ calls = 0
+ disposed = false
+ admit(req: IncomingMessage) {
+ this.calls += 1
+ if (req.headers?.origin === 'evil')
+ return { rejection: 403 as const }
+ return req.headers?.cookie === 'api' ? { peer: apiPeer } : { rejection: 401 as const }
+ }
+
+ requestRejection(req: IncomingMessage) {
+ const admission = this.admit(req)
+ return 'rejection' in admission ? admission.rejection : undefined
+ }
+
+ admitConnection(req: IncomingMessage) {
+ const admission = this.admit(req)
+ return 'rejection' in admission ? admission : { ...admission, release: async () => {} }
+ }
+ }
+ const context = new Context()
+ const connection = new Connection(context, 'connection')
+ cleanups.push(() => context.fiber.dispose())
+ return { context, connection, browserPeer, apiPeer, lifetime, Connection }
+}
+
+function attach(connection: unknown) {
+ const detach = gate.attach({ connection } as ConnectionHost)
+ cleanups.push(detach)
+ return detach
+}
+
+describe('gate.attach modern admission', () => {
+ beforeEach(() => vi.stubEnv('DSH_TAURI_EMBEDDED', '1'))
+
+ it('admits the existing browser peer for HTTP and connection upgrade', async () => {
+ const { connection, browserPeer } = modernService()
+ attach(connection)
+ expect(connection.admit(request)).toEqual({ peer: browserPeer })
+ const upgrade = connection.admitConnection(request)
+ expect(upgrade).toMatchObject({ peer: browserPeer, release: expect.any(Function) })
+ if ('release' in upgrade)
+ await upgrade.release()
+ expect(browserPeer.signal.aborted).toBe(false)
+ expect(connection.requestRejection(request)).toBeUndefined()
+ })
+
+ it('preserves API identity and Host/Origin rejection', () => {
+ const { connection, apiPeer } = modernService()
+ attach(connection)
+ expect(connection.admit({ headers: { cookie: 'api' } } as IncomingMessage)).toEqual({ peer: apiPeer })
+ expect(connection.admit({ headers: { origin: 'evil' } } as IncomingMessage)).toEqual({ rejection: 403 })
+ expect(connection.calls).toBe(2)
+ })
+
+ it('preserves service disposal rejection before the browser peer signal aborts', () => {
+ const { connection, browserPeer } = modernService()
+ attach(connection)
+ connection.disposed = true
+ expect(browserPeer.signal.aborted).toBe(false)
+ expect(connection.admit(request)).toEqual({ rejection: 401 })
+ expect(connection.requestRejection(request)).toBe(401)
+ })
+
+ it('does not revive a disposed browser peer through admission or requestRejection', () => {
+ const { connection, lifetime } = modernService()
+ attach(connection)
+ lifetime.abort()
+ expect(connection.admit(request)).toEqual({ rejection: 401 })
+ expect(connection.admitConnection(request)).toEqual({ rejection: 401 })
+ expect(connection.requestRejection(request)).toBe(401)
+ })
+
+ it('uses each Cordis access receiver and restores inherited property shape', () => {
+ const { connection, context, Connection } = modernService()
+ const instanceBefore = Object.getOwnPropertyDescriptors(connection)
+ const prototypeBefore = Object.getOwnPropertyDescriptors(Connection.prototype)
+ const detach = attach(context.connection)
+ expect(context.connection.admit(request)).toEqual({ peer: connection.browserPeer })
+ expect(context.extend().connection.admit(request)).toEqual({ peer: connection.browserPeer })
+ expect(connection.calls).toBe(2)
+ detach()
+ cleanups.pop()
+ const instanceAfter = Object.getOwnPropertyDescriptors(connection)
+ instanceAfter.calls = instanceBefore.calls!
+ expect(instanceAfter).toEqual(instanceBefore)
+ expect(Object.getOwnPropertyDescriptors(Connection.prototype)).toEqual(prototypeBefore)
+ expect(connection.admit(request)).toEqual({ rejection: 401 })
+ })
+})
+
describe('gate.attach without the carrier marker', () => {
+ it.each([undefined, '0', 'true'])('does not change modern admission for marker %s', (marker) => {
+ vi.stubEnv('DSH_TAURI_EMBEDDED', marker)
+ const { connection } = modernService()
+ const original = connection.admit
+ attach(connection)
+ expect(connection.admit).toBe(original)
+ expect(connection.admit(request)).toEqual({ rejection: 401 })
+ })
+
it('leaves both gates untouched', () => {
const { connection } = makeHost(401)
const rejection = connection.requestRejection
@@ -106,14 +216,15 @@ describe('gate.attach with the carrier marker', () => {
const detach = gate.attach(host)
expect(warn).not.toHaveBeenCalled()
- const { connection } = host
- expect(connection.authorizeIndex(request, response)).toBe(true)
+ expect(host.connection.authorizeIndex!(request, response)).toBe(true)
detach()
- expect(connection.authorizeIndex).toBe(authorizeIndex)
+ expect(host.connection.authorizeIndex).toBe(authorizeIndex)
})
it('restores both gates on detach', () => {
const { connection } = makeHost(401)
+ Object.defineProperty(connection, 'requestRejection', { enumerable: false })
+ const descriptors = Object.getOwnPropertyDescriptors(connection)
const rejection = connection.requestRejection
const authorize = connection.authorizeIndex
@@ -121,6 +232,7 @@ describe('gate.attach with the carrier marker', () => {
expect(connection.requestRejection).toBe(rejection)
expect(connection.authorizeIndex).toBe(authorize)
+ expect(Object.getOwnPropertyDescriptors(connection)).toEqual(descriptors)
})
it('stays inert and warns when the core lacks the gates', () => {
diff --git a/packages/dsh-tauri/src/host/service/gate.ts b/packages/dsh-tauri/src/host/service/gate.ts
index 02bfde27..bf29aead 100644
--- a/packages/dsh-tauri/src/host/service/gate.ts
+++ b/packages/dsh-tauri/src/host/service/gate.ts
@@ -4,31 +4,12 @@ import process from 'node:process'
import { PLUGIN_ID } from '../../shared/constants'
import { defineService } from './index'
-/**
- * 桌面壳在 spawn 时注入的载体标记;与 `src-tauri/src/service/workflow/launch.rs` 的
- * envs 注入点逐字一致。未注入时本插件完全不接管鉴权,同一 profile 下独立运行的
- * `dsh web` 保持 browser-session 鉴权。
- */
const EMBEDDED_ENV = 'DSH_TAURI_EMBEDDED'
-/**
- * 桌面载体鉴权适配。
- *
- * 内嵌 WebView 是 `tauri.localhost` 下的跨源沙箱 iframe,`SameSite=Strict` 的
- * browser-session Cookie 不会被携带,根路径 token 交换也就无法完成。这里在
- * `connection` 服务实例上覆写两道闸门:`requestRejection` 保留 Host/Origin fence
- * 的 403、只把 401 降级为放行;`authorizeIndex` 直接放行 index。
- *
- * 两道闸门必须**各自独立**接管:0.1.6 及更早两处都在 `connection` 上;0.1.7 起
- * `requestRejection` 移到了 peer 上,`connection` 只剩 `authorizeIndex`(且该方法
- * 会自行写出 401/303,返回 true 才是「调用方可以发 index.html」)。此前把两者绑成
- * 一个整体,缺一道就整个适配 noop —— 表现为嵌入 WebView 与健康探测都恒拿 401。
- */
export const gate = defineService({
attach(ctx: ConnectionHost): () => void {
- if (process.env[EMBEDDED_ENV] !== '1') {
+ if (process.env[EMBEDDED_ENV] !== '1')
return noop
- }
const { connection } = ctx
if (connection === undefined || connection === null) {
@@ -37,53 +18,47 @@ export const gate = defineService({
}
const restores: Array<() => void> = []
-
- // `ctx.connection` 可能只是 cordis 的取用代理:只覆写实例属性时,赋值落在代理
- // 自身,`dsh-host-frontend-static` 里 `ctx.connection.authorizeIndex` 取到的仍是
- // 原型上的真方法(0.1.7 实测:无告警、覆写已装,401 照旧)。原型与实例一起接管,
- // detach 时逐条还原。
- const targets: ConnectionHost['connection'][] = [connection]
- const prototype = Object.getPrototypeOf(connection) as ConnectionHost['connection'] | null
- if (prototype !== null && prototype !== connection && prototype !== Object.prototype) {
- targets.push(prototype)
+ // issue #1083: alpha.3 admission owns authentication; older admit delegates to requestRejection.
+ if (connection.browserPeer !== undefined && typeof connection.admit === 'function') {
+ const admit = connection.admit
+ replace('admit', function (this: ConnectionHost['connection'], request: IncomingMessage) {
+ const admission = admit.call(this, request)
+ const peer = this.browserPeer
+ return 'rejection' in admission && admission.rejection === 401 && this.disposed !== true && peer?.signal.aborted === false
+ ? { peer }
+ : admission
+ })
}
-
- for (const target of targets) {
- const rejection = target.requestRejection
- if (typeof rejection === 'function') {
- target.requestRejection = (request: IncomingMessage) => {
- const rejected = rejection.call(target, request)
- return rejected === 401 ? undefined : rejected
- }
- restores.push(() => {
- target.requestRejection = rejection
- })
- }
-
- const authorize = target.authorizeIndex
- if (typeof authorize === 'function') {
- target.authorizeIndex = () => true
- restores.push(() => {
- target.authorizeIndex = authorize
- })
- }
+ else if (typeof connection.requestRejection === 'function') {
+ const rejection = connection.requestRejection
+ replace('requestRejection', function (this: ConnectionHost['connection'], request: IncomingMessage) {
+ const rejected = rejection.call(this, request)
+ return rejected === 401 ? undefined : rejected
+ })
}
- if (restores.length === 0) {
- warn(ctx, 'connection 服务缺少 requestRejection/authorizeIndex,桌面载体鉴权适配未生效')
- return noop
- }
+ if (typeof connection.authorizeIndex === 'function')
+ replace('authorizeIndex', () => true)
+
+ if (restores.length === 0)
+ warn(ctx, 'connection 服务缺少 admit/requestRejection/authorizeIndex,桌面载体鉴权适配未生效')
return () => {
- for (const restore of restores) {
+ for (const restore of restores.splice(0).reverse())
restore()
- }
+ }
+
+ function replace(key: keyof ConnectionHost['connection'], value: unknown): void {
+ let owner = connection
+ while (!Object.hasOwn(owner, key))
+ owner = Object.getPrototypeOf(owner) as typeof connection
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key)!
+ Object.defineProperty(owner, key, { ...descriptor, value })
+ restores.push(() => Object.defineProperty(owner, key, descriptor))
}
},
})
-// --- internal ---
-
function noop(): void {}
function warn(ctx: ConnectionHost, message: string): void {
diff --git a/packages/dsh-tauri/src/host/types/index.ts b/packages/dsh-tauri/src/host/types/index.ts
index 0219c4cb..5b56ccc4 100644
--- a/packages/dsh-tauri/src/host/types/index.ts
+++ b/packages/dsh-tauri/src/host/types/index.ts
@@ -3,16 +3,12 @@ import type { ConnectionGate } from './harness'
export * from './harness'
-/**
- * 桌面载体鉴权适配要覆写的两道闸门。
- *
- * `requestRejection` 取自 dsh-tauri 的 `ConnectionGate`;`authorizeIndex` 只被
- * frontend-static 以 `() => ctx.connection.authorizeIndex(req, res)` 调用,返回值即
- * 「index 是否继续由调用方写出」,因此按调用点在这里补齐。
- */
export interface ConnectionHost {
- connection: ConnectionGate & {
- authorizeIndex: (request: IncomingMessage, response: ServerResponse) => boolean
+ connection: Partial<ConnectionGate> & {
+ admit?: (request: IncomingMessage) => { peer: unknown } | { rejection: 401 | 403 }
+ browserPeer?: { readonly signal: AbortSignal }
+ readonly disposed?: boolean
+ authorizeIndex?: (request: IncomingMessage, response: ServerResponse) => boolean
}
logger?: {
warn?: (message: string, error?: unknown) => void