@linxin666/dsh-ssh 0.4.6 → 0.4.8

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.
@@ -93,6 +93,25 @@ export function buildConnectConfig(entry: SshHostEntry, sock: ConnectConfig['soc
93
93
  config.passphrase = entry.auth.passphrase
94
94
  }
95
95
  }
96
+ // Agent forwarding is additive: it never changes how the host
97
+ // authenticates, it only lets this connection broker signatures from the
98
+ // local agent for the remote side (OpenSSH ForwardAgent / ssh -A).
99
+ if (entry.forwardAgent === true) {
100
+ // Agent auth already resolved an endpoint, and reusing it keeps the
101
+ // forwarded agent identical to the one that authenticated.
102
+ const agentPath = typeof config.agent === 'string'
103
+ ? config.agent
104
+ : resolveForwardAgentPath(entry.auth.agentPath)
105
+ if (agentPath === undefined) {
106
+ // ssh2's own message for this case ("You must set a valid agent path to
107
+ // allow agent forwarding") names neither the host nor a way out, so the
108
+ // engine refuses first with an actionable one.
109
+ throw new Error('agent forwarding is enabled for this host but no ssh-agent endpoint is available: '
110
+ + 'set SSH_AUTH_SOCK, start Pageant on Windows, or configure an agent path')
111
+ }
112
+ config.agent = agentPath
113
+ config.agentForward = true
114
+ }
96
115
  return config
97
116
  }
98
117
 
@@ -106,6 +125,19 @@ export function resolveAgentPath(agentPath?: string): string | undefined {
106
125
  return undefined
107
126
  }
108
127
 
128
+ /**
129
+ * Resolve the ssh-agent endpoint that forwarding brokers signatures through:
130
+ * an explicitly configured agent path wins, then SSH_AUTH_SOCK, then Pageant
131
+ * on Windows. Undefined means no endpoint exists on this machine.
132
+ *
133
+ * Forwarding shares the auth resolution on purpose — the endpoint a host
134
+ * signs through is the same one it authenticates with — but it is a separate
135
+ * name so the forwarding path can evolve without touching auth.
136
+ */
137
+ export function resolveForwardAgentPath(agentPath?: string): string | undefined {
138
+ return resolveAgentPath(agentPath)
139
+ }
140
+
109
141
  /** Keyboard-interactive handler callback for 2FA / dynamic prompt flow. */
110
142
  export type KeyboardInteractiveHandler = (
111
143
  name: string,
@@ -228,6 +260,12 @@ export function parseJumpSpec(spec: string): { host: string; port?: number; user
228
260
  * Resolve one ProxyJump spec: an alias configured in this plugin wins, and any
229
261
  * other value is read as an OpenSSH address whose credentials come from the
230
262
  * target entry (an ad-hoc hop has no stored auth of its own).
263
+ *
264
+ * An address hop deliberately carries no forwardAgent flag: OpenSSH's
265
+ * ForwardAgent is a per-Host setting and an ad-hoc address was never
266
+ * configured, so it must never inherit the target's opt-in. A hop written as
267
+ * an alias uses that alias's own entry, which is how a user forwards on a
268
+ * bastion on purpose.
231
269
  */
232
270
  export function resolveHop(engine: PoolEngine, entry: SshHostEntry, spec: string): SshHostEntry {
233
271
  const configured = engine.store.find(spec)
package/src/loopback.ts CHANGED
@@ -8,6 +8,14 @@
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).
11
19
  * @module dsh-web-shared/host/loopback
12
20
  */
13
21
 
@@ -36,13 +44,29 @@ export function isLoopbackHostname(hostname: string): boolean {
36
44
  return isIPv4Loopback(hostname)
37
45
  }
38
46
 
47
+ /**
48
+ * Whether a reverse proxy stood between the client and this host: the request
49
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
50
+ * hop that forwards traffic, so the request did not originate on this machine.
51
+ * @param request - node HTTP request.
52
+ * @returns true when a forwarding header is present.
53
+ */
54
+ export function isProxiedRequest(request: IncomingMessage): boolean {
55
+ return request.headers['cf-connecting-ip'] !== undefined
56
+ || request.headers['x-forwarded-for'] !== undefined
57
+ }
58
+
39
59
  /**
40
60
  * Request-level trust fence: a loopback socket address AND a loopback Host
41
61
  * header, plus browser same-origin markers. The socket address is
42
- * authoritative; X-Forwarded-For is never trusted.
62
+ * authoritative for a direct connection; a request that carries a forwarding
63
+ * header is refused outright, because a proxy in front of the host makes both
64
+ * the socket address and the Host header describe the proxy rather than the
65
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
43
66
  */
44
67
  export function isLoopbackRequest(request: IncomingMessage): boolean {
45
68
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false
69
+ if (isProxiedRequest(request)) return false
46
70
  const host = request.headers.host
47
71
  if (typeof host !== 'string') return false
48
72
  let hostUrl: URL
package/src/protocol.ts CHANGED
@@ -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. */
package/src/routes.ts CHANGED
@@ -130,8 +130,11 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
130
130
  // Connection-relevant changes invalidate the pooled connection:
131
131
  // without this the pool would keep running commands on the old
132
132
  // host/credentials until the idle sweep (up to 30 min later).
133
+ // Agent forwarding belongs here too: it is fixed per connection
134
+ // (ssh2 negotiates it when the channel opens), so toggling it must
135
+ // reconnect or the new setting silently never takes effect.
133
136
  const patch = body as Record<string, unknown>
134
- if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand'].some(key => patch[key] !== undefined)) {
137
+ if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand', 'forwardAgent'].some(key => patch[key] !== undefined)) {
135
138
  engine.dropAlias(alias)
136
139
  }
137
140
  writeJson(res, 200, { host: store.summarize(entry) })
package/src/store.ts CHANGED
@@ -72,6 +72,9 @@ export function validateHostPayload(payload: unknown): string | undefined {
72
72
  if (p.tags !== undefined && (!Array.isArray(p.tags) || p.tags.some(x => typeof x !== 'string'))) {
73
73
  return 'tags must be an array of strings'
74
74
  }
75
+ if (p.forwardAgent !== undefined && typeof p.forwardAgent !== 'boolean') {
76
+ return 'forwardAgent must be a boolean'
77
+ }
75
78
  return undefined
76
79
  }
77
80
 
@@ -136,6 +139,9 @@ export class HostStore {
136
139
  ...(entry.environment !== undefined ? { environment: entry.environment } : {}),
137
140
  tags: [...entry.tags],
138
141
  ...(entry.location !== undefined ? { location: entry.location } : {}),
142
+ // Always a definite boolean, unlike the conditional optional fields:
143
+ // the tool bridge rejects undefined-valued JSON properties.
144
+ forwardAgent: entry.forwardAgent === true,
139
145
  createdAt: entry.createdAt,
140
146
  updatedAt: entry.updatedAt,
141
147
  }
@@ -171,6 +177,9 @@ export class HostStore {
171
177
  environment: payload.environment?.trim() || undefined,
172
178
  tags: [...(payload.tags ?? [])].map(tag => tag.trim()).filter(tag => tag !== ''),
173
179
  location: payload.location?.trim() || undefined,
180
+ // Stored only when enabled, so a store file written without agent
181
+ // forwarding stays byte-identical to the pre-feature format.
182
+ forwardAgent: payload.forwardAgent === true ? true : undefined,
174
183
  createdAt: now,
175
184
  updatedAt: now,
176
185
  }
@@ -201,6 +210,9 @@ export class HostStore {
201
210
  if (patch.proxyCommand !== undefined && typeof patch.proxyCommand !== 'string') {
202
211
  throw new Error('proxyCommand must be a string when provided')
203
212
  }
213
+ if (patch.forwardAgent !== undefined && typeof patch.forwardAgent !== 'boolean') {
214
+ throw new Error('forwardAgent must be a boolean')
215
+ }
204
216
  // The mutual exclusion is checked on the MERGED view: a patch that only
205
217
  // adds one transport must not slip past a stored value of the other.
206
218
  const mergedProxyCommand = patch.proxyCommand !== undefined
@@ -250,6 +262,8 @@ export class HostStore {
250
262
  if (patch.environment !== undefined) entry.environment = patch.environment.trim() || undefined
251
263
  if (patch.tags !== undefined) entry.tags = [...patch.tags].map(tag => tag.trim()).filter(tag => tag !== '')
252
264
  if (patch.location !== undefined) entry.location = patch.location.trim() || undefined
265
+ // PATCH semantics: an omitted key keeps the stored value, false clears it.
266
+ if (patch.forwardAgent !== undefined) entry.forwardAgent = patch.forwardAgent === true ? true : undefined
253
267
  entry.updatedAt = Date.now()
254
268
  this.save(file)
255
269
  return entry
@@ -326,6 +340,7 @@ export class HostStore {
326
340
  environment: block.props.environment,
327
341
  tags: (block.props.tags ?? '').split(',').map(tag => tag.trim()).filter(tag => tag !== ''),
328
342
  location: block.props.location,
343
+ forwardAgent: parseForwardAgentValue(block.props.forwardagent),
329
344
  }
330
345
  try {
331
346
  this.create(payload)
@@ -411,6 +426,17 @@ export function normalizeProxyCommand(raw: string | undefined): string | undefin
411
426
  return trimmed
412
427
  }
413
428
 
429
+ /**
430
+ * Read an ssh_config `ForwardAgent` value into the stored boolean flag. Only
431
+ * an explicit yes/true/on enables forwarding; an absent value, no/false/off,
432
+ * and anything unrecognized leave it off instead of failing the import — an
433
+ * unknown keyword must never cost the user the whole Host block.
434
+ */
435
+ export function parseForwardAgentValue(raw: string | undefined): boolean {
436
+ const value = raw?.trim().toLowerCase()
437
+ return value === 'yes' || value === 'true' || value === 'on'
438
+ }
439
+
414
440
  /** Expand a leading `~` in a filesystem path. */
415
441
  export function expandHome(path: string): string {
416
442
  if (path === '~') return homedir()
package/src/tools.ts CHANGED
@@ -28,6 +28,7 @@ export interface AgentHostRow {
28
28
  keyReady: boolean
29
29
  proxyJump: string[]
30
30
  proxyCommandConfigured: boolean
31
+ forwardAgent: boolean
31
32
  description?: string
32
33
  environment?: string
33
34
  tags: string[]
@@ -52,11 +53,14 @@ function renderHosts(hosts: AgentHostRow[]): string {
52
53
  host.user,
53
54
  host.auth,
54
55
  host.proxyJump.length > 0 ? 'jump:' + host.proxyJump.join(',') : host.proxyCommandConfigured ? 'proxy-command' : '-',
56
+ // Forwarding is a security-relevant opt-in (the remote can sign with this
57
+ // machine's agent), so the model must see it in the table, not only in JSON.
58
+ host.forwardAgent ? 'yes' : '-',
55
59
  host.environment ?? '-',
56
60
  (host.tags.length > 0 ? host.tags.join(',') : '-'),
57
61
  host.description ?? '',
58
62
  ].join(' | '))
59
- return ['alias | host | port | user | auth | proxy | environment | tags | description', '--- | --- | --- | --- | --- | --- | --- | --- | ---', ...rows].join('\n')
63
+ return ['alias | host | port | user | auth | proxy | forward | environment | tags | description', '--- | --- | --- | --- | --- | --- | --- | --- | --- | ---', ...rows].join('\n')
60
64
  }
61
65
 
62
66
  /** Render one exec result (mirrors the bash-tool exit-code convention). */
@@ -91,7 +95,7 @@ function renderTunnel(tunnel: TunnelInfo): string {
91
95
  export function sshListTool(engine: SshEngine) {
92
96
  return defineTool({
93
97
  name: 'ssh_list',
94
- description: 'List configured SSH hosts (alias, host, user, auth, environment, tags, description). Use ssh_exec etc. with the alias.',
98
+ description: 'List configured SSH hosts (alias, host, user, auth, agent forwarding, environment, tags, description). Use ssh_exec etc. with the alias.',
95
99
  parameters: {
96
100
  query: { type: 'string', description: 'Optional fuzzy match against alias, description, host, and tags.' },
97
101
  },
@@ -115,6 +119,7 @@ export function sshListTool(engine: SshEngine) {
115
119
  keyReady: { type: 'boolean', required: true },
116
120
  proxyJump: { type: 'array', items: { type: 'string' }, required: true },
117
121
  proxyCommandConfigured: { type: 'boolean', required: true },
122
+ forwardAgent: { type: 'boolean', required: true },
118
123
  description: { type: 'string' },
119
124
  environment: { type: 'string' },
120
125
  tags: { type: 'array', items: { type: 'string' }, required: true },