dsh-remote 1.1.2 → 1.2.1

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.
package/lib/openssh.js CHANGED
@@ -317,6 +317,9 @@ export class OpenSshConnection extends EventEmitter {
317
317
  * Local forward: carry bytes to <destHost>:<destPort> as seen FROM the
318
318
  * remote, through `ssh -W`.
319
319
  *
320
+ * The channel is handed over as soon as the child is running — NOT when
321
+ * `ssh -W` exits. See the body for why that distinction is load-bearing.
322
+ *
320
323
  * @returns {boolean} true synchronously, so capability probes can be sync.
321
324
  */
322
325
  forwardOut(_srcHost, _srcPort, destHost, destPort, cb) {
@@ -327,26 +330,68 @@ export class OpenSshConnection extends EventEmitter {
327
330
  setImmediate(() => cb(err))
328
331
  return true
329
332
  }
330
- // `ssh -W` reports failures on stderr and then exits; surface that as the
331
- // channel error so the caller destroys its socket instead of hanging.
333
+ // `ssh -W` is the tunnel itself: for as long as the channel is usable the
334
+ // child stays ALIVE and only exits when the peer or the caller closes it.
335
+ // Waiting for 'close' to declare success therefore never resolves for a
336
+ // healthy tunnel; the caller never writes the first byte and the peer times
337
+ // out. Hand the channel over on the next tick instead — ssh buffers stdin
338
+ // until the remote channel opens — and report failures by destroying it.
339
+ //
340
+ // The one-tick delay is load-bearing: a spawn error (bad binary, EACCES)
341
+ // arrives in that same window, and the calling Promise only attaches its
342
+ // handlers in the microtask after `cb`. Without the delay the error would
343
+ // be emitted into the no-op listener and the caller would receive an
344
+ // already-destroyed channel (the local socket would hang forever).
332
345
  let stderr = ''
333
346
  let handed = false
347
+ let failed = false
348
+ let closing = false
349
+ let ended = false
334
350
  const channel = new Duplex({
335
351
  read() {},
336
352
  write(chunk, _enc, done) { try { child.stdin.write(chunk, done) } catch (e) { done(e) } },
337
353
  final(done) { try { child.stdin.end(done) } catch { done() } },
338
354
  destroy(err, done) { try { child.kill() } catch {} ; done(err) },
339
355
  })
340
- channel.close = () => { try { child.kill() } catch {} }
356
+ channel.close = () => { closing = true; try { child.kill() } catch {} }
357
+ // Until the caller attaches its own 'error' handler (one microtask after
358
+ // cb) a failure must not become an unhandled 'error' event.
359
+ channel.on('error', () => { /* callers attach their own kill handler */ })
360
+ const endReadable = () => {
361
+ if (ended) return
362
+ ended = true
363
+ try { channel.push(null) } catch { /* already gone */ }
364
+ }
365
+ const fail = (err) => {
366
+ if (failed) return
367
+ failed = true
368
+ if (handed) channel.destroy(err)
369
+ else { handed = true; cb(err) }
370
+ }
341
371
  child.stderr.on('data', (d) => { stderr += d })
342
372
  child.stdout.on('data', (d) => channel.push(d))
343
- child.stdout.on('end', () => channel.push(null))
344
- child.on('error', (e) => { if (!handed) { handed = true; cb(e); return } channel.destroy(e) })
373
+ // stdout's EOF is deliberately NOT forwarded yet: a non-zero exit can
374
+ // follow it (truncated response), and ending first would let the caller's
375
+ // pipe close the socket as if the stream had finished cleanly. Only the
376
+ // child's exit verdict decides: code 0 (or a caller close) means EOF.
377
+ child.on('error', fail)
345
378
  child.on('close', (code) => {
346
- if (handed) { channel.push(null); return }
379
+ if (failed) return
380
+ if (!handed) {
381
+ // Exited before the deferred success handover: keep the old contract.
382
+ if (code === 0) { handed = true; cb(null, channel); endReadable(); return }
383
+ handed = true
384
+ cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
385
+ return
386
+ }
387
+ if (closing) { endReadable(); return }
388
+ if (code === 0) { endReadable(); return }
389
+ channel.destroy(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
390
+ })
391
+ setImmediate(() => {
392
+ if (handed || failed) return
347
393
  handed = true
348
- if (code === 0) { cb(null, channel); return }
349
- cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
394
+ cb(null, channel)
350
395
  })
351
396
  return true
352
397
  }
@@ -559,6 +604,12 @@ export class SystemOpenSshPool {
559
604
  const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
560
605
  if (!isCurrent()) throw new Error('ssh target changed during connect')
561
606
  if (probe.code !== 0) {
607
+ // dsh-remote-fix3: _runSsh reports its own timer as code -1 / signal
608
+ // TIMEOUT with empty stderr, so the old message degraded to a bare
609
+ // `ssh failed (exit -1)` and told the settings page nothing actionable.
610
+ if (probe.signal === 'TIMEOUT') {
611
+ throw new Error(`ssh timed out after ${this.config.connectTimeoutMs || 15000}ms (no reply from the host — raise the connect timeout if this link is just slow)`)
612
+ }
562
613
  throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
563
614
  }
564
615
  void secret
package/lib/remote-git.js CHANGED
@@ -37,15 +37,16 @@ async function runGit(pool, cwd, args, signal, limit = LIMIT) {
37
37
  signal?.addEventListener('abort', abort, { once: true })
38
38
  let output = [], size = 0, tapped = false, truncated = false
39
39
  try {
40
- const command = ['git', '--no-pager', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', '-c', 'color.ui=false', '-C', gitPath(cwd), ...args].map(shq).join(' ')
41
- const result = await pool.exec(command, { timeoutMs: 15000, signal: cancel.signal, onData(channel, chunk) {
40
+ const argv = [ '--no-pager', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', '-c', 'color.ui=false', '-C', gitPath(cwd), ...args]
41
+ const options = { timeoutMs: 15000, signal: cancel.signal, onData(channel, chunk) {
42
42
  if (channel !== 'stdout') return
43
43
  tapped = true
44
44
  const bytes = Buffer.from(chunk)
45
45
  if (size < limit) output.push(bytes.subarray(0, limit - size))
46
46
  size += bytes.length
47
47
  if (size > limit) { truncated = true; cancel.abort() }
48
- } })
48
+ } }
49
+ const result = pool.local ? await pool.execFile('git', argv, options) : await pool.exec(['git', ...argv].map(shq).join(' '), options)
49
50
  const stdout = tapped ? Buffer.concat(output).toString('utf8') : String(result.stdout || '').slice(0, limit)
50
51
  return { ...result, stdout, truncated: truncated || !tapped && String(result.stdout || '').length > limit }
51
52
  } finally { signal?.removeEventListener('abort', abort) }
@@ -57,7 +58,7 @@ export async function inspectRemoteGit(binding, { action = 'status', path: relat
57
58
  if (!['status', 'diff'].includes(action)) throw Object.assign(new Error('action must be status or diff'), { httpStatus: 400 })
58
59
  if (action === 'diff' && !safeRelative(relative)) throw Object.assign(new Error('A repository-relative Git file path is required'), { httpStatus: 400 })
59
60
  await pool.detect()
60
- if (pool.platform === 'windows' && !pool.gitBashPath) return { ok: true, available: false, reason: 'unsupported-shell' }
61
+ if (!pool.local && pool.platform === 'windows' && !pool.gitBashPath) return { ok: true, available: false, reason: 'unsupported-shell' }
61
62
  const top = await runGit(pool, ws, ['rev-parse', '--show-toplevel', '--show-prefix'], signal, 8192)
62
63
  if (top.code !== 0) {
63
64
  if (top.code === 127 || /not recognized|command not found/i.test(top.stderr || '')) return { ok: true, available: false, reason: 'git-unavailable' }
@@ -71,6 +72,7 @@ export async function inspectRemoteGit(binding, { action = 'status', path: relat
71
72
  // Git canonicalizes symlinked workspace roots. Keep filtering in that same
72
73
  // world, but return navigation paths under the user's original workspace.
73
74
  const gitWorkspace = prefix ? joinRemotePath(repo, prefix) : repo
75
+ if (pool.local) await pool.checkPath(gitWorkspace)
74
76
  const navigationPath = target => {
75
77
  const within = relPathUnder(gitWorkspace, target)
76
78
  return within === null ? null : within ? joinRemotePath(ws, within) : ws
@@ -13,7 +13,7 @@
13
13
  * @param {object} deps.store - machine-registry store (`currentId` tags new definitions).
14
14
  * @returns {Array<object>} route descriptors for registerHttpTransports.
15
15
  */
16
- export function createForwardRoutes({ sendJson, readBody, forwards, store }) {
16
+ export function createForwardRoutes({ sendJson, readBody, forwards, store, activeMachineId }) {
17
17
  return [
18
18
  {
19
19
  kind: 'exact',
@@ -43,18 +43,38 @@ export function createForwardRoutes({ sendJson, readBody, forwards, store }) {
43
43
  targetHost: body.targetHost || '127.0.0.1',
44
44
  targetPort,
45
45
  autoStart: !!body.autoStart,
46
- machineId: store.currentId,
46
+ // Tag what the ACTIVE POOL is actually on (ephemeral included),
47
+ // not the registry's currentId: rw_connect(save:false) keeps
48
+ // currentId on the old machine while the pool talks to the new one.
49
+ machineId: typeof activeMachineId === 'function' ? activeMachineId() : store.currentId,
47
50
  })
48
51
  return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
49
52
  }
53
+ if (action === 'update') {
54
+ // Mutable fields of an existing definition — currently the 自动重连
55
+ // checkbox shown on each row. Requires an explicit boolean: a
56
+ // missing field must not silently flip the flag to false.
57
+ if (typeof body.autoStart !== 'boolean') {
58
+ return sendJson(res, 400, { ok: false, error: 'autoStart 必须是布尔值' })
59
+ }
60
+ const d = forwards.update(String(body.id || ''), { autoStart: body.autoStart })
61
+ if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() })
62
+ return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
63
+ }
50
64
  if (action === 'start' || action === 'stop') {
51
65
  const d = forwards.list().find((f) => f.id === body.id)
52
66
  if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found' })
53
67
  if (action === 'start') {
54
68
  const r = await forwards.start(d)
55
- if (!r.ok) return sendJson(res, 500, { ok: false, error: r.error })
69
+ // Always return the CURRENT list, even on failure: a start that
70
+ // lost a race but found the tunnel already listening (see
71
+ // ForwardManager.start) must let the UI leave 启动 instead of
72
+ // staying on a stale row until the next click.
73
+ if (!r.ok) return sendJson(res, 500, { ok: false, error: r.error, forwards: forwards.list() })
56
74
  } else {
57
- forwards.stop(d.id)
75
+ // A user stop is intentional: clear the persisted "was running"
76
+ // flag so 自动重连 does not bring it back on the next connect.
77
+ forwards.stop(d.id, { forget: true })
58
78
  }
59
79
  return sendJson(res, 200, { ok: true, forwards: forwards.list() })
60
80
  }
package/lib/routes-fs.js CHANGED
@@ -38,19 +38,19 @@ export function createFsRoutes({
38
38
  }
39
39
  }
40
40
 
41
- const checkExpectedRevision = (body, snapshot) => {
41
+ const checkExpectedRevision = (body, snapshot, local = false) => {
42
42
  if (body.expectedRevision != null) {
43
43
  if (typeof body.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(body.expectedRevision)) {
44
44
  throw Object.assign(new Error('expectedRevision must be a SHA-256 revision returned by a complete file preview'), { httpStatus: 400 })
45
45
  }
46
46
  if (!snapshot.stat || !snapshot.bytes || remoteRevision(snapshot.bytes) !== body.expectedRevision) {
47
- throw Object.assign(new Error('远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
47
+ throw Object.assign(new Error(local ? '本地文件已变化,已放弃保存。请重新读取并比较后重试。' : '远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
48
48
  }
49
49
  }
50
50
  if (body.expectedMtime != null) {
51
51
  if (!Number.isFinite(Number(body.expectedMtime))) throw Object.assign(new Error('expectedMtime must be a finite timestamp'), { httpStatus: 400 })
52
52
  if (!snapshot.stat || snapshot.stat.mtime !== Number(body.expectedMtime)) {
53
- throw Object.assign(new Error('远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
53
+ throw Object.assign(new Error(local ? '本地文件已变化,已放弃保存。请重新读取并比较后重试。' : '远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
54
54
  }
55
55
  }
56
56
  }
@@ -73,7 +73,7 @@ export function createFsRoutes({
73
73
  try { body = JSON.parse((await readBody(req)) || '{}') } catch { body = {} }
74
74
  }
75
75
  const hint = requestSessionHint(req, body)
76
- const b = await bindOrReply(req, res, hint)
76
+ const b = await bindOrReply(req, res, { ...body, ...hint })
77
77
  if (!b) return
78
78
  // Identity echo (external-switch defense): name the machine this
79
79
  // listing is answered for, straight from the pool's target — the
@@ -93,7 +93,7 @@ export function createFsRoutes({
93
93
  : (body.path ? String(body.path) : (b.ws || ''))
94
94
  const canon = normalizeRemotePath(raw)
95
95
  const win = b.pool.platform === 'windows'
96
- if (canon === '/' || raw === '' || raw === '/') {
96
+ if (!b.local && (canon === '/' || raw === '' || raw === '/')) {
97
97
  if (win || b.pool.platform !== 'posix') {
98
98
  const drives = await listRemoteDrives(b.pool)
99
99
  if (drives.length) return sendJson(res, 200, { path: '', platform: 'windows', items: drives, bound: b.bound, machine })
@@ -115,7 +115,7 @@ export function createFsRoutes({
115
115
  machine,
116
116
  })
117
117
  } catch (err) {
118
- return sendJson(res, 500, { error: String((err && err.message) || err) })
118
+ return sendJson(res, err.httpStatus || 500, { error: String((err && err.message) || err) })
119
119
  }
120
120
  },
121
121
  },
@@ -156,6 +156,7 @@ export function createFsRoutes({
156
156
  return sendJson(res, 200, preview)
157
157
  } catch (err) {
158
158
  if (missingRemoteFile(err)) {
159
+ if (b.local) return sendJson(res, 404, { ok: false, source: 'local', path: target, code: 'LOCAL_FILE_NOT_FOUND', error: '本地项目中不存在此文件。' })
159
160
  const localCopy = await localCopyInfo(b, target)
160
161
  return sendJson(res, 404, { ok: false, source: 'remote', path: target,
161
162
  code: localCopy ? 'REMOTE_FILE_MISSING_LOCAL_COPY' : 'REMOTE_FILE_NOT_FOUND',
@@ -163,7 +164,7 @@ export function createFsRoutes({
163
164
  ...(localCopy ? { localCopy } : {}),
164
165
  })
165
166
  }
166
- return sendJson(res, 500, { ok: false, error: 'read failed: ' + ((err && err.message) || err) })
167
+ return sendJson(res, err.httpStatus || 500, { ok: false, error: 'read failed: ' + ((err && err.message) || err) })
167
168
  }
168
169
  } catch (err) {
169
170
  return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
@@ -183,12 +184,12 @@ export function createFsRoutes({
183
184
  if (!b) return
184
185
  const sftp = await b.pool.sftp()
185
186
  const before = await captureRemoteFile(sftp, p, { read: body.expectedRevision != null, maxReadBytes: 2 * 1024 * 1024 })
186
- checkExpectedRevision(body, before)
187
+ checkExpectedRevision(body, before, b.local)
187
188
  const buf = encodeText(String(body.content ?? ''), body.encoding || config.encoding)
188
189
  if (!before.stat) await mkdirRemoteDirs(sftp, remoteDirname(p))
189
190
  await atomicRemoteWrite(sftp, before, buf)
190
- audit('write', `write ${p}`, 0, b)
191
- onRemoteMutation()
191
+ if (!b.local) audit('write', `write ${p}`, 0, b)
192
+ if (!b.local) onRemoteMutation()
192
193
  const st2 = await sftp.stat(p).catch(() => null)
193
194
  return sendJson(res, 200, { ok: true, bytes: buf.byteLength, mtime: st2 ? st2.mtime : Math.floor(Date.now() / 1000), revision: remoteRevision(buf) })
194
195
  } catch (err) {
@@ -206,13 +207,15 @@ export function createFsRoutes({
206
207
  const op = String(body.op || '')
207
208
  const b = await bindOrReply(req, res, body)
208
209
  if (!b) return
210
+ if (b.local && op === 'download') return sendJson(res, 400, { ok: false, error: 'Local files are already on this host; no mirror download is needed' })
209
211
  const sftp = await b.pool.sftp()
210
212
  if (op === 'mkdir') {
211
213
  const p = normalizeRemotePath(String(body.path || ''))
212
214
  if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
213
- await mkdirRemoteDirs(sftp, p)
214
- audit('mkdir', `mkdir ${p}`, 0, b)
215
- onRemoteMutation()
215
+ if (b.local) await b.pool.mkdirTree(p)
216
+ else await mkdirRemoteDirs(sftp, p)
217
+ if (!b.local) audit('mkdir', `mkdir ${p}`, 0, b)
218
+ if (!b.local) onRemoteMutation()
216
219
  return sendJson(res, 200, { ok: true })
217
220
  }
218
221
  if (op === 'rename') {
@@ -220,8 +223,8 @@ export function createFsRoutes({
220
223
  const d = normalizeRemotePath(String(body.dest || ''))
221
224
  if (!p || !d) return sendJson(res, 400, { ok: false, error: 'path and dest required' })
222
225
  await sftp.rename(p, d)
223
- audit('move', `move ${p} → ${d}`, 0, b)
224
- onRemoteMutation()
226
+ if (!b.local) audit('move', `move ${p} → ${d}`, 0, b)
227
+ if (!b.local) onRemoteMutation()
225
228
  return sendJson(res, 200, { ok: true })
226
229
  }
227
230
  if (op === 'remove') {
@@ -230,12 +233,13 @@ export function createFsRoutes({
230
233
  const st = await sftp.stat(p).catch(() => null)
231
234
  if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
232
235
  if (st.isDirectory && st.isDirectory()) {
233
- await removeRemoteTree(sftp, p)
236
+ if (b.local) await b.pool.removeTree(p)
237
+ else await removeRemoteTree(sftp, p)
234
238
  } else {
235
239
  await sftp.unlink(p)
236
240
  }
237
- audit('remove', `remove ${p}`, 0, b)
238
- onRemoteMutation()
241
+ if (!b.local) audit('remove', `remove ${p}`, 0, b)
242
+ if (!b.local) onRemoteMutation()
239
243
  return sendJson(res, 200, { ok: true })
240
244
  }
241
245
  if (op === 'write' || op === 'append') {
@@ -245,13 +249,13 @@ export function createFsRoutes({
245
249
  read: op === 'append' || body.expectedRevision != null,
246
250
  maxReadBytes: config.maxFileBytes > 0 ? Math.min(config.maxFileBytes, 2 * 1024 * 1024) : 2 * 1024 * 1024,
247
251
  })
248
- checkExpectedRevision(body, before)
252
+ checkExpectedRevision(body, before, b.local)
249
253
  const content = op === 'append' && before.bytes ? decodeBuf(before.bytes, body.encoding || config.encoding) : ''
250
254
  const buf = encodeText(content + String(body.content ?? ''), body.encoding || config.encoding)
251
255
  if (op === 'write' && !before.stat) await mkdirRemoteDirs(sftp, remoteDirname(p))
252
256
  await atomicRemoteWrite(sftp, before, buf)
253
- audit(op, `${op} ${p}`, 0, b)
254
- onRemoteMutation()
257
+ if (!b.local) audit(op, `${op} ${p}`, 0, b)
258
+ if (!b.local) onRemoteMutation()
255
259
  return sendJson(res, 200, { ok: true, bytes: buf.byteLength, revision: remoteRevision(buf) })
256
260
  }
257
261
  if (op === 'download') {
@@ -270,7 +274,7 @@ export function createFsRoutes({
270
274
  assertDownloadHasNoSymlinks(base, local)
271
275
  mkdirSync(path.dirname(local), { recursive: true })
272
276
  await sftp.fastGet(p, local)
273
- audit('download', `download ${p}`, 0, b)
277
+ if (!b.local) audit('download', `download ${p}`, 0, b)
274
278
  return sendJson(res, 200, { ok: true, bytes: st.size, local })
275
279
  }
276
280
  return sendJson(res, 400, { ok: false, error: 'unknown op' })
package/lib/self-heal.js CHANGED
@@ -17,10 +17,11 @@
17
17
  // self-contained). Any richer import could itself be the file that is missing,
18
18
  // and then the guard dies together with the guarded.
19
19
 
20
- import { readFileSync } from 'node:fs'
20
+ import { readFileSync, realpathSync } from 'node:fs'
21
21
  import path from 'node:path'
22
+ import { fileURLToPath } from 'node:url'
22
23
 
23
- import { applyUpdate, isInstalledCopy, diskVersion } from './update.js'
24
+ import { isInstalledCopy, diskVersion } from './update.js'
24
25
 
25
26
  /**
26
27
  * Whether `err` is the specific crash a half-applied update produces: Node
@@ -54,6 +55,13 @@ export function isMissingOwnModuleError(err) {
54
55
  * when options.dir is set, the version is read from THAT directory's
55
56
  * package.json rather than this package's own install dir.
56
57
  */
58
+ async function applyFreshUpdate(version, options) {
59
+ // A previous updater may already be in the ESM cache. Load the newly laid
60
+ // update.js with a fresh URL so repair never reuses that stale updater.
61
+ const { applyUpdate } = await import('./update.js?self-heal=' + Date.now())
62
+ return applyUpdate(version, options)
63
+ }
64
+
57
65
  export async function repairInstall(options = {}) {
58
66
  let version = diskVersion()
59
67
  if (options.dir) {
@@ -66,7 +74,7 @@ export async function repairInstall(options = {}) {
66
74
  if (!/^\d+\.\d+\.\d+/.test(version)) {
67
75
  throw new Error(`cannot self-repair: on-disk package.json version is unusable (${JSON.stringify(version)})`)
68
76
  }
69
- return applyUpdate(version, options)
77
+ return applyFreshUpdate(version, options)
70
78
  }
71
79
 
72
80
  /** Actionable suffix attached to every failure we hand back to the user. */
@@ -93,7 +101,7 @@ const REINSTALL_HINT = 'please reinstall the plugin once (e.g. `dsh plugin --pro
93
101
  * forwarded to applyUpdate; log defaults to console.warn.
94
102
  */
95
103
  export async function importWithSelfHeal(importer, options = {}) {
96
- const { log = console.warn, ...repairOpts } = options || {}
104
+ const { log = console.warn, retryImporter, ...repairOpts } = options || {}
97
105
  let firstErr
98
106
  try {
99
107
  return { module: await importer(), repaired: false }
@@ -119,7 +127,9 @@ export async function importWithSelfHeal(importer, options = {}) {
119
127
  log(`[dsh-remote] startup repair applied ${repairOutcome.changed?.length ?? 0} file(s); retrying the load`)
120
128
 
121
129
  try {
122
- return { module: await importer(), repaired: true }
130
+ // Node 22 can cache a failed ESM resolution. Retry with a fresh URL when
131
+ // the caller supplies one, rather than reusing the negative cache.
132
+ return { module: await (retryImporter || importer)(), repaired: true }
123
133
  } catch (secondErr) {
124
134
  const wrapped = new Error(
125
135
  `[dsh-remote] the install was re-laid from npm but loading still fails: ${(secondErr && secondErr.message) || secondErr}. ${REINSTALL_HINT}`,
@@ -128,3 +138,46 @@ export async function importWithSelfHeal(importer, options = {}) {
128
138
  throw wrapped
129
139
  }
130
140
  }
141
+
142
+
143
+ /**
144
+ * External repair entry point. It deliberately lives in this shallow module,
145
+ * not in index/main: a broken static dependency graph must not be needed to
146
+ * repair itself. `--dir` and `--tarball` are also useful for offline recovery
147
+ * and deterministic tests; normal users only need `node lib/self-heal.js`.
148
+ */
149
+ const cliFile = (value) => {
150
+ try { return realpathSync(value) } catch { return path.resolve(value) }
151
+ }
152
+ const isMainModule = process.argv[1] && (() => {
153
+ const actual = cliFile(process.argv[1])
154
+ const self = cliFile(fileURLToPath(import.meta.url))
155
+ return process.platform === 'win32' ? actual.toLowerCase() === self.toLowerCase() : actual === self
156
+ })()
157
+ if (isMainModule) {
158
+ const args = process.argv.slice(2)
159
+ const valueFor = (flag) => {
160
+ const i = args.indexOf(flag)
161
+ return i >= 0 && i + 1 < args.length ? args[i + 1] : ''
162
+ }
163
+ if (args.includes('--help') || args.includes('-h')) {
164
+ console.log('Usage: node lib/self-heal.js [--version x.y.z] [--dir <package dir>] [--tarball <local tgz>]')
165
+ } else {
166
+ const dir = valueFor('--dir') || undefined
167
+ const tarballPath = valueFor('--tarball') || undefined
168
+ const version = valueFor('--version')
169
+ try {
170
+ if (version && !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
171
+ throw new Error(`invalid version: ${JSON.stringify(version)}`)
172
+ }
173
+ const result = version
174
+ ? await applyFreshUpdate(version, { dir, tarballPath })
175
+ : await repairInstall({ dir, tarballPath })
176
+ console.log(`[dsh-remote] repair completed: ${result.to}, ${result.changed?.length ?? 0} file(s) changed. Restart DSH to load the repaired package.`)
177
+ } catch (error) {
178
+ console.error(`[dsh-remote] repair failed: ${(error && error.message) || error}`)
179
+ console.error(REINSTALL_HINT)
180
+ process.exitCode = 1
181
+ }
182
+ }
183
+ }
package/lib/sshconfig.js CHANGED
@@ -476,6 +476,10 @@ function targetFromResolved(resolved, text, { defaultPort }) {
476
476
  port: resolved.port || defaultPort,
477
477
  username: resolved.user || '',
478
478
  privateKeyPath: identityPath(resolved.identityFile, ctx),
479
+ // Preserve raw connection settings for client-side effective-config
480
+ // grouping; the normalized privateKeyPath/proxy above stays unchanged.
481
+ identityFile: resolved.identityFile,
482
+ proxyCommand: resolved.proxyCommand,
479
483
  agentSocket: identityAgentPath(resolved.identityAgent, ctx),
480
484
  identitiesOnly: /^yes$/i.test(resolved.identitiesOnly || ''),
481
485
  proxy,
@@ -583,6 +587,8 @@ export function resolveMachineSshConfig(machine, opts = {}) {
583
587
  port: Number(port) || 22,
584
588
  username: String(username || ''),
585
589
  privateKeyPath,
590
+ identityFile: target.identityFile,
591
+ proxyCommand: target.proxyCommand,
586
592
  agentSocket: target.agentSocket,
587
593
  identitiesOnly: target.identitiesOnly,
588
594
  proxy,
package/lib/telemetry.js CHANGED
@@ -22,8 +22,9 @@
22
22
  import { createHmac, randomUUID } from 'node:crypto'
23
23
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
24
24
  import path from 'node:path'
25
+ import { setTimeout as delay } from 'node:timers/promises'
25
26
 
26
- /** 上报端点(CloudBase HTTP 访问服务)。改域名只需改这一行。
27
+ /** 上报端点(Cloudflare Worker)。改域名只需改这一行。
27
28
  * 可用 `DSH_REMOTE_HEARTBEAT_URL` 覆盖——存在的理由不是"让用户改"
28
29
  * (默认行为不该需要配置),而是:① 测试必须能把它重定向掉,
29
30
  * 否则跑一次 npm test 就会往生产统计里灌假装机(发生过);
@@ -48,8 +49,8 @@ const TIMEOUT_MS = 15000
48
49
  /** 启动后延迟多久再发:避开启动高峰(插件树/路由/服务都在抢事件循环)。
49
50
  * 仍不 await——延迟是为了让心跳真的成功,不是为了让用户等待。 */
50
51
  const STARTUP_DELAY_MS = 3000
51
- /** 两次上报之间的最小间隔(同一天内重复启动不再上报)。 */
52
- const MIN_INTERVAL_MS = 6 * 60 * 60 * 1000
52
+ /** 每 15 分钟检查是否跨日或需要重试;成功后当天不再发送。 */
53
+ const CHECK_INTERVAL_MS = 15 * 60 * 1000
53
54
 
54
55
  /** 安装身份的进程内缓存,**按身份文件路径分键**。
55
56
  * ★ 不能只用一个全局变量:同一进程内出现第二个 DSH_HOME(隔离沙箱、
@@ -88,8 +89,11 @@ export function pseudonym(home) {
88
89
  return createHmac('sha256', SALT).update(installId(home)).digest('hex').slice(0, 32)
89
90
  }
90
91
 
91
- /** 是否到该上报了(进程内节流,避免每次工具调用都发)。 */
92
- let lastSentAt = 0
92
+ /** 与服务端一致,按北京时间分日;隔离不同 DSH_HOME 的节流和并发状态。 */
93
+ const reports = new Map()
94
+ function heartbeatDay() {
95
+ return new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString().slice(0, 10)
96
+ }
93
97
 
94
98
  /** 是否处于测试进程。
95
99
  *
@@ -119,21 +123,20 @@ export function inTestProcess() {
119
123
  * 且**不导出给业务代码**(导出名带下划线前缀,见文件末尾)。
120
124
  */
121
125
  async function deliver(home, version, options = {}) {
122
- const now = Date.now()
123
- if (now - lastSentAt < MIN_INTERVAL_MS) return false
124
-
125
- const delayMs = options.delayMs === undefined ? STARTUP_DELAY_MS : Math.max(0, options.delayMs)
126
- // 先占位,防止并发触发重复上报(本插件是单进程,够用)
127
- lastSentAt = now
126
+ const key = path.resolve(home)
127
+ const previous = reports.get(key)
128
+ if (previous?.pending || previous?.day === heartbeatDay()) return false
129
+ const allowed = () => !options.signal?.aborted && (!options.allowed || options.allowed())
130
+ const state = { pending: true }
131
+ reports.set(key, state)
128
132
  try {
129
- if (delayMs) await new Promise((r) => {
130
- // ★ 这里**不能 unref**。曾经 unref 过延迟定时器,结果是:await 一个已
131
- // unref 的定时器不会让事件循环保活,当进程恰好没有别的 pending 句柄时
132
- // Node 会**直接退出**,心跳一次都发不出去(CI 上稳定复现:本地因为其它
133
- // 测试还留着句柄而侥幸变绿)。延迟是为了让心跳成功,就必须让它把进程
134
- // 留住这几秒;插件真实运行时也不可能因为多等 3s 影响用户。
135
- setTimeout(r, delayMs)
136
- })
133
+ if (!allowed()) return false
134
+ const delayMs = options.delayMs === undefined ? STARTUP_DELAY_MS : Math.max(0, options.delayMs)
135
+ // 短启动延迟保活,卸载时可取消;周期检查本身不保持进程存活。
136
+ if (delayMs) await delay(delayMs, undefined, { signal: options.signal })
137
+ // 延迟期间用户可能已关闭统计或卸载插件,外呼前重新检查。
138
+ if (!allowed()) return false
139
+ const day = heartbeatDay()
137
140
  const body = JSON.stringify({
138
141
  idHash: pseudonym(home),
139
142
  version: String(version || '0.0.0'),
@@ -144,21 +147,25 @@ async function deliver(home, version, options = {}) {
144
147
  const controller = new AbortController()
145
148
  const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
146
149
  try {
147
- await fetch(heartbeatUrl(), {
150
+ const response = await fetch(heartbeatUrl(), {
148
151
  method: 'POST',
149
152
  headers: { 'content-type': 'application/json' },
150
153
  body,
151
- signal: controller.signal,
154
+ signal: options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal,
152
155
  })
156
+ if (!response.ok) return false
157
+ state.day = day
153
158
  } finally {
154
159
  clearTimeout(timer)
155
160
  }
156
161
  return true
157
162
  } catch {
158
163
  // 网络不可达 / 端点变更 / 被拦截:一律忽略。
159
- // 允许下次重试:回滚节流,避免一次失败就把身份静默六个小时。
160
- lastSentAt = 0
161
164
  return false
165
+ } finally {
166
+ state.pending = false
167
+ // 只有服务端确认成功才占用当天额度;失败由周期检查低频重试。
168
+ if (!state.day && reports.get(key) === state) reports.delete(key)
162
169
  }
163
170
  }
164
171
 
@@ -169,7 +176,7 @@ async function deliver(home, version, options = {}) {
169
176
  * @param version - 运行中的插件版本(用 LOADED_VERSION,即真正在跑的代码版本)。
170
177
  * @param options.delayMs - 发送前延迟(默认 {@link STARTUP_DELAY_MS});
171
178
  * 避开启动高峰。测试可传 0。
172
- * @returns 是否真的发出了请求(仅用于测试与自检)。
179
+ * @returns 是否收到成功响应(仅用于测试与自检)。
173
180
  */
174
181
  export async function sendHeartbeat(home, version, options = {}) {
175
182
  // 测试进程一律不外呼:统计数据的可信度比"测试里能验证外呼"重要得多。
@@ -177,9 +184,38 @@ export async function sendHeartbeat(home, version, options = {}) {
177
184
  return deliver(home, version, options)
178
185
  }
179
186
 
187
+ /** 注册启动和运行期间的安装心跳;返回卸载清理函数。后台运行也属于本口径。 */
188
+ function heartbeatLoop(home, version, { allowed = () => true, send = sendHeartbeat } = {}) {
189
+ const controller = new AbortController()
190
+ let stopped = false
191
+ const tick = async (startup = false) => {
192
+ try {
193
+ if (stopped || !allowed()) return
194
+ await send(home, version, {
195
+ delayMs: startup ? STARTUP_DELAY_MS : 0,
196
+ allowed: () => !stopped && allowed(),
197
+ signal: controller.signal,
198
+ })
199
+ } catch { /* 旁路故障永不影响宿主,也不产生未处理的 rejection。 */ }
200
+ }
201
+ void tick(true)
202
+ const timer = setInterval(() => { void tick() }, CHECK_INTERVAL_MS)
203
+ timer.unref?.()
204
+ return () => {
205
+ stopped = true
206
+ clearInterval(timer)
207
+ controller.abort()
208
+ }
209
+ }
210
+
211
+ export function startHeartbeat(home, version, options) {
212
+ if (inTestProcess()) return () => {}
213
+ return heartbeatLoop(home, version, options)
214
+ }
215
+
180
216
  /** 清空节流与缓存(仅测试用)。 */
181
217
  export function _resetForTest() {
182
- lastSentAt = 0
218
+ reports.clear()
183
219
  idCache.clear()
184
220
  }
185
221
 
@@ -245,3 +281,6 @@ export function installIdPath(home) {
245
281
  * 而不是来自这个函数——它只是把守卫那道门打开给测试用。
246
282
  */
247
283
  export const _deliverForTest = deliver
284
+
285
+ // 测试注入发送函数,验证生命周期时不访问生产端点。
286
+ export const _startHeartbeatLoopForTest = heartbeatLoop