dsh-remote-go 0.1.0 → 0.2.0

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.
@@ -3,19 +3,233 @@
3
3
  * SFTP directly to a user-selected local directory. Nothing is archived or held in
4
4
  * memory, and there is no byte or entry cap. Existing target names are renamed with
5
5
  * a ` (2)`, ` (3)` suffix so a download never overwrites local data.
6
+ *
7
+ * The destination is a **write primitive that a remote host chooses the contents of** (the
8
+ * file or folder name comes from the remote tree), so it is fenced like one: only folders
9
+ * under the local user's home, and never a system, autorun or credential folder. Without this
10
+ * fence a compromised remote could ask the GUI to save its tree into
11
+ * `…\Start Menu\Programs\Startup` (or `~/.ssh/authorized_keys`) and run code on this machine at
12
+ * the next logon.
6
13
  */
7
14
  import path from 'node:path'
15
+ import { homedir } from 'node:os'
8
16
  import { mkdir, open, rm, stat } from 'node:fs/promises'
9
17
  import { errors, isRemoteGoError } from './errors.js'
10
18
  import { remoteFileName, safeLocalSegment } from './remote-path.js'
11
19
 
12
- async function requireDestination(destination) {
13
- if (typeof destination !== 'string' || destination.trim() === '' || destination.includes('\0')) {
14
- throw errors.invalidInput('destination', {
15
- zh: '请选择本机的保存文件夹。',
16
- en: 'Choose a destination folder on this machine.',
20
+ /**
21
+ * Path segments that execute something when the user logs in, or that authorize a login.
22
+ * Matched case-insensitively as a whole segment anywhere below the home directory, so both
23
+ * `…\Start Menu\Programs\Startup` and `~/.config/autostart` are covered. Shell startup files
24
+ * and the per-user containers that hold them (`~/.config`, `~/.local`, whose `bin` is on PATH in
25
+ * many distributions) are refused for the same reason, as are the macOS login-item folders
26
+ * (`~/Library/LaunchAgents`, `LaunchDaemons`, `StartupItems`) and the X session files.
27
+ */
28
+ const FORBIDDEN_SEGMENTS = new Map([
29
+ ['startup', 'autorun'],
30
+ ['startupfolder', 'autorun'],
31
+ ['startupitems', 'autorun'],
32
+ ['autostart', 'autorun'],
33
+ ['systemd', 'autorun'],
34
+ ['launchagents', 'autorun'],
35
+ ['launchdaemons', 'autorun'],
36
+ ['.ssh', 'credentials'],
37
+ ['.gnupg', 'credentials'],
38
+ ['.config', 'login'],
39
+ ['.local', 'login'],
40
+ ['.bashrc', 'login'],
41
+ ['.bash_profile', 'login'],
42
+ ['.bash_login', 'login'],
43
+ ['.bash_logout', 'login'],
44
+ ['.profile', 'login'],
45
+ ['.zshrc', 'login'],
46
+ ['.zprofile', 'login'],
47
+ ['.zshenv', 'login'],
48
+ ['.zlogin', 'login'],
49
+ ['.zlogout', 'login'],
50
+ ['.kshrc', 'login'],
51
+ ['.cshrc', 'login'],
52
+ ['.tcshrc', 'login'],
53
+ ['.login', 'login'],
54
+ ['.logout', 'login'],
55
+ ['.xsessionrc', 'login'],
56
+ ['.xprofile', 'login'],
57
+ ['.xinitrc', 'login'],
58
+ ])
59
+
60
+ /** `shell:startup` / `shell:common startup` name an autorun folder without spelling a path. */
61
+ const SHELL_FOLDER_RE = /^\s*shell\s*:/i
62
+
63
+ /** Directories that belong to the OS; never a download target even if home somehow covers them. */
64
+ const SYSTEM_ROOTS = Object.freeze(
65
+ process.platform === 'win32'
66
+ ? ['C:\\Windows', 'C:\\Program Files', 'C:\\Program Files (x86)', 'C:\\ProgramData']
67
+ : ['/etc', '/usr', '/bin', '/sbin', '/lib', '/lib64', '/boot', '/opt', '/var', '/dev', '/proc', '/sys'],
68
+ )
69
+
70
+ /** A stronger reason wins when several segments of one path match (most specific first). */
71
+ const REASON_PRIORITY = ['autorun', 'credentials', 'login', 'system']
72
+
73
+ /**
74
+ * One resolved path, comparable on this platform. Windows and macOS both have a
75
+ * case-insensitive default filesystem, so a case-insensitive compare is the one the OS itself
76
+ * would do (`C:\Users` vs `c:\users`, `/Users/Me` vs `/Users/me`).
77
+ */
78
+ function comparable(value) {
79
+ return process.platform === 'win32' || process.platform === 'darwin' ? value.toLowerCase() : value
80
+ }
81
+
82
+ function segmentsOf(resolved) {
83
+ return resolved.split(/[\\/]+/).filter((segment) => segment !== '')
84
+ }
85
+
86
+ function isInside(root, target) {
87
+ const base = root.endsWith(path.sep) ? root : `${root}${path.sep}`
88
+ return target === root || target.startsWith(base)
89
+ }
90
+
91
+ /**
92
+ * Locations whose *contents* run or authenticate at logon. A download may neither land inside
93
+ * one of them nor create one of their ancestors: a remote folder named `Microsoft` under
94
+ * `~/AppData/Roaming` would otherwise put a whole `Windows\Start Menu\Programs\Startup` tree on
95
+ * disk without any single path segment looking suspicious (macOS has the same shape under
96
+ * `~/Library`).
97
+ * @param {string} home - resolved home directory.
98
+ * @returns {string[]} resolved sensitive roots that exist by definition (not on disk).
99
+ */
100
+ function sensitiveRoots(home) {
101
+ const roots = ['.config', '.local', '.ssh', '.gnupg'].map((name) => path.join(home, name))
102
+ roots.push(path.join(home, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu'))
103
+ for (const name of ['LaunchAgents', 'LaunchDaemons', 'StartupItems']) {
104
+ roots.push(path.join(home, 'Library', name))
105
+ }
106
+ const appData = typeof process.env.APPDATA === 'string' && process.env.APPDATA.trim() !== ''
107
+ if (appData) roots.push(path.join(process.env.APPDATA, 'Microsoft', 'Windows', 'Start Menu'))
108
+ return roots
109
+ }
110
+
111
+ /**
112
+ * Whether a path is a sensitive location, inside one, or an ancestor of one.
113
+ * @param {string} target - resolved candidate path.
114
+ * @param {string} home - resolved home directory.
115
+ * @returns {boolean}
116
+ */
117
+ function isProtectedLocation(target, home) {
118
+ const resolved = comparable(target)
119
+ for (const root of sensitiveRoots(home)) {
120
+ const sensitive = comparable(path.resolve(root))
121
+ if (isInside(sensitive, resolved) || isInside(resolved, sensitive)) return true
122
+ }
123
+ return false
124
+ }
125
+
126
+ /** The concrete home directory a policy call is judged against. */
127
+ function homeOf(options = {}) {
128
+ return path.resolve(options.home ?? homedir())
129
+ }
130
+
131
+ /**
132
+ * Whether one local folder may receive a remote download.
133
+ * @param {unknown} destination - the folder the client asked to save into.
134
+ * @param {{ home?: string }} [options] - the local user's home (defaults to the OS home).
135
+ * @returns {'invalid'|'outside-home'|'autorun'|'credentials'|'login'|'system'|'protected'|null}
136
+ * a refusal reason, or null when the folder is acceptable. Pure: no filesystem access, so it
137
+ * is testable.
138
+ */
139
+ export function destinationPolicy(destination, options = {}) {
140
+ if (typeof destination !== 'string' || destination.trim() === '' || destination.includes('\0')) return 'invalid'
141
+ if (SHELL_FOLDER_RE.test(destination)) return 'autorun'
142
+ const home = comparable(homeOf(options))
143
+ const target = comparable(path.resolve(destination))
144
+ if (!isInside(home, target)) return 'outside-home'
145
+ const segments = segmentsOf(target)
146
+ const reasons = new Set()
147
+ for (const segment of segments) {
148
+ const reason = FORBIDDEN_SEGMENTS.get(segment.toLowerCase())
149
+ if (reason !== undefined) reasons.add(reason)
150
+ }
151
+ // `…\Start Menu\Programs`: a two-segment location whose entries appear in the Start menu.
152
+ for (let at = 1; at < segments.length; at += 1) {
153
+ if (segments[at - 1].toLowerCase() === 'start menu' && segments[at].toLowerCase() === 'programs') {
154
+ reasons.add('autorun')
155
+ }
156
+ }
157
+ for (const root of SYSTEM_ROOTS) {
158
+ if (isInside(comparable(path.resolve(root)), target)) reasons.add('system')
159
+ }
160
+ for (const reason of REASON_PRIORITY) if (reasons.has(reason)) return reason
161
+ return null
162
+ }
163
+
164
+ /** The client-facing refusal for one destination policy result. */
165
+ function destinationRefusal(reason) {
166
+ if (reason === 'outside-home') {
167
+ return errors.invalidInput('destination', {
168
+ zh: '只能保存到本机用户主目录下的文件夹(防止写入系统或自启动位置)。',
169
+ en: 'Downloads must go to a folder under this machine’s home directory (system and autorun locations are refused).',
170
+ })
171
+ }
172
+ if (reason === 'autorun') {
173
+ return errors.invalidInput('destination', {
174
+ zh: '不能保存到自启动目录(例如 Startup / autostart / shell:startup)。',
175
+ en: 'An autorun folder (for example Startup / autostart / shell:startup) cannot be a download target.',
176
+ })
177
+ }
178
+ if (reason === 'credentials') {
179
+ return errors.invalidInput('destination', {
180
+ zh: '不能保存到 SSH / GPG 配置目录(例如 .ssh)。',
181
+ en: 'An SSH / GPG configuration folder (for example .ssh) cannot be a download target.',
182
+ })
183
+ }
184
+ if (reason === 'login') {
185
+ return errors.invalidInput('destination', {
186
+ zh: '不能保存到登录脚本或用户配置目录(例如 .bashrc / .profile / .config / .local)。',
187
+ en: 'A login script or user configuration folder (for example .bashrc / .profile / .config / .local) cannot be a download target.',
17
188
  })
18
189
  }
190
+ if (reason === 'protected') {
191
+ return errors.invalidInput('destination', {
192
+ zh: '不能保存到会在登录或启动时生效的位置(自启动、登录脚本或凭据目录及其上级目录)。',
193
+ en: 'A location that runs or authenticates at logon (autorun, login scripts, credentials, or one of their parent folders) cannot be a download target.',
194
+ })
195
+ }
196
+ if (reason === 'system') {
197
+ return errors.invalidInput('destination', {
198
+ zh: '不能保存到系统目录。',
199
+ en: 'A system directory cannot be a download target.',
200
+ })
201
+ }
202
+ return errors.invalidInput('destination', {
203
+ zh: '请选择本机的保存文件夹。',
204
+ en: 'Choose a destination folder on this machine.',
205
+ })
206
+ }
207
+
208
+ /**
209
+ * Refuse a path the remote host named inside an already-accepted destination.
210
+ *
211
+ * The destination is chosen locally, but the *name* below it comes from the remote tree
212
+ * (`~/Downloads/…`, `~/.config` + a remote folder called `autostart`, `~` + a remote file called
213
+ * `.bash_login`). This is the check that turns those combinations into a refusal.
214
+ * @param {string} candidate - resolved folder or file path about to be created.
215
+ * @param {{ home?: string }} [options]
216
+ * @throws {import('./errors.js').RemoteGoError} `invalid-input` when the path is protected.
217
+ */
218
+ function assertCandidateAllowed(candidate, options = {}) {
219
+ const refusal = destinationPolicy(candidate, options)
220
+ if (refusal !== null) throw destinationRefusal(refusal)
221
+ if (isProtectedLocation(candidate, homeOf(options))) throw destinationRefusal('protected')
222
+ }
223
+
224
+ /**
225
+ * Resolve and check one download destination.
226
+ * @param {unknown} destination - absolute local folder.
227
+ * @param {{ home?: string }} [options] - the local user's home, for tests.
228
+ * @returns {Promise<string>} the resolved folder.
229
+ */
230
+ async function requireDestination(destination, options = {}) {
231
+ const refusal = destinationPolicy(destination, options)
232
+ if (refusal !== null) throw destinationRefusal(refusal)
19
233
  const base = path.resolve(destination)
20
234
  try {
21
235
  const info = await stat(base)
@@ -35,10 +249,13 @@ async function requireDestination(destination) {
35
249
  return base
36
250
  }
37
251
 
38
- async function createUniqueFolder(base, name) {
252
+ async function createUniqueFolder(base, name, options = {}) {
39
253
  const safeName = safeLocalSegment(name) || 'download'
40
254
  for (let index = 1; index <= 999; index += 1) {
41
255
  const candidate = path.join(base, index === 1 ? safeName : `${safeName} (${index})`)
256
+ // The root's name comes from the remote tree, so it is judged before anything is created:
257
+ // `~/.config` + a remote folder called `autostart` must fail here, with zero writes.
258
+ assertCandidateAllowed(candidate, options)
42
259
  try {
43
260
  await mkdir(candidate)
44
261
  return candidate
@@ -52,13 +269,15 @@ async function createUniqueFolder(base, name) {
52
269
  })
53
270
  }
54
271
 
55
- async function createUniqueFile(base, name) {
272
+ async function createUniqueFile(base, name, options = {}) {
56
273
  const safeName = safeLocalSegment(name) || 'download'
57
274
  const extension = path.extname(safeName)
58
275
  const stem = path.basename(safeName, extension) || 'download'
59
276
  for (let index = 1; index <= 999; index += 1) {
60
277
  const fileName = index === 1 ? safeName : `${stem} (${index})${extension}`
61
278
  const candidate = path.join(base, fileName)
279
+ // The remote names the file: `~` + `.bash_login` is a login script, not a download.
280
+ assertCandidateAllowed(candidate, options)
62
281
  try {
63
282
  const handle = await open(candidate, 'wx', 0o600)
64
283
  await handle.close()
@@ -85,7 +304,7 @@ function toDownloadError(error) {
85
304
  * @param {object} runtime - connected host runtime.
86
305
  * @param {string} remotePath - normalized absolute remote path.
87
306
  * @param {unknown} destination - absolute local directory.
88
- * @param {{ onProgress?: Function, isCancelled?: () => boolean }} [options]
307
+ * @param {{ onProgress?: Function, isCancelled?: () => boolean, home?: string }} [options]
89
308
  * @returns {Promise<{ path: string, kind: 'file', name: string, destination: string,
90
309
  * totalBytes: number, files: number }>}
91
310
  */
@@ -99,11 +318,11 @@ export async function saveHostFile(runtime, remotePath, destination, options = {
99
318
  if (typeof runtime.ssh.saveRemoteFile !== 'function') {
100
319
  throw errors.internal('the SSH transport does not support file saves')
101
320
  }
102
- const base = await requireDestination(destination)
321
+ const base = await requireDestination(destination, options)
103
322
  const name = remoteFileName(remotePath)
104
323
  let localPath = null
105
324
  try {
106
- localPath = await createUniqueFile(base, name)
325
+ localPath = await createUniqueFile(base, name, options)
107
326
  const result = await runtime.ssh.saveRemoteFile(remotePath, localPath, options)
108
327
  return {
109
328
  path: remotePath,
@@ -124,7 +343,7 @@ export async function saveHostFile(runtime, remotePath, destination, options = {
124
343
  * @param {object} runtime - connected host runtime.
125
344
  * @param {string} remotePath - normalized absolute remote folder path.
126
345
  * @param {unknown} destination - absolute local directory.
127
- * @param {{ onInventory?: Function, onProgress?: Function, isCancelled?: () => boolean }} [options]
346
+ * @param {{ onInventory?: Function, onProgress?: Function, isCancelled?: () => boolean, home?: string }} [options]
128
347
  * @returns {Promise<{ path: string, kind: 'folder', name: string, destination: string,
129
348
  * totalBytes: number, files: number, cancelled?: boolean }>}
130
349
  */
@@ -138,11 +357,11 @@ export async function saveHostFolder(runtime, remotePath, destination, options =
138
357
  if (typeof runtime.ssh.saveRemoteTree !== 'function') {
139
358
  throw errors.internal('the SSH transport does not support folder saves')
140
359
  }
141
- const base = await requireDestination(destination)
360
+ const base = await requireDestination(destination, options)
142
361
  const name = remoteFileName(remotePath)
143
362
  let root = null
144
363
  try {
145
- root = await createUniqueFolder(base, name)
364
+ root = await createUniqueFolder(base, name, options)
146
365
  const result = await runtime.ssh.saveRemoteTree(remotePath, root, options)
147
366
  return {
148
367
  path: remotePath,
package/src/probe.js CHANGED
@@ -78,7 +78,19 @@ export function toProbeFacts(values) {
78
78
 
79
79
  export async function probeRemote(ssh, options = {}) {
80
80
  const script = buildProbeScript()
81
- const result = await ssh.exec(script, { timeoutMs: options.timeoutMs ?? 60_000 })
81
+ const timeoutMs = options.timeoutMs ?? 60_000
82
+ const result = await ssh.exec(script, { timeoutMs })
83
+ // A probe that ran out of time says nothing about the remote's DSH: report a timeout
84
+ // (retryable network), not a missing remote runtime (L).
85
+ if (result.timedOut === true) {
86
+ throw errors.network(
87
+ {
88
+ zh: `远端环境探测超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是链路很慢或远端负载过高。`,
89
+ en: `The remote environment probe did not finish within ${Math.round(timeoutMs / 1000)}s; the link may be slow or the remote overloaded.`,
90
+ },
91
+ { technical: `reason=probe-timeout timeoutMs=${timeoutMs}` },
92
+ )
93
+ }
82
94
  if (result.code !== 0) {
83
95
  throw errors.remoteDshMissing({
84
96
  zh: `远端环境探测失败(退出码 ${result.code}):${headTail(result.stderr || result.stdout, 400)}`,
package/src/prompts.js CHANGED
@@ -6,29 +6,84 @@ import { createDecision, nowIso } from './util.js'
6
6
 
7
7
  /**
8
8
  * Park the SSH handshake until the user answers the fingerprint prompt.
9
+ *
10
+ * A jump host and the target are different machines with different keys: the `role`
11
+ * decides which context the answer belongs to, so a jump-host confirmation can never be
12
+ * mistaken for the target's (B1).
13
+ *
14
+ * @param {object} ctx - service context.
15
+ * @param {object} runtime - host runtime.
16
+ * @param {{ sha256: string, keyType?: string }} info - the advertised host key.
17
+ * @param {{ role?: 'target' | 'jump', host?: string | null }} [options]
18
+ * @returns {Promise<boolean>} whether the user accepted the key.
9
19
  */
10
- export function requestHostKey(ctx, runtime, info) {
11
- const policy = runtime.entry.hostKeyPolicy ?? ctx.settings().hostKeyPolicy
20
+ export function requestHostKey(ctx, runtime, info, options = {}) {
21
+ const role = options.role === 'jump' ? 'jump' : 'target'
22
+ const isJump = role === 'jump'
23
+ // A per-host policy describes the target the user saved. A jump host has its own
24
+ // security context, so only the global policy applies to it.
25
+ const policy = isJump
26
+ ? (ctx.settings()?.hostKeyPolicy ?? 'first-use')
27
+ : (runtime.entry.hostKeyPolicy ?? ctx.settings()?.hostKeyPolicy ?? 'first-use')
12
28
  if (policy === 'strict') throw errors.hostKeyUnknown(info.sha256)
29
+ const hostLabel = isJump && options.host ? ` ${options.host}` : ''
13
30
  ctx.progress.log(
14
31
  runtime,
15
32
  'info',
16
- `waiting for the host key to be confirmed (${info.keyType} ${info.sha256}); the SSH handshake is paused`,
33
+ `waiting for the ${isJump ? `jump host${hostLabel}` : 'host'} key to be confirmed (${
34
+ info.keyType
35
+ } ${info.sha256}); the SSH handshake is paused`,
17
36
  )
18
- const decision = createDecision(ctx.timers.hostKeyConfirmMs, () => {
19
- ctx.progress.set(runtime, {
20
- status: 'error',
21
- phase: null,
22
- progress: null,
23
- error: toErrorView(errors.hostKeyUnknown(info.sha256)),
24
- })
25
- return false
26
- })
27
- runtime.pendingHostKey = { sha256: info.sha256, keyType: info.keyType, resolve: decision.settle }
28
- runtime.fingerprint = { sha256: info.sha256, keyType: info.keyType, status: 'pending', pinned: null }
37
+ const pending = {
38
+ sha256: info.sha256,
39
+ keyType: info.keyType,
40
+ role,
41
+ host: typeof options.host === 'string' && options.host !== '' ? options.host : null,
42
+ port: Number(options.port) || 22,
43
+ resolve: null,
44
+ }
45
+ const decision = createDecision(
46
+ ctx.timers.hostKeyConfirmMs,
47
+ () => {
48
+ // A prompt whose link already went away must not overwrite the state of that teardown.
49
+ if (runtime.pendingHostKey !== pending) return false
50
+ runtime.pendingHostKey = null
51
+ if (runtime.desired !== 'connected' || runtime.closing === true) return false
52
+ runtime.connectCancelled = true
53
+ ctx.progress.set(runtime, {
54
+ status: 'error',
55
+ phase: null,
56
+ progress: null,
57
+ error: toErrorView(errors.hostKeyUnknown(info.sha256)),
58
+ })
59
+ return false
60
+ },
61
+ () => {
62
+ if (runtime.pendingHostKey === pending) runtime.pendingHostKey = null
63
+ },
64
+ )
65
+ pending.resolve = decision.settle
66
+ runtime.pendingHostKey = pending
67
+ const fingerprint = { sha256: info.sha256, keyType: info.keyType, status: 'pending', pinned: null }
68
+ if (isJump) {
69
+ // The jump pin belongs to *this* jump host: an edited `jumpHost` must not be checked
70
+ // against the previous machine's key (review blocker 3).
71
+ runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port }
72
+ // The Client's dialog renders `HostView.fingerprint`, so the key being confirmed right now
73
+ // has to be the one shown there - even though the pin it may produce stays separate (B1).
74
+ runtime.fingerprint = { ...fingerprint }
75
+ } else {
76
+ runtime.fingerprint = fingerprint
77
+ }
29
78
  runtime.status = 'fingerprint-pending'
30
79
  runtime.phase = 'ssh'
31
- runtime.progress = { code: 'host-key-confirm', params: { sha256: info.sha256, keyType: info.keyType } }
80
+ // The role only travels for a jump host: the target prompt keeps its original shape.
81
+ runtime.progress = isJump
82
+ ? {
83
+ code: 'host-key-confirm',
84
+ params: { sha256: info.sha256, keyType: info.keyType, role: 'jump', host: pending.host },
85
+ }
86
+ : { code: 'host-key-confirm', params: { sha256: info.sha256, keyType: info.keyType } }
32
87
  ctx.emitState()
33
88
  return decision.promise
34
89
  }
@@ -36,6 +91,10 @@ export function requestHostKey(ctx, runtime, info) {
36
91
  /**
37
92
  * Answer the host-key prompt. Pinning is written straight through to the store so
38
93
  * a failed first attempt still remembers the key the user accepted.
94
+ *
95
+ * A jump host's key is remembered in memory only (`runtime.jumpFingerprint`): the store's
96
+ * `pinnedFingerprint` describes the target, and writing a jump key there would pin the
97
+ * target to the wrong machine forever (B1).
39
98
  */
40
99
  export async function confirmHostKey(ctx, runtime, decision) {
41
100
  const pending = runtime.pendingHostKey
@@ -45,22 +104,48 @@ export async function confirmHostKey(ctx, runtime, decision) {
45
104
  en: 'No host key is pending confirmation.',
46
105
  })
47
106
  }
107
+ // A prompt is only answerable while it is the live one: a timeout, a disconnect or a
108
+ // replacement attempt already settled it, and a late answer must not revive it (M1).
109
+ if (runtime.status !== 'fingerprint-pending') {
110
+ throw errors.invalidInput('fingerprint', {
111
+ zh: '这个指纹提示已经失效,请在下次连接时重新确认。',
112
+ en: 'This host-key prompt is no longer active; confirm the key on the next connection.',
113
+ })
114
+ }
48
115
  if (decision.sha256 && pending.sha256 && decision.sha256 !== pending.sha256) {
49
116
  throw errors.invalidInput('fingerprint', {
50
117
  zh: '确认的指纹与待确认的不一致。',
51
118
  en: 'The confirmed fingerprint does not match the pending one.',
52
119
  })
53
120
  }
54
- if (decision.accept && decision.remember) {
121
+ if (decision.accept !== true) runtime.connectCancelled = true
122
+ if (decision.accept && decision.remember && pending.role !== 'jump') {
55
123
  await ctx.store.patchHost(runtime.id, { pinnedFingerprint: pending.sha256 })
56
124
  runtime.entry = { ...runtime.entry, pinnedFingerprint: pending.sha256 }
57
125
  }
58
- runtime.fingerprint = {
126
+ const fingerprint = {
59
127
  sha256: pending.sha256,
60
128
  keyType: pending.keyType,
61
129
  status: 'pinned',
62
130
  pinned: decision.remember ? pending.sha256 : null,
63
131
  }
132
+ if (pending.role === 'jump') {
133
+ // Keep the identity with the pin: the same remembered pin may only be used for the same
134
+ // jump host and port (review blocker 3).
135
+ runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port }
136
+ // The dialog that asked about the jump host must not start describing the target as soon
137
+ // as it is answered: keep showing what was confirmed until the target is dialled.
138
+ runtime.fingerprint = { ...fingerprint }
139
+ ctx.progress.log(
140
+ runtime,
141
+ 'info',
142
+ `jump host key accepted${decision.remember ? ' and remembered for this session' : ''} (${
143
+ pending.host ?? 'jump host'
144
+ }: ${pending.sha256})`,
145
+ )
146
+ } else {
147
+ runtime.fingerprint = fingerprint
148
+ }
64
149
  runtime.pendingHostKey = null
65
150
  runtime.status = 'connecting'
66
151
  runtime.progress = { code: 'auth-checking' }
@@ -69,6 +154,18 @@ export async function confirmHostKey(ctx, runtime, decision) {
69
154
  return { ok: true }
70
155
  }
71
156
 
157
+ /**
158
+ * Abandon a pending host-key prompt (teardown, host removal, lost transport). Resolving it
159
+ * with `false` makes the stalled `verifyHostKey` throw instead of holding the connect
160
+ * promise open until the prompt times out (M1).
161
+ * @param {object} runtime - host runtime.
162
+ */
163
+ export function cancelHostKeyPrompt(runtime) {
164
+ const pending = runtime.pendingHostKey
165
+ runtime.pendingHostKey = null
166
+ if (pending) pending.resolve(false)
167
+ }
168
+
72
169
  /**
73
170
  * Pause the pipeline for a decision about foreign remote processes.
74
171
  * Mirrors the host-key prompt: a status, a promise, and a bounded timeout.
package/src/redact.js CHANGED
@@ -4,27 +4,41 @@
4
4
 
5
5
  const SECRET_QUERY_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'key', 'secret', 'password', 'passwd', 'auth']
6
6
  const SECRET_HEADER_RE = /\b(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*[^\r\n]+/gi
7
+ /** Custom authentication headers (`x-auth-token`, `x-dsh-session-key`, …) are secrets too. */
8
+ const SECRET_CUSTOM_HEADER_RE = /\b(x-[a-z0-9-]*(?:token|key|secret|auth)[a-z0-9-]*)\s*:\s*[^\r\n]+/gi
7
9
  const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g
8
10
  const TOKEN_QUERY_RE = new RegExp(`([?&](?:${SECRET_QUERY_KEYS.join('|')})=)[^&#\\s"']+`, 'gi')
11
+ /**
12
+ * A bare `token=…` outside a query string (log lines, `#fragment`, key=value dumps). The
13
+ * value never contains `<`/`>` so an already-redacted `<redacted>` is left alone.
14
+ */
15
+ const BARE_TOKEN_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'secret', 'password', 'passwd']
16
+ const BARE_TOKEN_RE = new RegExp(`\\b((?:${BARE_TOKEN_KEYS.join('|')})\\s*=\\s*)[^\\s&;,'"<>]+`, 'gi')
9
17
  const PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g
10
- const PASSWORD_FLAG_RE = /(--password[=\s]+|-p\s+|password[=:]\s*)(\S+)/gi
18
+ /**
19
+ * `--password X`, `password=X` and the short `-p X` form. The short form is also ssh's
20
+ * port flag (`ssh -p 2222`), so a bare number is left alone: a port is not a secret and
21
+ * mangling it would make the technical detail unreadable.
22
+ */
23
+ const PASSWORD_FLAG_RE = /(--password[=\s]+|password[=:]\s*|-p\s+(?!\d+\b))(\S+)/gi
11
24
  const DSH_TOKEN_LINE_RE = /(dsh web:\s*\S*?\?token=)[A-Za-z0-9._~+/=-]+/g
12
- const LONG_HEX_RE = /\b[a-f0-9]{40,}\b/gi
13
- const LONG_BASE64_RE = /\b[A-Za-z0-9+/]{48,}={0,2}\b/g
14
25
 
15
26
  export function redactText(text, options = {}) {
16
27
  if (typeof text !== 'string' || text === '') return text
17
28
  let out = text
18
29
  out = out.replace(PRIVATE_KEY_RE, '-----BEGIN PRIVATE KEY-----<redacted>-----END PRIVATE KEY-----')
19
30
  out = out.replace(SECRET_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`)
31
+ out = out.replace(SECRET_CUSTOM_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`)
20
32
  out = out.replace(BEARER_RE, (_match, scheme) => `${scheme} <redacted>`)
21
33
  out = out.replace(TOKEN_QUERY_RE, '$1<redacted>')
22
34
  out = out.replace(DSH_TOKEN_LINE_RE, '$1<redacted>')
35
+ out = out.replace(BARE_TOKEN_RE, '$1<redacted>')
23
36
  out = out.replace(PASSWORD_FLAG_RE, '$1<redacted>')
24
37
  if (!options.keepPaths) {
25
38
  // Home directories of the remote account are not secrets, but avoid leaking
26
39
  // arbitrary local user names into exported diagnostics.
27
40
  out = out.replace(/(\/home\/)[^/\s]+/g, '$1<user>')
41
+ out = out.replace(/(\/Users\/)[^/\s]+/g, '$1<user>')
28
42
  out = out.replace(/\b(C:\\Users\\)[^\\\s]+/gi, '$1<user>')
29
43
  }
30
44
  return out
@@ -13,7 +13,7 @@ export { normalizeRemoteFilePath, remoteFileName } from './remote-path.js'
13
13
  * Save one file or one folder for a download job.
14
14
  * @param {object} runtime - the connected host runtime.
15
15
  * @param {unknown} rawPath - the requested absolute remote path.
16
- * @param {{ destination?: string, onProgress?: Function, onInventory?: Function,
16
+ * @param {{ destination?: string, home?: string, onProgress?: Function, onInventory?: Function,
17
17
  * isCancelled?: () => boolean }} [options]
18
18
  * @returns {Promise<{ path: string, kind: 'file'|'folder', name: string,
19
19
  * destination: string, totalBytes: number, files: number, cancelled?: boolean }>}
@@ -33,7 +33,7 @@ export async function readHostDownload(runtime, rawPath, options = {}) {
33
33
  let destination
34
34
  try {
35
35
  const info = await ssh.inspectRemotePath(remotePath)
36
- destination = await requireDestination(options.destination)
36
+ destination = await requireDestination(options.destination, { home: options.home })
37
37
  if (info.isFile) return await saveHostFile(runtime, remotePath, destination, options)
38
38
  if (info.isDirectory) return await saveHostFolder(runtime, remotePath, destination, options)
39
39
  throw errors.remoteFileUnavailable({
@@ -71,3 +71,67 @@ export function safeLocalSegment(value) {
71
71
  if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(text)) text = '_' + text
72
72
  return text
73
73
  }
74
+
75
+ /**
76
+ * Windows treats these names as its own metadata or as shell entries: writing them into
77
+ * a download either corrupts a folder view (`desktop.ini`, `thumbs.db`) or leaves a file
78
+ * that a double click executes instead of showing (`.lnk`, `.url`). A remote host never
79
+ * gets to plant one in a local download.
80
+ */
81
+ const IGNORED_LOCAL_NAMES = new Set(['desktop.ini', 'thumbs.db', 'ehthumbs.db', '.ds_store'])
82
+ const IGNORED_LOCAL_SUFFIXES = ['.lnk', '.url']
83
+
84
+ /**
85
+ * Whether a remote name must be left out of a local folder download.
86
+ * @param {unknown} value - one remote path segment (file or directory name).
87
+ * @returns {boolean}
88
+ */
89
+ export function isIgnoredLocalName(value) {
90
+ const name = String(value ?? '')
91
+ .trim()
92
+ .toLowerCase()
93
+ if (name === '') return false
94
+ if (IGNORED_LOCAL_NAMES.has(name)) return true
95
+ return IGNORED_LOCAL_SUFFIXES.some((suffix) => name.endsWith(suffix))
96
+ }
97
+
98
+ /**
99
+ * Pick a local path that no earlier member of the same download already claimed.
100
+ *
101
+ * A case-insensitive filesystem (the Windows/macOS defaults) maps `Report.md` and
102
+ * `report.md` to one file: keeping both names would silently drop one of the two remote
103
+ * files. The later one is renamed `report (2).md` instead, so the file count on disk
104
+ * matches the inventory.
105
+ *
106
+ * @param {string} desired - absolute local path the member maps to.
107
+ * @param {Set<string>} taken - keys of the paths already claimed (use {@link localPathKey}).
108
+ * @param {{ caseInsensitive?: boolean }} [options]
109
+ * @returns {string} the chosen path (equal to `desired` when it is free).
110
+ */
111
+ export function uniqueLocalPath(desired, taken, options = {}) {
112
+ const key = (value) => localPathKey(value, options)
113
+ if (!taken.has(key(desired))) return desired
114
+ const directory = path.dirname(desired)
115
+ const extension = path.extname(desired)
116
+ const base = path.basename(desired, extension)
117
+ for (let index = 2; index < 1000; index += 1) {
118
+ const candidate = path.join(directory, `${base} (${index})${extension}`)
119
+ if (!taken.has(key(candidate))) return candidate
120
+ }
121
+ throw errors.remoteFileUnavailable({
122
+ zh: '远端有太多文件映射到同一个本地文件名,无法安全保存。',
123
+ en: 'Too many remote files map to the same local file name to save them safely.',
124
+ })
125
+ }
126
+
127
+ /**
128
+ * The collision key of a local path: separator-normalized, and lowercased when the local
129
+ * filesystem ignores case.
130
+ * @param {string} value - absolute or relative local path.
131
+ * @param {{ caseInsensitive?: boolean }} [options]
132
+ * @returns {string}
133
+ */
134
+ export function localPathKey(value, options = {}) {
135
+ const text = String(value ?? '').replace(/\\/g, '/')
136
+ return options.caseInsensitive === true ? text.toLowerCase() : text
137
+ }