Skip to content

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

feat(ssh): connection state vocabulary, password auth chain, keepalive watchdog and auto-reconnect

Menghuan19186a127c21aa24
diff --git a/packages/dsh-tauri-ssh/src/host/apply.test.ts b/packages/dsh-tauri-ssh/src/host/apply.test.ts
index a0761587..229849be 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.test.ts
@@ -79,6 +79,11 @@ const baseConfig: SshRemoteConfig = {
healthCheckTimeoutMs: 1000,
healthPollIntervalMs: 5,
healthPollAttempts: 3,
+ keepaliveIntervalMs: 10000,
+ keepaliveCountMax: 3,
+ reconnectInitialDelayMs: 1,
+ reconnectMaxDelayMs: 2,
+ reconnectMaxAttempts: 2,
}
// Every service construction points the credential/discovery layer at a
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.ts b/packages/dsh-tauri-ssh/src/host/routes/index.ts
index 77d8d651..4734753c 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.ts
@@ -52,6 +52,10 @@ export interface SshMachineListItem extends MachineView {
tunnelBaseUrl?: string
lastError?: string
dshMissing?: boolean
+ /** Epoch ms of the next scheduled reconnect retry (while reconnecting). */
+ nextRetryAt?: number
+ /** Which credential the live (or last successful) connection used. */
+ authMethod?: SshMachineStatus['authMethod']
}
/** The manager face this API needs (the plugin's service). */
@@ -216,6 +220,8 @@ function listItemOf(host: SshApiHost, view: MachineView): SshMachineListItem {
...status.lastError === undefined ? {} : { lastError: status.lastError },
...status.dshMissing === true ? { dshMissing: true } : {},
...status.progress === undefined ? {} : { progress: status.progress },
+ ...status.nextRetryAt === undefined ? {} : { nextRetryAt: status.nextRetryAt },
+ ...status.authMethod === undefined ? {} : { authMethod: status.authMethod },
}
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
index 48e9b849..9a27be64 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
@@ -1,3 +1,4 @@
+import type { AddressInfo } from 'node:net'
import type { MachineProfile } from '../types/index.js'
import { Buffer } from 'node:buffer'
import { EventEmitter } from 'node:events'
@@ -5,7 +6,7 @@ import { Server, connect as tcpConnect } from 'node:net'
import { PassThrough } from 'node:stream'
import { describe, expect, it, vi } from 'vitest'
import { MachineId } from '../types/index.js'
-import { loginShell, shQuote, Ssh2Transport } from './transport.js'
+import { classifyConnectFailure, describeConnectFailure, loginShell, shQuote, Ssh2Transport } from './transport.js'
const profile: MachineProfile = {
id: MachineId('m1'),
@@ -52,6 +53,9 @@ class StubResolver {
type HostVerifier = (key: Buffer, verify: (valid: boolean) => void) => void
+/** Transport options with the agent step disabled — deterministic chains. */
+const noAgent = { keepaliveIntervalMs: 10_000, keepaliveCountMax: 3, agentSocket: '' }
+
class FakeClient extends EventEmitter {
connectConfig: Record<string, unknown> | undefined
hostKeyAccepted: boolean | undefined
@@ -62,6 +66,8 @@ class FakeClient extends EventEmitter {
execHang = false
/** When set, the exec stream emits this error instead of data/close. */
streamError: Error | undefined
+ /** The auth descriptor the fake server "accepted" (null = auth rejected). */
+ acceptedAuth: unknown
constructor(
private readonly mode: 'ready' | 'error',
@@ -73,13 +79,31 @@ class FakeClient extends EventEmitter {
connect(config: Record<string, unknown>): this {
this.connectConfig = config
const hostVerifier = config.hostVerifier as HostVerifier | undefined
+ const authHandler = config.authHandler as AuthHandler | undefined
const finish = (): void => {
if (this.mode === 'error') {
- queueMicrotask(() => this.emit('error', new Error(this.errorMessage)))
+ const emitError = (): void => queueMicrotask(() => this.emit('error', new Error(this.errorMessage)))
+ // A real server drives the auth chain before declaring failure, so
+ // the transport's passwordOffered bookkeeping is set by the time the
+ // error lands; the fake mirrors that.
+ if (authHandler === undefined) {
+ emitError()
+ return
+ }
+ authHandler(null, false, () => emitError())
}
- else {
+ else if (authHandler === undefined) {
queueMicrotask(() => this.emit('ready'))
}
+ else {
+ // A real server drives the auth chain itself; the fake accepts the
+ // first offered descriptor (or stores null when the chain gives up)
+ // and only then reports ready.
+ authHandler(null, false, (descriptor) => {
+ this.acceptedAuth = descriptor
+ queueMicrotask(() => this.emit('ready'))
+ })
+ }
}
if (hostVerifier === undefined) {
finish()
@@ -190,6 +214,13 @@ function authHandlerOf(client: FakeClient): AuthHandler {
return handler as AuthHandler
}
+/** Build a constructable once-implementation for the mocked Client (arrows cannot be `new`-ed). */
+function errorClientOnce(message: string): () => FakeClient {
+ return function () {
+ return fakeClientFactory('error', message)
+ }
+}
+
/** 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))
@@ -208,7 +239,7 @@ describe('shQuote / loginShell', () => {
describe('ssh2Transport', () => {
it('connects with password auth and resolves on ready', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
const session = await transport.connect(profile, () => true)
expect(session).toBeDefined()
const client = lastClient()
@@ -223,15 +254,32 @@ describe('ssh2Transport', () => {
expect(client.ended).toBe(true)
})
+ it('tries the ssh-agent first, then keys, then the stored password, then gives up', async () => {
+ const resolver = new StubResolver({
+ keys: [{ privateKey: 'KEY-A' }],
+ })
+ const transport = new Ssh2Transport(15000, resolver, { ...noAgent, agentSocket: '/tmp/agent.sock' })
+ const session = await transport.connect(profile, () => true)
+ const client = lastClient()
+ const handler = authHandlerOf(client)
+ // The fake server accepted the first offer (the agent); the rest of the
+ // chain is what ssh2 would try next had it been refused.
+ expect(client.acceptedAuth).toEqual({ type: 'agent', username: 'root', agent: '/tmp/agent.sock' })
+ expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY-A' })
+ expect(await nextAuth(handler)).toEqual({ type: 'password', username: 'root', password: 'sekrit' })
+ expect(await nextAuth(handler)).toBe(false)
+ await session.close()
+ })
+
it('tries the resolved keys first, then the stored password, then gives up', async () => {
const resolver = new StubResolver({
keys: [{ privateKey: 'KEY-A' }, { privateKey: 'KEY-B', passphrase: 'PASS' }],
})
- const transport = new Ssh2Transport(15000, resolver)
+ const transport = new Ssh2Transport(15000, resolver, noAgent)
const session = await transport.connect(profile, () => true)
const client = lastClient()
const handler = authHandlerOf(client)
- expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY-A' })
+ expect(client.acceptedAuth).toEqual({ type: 'publickey', username: 'root', key: 'KEY-A' })
expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY-B', passphrase: 'PASS' })
expect(await nextAuth(handler)).toEqual({ type: 'password', username: 'root', password: 'sekrit' })
expect(await nextAuth(handler)).toBe(false)
@@ -240,18 +288,60 @@ describe('ssh2Transport', () => {
it('tries only keys when no password is stored', async () => {
const resolver = new StubResolver({ keys: [{ privateKey: 'KEY', passphrase: 'PASS' }] })
- const transport = new Ssh2Transport(15000, resolver)
+ const transport = new Ssh2Transport(15000, resolver, noAgent)
const session = await transport.connect(withoutPassword(profile), () => true)
- const handler = authHandlerOf(lastClient())
- expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY', passphrase: 'PASS' })
+ const client = lastClient()
+ const handler = authHandlerOf(client)
+ expect(client.acceptedAuth).toEqual({ type: 'publickey', username: 'root', key: 'KEY', passphrase: 'PASS' })
expect(await nextAuth(handler)).toBe(false)
await session.close()
})
it('gives up immediately when nothing resolves', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
const session = await transport.connect(withoutPassword(profile), () => true)
- expect(await nextAuth(authHandlerOf(lastClient()))).toBe(false)
+ expect(lastClient().acceptedAuth).toBe(false)
+ await session.close()
+ })
+
+ it('reads SSH_AUTH_SOCK when no agent socket is injected', async () => {
+ const previous = process.env.SSH_AUTH_SOCK
+ try {
+ process.env.SSH_AUTH_SOCK = '/tmp/from-env.sock'
+ const transport = new Ssh2Transport(15000, new StubResolver(), { keepaliveIntervalMs: 10_000, keepaliveCountMax: 3 })
+ const session = await transport.connect(profile, () => true)
+ expect(lastClient().acceptedAuth).toEqual({ type: 'agent', username: 'root', agent: '/tmp/from-env.sock' })
+ await session.close()
+ }
+ finally {
+ if (previous === undefined)
+ delete process.env.SSH_AUTH_SOCK
+ else
+ process.env.SSH_AUTH_SOCK = previous
+ }
+ })
+
+ it('configures the keepalive watchdog from the injected options', async () => {
+ const transport = new Ssh2Transport(15000, new StubResolver(), { keepaliveIntervalMs: 25_000, keepaliveCountMax: 7, agentSocket: '' })
+ const session = await transport.connect(profile, () => true)
+ expect(lastClient().connectConfig).toMatchObject({ keepaliveInterval: 25_000, keepaliveCountMax: 7 })
+ await session.close()
+ })
+
+ it('defaults the keepalive watchdog to 10 s and 3 missed beats', async () => {
+ const transport = new Ssh2Transport(15000, new StubResolver(), { agentSocket: '' })
+ const session = await transport.connect(profile, () => true)
+ expect(lastClient().connectConfig).toMatchObject({ keepaliveInterval: 10_000, keepaliveCountMax: 3 })
+ await session.close()
+ })
+
+ it('reports the winning auth method on the session', async () => {
+ const resolver = new StubResolver({ keys: [{ privateKey: 'KEY-A' }] })
+ const transport = new Ssh2Transport(15000, resolver, { ...noAgent, agentSocket: '/tmp/agent.sock' })
+ const session = await transport.connect(profile, () => true)
+ // The fake server accepted the agent offer, so the session reports it.
+ expect(lastClient().acceptedAuth).toMatchObject({ type: 'agent' })
+ expect(session.authMethod).toBe('agent')
await session.close()
})
@@ -275,7 +365,7 @@ describe('ssh2Transport', () => {
it('rejects on transport errors', async () => {
const { Client } = await import('ssh2')
- vi.mocked(Client).mockImplementationOnce(() => fakeClientFactory('error', 'ECONNREFUSED'))
+ vi.mocked(Client).mockImplementationOnce(errorClientOnce('ECONNREFUSED'))
const transport = new Ssh2Transport(15000, new StubResolver())
await expect(transport.connect(profile, () => true)).rejects.toThrow('ECONNREFUSED')
})
@@ -476,11 +566,97 @@ describe('ssh2Transport', () => {
})
it('fires the closed callback immediately for an already-closed session', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
const session = await transport.connect(profile, () => true)
lastClient().emit('close')
const callback = vi.fn()
session.onClosed(callback)
expect(callback).toHaveBeenCalledTimes(1)
})
+
+ it('rebinds the preferred local port for a reconnect-stable tunnel URL', async () => {
+ // Reserve a port, then release it: the tunnel must bind exactly it.
+ const holder = new Server()
+ await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', () => resolve()))
+ const freePort = (holder.address() as AddressInfo).port
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const session = await transport.connect(profile, () => true)
+ const tunnel = await session.openTunnel(3080, freePort)
+ expect(tunnel.localPort).toBe(freePort)
+ await tunnel.close()
+ await session.close()
+ })
+
+ it('falls back to an ephemeral port when the preferred one is taken', async () => {
+ // Keep a listener on the port so the preferred bind fails.
+ const holder = new Server()
+ await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', () => resolve()))
+ const takenPort = (holder.address() as AddressInfo).port
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const session = await transport.connect(profile, () => true)
+ const tunnel = await session.openTunnel(3080, takenPort)
+ expect(tunnel.localPort).not.toBe(takenPort)
+ expect(tunnel.localPort).toBeGreaterThan(0)
+ await tunnel.close()
+ await session.close()
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ })
+})
+
+describe('classifyConnectFailure', () => {
+ it('classifies network-level failures as unreachable', () => {
+ for (const code of ['ENOTFOUND', 'ECONNREFUSED', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH']) {
+ const error = Object.assign(new Error(`connect ${code} 10.0.0.1:22`), { code })
+ expect(classifyConnectFailure(error, false)).toBe('unreachable')
+ expect(classifyConnectFailure(error, true)).toBe('unreachable')
+ }
+ expect(classifyConnectFailure(new Error('Timed out while waiting for handshake'), false)).toBe('unreachable')
+ expect(classifyConnectFailure(new Error('Connection closed prematurely'), true)).not.toBe('unreachable')
+ })
+
+ it('splits exhausted auth into key-rejected and password-rejected', () => {
+ const error = new Error('All configured authentication methods failed')
+ expect(classifyConnectFailure(error, false)).toBe('key-rejected')
+ expect(classifyConnectFailure(error, true)).toBe('password-rejected')
+ })
+
+ it('leaves everything else as other', () => {
+ expect(classifyConnectFailure(new Error('Host key verification failed'), false)).toBe('other')
+ expect(classifyConnectFailure('plain string', true)).toBe('other')
+ })
+})
+
+describe('describeConnectFailure', () => {
+ it('gives each class an operator-distinct, actionable message', () => {
+ const refused = Object.assign(new Error('connect ECONNREFUSED 10.0.0.1:22'), { code: 'ECONNREFUSED' })
+ const messages = [
+ describeConnectFailure('key-rejected', new Error('All configured authentication methods failed')),
+ describeConnectFailure('password-rejected', new Error('All configured authentication methods failed')),
+ describeConnectFailure('unreachable', refused),
+ ]
+ expect(new Set(messages).size).toBe(3)
+ expect(messages[0]).toContain('check your keys or store a password')
+ expect(messages[1]).toContain('update the stored password')
+ expect(messages[2]).toContain('host unreachable')
+ expect(messages[2]).toContain('ECONNREFUSED')
+ })
+
+ it('wraps transport failures with the classified message', async () => {
+ const { Client } = await import('ssh2')
+ vi.mocked(Client).mockImplementationOnce(errorClientOnce('connect ECONNREFUSED 127.0.0.1:1'))
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ await expect(transport.connect(profile, () => true)).rejects.toThrow(/host unreachable: .*ECONNREFUSED/)
+ })
+
+ it('keeps the auth-failure message distinguishable when the chain exhausts', async () => {
+ const { Client } = await import('ssh2')
+ vi.mocked(Client).mockImplementationOnce(errorClientOnce('All configured authentication methods failed'))
+ const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ // With a stored password in the chain the message points at the password.
+ await expect(transport.connect(profile, () => true)).rejects.toThrow(/stored password was rejected/)
+ vi.mocked(Client).mockImplementationOnce(errorClientOnce('All configured authentication methods failed'))
+ // Without one it points at the keys/agent.
+ await expect(transport.connect(withoutPassword(profile), () => true)).rejects.toThrow(/no key or ssh-agent was accepted/)
+ })
})
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-ssh/src/host/service/transport.ts
index ae78a0b8..575545b8 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.ts
@@ -8,9 +8,10 @@
import type { Buffer } from 'node:buffer'
import type { AddressInfo, Server } from 'node:net'
import type { ConnectConfig } from 'ssh2'
-import type { MachineProfile } from '../types/index.js'
+import type { MachineProfile, SshAuthMethod } from '../types/index.js'
import type { ResolvedSshAuth } from './ssh-config.js'
import { createServer } from 'node:net'
+import process from 'node:process'
import { Client } from 'ssh2'
/** The credential-resolution face the transport needs (SshConfigResolver implements it). */
@@ -44,6 +45,11 @@ export interface SshTunnelHandle {
/** One authenticated SSH session. */
export interface SshSession {
+ /**
+ * Which credential this session authenticated with (`agent`, `key`, or
+ * `password`); absent when the transport cannot tell.
+ */
+ readonly authMethod?: SshAuthMethod | undefined
/**
* Run one command through the remote login shell.
* @param command - the full command line.
@@ -55,9 +61,12 @@ export interface SshSession {
* Forward a remote loopback port to a new local loopback listener
* (`ssh -L` semantics).
* @param remotePort - the remote 127.0.0.1 port to reach.
+ * @param preferredLocalPort - keep the tunnel's published URL stable across
+ * reconnects by re-binding this port when possible (falls back to an
+ * ephemeral port when it is taken).
* @returns the local listener handle.
*/
- openTunnel: (remotePort: number) => Promise<SshTunnelHandle>
+ openTunnel: (remotePort: number, preferredLocalPort?: number) => Promise<SshTunnelHandle>
/**
* Register the session-closed callback (connection dropped, server went
* away, or {@link close} ran).
@@ -94,22 +103,110 @@ export function loginShell(command: string): string {
return `sh -lc ${shQuote(command)}`
}
+/** The three operator-distinguishable connection failure classes. */
+export type SshConnectFailureKind
+ = | 'key-rejected'
+ | 'password-rejected'
+ | 'unreachable'
+ | 'other'
+
+/** Network-level error codes that mean "the host cannot be reached at all". */
+const UNREACHABLE_CODES = new Set([
+ 'ENOTFOUND',
+ 'EAI_AGAIN',
+ 'ECONNREFUSED',
+ 'ETIMEDOUT',
+ 'EHOSTUNREACH',
+ 'ENETUNREACH',
+ 'ECONNRESET',
+])
+
+/** Whether one raw transport error reads as "host unreachable". */
+function isUnreachable(error: Error): boolean {
+ const code = (error as NodeJS.ErrnoException).code
+ if (code !== undefined && UNREACHABLE_CODES.has(code))
+ return true
+ return /timed?\s?out|connection refused|econnrefused|no route to host|name or service not known|getaddrinfo/iu.test(error.message)
+}
+
+/**
+ * Classify one connection failure into the three operator-distinguishable
+ * classes (key/agent rejected → check keys or store a password; password
+ * rejected → update the stored password; unreachable → network/host name).
+ * @param error - the raw transport failure.
+ * @param passwordOffered - whether the stored password was part of the chain.
+ * @returns the failure class.
+ */
+export function classifyConnectFailure(error: unknown, passwordOffered: boolean): SshConnectFailureKind {
+ const message = error instanceof Error ? error.message : String(error)
+ const normalized = error instanceof Error ? error : new Error(message)
+ if (isUnreachable(normalized))
+ return 'unreachable'
+ if (/all configured authentication methods failed|authentication failed|no supported authentication/iu.test(message)) {
+ return passwordOffered ? 'password-rejected' : 'key-rejected'
+ }
+ return 'other'
+}
+
+/** One operator-facing message for a classified connection failure. */
+export function describeConnectFailure(kind: SshConnectFailureKind, error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error)
+ switch (kind) {
+ case 'key-rejected':
+ return 'authentication failed: no key or ssh-agent was accepted — check your keys or store a password for this machine'
+ case 'password-rejected':
+ return 'authentication failed: the stored password was rejected — update the stored password'
+ case 'unreachable':
+ return `host unreachable: ${message === '' ? 'SSH connection failed' : message}`
+ default:
+ return message === '' ? 'SSH connection failed' : message
+ }
+}
+
+/** Transport timing/watchdog options; the manager passes the plugin config through. */
+export interface Ssh2TransportOptions {
+ /** ssh2 keepalive heartbeat interval in milliseconds (default 10 s). */
+ keepaliveIntervalMs?: number
+ /** Unanswered-heartbeat threshold that declares the connection dead (default 3). */
+ keepaliveCountMax?: number
+ /**
+ * ssh-agent socket path. `undefined` reads `SSH_AUTH_SOCK` per connect
+ * (an empty/unset variable disables the agent step); an explicit empty
+ * string disables it too.
+ */
+ agentSocket?: string
+}
+
/**
* ssh2-backed transport. One `Client` per session; exec and tunnel run over
* the shared connection. Credentials come from the injected
* {@link SshCredentialsResolver}: the host's own `~/.ssh` (config aliases,
* IdentityFiles, default keys) with the profile's stored password/passphrase
- * as fallbacks — the connection behaves like a local `ssh` invocation.
+ * as fallbacks — the connection behaves like a local `ssh` invocation. The
+ * auth chain order is fixed: ssh-agent → private keys → stored password;
+ * without an agent or a stored password the chain degrades to exactly the
+ * previous behavior.
*/
export class Ssh2Transport implements SshTransport {
+ private readonly options: Required<Pick<Ssh2TransportOptions, 'keepaliveIntervalMs' | 'keepaliveCountMax'>> & Pick<Ssh2TransportOptions, 'agentSocket'>
+
/**
* @param readyTimeoutMs - handshake deadline for {@link Client.connect}.
* @param resolver - the `~/.ssh` credential resolver (host, port, user, keys).
+ * @param options - keepalive watchdog timing and the agent socket override;
+ * omitted fields fall back to the 10 s / 3-beat defaults.
*/
constructor(
private readonly readyTimeoutMs: number,
private readonly resolver: SshCredentialsResolver,
- ) {}
+ options?: Ssh2TransportOptions,
+ ) {
+ this.options = {
+ keepaliveIntervalMs: options?.keepaliveIntervalMs ?? 10_000,
+ keepaliveCountMax: options?.keepaliveCountMax ?? 3,
+ ...options?.agentSocket === undefined ? {} : { agentSocket: options.agentSocket },
+ }
+ }
async connect(
profile: MachineProfile,
@@ -132,24 +229,40 @@ export class Ssh2Transport implements SshTransport {
signal?.removeEventListener('abort', onAbort)
fn()
}
+ // The auth chain's shared bookkeeping: which method won (reported on
+ // the session once ready) and whether the stored password participated
+ // (drives the failure classification when everything is rejected).
+ let winningMethod: SshAuthMethod | undefined
+ let passwordOffered = false
client.on('ready', () => {
- settle(() => resolve(new Ssh2Session(client)))
+ settle(() => resolve(new Ssh2Session(client, winningMethod)))
})
client.on('error', (error) => {
- settle(() => reject(error))
+ settle(() => reject(describedConnectFailure(error, passwordOffered)))
})
void this.resolver.resolve(profile).then((auth) => {
- // Try every resolved identity in order, then the stored password —
- // the same preference order as OpenSSH (publickey before password).
- // ssh2 parses each key itself and skips invalid ones, so a bad or
- // passphrase-locked key never aborts the attempt. Each credential is
- // offered at most once; the handler then gives up.
+ const agentSocket = this.options.agentSocket === undefined
+ ? process.env.SSH_AUTH_SOCK
+ : this.options.agentSocket
+ const agent = agentSocket === undefined || agentSocket === '' ? undefined : agentSocket
+ // Try the ssh-agent first, then every resolved identity in order,
+ // then the stored password — the same preference order as OpenSSH
+ // (agent, publickey, password). ssh2 parses each key itself and
+ // skips invalid ones, so a bad or passphrase-locked key never aborts
+ // the attempt. Each credential is offered at most once; the handler
+ // then gives up.
+ let agentOffered = false
let keyIndex = 0
- let passwordOffered = false
const authHandler: NonNullable<ConnectConfig['authHandler']> = (_methodsLeft, _partialSuccess, callback) => {
- const key = auth.keys[keyIndex]
- if (key !== undefined) {
+ if (agent !== undefined && !agentOffered) {
+ agentOffered = true
+ winningMethod = 'agent'
+ callback({ type: 'agent', username: auth.username, agent })
+ }
+ else if (keyIndex < auth.keys.length) {
+ const key = auth.keys[keyIndex]!
keyIndex += 1
+ winningMethod = 'key'
callback({
type: 'publickey',
username: auth.username,
@@ -159,6 +272,7 @@ export class Ssh2Transport implements SshTransport {
}
else if (auth.password !== undefined && !passwordOffered) {
passwordOffered = true
+ winningMethod = 'password'
callback({ type: 'password', username: auth.username, password: auth.password })
}
else {
@@ -172,11 +286,11 @@ export class Ssh2Transport implements SshTransport {
port: auth.port,
username: auth.username,
readyTimeout: this.readyTimeoutMs,
- // Keep the connection alive during long remote commands (dsh
- // installs, health polling): default ssh2 keepalives are off, and
- // idle NAT/firewall state would otherwise drop a 10-minute install.
- keepaliveInterval: 10_000,
- keepaliveCountMax: 3,
+ // Keepalive watchdog: with these settings ssh2 declares the
+ // connection dead after `countMax` unanswered heartbeats and
+ // surfaces it as a close — the manager's reconnect trigger.
+ keepaliveInterval: this.options.keepaliveIntervalMs,
+ keepaliveCountMax: this.options.keepaliveCountMax,
authHandler,
// ssh2 accepts a synchronous boolean return OR the verify-callback
// form; always driving the callback keeps async verifiers uniform.
@@ -195,12 +309,28 @@ export class Ssh2Transport implements SshTransport {
}
}
+/**
+ * Wrap one raw ssh2 handshake failure with its classified, operator-facing
+ * message (the three-way auth/unreachable distinction rides the message; the
+ * raw error's own text never carries secrets).
+ */
+function describedConnectFailure(error: Error, passwordOffered: boolean): Error {
+ const kind = classifyConnectFailure(error, passwordOffered)
+ const message = describeConnectFailure(kind, error)
+ if (message === error.message)
+ return error
+ return new Error(message)
+}
+
/** The ssh2 session face over one authenticated `Client`. */
class Ssh2Session implements SshSession {
private readonly closed = new Set<() => void>()
private closedFired = false
- constructor(private readonly client: Client) {
+ constructor(
+ private readonly client: Client,
+ readonly authMethod: SshAuthMethod | undefined = undefined,
+ ) {
this.client.on('close', () => {
if (this.closedFired)
return
@@ -267,7 +397,16 @@ class Ssh2Session implements SshSession {
})
}
- openTunnel(remotePort: number): Promise<SshTunnelHandle> {
+ openTunnel(remotePort: number, preferredLocalPort?: number): Promise<SshTunnelHandle> {
+ return this.listenTunnel(remotePort, preferredLocalPort, true)
+ }
+
+ /**
+ * Bind the loopback forwarder, preferring `preferredLocalPort` so a
+ * reconnect can re-publish the same tunnel URL; a taken port falls back
+ * to an ephemeral one (only the first, deliberate preference retries).
+ */
+ private listenTunnel(remotePort: number, preferredLocalPort: number | undefined, allowFallback: boolean): Promise<SshTunnelHandle> {
return new Promise<SshTunnelHandle>((resolve, reject) => {
const sockets = new Set<import('node:net').Socket>()
const server: Server = createServer((socket) => {
@@ -281,8 +420,17 @@ class Ssh2Session implements SshSession {
socket.pipe(channel).pipe(socket)
})
})
- server.on('error', reject)
- server.listen(0, '127.0.0.1', () => {
+ server.on('error', (error: NodeJS.ErrnoException) => {
+ if (allowFallback && error.code === 'EADDRINUSE' && preferredLocalPort !== undefined) {
+ // The preferred port was reclaimed while we were away; an
+ // ephemeral port keeps the reconnect alive (the URL change rides
+ // the status publication).
+ void this.listenTunnel(remotePort, undefined, false).then(resolve, reject)
+ return
+ }
+ reject(error)
+ })
+ server.listen(preferredLocalPort ?? 0, '127.0.0.1', () => {
const { port } = server.address() as AddressInfo
resolve({
localPort: port,
diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.ts
index e001d597..5adb6500 100644
--- a/packages/dsh-tauri-ssh/src/host/storage/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/storage/index.ts
@@ -101,6 +101,19 @@ export interface Config {
installRef?: string
/** Deadline for one remote binary install (download + verify + extract + pnpm assembly). */
installTimeoutMs?: number
+ /** ssh2 keepalive interval in milliseconds — the connection watchdog's heartbeat. */
+ keepaliveIntervalMs: number
+ /** How many unanswered keepalives declare the connection dead (the watchdog threshold). */
+ keepaliveCountMax: number
+ /** Delay before the first reconnect retry, in milliseconds. */
+ reconnectInitialDelayMs: number
+ /** Ceiling of the exponential reconnect backoff, in milliseconds. */
+ reconnectMaxDelayMs: number
+ /**
+ * Give-up threshold: how many reconnect retries run (after the initial
+ * attempt) before the machine lands in the `given-up` terminal state.
+ */
+ reconnectMaxAttempts: number
}
/** Plugin config schema; schemastery fills defaults before construction. */
@@ -116,6 +129,11 @@ export const ConfigSchema: z<Config> = z.object({
installRepo: z.string(),
installRef: z.string(),
installTimeoutMs: z.number().default(1_800_000),
+ keepaliveIntervalMs: z.number().default(10_000),
+ keepaliveCountMax: z.number().default(3),
+ reconnectInitialDelayMs: z.number().default(1_000),
+ reconnectMaxDelayMs: z.number().default(20_000),
+ reconnectMaxAttempts: z.number().default(6),
})
/** Normalize a resolved namespace value into a machine profile map keyed by id. */
diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.ts
index 51021666..c93bfaaf 100644
--- a/packages/dsh-tauri-ssh/src/host/types/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts
@@ -94,8 +94,32 @@ export interface MachineSecretWrite {
passphrase?: string
}
-/** Live connection state of one machine. */
-export type SshConnectionState = 'disconnected' | 'connecting' | 'connected'
+/**
+ * Live connection state of one machine — the C-STATE vocabulary consumed by
+ * the status dot (S4) and the switcher (S5).
+ *
+ * - `disconnected` — not connected (never tried, or a deliberate disconnect);
+ * - `testing` — a one-shot `machine.test` probe is in flight;
+ * - `connecting` — a user-initiated connect is in flight;
+ * - `connected` — the tunnel link is live;
+ * - `reconnecting` — an established connection dropped and the automatic
+ * retry loop owns the machine (a scheduled retry is announced through
+ * {@link SshMachineStatus.nextRetryAt});
+ * - `given-up` — terminal failure state: either the first connect never
+ * succeeded or the reconnect budget ran out. `lastError` carries the
+ * reason; the same word is used for both sources on purpose (switchers
+ * need not distinguish them). A fresh `connect` attempt exits it.
+ */
+export type SshConnectionState
+ = | 'disconnected'
+ | 'testing'
+ | 'connecting'
+ | 'connected'
+ | 'reconnecting'
+ | 'given-up'
+
+/** Which credential the transport last authenticated with. */
+export type SshAuthMethod = 'agent' | 'key' | 'password'
/** One progress phase of a connection-plane operation, shown live in the UI. */
export type SshProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing'
@@ -123,6 +147,10 @@ export interface SshMachineStatus {
dshMissing?: boolean
/** Live progress of the in-flight operation; absent while idle. */
progress?: SshProgress
+ /** Epoch milliseconds of the next scheduled reconnect retry; present while `reconnecting` waits. */
+ nextRetryAt?: number
+ /** Which credential the live (or last successful) connection authenticated with. */
+ authMethod?: SshAuthMethod
}
/** A live machine link: the id and the tunnel base URL. */
@@ -203,6 +231,40 @@ export type SshErrorCode
| 'machine-dsh-missing'
| 'machine-install-failed'
| 'machine-ssh-error'
+ | 'machine-reconnecting'
+
+/**
+ * Connection-lifecycle stages this plugin feeds into the machine-level event
+ * channel (C-EVENT). The channel itself — `/api-ssh` `machine.events` — is
+ * owned by S2; these are the stages S3 appends to its stage enum, so the
+ * merged vocabulary is S2's bootstrap stages plus `auth` and `reconnect`.
+ */
+export const SSH_CONNECTION_EVENT_STAGES = ['auth', 'reconnect'] as const
+
+/** One connection-lifecycle stage of the machine event channel (S3's slice). */
+export type SshConnectionEventStage = typeof SSH_CONNECTION_EVENT_STAGES[number]
+
+/**
+ * One machine event: a displayable, secret-free line on the machine's log
+ * stream. `outcome` marks the line that closes a lifecycle run.
+ */
+export interface SshMachineEvent {
+ machineId: MachineId
+ stage: SshConnectionEventStage
+ /** Operator-facing text line; never carries secret values. */
+ text: string
+ /** Terminal outcome, present on the line that closes a run. */
+ outcome?: 'success' | 'failure'
+}
+
+/**
+ * Pluggable sink for {@link SshMachineEvent}s — the seam where the event
+ * routing lands. Today the default sink is a no-op; when S2's `machine.events`
+ * channel merges, the plugin assembly wires a sink that forwards into it.
+ */
+export interface SshMachineEventSink {
+ emit: (event: SshMachineEvent) => void
+}
/** Typed failure thrown by ssh primitives so consumers map business codes without string matching. */
export class SshError extends Error {