@linxin666/dsh-ssh 0.4.7 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,7 @@ export interface AgentHostRow {
19
19
  keyReady: boolean;
20
20
  proxyJump: string[];
21
21
  proxyCommandConfigured: boolean;
22
+ forwardAgent: boolean;
22
23
  description?: string;
23
24
  environment?: string;
24
25
  tags: string[];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-ssh",
3
3
  "description": "Remote SSH operations for the dsh web GUI: host config store (~/.dsh/dsh-ssh.json, import from ~/.ssh/config), a persistent ssh2 connection pool with jump-host support, exec / PTY web terminal / SFTP transfer / local port-forward tunnels / cluster execution, plus agent tools (ssh_list, ssh_exec, ssh_upload, ssh_download, ssh_tunnel, ssh_cluster). Hot-pluggable — mounted via ~/.dsh/cordis.patch.yml + a profile node_modules symlink, no dsh source changes.",
4
- "version": "0.4.7",
4
+ "version": "0.4.9",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "engines": {
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "dsh": {
25
25
  "engines": {
26
- "dsh": ">=0.2.1-rc.2"
26
+ "dsh": ">=0.2.1-rc.3"
27
27
  },
28
28
  "bundle": {
29
29
  "patch": "./cordis.patch.yml"
@@ -46,26 +46,26 @@
46
46
  "ws": "^8.18.0"
47
47
  },
48
48
  "peerDependencies": {
49
- "@deepseek-ai/dsh": ">=0.2.1-rc.2",
49
+ "@deepseek-ai/dsh": ">=0.2.1-rc.3",
50
50
  "react": "^18.2.0",
51
51
  "react-dom": "^18.2.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@deepseek-ai/cordis": "^4.0.5",
55
- "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.2",
56
- "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.2",
57
- "@deepseek-ai/dsh-client-ui-renderer": "^0.2.1-rc.2",
58
- "@deepseek-ai/dsh-client-ui-layout": "^0.2.1-rc.2",
59
- "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.2",
60
- "@deepseek-ai/dsh-client-ui-sidebar": "^0.2.1-rc.2",
61
- "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.2",
62
- "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.2",
63
- "@deepseek-ai/dsh-llm": "^0.2.1-rc.2",
64
- "@deepseek-ai/dsh-scope": "^0.2.1-rc.2",
65
- "@deepseek-ai/dsh-settings": "^0.2.1-rc.2",
66
- "@deepseek-ai/dsh-system-prompt": "^0.2.1-rc.2",
67
- "@deepseek-ai/dsh-timeout": "^0.2.1-rc.2",
68
- "@deepseek-ai/dsh-tools": "^0.2.1-rc.2",
55
+ "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.3",
56
+ "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.3",
57
+ "@deepseek-ai/dsh-client-ui-layout": "^0.2.1-rc.3",
58
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.1-rc.3",
59
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.3",
60
+ "@deepseek-ai/dsh-client-ui-sidebar": "^0.2.1-rc.3",
61
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.3",
62
+ "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.3",
63
+ "@deepseek-ai/dsh-llm": "^0.2.1-rc.3",
64
+ "@deepseek-ai/dsh-scope": "^0.2.1-rc.3",
65
+ "@deepseek-ai/dsh-settings": "^0.2.1-rc.3",
66
+ "@deepseek-ai/dsh-system-prompt": "^0.2.1-rc.3",
67
+ "@deepseek-ai/dsh-timeout": "^0.2.1-rc.3",
68
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.3",
69
69
  "@types/node": "^22.20.0",
70
70
  "@types/react": "~18.3.1",
71
71
  "@types/react-dom": "^18.3.5",
@@ -39,6 +39,8 @@ export const zh = {
39
39
  'hosts.deleteConfirm': '确定删除主机「{alias}」?将同时停止其隧道。',
40
40
  'hosts.imported': '解析 {parsed} 个配置块,新增 {added} 台主机,跳过 {skipped} 个。',
41
41
  'hosts.proxyBadge': '代理',
42
+ 'hosts.forwardAgentBadge': 'Agent 转发',
43
+ 'hosts.forwardAgentHint': '仅对可信主机开启:远端可用本机私钥签名(等价 ssh -A)。',
42
44
  'import.reason.wildcard': '通配符 pattern,需手动配置',
43
45
  'import.reason.existing': '别名已存在',
44
46
  'import.reason.match': 'Match 条件块,不支持',
@@ -62,8 +64,8 @@ export const zh = {
62
64
  'form.auth.password': '密码',
63
65
  'form.auth.agent': 'SSH Agent',
64
66
  'form.agentPath': 'Agent 路径',
65
- 'form.agentPathHint': '留空自动检测(SSH_AUTH_SOCK / Windows Pageant);也可填 socket 路径或 pageant',
66
- 'form.authKeepHint': '编辑时密钥/密码/Agent 留空将保留原认证方式与已存凭据;如需更换认证方式请填写新凭据。',
67
+ 'form.agentPathHint': '留空自动检测(SSH_AUTH_SOCK;Windows 上为原生 ssh-agent 命名管道);也可填 socket 路径或 pageant',
68
+ 'form.authKeepHint': '编辑时密码 / 私钥留空将保留已存凭据;Agent 路径留空是合法的自动检测,选「SSH Agent」即切换到 agent 认证。',
67
69
  'form.keyPath': '私钥路径',
68
70
  'form.keyPathHint': '如 ~/.ssh/id_ed25519',
69
71
  'form.passphrase': '密钥口令',
@@ -74,6 +76,8 @@ export const zh = {
74
76
  'form.proxyJumpHint': '逗号分隔的本地主机别名,或 [user@]host[:port] 地址,按顺序连接',
75
77
  'form.proxyCommand': 'ProxyCommand',
76
78
  'form.proxyCommandHint': 'OpenSSH ProxyCommand:%h 主机、%p 端口、%r 用户、%n 别名;留空或填 none 表示不使用。与跳板机别名互斥。',
79
+ 'form.forwardAgent': '启用 Agent 转发',
80
+ 'form.forwardAgentHint': '把本机 SSH Agent 转发到该主机(等价 ssh -A):远端可用本机私钥签名。仅对可信主机开启。',
77
81
  'form.description': '备注',
78
82
  'form.environment': '环境',
79
83
  'form.environmentHint': '如 development / production',
@@ -202,6 +206,8 @@ export const en: Record<keyof typeof zh, string> = {
202
206
  'hosts.deleteConfirm': 'Delete host "{alias}"? Its tunnels will be stopped.',
203
207
  'hosts.imported': 'Parsed {parsed} blocks, added {added} hosts, skipped {skipped}.',
204
208
  'hosts.proxyBadge': 'proxy',
209
+ 'hosts.forwardAgentBadge': 'agent-fwd',
210
+ 'hosts.forwardAgentHint': 'Enable only for hosts you trust: the remote can sign with your local private keys (equivalent to ssh -A).',
205
211
  'import.reason.wildcard': 'wildcard pattern — configure it by hand',
206
212
  'import.reason.existing': 'alias already configured',
207
213
  'import.reason.match': 'Match block — not supported',
@@ -224,8 +230,8 @@ export const en: Record<keyof typeof zh, string> = {
224
230
  'form.auth.password': 'Password',
225
231
  'form.auth.agent': 'SSH Agent',
226
232
  'form.agentPath': 'Agent path',
227
- 'form.agentPathHint': 'Leave empty to auto-detect (SSH_AUTH_SOCK / Pageant on Windows), or set a socket path or "pageant"',
228
- 'form.authKeepHint': 'While editing, empty secret fields keep the stored authentication and credentials; enter new values to switch methods.',
233
+ 'form.agentPathHint': 'Leave empty to auto-detect (SSH_AUTH_SOCK; the native ssh-agent named pipe on Windows), or set a socket path or "pageant"',
234
+ 'form.authKeepHint': 'While editing, an empty password or key field keeps the stored credential; an empty agent path is a valid auto-detect, so choosing SSH Agent switches the host to agent auth.',
229
235
  'form.keyPath': 'Private key path',
230
236
  'form.keyPathHint': 'e.g. ~/.ssh/id_ed25519',
231
237
  'form.passphrase': 'Key passphrase',
@@ -236,6 +242,8 @@ export const en: Record<keyof typeof zh, string> = {
236
242
  'form.proxyJumpHint': 'Comma-separated local aliases or [user@]host[:port] addresses, chained in order',
237
243
  'form.proxyCommand': 'ProxyCommand',
238
244
  'form.proxyCommandHint': 'OpenSSH ProxyCommand: %h host, %p port, %r user, %n alias; empty or none disables it. Mutually exclusive with the jump chain.',
245
+ 'form.forwardAgent': 'Enable agent forwarding',
246
+ 'form.forwardAgentHint': 'Forward your local SSH agent to this host (equivalent to ssh -A): the remote can sign with your private keys. Enable it only for hosts you trust.',
239
247
  'form.description': 'Description',
240
248
  'form.environment': 'Environment',
241
249
  'form.environmentHint': 'e.g. development / production',
@@ -32,6 +32,7 @@ interface FormState {
32
32
  agentPath: string
33
33
  proxyJump: string
34
34
  proxyCommand: string
35
+ forwardAgent: boolean
35
36
  description: string
36
37
  environment: string
37
38
  tags: string
@@ -57,6 +58,7 @@ function blankOf(editing: SshHostSummary | null | undefined): FormState {
57
58
  agentPath: '',
58
59
  proxyJump: (editing?.proxyJump ?? []).join(', '),
59
60
  proxyCommand: editing?.proxyCommand ?? '',
61
+ forwardAgent: editing?.forwardAgent === true,
60
62
  description: editing?.description ?? '',
61
63
  environment: editing?.environment ?? '',
62
64
  tags: (editing?.tags ?? []).join(', '),
@@ -104,12 +106,15 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
104
106
  }
105
107
  // Secrets are never echoed back by the API: when editing and the secret
106
108
  // fields are left empty, the auth block is omitted so the stored
107
- // authentication is preserved.
109
+ // authentication is preserved. The agent path is not a secret — an empty
110
+ // one is the documented "auto-detect" choice — so an agent form always
111
+ // submits its auth block; omitting it would make the PATCH a silent no-op
112
+ // that keeps the previous auth kind (#1910).
108
113
  const secretEmpty = form.authKind === 'password'
109
114
  ? form.password === ''
110
115
  : form.authKind === 'key'
111
116
  ? form.keyPath.trim() === ''
112
- : form.agentPath.trim() === ''
117
+ : false
113
118
  const auth: HostPayload['auth'] = editing != null && secretEmpty
114
119
  ? undefined
115
120
  : form.authKind === 'password'
@@ -126,6 +131,10 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
126
131
  // Always sent (never omitted): an empty value is the explicit clear,
127
132
  // because the API cannot express "remove this field" any other way.
128
133
  proxyCommand: form.proxyCommand.trim(),
134
+ // Always sent (never omitted): the flag is a plain boolean, so saving the
135
+ // form can both enable and clear forwarding (omitting it would keep the
136
+ // stored value under PATCH semantics).
137
+ forwardAgent: form.forwardAgent,
129
138
  description: form.description.trim() === '' ? undefined : form.description.trim(),
130
139
  environment: form.environment.trim() === '' ? undefined : form.environment.trim(),
131
140
  tags: splitList(form.tags),
@@ -227,6 +236,11 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
227
236
  />
228
237
  <span className={css.hint}>{tt('form.proxyCommandHint')}</span>
229
238
  </label>
239
+ <label className={css.field}>
240
+ <span className={css.fieldLabel}>{tt('form.forwardAgent')}</span>
241
+ <input type="checkbox" checked={form.forwardAgent} onChange={event => { set('forwardAgent', event.target.checked) }} />
242
+ <span className={css.hint}>{tt('form.forwardAgentHint')}</span>
243
+ </label>
230
244
  <div className={css.formRow}>
231
245
  <label className={css.field}>
232
246
  <span className={css.fieldLabel}>{tt('form.environment')}</span>
@@ -187,6 +187,9 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
187
187
  {host.proxyCommand !== undefined && (
188
188
  <span className={css.badge} data-kind="proxy" title={host.proxyCommand}>{tt('hosts.proxyBadge')}</span>
189
189
  )}
190
+ {host.forwardAgent === true && (
191
+ <span className={css.badge} data-kind="forward-agent" title={tt('hosts.forwardAgentHint')}>{tt('hosts.forwardAgentBadge')}</span>
192
+ )}
190
193
  </td>
191
194
  <td>{host.user}</td>
192
195
  <td><span className={css.badge} data-kind={host.auth}>{host.auth === 'key' ? tt('form.auth.key') : host.auth === 'password' ? tt('form.auth.password') : tt('form.auth.agent')}</span></td>
@@ -338,6 +338,12 @@
338
338
  border-color: var(--dsw-alias-state-business-primary);
339
339
  }
340
340
 
341
+ .badge[data-kind='forward-agent'] {
342
+ margin-left: 6px;
343
+ color: var(--dsw-alias-state-warn-primary);
344
+ border-color: var(--dsw-alias-state-warn-primary);
345
+ }
346
+
341
347
  .badge[data-status='ok'] {
342
348
  color: var(--dsw-alias-state-success-primary);
343
349
  border-color: var(--dsw-alias-state-success-primary);
@@ -7,8 +7,12 @@
7
7
  * The payload carries no conversation data and no identifiers beyond a random
8
8
  * UUID generated in localStorage; the server hashes it with a deployment salt
9
9
  * before storage and never persists IP addresses. Sends are fire-and-forget:
10
- * failures stay silent and simply retry on a later mount or day. The system
11
- * is documented in docs/telemetry.md.
10
+ * failures stay silent and simply retry on a later mount or day. Frames where
11
+ * storage is unavailable report nothing.
12
+ *
13
+ * The family-wide opt-out and the browser's Do Not Track signal both suppress
14
+ * the heartbeat; the Web Plugins settings switch writes the same localStorage
15
+ * key. The system is documented in docs/telemetry.md.
12
16
  */
13
17
 
14
18
  export type TelemetryChannel = 'market' | 'npm' | 'unknown'
@@ -22,6 +26,9 @@ export interface TelemetryItem {
22
26
  channel?: TelemetryChannel
23
27
  }
24
28
 
29
+ /** localStorage key carrying the family-wide telemetry opt-out ('1' = off). */
30
+ export const TELEMETRY_OPT_OUT_KEY = 'dsh-web-ui-telemetry-opt-out'
31
+
25
32
  const VISITOR_KEY = 'dsh-web-ui-telemetry-visitor'
26
33
  const DAY_KEY_PREFIX = 'dsh-web-ui-telemetry-day:'
27
34
  const ENDPOINT = 'https://dsh-market.com/api/telemetry/event'
@@ -41,6 +48,41 @@ function bakedVersion(): string | undefined {
41
48
  }
42
49
  }
43
50
 
51
+ /** Whether the user switched the family-wide opt-out on (reads storage only). */
52
+ export function isTelemetryOptedOut(): boolean {
53
+ try {
54
+ return localStorage.getItem(TELEMETRY_OPT_OUT_KEY) === '1'
55
+ } catch {
56
+ // Storage unavailable: there is no stored opt-out to honour.
57
+ return false
58
+ }
59
+ }
60
+
61
+ /** Turn the family-wide opt-out on or off (writing '1' / removing the key); never throws. */
62
+ export function setTelemetryOptedOut(optedOut: boolean): void {
63
+ try {
64
+ if (optedOut) localStorage.setItem(TELEMETRY_OPT_OUT_KEY, '1')
65
+ else localStorage.removeItem(TELEMETRY_OPT_OUT_KEY)
66
+ } catch {
67
+ // Storage unavailable: the preference cannot be persisted on this machine.
68
+ }
69
+ }
70
+
71
+ /** Whether the browser itself asks not to be tracked; a failed read means no signal. */
72
+ function doNotTrackRequested(): boolean {
73
+ try {
74
+ // '1' per the DNT header spec, 'yes' from older Firefox builds.
75
+ return navigator.doNotTrack === '1' || navigator.doNotTrack === 'yes'
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ /** Whether a heartbeat must be suppressed right now: opt-out stored, or the browser asks not to be tracked. */
82
+ export function isTelemetrySuppressed(): boolean {
83
+ return isTelemetryOptedOut() || doNotTrackRequested()
84
+ }
85
+
44
86
  /** Read or lazily create the anonymous visitor id; null when storage is unavailable. */
45
87
  function visitorId(): string | null {
46
88
  try {
@@ -74,6 +116,9 @@ function pruneDayKeys(today: string): void {
74
116
  */
75
117
  export function reportDailyHeartbeat(items: readonly TelemetryItem[]): void {
76
118
  try {
119
+ // First guard: a stored opt-out or the browser's Do Not Track stops every
120
+ // read below from minting an id, marking the day, or reaching the network.
121
+ if (isTelemetrySuppressed()) return
77
122
  if (items.length === 0) return
78
123
  const today = new Date().toISOString().slice(0, 10)
79
124
  // Automation contexts (CDP-driven QA browsers, fresh isolated profiles)
@@ -14,7 +14,10 @@ import { startProxyCommand, type ProxyTarget } from './proxy-command.ts'
14
14
  export interface EngineOptions {
15
15
  /** Connections idle longer than this are closed (ms). */
16
16
  idleTimeoutMs?: number
17
- /** SSH handshake timeout (ms). */
17
+ /**
18
+ * Ceiling for the whole pre-ready sequence (ms): TCP connect, SSH key
19
+ * exchange and user authentication. Passed to ssh2's `readyTimeout`.
20
+ */
18
21
  connectTimeoutMs?: number
19
22
  /** Keepalive ping interval (ms). */
20
23
  keepaliveIntervalMs?: number
@@ -28,10 +31,17 @@ export interface EngineOptions {
28
31
  sftpConcurrency?: number
29
32
  }
30
33
 
34
+ /**
35
+ * Default ceiling for TCP connect, SSH key exchange and user authentication
36
+ * together (ms). Password authentication behind PAM / LDAP can outlast the
37
+ * previous 15 s ceiling while the server still eventually accepts it.
38
+ */
39
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 30_000
40
+
31
41
  /** Default engine knobs (applied when an option is omitted). */
32
42
  export const DEFAULTS: Required<EngineOptions> = {
33
43
  idleTimeoutMs: 30 * 60_000,
34
- connectTimeoutMs: 15_000,
44
+ connectTimeoutMs: DEFAULT_CONNECT_TIMEOUT_MS,
35
45
  keepaliveIntervalMs: 15_000,
36
46
  maxOutputBytes: 2 * 1024 * 1024,
37
47
  defaultExecTimeoutMs: 60_000,
@@ -93,19 +103,62 @@ export function buildConnectConfig(entry: SshHostEntry, sock: ConnectConfig['soc
93
103
  config.passphrase = entry.auth.passphrase
94
104
  }
95
105
  }
106
+ // Agent forwarding is additive: it never changes how the host
107
+ // authenticates, it only lets this connection broker signatures from the
108
+ // local agent for the remote side (OpenSSH ForwardAgent / ssh -A).
109
+ if (entry.forwardAgent === true) {
110
+ // Agent auth already resolved an endpoint, and reusing it keeps the
111
+ // forwarded agent identical to the one that authenticated.
112
+ const agentPath = typeof config.agent === 'string'
113
+ ? config.agent
114
+ : resolveForwardAgentPath(entry.auth.agentPath)
115
+ if (agentPath === undefined) {
116
+ // ssh2's own message for this case ("You must set a valid agent path to
117
+ // allow agent forwarding") names neither the host nor a way out, so the
118
+ // engine refuses first with an actionable one.
119
+ throw new Error('agent forwarding is enabled for this host but no ssh-agent endpoint is available: '
120
+ + 'set SSH_AUTH_SOCK, start Pageant on Windows, or configure an agent path')
121
+ }
122
+ config.agent = agentPath
123
+ config.agentForward = true
124
+ }
96
125
  return config
97
126
  }
98
127
 
128
+ /**
129
+ * The default ssh-agent endpoint on Windows: the named pipe the native
130
+ * OpenSSH ssh-agent service listens on. ssh2 connects to a named pipe for any
131
+ * path matching its Windows pipe form, so the default is a real endpoint
132
+ * rather than a protocol name (#1910). PuTTY Pageant is still reachable — it
133
+ * is what the literal `pageant` agent path selects — but it is no longer the
134
+ * assumption.
135
+ */
136
+ export const WINDOWS_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent'
137
+
99
138
  /** Resolve the ssh2 agent path for 'agent' auth. */
100
139
  export function resolveAgentPath(agentPath?: string): string | undefined {
101
140
  const explicit = normalizeAgentPath(agentPath)
102
141
  if (explicit !== undefined) return explicit
103
142
  const sock = process.env.SSH_AUTH_SOCK
104
143
  if (sock !== undefined && sock !== '') return sock
105
- if (process.platform === 'win32') return 'pageant'
144
+ if (process.platform === 'win32') return WINDOWS_AGENT_PIPE
106
145
  return undefined
107
146
  }
108
147
 
148
+ /**
149
+ * Resolve the ssh-agent endpoint that forwarding brokers signatures through:
150
+ * an explicitly configured agent path wins, then SSH_AUTH_SOCK, then the
151
+ * native OpenSSH named pipe on Windows. Undefined means no endpoint exists on
152
+ * this machine.
153
+ *
154
+ * Forwarding shares the auth resolution on purpose — the endpoint a host
155
+ * signs through is the same one it authenticates with — but it is a separate
156
+ * name so the forwarding path can evolve without touching auth.
157
+ */
158
+ export function resolveForwardAgentPath(agentPath?: string): string | undefined {
159
+ return resolveAgentPath(agentPath)
160
+ }
161
+
109
162
  /** Keyboard-interactive handler callback for 2FA / dynamic prompt flow. */
110
163
  export type KeyboardInteractiveHandler = (
111
164
  name: string,
@@ -115,11 +168,40 @@ export type KeyboardInteractiveHandler = (
115
168
  finish: (responses: string[]) => void,
116
169
  ) => void
117
170
 
171
+ /**
172
+ * Name the phase that actually stalled. ssh2 reports every pre-ready timeout
173
+ * as "Timed out while waiting for handshake", including one that expires
174
+ * during user authentication after a completed key exchange.
175
+ *
176
+ * @param timeoutMs - the configured `readyTimeout` (0 disables it).
177
+ * @param handshakeComplete - whether ssh2 completed the key exchange.
178
+ * @returns the operator-facing timeout message.
179
+ */
180
+ export function readyTimeoutMessage(timeoutMs: number | undefined, handshakeComplete: boolean): string {
181
+ const budget = typeof timeoutMs === 'number' && timeoutMs > 0 ? ' after ' + timeoutMs + ' ms' : ''
182
+ const hint = ' - raise the dsh-ssh connectTimeoutMs setting if this host is slow'
183
+ return handshakeComplete
184
+ ? 'SSH authentication timed out' + budget + ': TCP connect and key exchange completed, but the server did not finish authenticating the user' + hint
185
+ : 'SSH connection timed out' + budget + ' before key exchange completed: TCP connect or the SSH key exchange did not finish' + hint
186
+ }
187
+
188
+ /**
189
+ * Whether ssh2 ended the attempt with its pre-ready timeout. The level is the
190
+ * stable discriminator; the message is reused for connect, key exchange and
191
+ * authentication alike.
192
+ */
193
+ export function isReadyTimeout(error: Error): boolean {
194
+ return (error as Error & { level?: unknown }).level === 'client-timeout'
195
+ }
196
+
118
197
  /** Connect one ssh2 client (resolve on ready, reject on error/close). */
119
198
  export function connectClient(config: ConnectConfig, onKeyboardInteractive?: KeyboardInteractiveHandler): Promise<Client> {
120
199
  return new Promise((resolve, reject) => {
121
200
  const client = new Client()
122
201
  let settled = false
202
+ // Key exchange completion is the only public phase boundary ssh2 exposes
203
+ // between "TCP connect / SSH handshake" and "user authentication".
204
+ let handshakeComplete = false
123
205
  const fail = (error: unknown): void => {
124
206
  if (settled) return
125
207
  settled = true
@@ -131,8 +213,12 @@ export function connectClient(config: ConnectConfig, onKeyboardInteractive?: Key
131
213
  try { (sock as { destroy: () => void }).destroy() } catch { /* already closed */ }
132
214
  }
133
215
  try { client.destroy() } catch { /* already closed */ }
134
- reject(error instanceof Error ? error : new Error(String(error)))
216
+ const cause = error instanceof Error ? error : new Error(String(error))
217
+ reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause)
135
218
  }
219
+ client.once('handshake', () => {
220
+ handshakeComplete = true
221
+ })
136
222
  client.once('ready', () => {
137
223
  if (settled) return
138
224
  settled = true
@@ -228,6 +314,12 @@ export function parseJumpSpec(spec: string): { host: string; port?: number; user
228
314
  * Resolve one ProxyJump spec: an alias configured in this plugin wins, and any
229
315
  * other value is read as an OpenSSH address whose credentials come from the
230
316
  * target entry (an ad-hoc hop has no stored auth of its own).
317
+ *
318
+ * An address hop deliberately carries no forwardAgent flag: OpenSSH's
319
+ * ForwardAgent is a per-Host setting and an ad-hoc address was never
320
+ * configured, so it must never inherit the target's opt-in. A hop written as
321
+ * an alias uses that alias's own entry, which is how a user forwards on a
322
+ * bastion on purpose.
231
323
  */
232
324
  export function resolveHop(engine: PoolEngine, entry: SshHostEntry, spec: string): SshHostEntry {
233
325
  const configured = engine.store.find(spec)
package/src/engine.ts CHANGED
@@ -51,6 +51,16 @@ export class SshEngine {
51
51
  this.sweepTimer.unref?.()
52
52
  }
53
53
 
54
+ /**
55
+ * Change the pre-ready ceiling (TCP connect + key exchange + user
56
+ * authentication) for connections opened from now on. A pooled connection
57
+ * keeps serving until it reconnects, because the ceiling governs the
58
+ * connect path only.
59
+ */
60
+ setConnectTimeout(timeoutMs: number): void {
61
+ this.opts.connectTimeoutMs = timeoutMs
62
+ }
63
+
54
64
  // ---------------------------------------------------------------- config
55
65
 
56
66
  /** Secret-free host list (filtered by the optional query). */
package/src/index.ts CHANGED
@@ -14,6 +14,7 @@ import type {} from '@deepseek-ai/dsh-host-webserver'
14
14
  import type {} from '@deepseek-ai/dsh-system-prompt'
15
15
  import type {} from '@deepseek-ai/dsh-tools'
16
16
  import { SshEngine } from './engine.ts'
17
+ import { DEFAULT_CONNECT_TIMEOUT_MS } from './engine/connection-pool.ts'
17
18
  import { makeRoutes } from './routes.ts'
18
19
  import { HostStore } from './store.ts'
19
20
  import { sshClusterTool, sshDownloadTool, sshExecTool, sshListTool, sshTunnelTool, sshUploadTool } from './tools.ts'
@@ -54,6 +55,13 @@ export interface Config {
54
55
  * Nerd Font stack here to render powerline/Nerd glyphs.
55
56
  */
56
57
  terminalFontFamily?: string
58
+ /**
59
+ * Ceiling for the whole pre-ready SSH sequence in milliseconds: TCP
60
+ * connect, key exchange and user authentication (default 30000). Raise it
61
+ * for hosts whose password authentication is slow (for example PAM / LDAP
62
+ * behind a distant directory service).
63
+ */
64
+ connectTimeoutMs?: number
57
65
  }
58
66
 
59
67
  /** The stable reference a `volatile()` config field resolves to; its owner updates it in place. */
@@ -70,6 +78,7 @@ export interface ResolvedConfig {
70
78
  announceToAgent?: ConfigField<boolean>
71
79
  enabled?: ConfigField<boolean>
72
80
  terminalFontFamily?: ConfigField<string>
81
+ connectTimeoutMs?: ConfigField<number>
73
82
  }
74
83
 
75
84
  /**
@@ -84,6 +93,8 @@ export const Config = z.object({
84
93
  announceToAgent: z.boolean().default(false).volatile(),
85
94
  enabled: z.boolean().default(true).volatile(),
86
95
  terminalFontFamily: z.string().default('').volatile(),
96
+ connectTimeoutMs: z.number().step(1).min(1_000).max(600_000).default(DEFAULT_CONNECT_TIMEOUT_MS).volatile()
97
+ .description('TCP connect, SSH key exchange and user authentication timeout in milliseconds; raise it for hosts whose authentication is slow.'),
87
98
  })
88
99
 
89
100
  /** Schema defaults, re-read for hand-built test contexts (the loader applies them normally). */
@@ -136,7 +147,7 @@ export const apply = mountOnce('@linxin666/dsh-ssh', applyImpl)
136
147
 
137
148
  function applyImpl(ctx: Context, config?: ResolvedConfig): void {
138
149
  const store = new HostStore()
139
- const engine = new SshEngine(store)
150
+ const engine = new SshEngine(store, { connectTimeoutMs: readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS) })
140
151
  ctx.effect(() => () => { engine.dispose() }, 'dsh-ssh: engine')
141
152
 
142
153
  const resolve = (): { announceToAgent: boolean; enabled: boolean } => {
@@ -176,6 +187,10 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
176
187
  // is kept under one disposer: re-registering first tears the old one down
177
188
  // so duplicate-name registrations never throw.
178
189
  const sync = (): void => {
190
+ // A settings edit reaches this instance without a remount; apply the
191
+ // connection ceiling before re-deriving the surfaces so connections opened
192
+ // by the request that follows use the new value.
193
+ engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS))
179
194
  const value = resolve()
180
195
  if (disposeSection !== undefined) {
181
196
  disposeSection()
package/src/loopback.ts CHANGED
@@ -8,6 +8,19 @@
8
8
  * Semantics: RFC 5735 IPv4 127/8, ::1, IPv4-mapped ::ffff:127/8 (matching the
9
9
  * remote-web-ui gate), localhost hostnames, plus the browser same-origin
10
10
  * markers (sec-fetch-site and Origin) for the request-level fence.
11
+ *
12
+ * A reverse proxy in front of the host rewrites the Host header to its own
13
+ * upstream literal (a Cloudflare tunnel, frp and an nginx reverse proxy all
14
+ * dial 127.0.0.1:<port>), and the socket the origin sees is the proxy's, which
15
+ * is loopback by construction. Both halves of the fence then hold for a public
16
+ * request. Forwarding headers are the signal that a hop stands in between: a
17
+ * request that carries CF-Connecting-IP or X-Forwarded-For is answered through
18
+ * a proxy and is never treated as a local one (issue #1906).
19
+ *
20
+ * An operator who runs that proxy or tunnel themselves can opt into the
21
+ * narrower case: isForwardedLoopbackRequest describes a forwarded request that
22
+ * still landed on this machine's loopback upstream, and a route family admits
23
+ * it only behind its own default-off switch (issue #1918).
11
24
  * @module dsh-web-shared/host/loopback
12
25
  */
13
26
 
@@ -36,13 +49,29 @@ export function isLoopbackHostname(hostname: string): boolean {
36
49
  return isIPv4Loopback(hostname)
37
50
  }
38
51
 
52
+ /**
53
+ * Whether a reverse proxy stood between the client and this host: the request
54
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
55
+ * hop that forwards traffic, so the request did not originate on this machine.
56
+ * @param request - node HTTP request.
57
+ * @returns true when a forwarding header is present.
58
+ */
59
+ export function isProxiedRequest(request: IncomingMessage): boolean {
60
+ return request.headers['cf-connecting-ip'] !== undefined
61
+ || request.headers['x-forwarded-for'] !== undefined
62
+ }
63
+
39
64
  /**
40
65
  * Request-level trust fence: a loopback socket address AND a loopback Host
41
66
  * header, plus browser same-origin markers. The socket address is
42
- * authoritative; X-Forwarded-For is never trusted.
67
+ * authoritative for a direct connection; a request that carries a forwarding
68
+ * header is refused outright, because a proxy in front of the host makes both
69
+ * the socket address and the Host header describe the proxy rather than the
70
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
43
71
  */
44
72
  export function isLoopbackRequest(request: IncomingMessage): boolean {
45
73
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false
74
+ if (isProxiedRequest(request)) return false
46
75
  const host = request.headers.host
47
76
  if (typeof host !== 'string') return false
48
77
  let hostUrl: URL
@@ -61,3 +90,30 @@ export function isLoopbackRequest(request: IncomingMessage): boolean {
61
90
  return false
62
91
  }
63
92
  }
93
+
94
+ /**
95
+ * Whether a forwarded request landed on this machine's loopback upstream: a
96
+ * forwarding header (the proxy's own stamp), a loopback socket address (the
97
+ * proxy dials 127.0.0.1:<port>), and a loopback Host header (the proxy rewrote
98
+ * the authority to its upstream literal).
99
+ *
100
+ * This is a fact about the route, not a trust decision. A public request to a
101
+ * tunnel satisfies all three by construction, because the proxy is the client
102
+ * of this process: only a caller that operates the proxy can decide it stands
103
+ * for the browser, which is why every consumer keeps this behind an explicit
104
+ * default-off switch and its own browser markers. isLoopbackRequest is
105
+ * unchanged and still refuses a forwarded request (issue #1906).
106
+ * @param request - node HTTP request.
107
+ * @returns true when a forwarding header, a loopback socket, and a loopback Host all hold.
108
+ */
109
+ export function isForwardedLoopbackRequest(request: IncomingMessage): boolean {
110
+ if (!isProxiedRequest(request)) return false
111
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false
112
+ const host = request.headers.host
113
+ if (typeof host !== 'string') return false
114
+ try {
115
+ return isLoopbackHostname(new URL('http://' + host).hostname)
116
+ } catch {
117
+ return false
118
+ }
119
+ }
package/src/protocol.ts CHANGED
@@ -29,7 +29,7 @@ export interface SshHostEntry {
29
29
  /**
30
30
  * ssh-agent endpoint for 'agent' auth. A socket path, the special value
31
31
  * 'pageant' (PuTTY Pageant on Windows), or undefined for auto-detect
32
- * (SSH_AUTH_SOCK, then Pageant on Windows).
32
+ * (SSH_AUTH_SOCK, then the native OpenSSH named pipe on Windows).
33
33
  */
34
34
  agentPath?: string
35
35
  }
@@ -50,6 +50,12 @@ export interface SshHostEntry {
50
50
  tags: string[]
51
51
  /** Physical location note. */
52
52
  location?: string
53
+ /**
54
+ * Opt-in ssh-agent forwarding (OpenSSH ForwardAgent / ssh -A): the host's
55
+ * sessions request agent forwarding so the remote can sign with this
56
+ * machine's agent. Default off; stored only when enabled.
57
+ */
58
+ forwardAgent?: boolean
53
59
  createdAt: number
54
60
  updatedAt: number
55
61
  }
@@ -70,6 +76,12 @@ export interface SshHostSummary {
70
76
  environment?: string
71
77
  tags: string[]
72
78
  location?: string
79
+ /**
80
+ * Whether agent forwarding is enabled. Always projected as a definite
81
+ * boolean: the browser and the tool bridge need a value even for entries
82
+ * stored before the feature existed.
83
+ */
84
+ forwardAgent: boolean
73
85
  createdAt: number
74
86
  updatedAt: number
75
87
  }
@@ -160,6 +172,11 @@ export interface HostPayload {
160
172
  environment?: string
161
173
  tags?: string[]
162
174
  location?: string
175
+ /**
176
+ * Agent forwarding for this host. Omitted on update keeps the stored value;
177
+ * false clears it (PATCH semantics).
178
+ */
179
+ forwardAgent?: boolean
163
180
  }
164
181
 
165
182
  /** Why one ssh_config Host block was not imported. */