DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh): ProxyJump 跳板链支持——config 主机经跳板连接不再盲重试
Menghuan19187273cc0f0a01
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.tsindex ca445a2a..293ca7c5 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts@@ -8,7 +8,7 @@ import type { Config } from '../storage/index'* @module dsh-tauri-ssh/host/service/manager*/-import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshTestResult } from '../types/index'+import type { MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshTestResult } from '../types/index'import type { BootstrapHooks } from './bootstrap'import type { SshMachineEvents } from './events'import type { KnownHostsStore } from './host-keys'@@ -16,7 +16,7 @@ import type { SshSession, SshTransport, SshTunnelHandle } from './transport'import { homedir } from 'node:os'import process from 'node:process'import { join } from 'pathe'-import { SshError } from '../types/index'+import { MachineId, SshError } from '../types/index'import { checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, runInstallScript, skippedVerificationSummary } from './bootstrap'import { fingerprintHostKey } from './host-keys'@@ -140,7 +140,7 @@ export class SshManager {this.emit(machineId)let session: SshSessiontry {- session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)}catch (error) {delete state.progress@@ -208,7 +208,7 @@ export class SshManager {// 作一致性语义——sync 引擎经此开专用会话,裸 /api-ssh 调用方同样拿到// 可区分的 machine-reconnecting 而非并行建连)。this.refuseWhileReconnecting(machineId, this.ensureState(machineId))- return await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ return await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)}/**@@ -301,7 +301,7 @@ export class SshManager {}let session: SshSessiontry {- session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)}catch (error) {if (generation === state.generation) {@@ -442,7 +442,7 @@ export class SshManager {}let session: SshSessiontry {- session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)}catch (error) {if (generation === state.generation) {diff --git a/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts b/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.tsindex 25e291f2..012983ca 100644--- a/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts@@ -206,9 +206,23 @@ describe('lookupSshConfig', () => {user: 'first',port: 2222,identityFiles: ['~/.ssh/one', '~/.ssh/two'],+ proxyJump: [],})})+ it('resolves ProxyJump chains with overrides, none, and first-wins', () => {+ const blocks = parseSshConfig([+ 'Host ops',+ ' ProxyJump root@dev:2222,none',+ 'Host *',+ ' ProxyJump bastion',+ ].join('\n'))+ // 首个命中块先取值:ops 自己的 ProxyJump 胜出;none 过滤、逗号成链+ expect(lookupSshConfig(blocks, 'ops').proxyJump).toEqual(['root@dev:2222'])+ // 无块命中的回落到 Host *+ expect(lookupSshConfig(blocks, 'other').proxyJump).toEqual(['bastion'])+ })+it('skips negated blocks and non-matching wildcards', () => {const blocks = parseSshConfig(['Host !10.0.0.1 *.example.com',@@ -226,7 +240,7 @@ describe('lookupSshConfig', () => {})it('returns only the defaults shape for no matches', () => {- expect(lookupSshConfig([], 'anything')).toEqual({ identityFiles: [] })+ expect(lookupSshConfig([], 'anything')).toEqual({ identityFiles: [], proxyJump: [] })})})diff --git a/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts b/packages/dsh-tauri-ssh/src/host/service/ssh-config.tsindex 5e8cbe1a..466dcdec 100644--- a/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts+++ b/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts@@ -8,7 +8,9 @@ import type { MachineProfile } from '../types/index'* plus the ordered identity files to try). Keys are read fresh on every* connect — a key added to `~/.ssh` is picked up without touching DSH.*- * Deliberate subset: `Match` blocks, `ProxyJump`, and agent forwarding are+ * `ProxyJump` resolves to the ordered hop list (alias form `[user@]host[:port]`,+ * comma-separated for multi-hop; `none` disables); the transport walks it.+ * Deliberate subset: `Match` blocks, `ProxyCommand`, and agent forwarding are* out of scope; a host with no config match falls back to the profile fields* and the default identity files, exactly like a bare `ssh host` would.* @module dsh-tauri-ssh/host/service/ssh-config@@ -46,6 +48,11 @@ export interface SshHostSettings {port?: number/** Every `IdentityFile` from the matching blocks, in order. */identityFiles: string[]+ /**+ * The `ProxyJump` hops (first obtained value wins, comma-split, `none`+ * filtered out); each entry is the raw `[user@]alias[:port]` token.+ */+ proxyJump: string[]}/** The concrete connection plan one machine profile resolves to. */@@ -60,6 +67,8 @@ export interface ResolvedSshAuth {password?: string/** The identity files to try, in order, as raw file contents. */keys: Array<{ privateKey: string, passphrase?: string }>+ /** The resolved ProxyJump hop tokens (`[user@]alias[:port]`), in order; empty when direct. */+ proxyJump: string[]}/** Token expansion for `~`, `%d`, `%h`, `%r` in config paths (the OpenSSH subset). */@@ -188,7 +197,7 @@ export function parseSshConfig(text: string): SshHostBlock[] {* `IdentityFile` accumulates across all matching blocks.*/export function lookupSshConfig(blocks: SshHostBlock[], host: string): SshHostSettings {- const settings: SshHostSettings = { identityFiles: [] }+ const settings: SshHostSettings = { identityFiles: [], proxyJump: [] }for (const block of blocks) {const applies = block.patterns.some(pattern => hostPatternMatches(pattern, host))if (!applies)@@ -208,6 +217,12 @@ export function lookupSshConfig(blocks: SshHostBlock[], host: string): SshHostSeif (block.values.identityfile !== undefined) {settings.identityFiles.push(...block.values.identityfile)}+ if (settings.proxyJump.length === 0 && block.values.proxyjump !== undefined) {+ settings.proxyJump = block.values.proxyjump[0]!+ .split(',')+ .map(token => token.trim())+ .filter(token => token !== '' && token.toLowerCase() !== 'none')+ }}return settings}@@ -368,6 +383,7 @@ export class SshConfigResolver {port,username,keys,+ proxyJump: settings.proxyJump,...password === undefined ? {} : { password },}}diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts b/packages/dsh-tauri-ssh/src/host/service/transport.test.tsindex fb8e0b33..17181ca3 100644--- a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts@@ -39,6 +39,7 @@ class StubResolver {username: stringpassword?: stringkeys: Array<{ privateKey: string, passphrase?: string }>+ proxyJump: string[]}> {const password = input.password === undefined || input.password === '' ? undefined : input.passwordreturn {@@ -46,6 +47,7 @@ class StubResolver {port: this.plan.port ?? input.port,username: this.plan.username ?? input.user,keys: this.plan.keys ?? [],+ proxyJump: [],...password === undefined ? {} : { password },}}@@ -147,6 +149,9 @@ class FakeClient extends EventEmitter {/** The most recent exec stream (so end() can close it like a real channel). */lastStream: EventEmitter | undefined+ /** The direct-tcpip targets this client was asked to reach (jump chains). */+ forwardCalls: Array<{ dstIP: string, dstPort: number }> = []+forwardOut(_srcIP: string,_srcPort: number,@@ -154,6 +159,7 @@ class FakeClient extends EventEmitter {_dstPort: number,callback: (error: Error | undefined, channel?: unknown) => void,): this {+ this.forwardCalls.push({ dstIP: _dstIP, dstPort: _dstPort })queueMicrotask(() => {if (this.forwardError !== undefined) {callback(this.forwardError)@@ -221,6 +227,13 @@ function errorClientOnce(message: string): () => FakeClient {}}+/** The ready-mode counterpart of {@link errorClientOnce}. */+function readyClientOnce(): () => FakeClient {+ return function () {+ return fakeClientFactory('ready', '')+ }+}+/** Drive one authHandler round and return what it asks for next. */function nextAuth(handler: AuthHandler): Promise<unknown> {return new Promise(resolve => handler(null, false, resolve))@@ -660,3 +673,122 @@ describe('describeConnectFailure', () => {await expect(transport.connect(withoutPassword(profile), () => true)).rejects.toThrow(/no key or ssh-agent was accepted/)})})++/** A resolver that answers per config alias: ops jumps through dev. */+class JumpResolver {+ constructor(private readonly plans: Record<string, {+ host: string+ port: number+ username?: string+ proxyJump?: string[]+ }>) {}++ async resolve(input: MachineProfile): Promise<{+ host: string+ port: number+ username: string+ keys: Array<{ privateKey: string, passphrase?: string }>+ proxyJump: string[]+ }> {+ const plan = this.plans[input.host]+ if (plan === undefined)+ throw new Error(`unknown host ${input.host}`)+ return {+ host: plan.host,+ port: plan.port,+ username: plan.username ?? input.user,+ keys: [{ privateKey: 'jump-or-target-key' }],+ proxyJump: plan.proxyJump ?? [],+ }+ }+}++describe('ssh2Transport ProxyJump', () => {+ const opsProfile: MachineProfile = {+ id: MachineId('ops'),+ name: 'ops',+ host: 'ops',+ port: 2222,+ user: 'root',+ remotePort: 3080,+ }++ it('walks the jump chain: hop connects directly, target rides the forwarded stream', async () => {+ const resolver = new JumpResolver({+ ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev'] },+ dev: { host: '10.1.0.2', port: 22 },+ })+ const labels: string[] = []+ const transport = new Ssh2Transport(15000, resolver, noAgent)+ const before = fakeClientInstances.length+ const session = await transport.connect(opsProfile, (label) => {+ labels.push(label)+ return true+ })+ expect(session).toBeDefined()+ const [jump, target] = fakeClientInstances.slice(before)+ // 跳板直连自己的解析地址;目标经 forwardOut 流(sock)且地址为 ops 解析结果+ expect(jump?.connectConfig?.host).toBe('10.1.0.2')+ expect(jump?.connectConfig?.sock).toBeUndefined()+ expect(jump?.forwardCalls).toEqual([{ dstIP: '192.168.42.192', dstPort: 2222 }])+ expect(target?.connectConfig?.host).toBe('192.168.42.192')+ expect(target?.connectConfig?.sock).toBeDefined()+ // TOFU 按跳标签记录:跳板记在自己别名下,目标记机器 id+ expect(labels).toEqual(['dev', 'ops'])+ // 目标会话关闭时跳板一并收掉+ await session.close()+ expect(jump?.ended).toBe(true)+ })++ it('supports user@ and :port overrides and comma-separated multi-hop chains', async () => {+ const resolver = new JumpResolver({+ ops: { host: '192.168.42.192', port: 2222, proxyJump: ['root@dev:22', 'admin@bastion'] },+ dev: { host: '10.1.0.2', port: 22 },+ bastion: { host: '10.1.0.3', port: 2222 },+ })+ const transport = new Ssh2Transport(15000, resolver, noAgent)+ const before = fakeClientInstances.length+ await transport.connect(opsProfile, () => true)+ const [first, second, target] = fakeClientInstances.slice(before)+ expect(first?.connectConfig?.host).toBe('10.1.0.2')+ expect(first?.forwardCalls).toEqual([{ dstIP: '10.1.0.3', dstPort: 2222 }])+ expect(second?.connectConfig?.host).toBe('10.1.0.3')+ expect(second?.forwardCalls).toEqual([{ dstIP: '192.168.42.192', dstPort: 2222 }])+ expect(target?.connectConfig?.sock).toBeDefined()+ })++ it('rejects a proxy jump cycle before dialing', async () => {+ const resolver = new JumpResolver({+ ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev', 'dev'] },+ dev: { host: '10.1.0.2', port: 22 },+ })+ const transport = new Ssh2Transport(15000, resolver, noAgent)+ await expect(transport.connect(opsProfile, () => true)).rejects.toThrow(/proxy jump cycle/iu)+ })++ it('rejects a nested ProxyJump on the jump alias', async () => {+ const resolver = new JumpResolver({+ ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev'] },+ dev: { host: '10.1.0.2', port: 22, proxyJump: ['third'] },+ })+ const transport = new Ssh2Transport(15000, resolver, noAgent)+ await expect(transport.connect(opsProfile, () => true)).rejects.toThrow(/nested ProxyJump/iu)+ })++ it('closes the jump session when the target handshake fails', async () => {+ const resolver = new JumpResolver({+ ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev'] },+ dev: { host: '10.1.0.2', port: 22 },+ })+ const transport = new Ssh2Transport(15000, resolver, noAgent)+ const before = fakeClientInstances.length+ // 第一跳就绪,目标握手失败+ const { Client } = await import('ssh2')+ vi.mocked(Client)+ .mockImplementationOnce(readyClientOnce())+ .mockImplementationOnce(errorClientOnce('Connection lost before handshake'))+ await expect(transport.connect(opsProfile, () => true)).rejects.toThrow(/Connection lost/iu)+ const [jump] = fakeClientInstances.slice(before)+ expect(jump?.ended).toBe(true)+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-ssh/src/host/service/transport.tsindex b1b28292..a61082c5 100644--- a/packages/dsh-tauri-ssh/src/host/service/transport.ts+++ b/packages/dsh-tauri-ssh/src/host/service/transport.ts@@ -7,12 +7,14 @@import type { Buffer } from 'node:buffer'import type { AddressInfo, Server } from 'node:net'+import type { Duplex } from 'node:stream'import type { ConnectConfig } from 'ssh2'import type { MachineProfile, SshAuthMethod } from '../types/index'import type { ResolvedSshAuth } from './ssh-config'import { createServer } from 'node:net'import process from 'node:process'import { Client } from 'ssh2'+import { MachineId } from '../types/index'/** The credential-resolution face the transport needs (SshConfigResolver implements it). */export interface SshCredentialsResolver {@@ -83,22 +85,57 @@ export interface SshSession {close: () => Promise<void>}+/**+ * TOFU host-key gate, keyed by hop label: the target machine id for the final+ * hop, the `ProxyJump` alias for each jump host (jump keys are remembered+ * under their own alias, so a host used as both jump and machine shares one+ * TOFU record). May be async (the ssh2 callback form waits for the verdict).+ */+export type SshHostKeyVerifier = (label: string, hostKey: Buffer) => boolean | Promise<boolean>+/** Transport factory: authenticate one machine and return its session. */export interface SshTransport {/*** @param profile - the machine profile to connect.- * @param hostKeyVerifier - TOFU host-key gate; may be async (the ssh2- * callback form waits for the verdict).+ * @param hostKeyVerifier - TOFU host-key gate, per hop label.* @param signal - aborts the handshake.* @returns the authenticated session.*/connect: (profile: MachineProfile,- hostKeyVerifier: (hostKey: Buffer) => boolean | Promise<boolean>,+ hostKeyVerifier: SshHostKeyVerifier,signal?: AbortSignal,) => Promise<SshSession>}+/** One parsed ProxyJump hop: the `[user@]alias[:port]` token, split. */+interface ProxyJumpHop {+ /** The config alias (drives the jump's own Host-block lookup). */+ alias: string+ /** Optional `user@` override. */+ user?: string+ /** Optional `:port` override. */+ port?: number+}++/** Parse one ProxyJump token (`[user@]alias[:port]`). */+function parseProxyJumpHop(token: string): ProxyJumpHop {+ let rest = token+ let user: string | undefined+ const at = rest.lastIndexOf('@')+ if (at !== -1) {+ user = rest.slice(0, at)+ rest = rest.slice(at + 1)+ }+ let port: number | undefined+ const colon = rest.lastIndexOf(':')+ if (colon !== -1 && /^\d+$/u.test(rest.slice(colon + 1))) {+ port = Number(rest.slice(colon + 1))+ rest = rest.slice(0, colon)+ }+ return { alias: rest, ...user === undefined ? {} : { user }, ...port === undefined ? {} : { port } }+}+/** Wrap one string for safe inclusion in a remote shell command line. */export function shQuote(value: string): string {return `'${value.replace(/'/gu, `'\\''`)}'`@@ -216,10 +253,92 @@ export class Ssh2Transport implements SshTransport {async connect(profile: MachineProfile,- hostKeyVerifier: (hostKey: Buffer) => boolean | Promise<boolean>,+ hostKeyVerifier: SshHostKeyVerifier,signal?: AbortSignal,): Promise<SshSession> {- return new Promise<SshSession>((resolve, reject) => {+ const hops: Ssh2Session[] = []+ try {+ const session = await this.connectTarget(profile, String(profile.id), hostKeyVerifier, signal, hops, new Set())+ // 跳板会话与目标会话同生命周期:目标关闭时逐个收掉跳板(反序无必要,+ // 逐跳 close 会连带掐断穿过它的 direct-tcpip 通道)。+ session.onClosed(() => {+ for (const hop of hops)+ void hop.close().catch(() => undefined)+ })+ return session+ }+ catch (error) {+ for (const hop of hops)+ void hop.close().catch(() => undefined)+ throw error+ }+ }++ /**+ * Connect one target, walking its resolved ProxyJump chain first. The whole+ * chain resolves locally up front (config files only), then hops connect in+ * order: hop i opens a direct-tcpip channel (`ssh -W` semantics) to the+ * next hop's resolved host:port — the last hop points at the real target —+ * and the next handshake rides that stream as its socket. A jump alias+ * whose own config also sets ProxyJump is rejected (nested chains), as is+ * any cycle. Stored secrets do not cross hops: jump auth uses the agent and+ * the alias's identity files, exactly like `ssh -J`.+ */+ private async connectTarget(+ profile: MachineProfile,+ label: string,+ hostKeyVerifier: SshHostKeyVerifier,+ signal: AbortSignal | undefined,+ hops: Ssh2Session[],+ visited: ReadonlySet<string>,+ ): Promise<Ssh2Session> {+ const auth = await this.resolver.resolve(profile)+ // 缺省视直连(兼容不填 proxyJump 的 resolver 实现)+ const proxyJump = auth.proxyJump ?? []+ if (proxyJump.length === 0)+ return this.connectWithAuth(auth, label, hostKeyVerifier, signal, undefined)++ const chain: Array<{ alias: string, auth: ResolvedSshAuth }> = []+ const seen = new Set(visited)+ for (const token of proxyJump) {+ const hop = parseProxyJumpHop(token)+ const key = hop.alias.toLowerCase()+ if (seen.has(key))+ throw new Error(`proxy jump cycle through "${hop.alias}"`)+ seen.add(key)+ const jumpProfile: MachineProfile = {+ id: MachineId(hop.alias),+ name: hop.alias,+ host: hop.alias,+ user: hop.user ?? '',+ port: hop.port ?? 22,+ remotePort: 3080,+ }+ const jumpAuth = await this.resolver.resolve(jumpProfile)+ if ((jumpAuth.proxyJump ?? []).length > 0)+ throw new Error(`nested ProxyJump on "${hop.alias}" is not supported`)+ chain.push({ alias: hop.alias, auth: jumpAuth })+ }++ let sock: Duplex | undefined+ for (const [index, hop] of chain.entries()) {+ const session = await this.connectWithAuth(hop.auth, hop.alias, hostKeyVerifier, signal, sock)+ hops.push(session)+ const next = index + 1 < chain.length ? chain[index + 1]!.auth : auth+ sock = await session.forwardOutStream(next.host, next.port)+ }+ return this.connectWithAuth(auth, label, hostKeyVerifier, signal, sock)+ }++ /** One ssh2 handshake: direct, or over a jump-forwarded stream when `sock` rides a hop. */+ private connectWithAuth(+ auth: ResolvedSshAuth,+ label: string,+ hostKeyVerifier: SshHostKeyVerifier,+ signal: AbortSignal | undefined,+ sock: Duplex | undefined,+ ): Promise<Ssh2Session> {+ return new Promise<Ssh2Session>((resolve, reject) => {if (signal?.aborted) {reject(abortError(signal))return@@ -246,7 +365,7 @@ export class Ssh2Transport implements SshTransport {client.on('error', (error) => {settle(() => reject(describedConnectFailure(error, passwordOffered)))})- void this.resolver.resolve(profile).then((auth) => {+ void Promise.resolve().then(() => {const agentSocket = this.options.agentSocket === undefined? process.env.SSH_AUTH_SOCK: this.options.agentSocket@@ -288,6 +407,7 @@ export class Ssh2Transport implements SshTransport {}}client.connect({+ ...sock === undefined ? {} : { sock: sock as ConnectConfig['sock'] },host: auth.host,port: auth.port,username: auth.username,@@ -301,7 +421,7 @@ export class Ssh2Transport implements SshTransport {// ssh2 accepts a synchronous boolean return OR the verify-callback// form; always driving the callback keeps async verifiers uniform.hostVerifier: (key: Buffer, verify: (valid: boolean) => void): void => {- const verdict = hostKeyVerifier(key)+ const verdict = hostKeyVerifier(label, key)if (verdict instanceof Promise) {void verdict.then(verify, () => verify(false))}@@ -346,6 +466,23 @@ class Ssh2Session implements SshSession {})}+ /**+ * Open one direct-tcpip channel (`ssh -W` semantics) through this session.+ * Internal to the ProxyJump chain: the next hop's handshake rides the+ * returned stream as its socket; closing this session kills the stream.+ */+ forwardOutStream(host: string, port: number): Promise<Duplex> {+ return new Promise((resolve, reject) => {+ this.client.forwardOut('127.0.0.1', 0, host, port, (error, stream) => {+ if (error !== undefined) {+ reject(error)+ return+ }+ resolve(stream)+ })+ })+ }+exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {return new Promise<SshExecResult>((resolve, reject) => {let settled = false