dsh-remote 1.3.0 → 1.4.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.
package/lib/openssh.js CHANGED
@@ -62,6 +62,7 @@ import { EventEmitter } from 'node:events'
62
62
  import { homedir, tmpdir } from 'node:os'
63
63
  import path from 'node:path'
64
64
  import { Duplex } from 'node:stream'
65
+ import { setTimeout as delay } from 'node:timers/promises'
65
66
  import { buildSftpSurface } from './sftp-surface.js'
66
67
  import { truncate } from './paths.js'
67
68
 
@@ -226,6 +227,74 @@ export function sshBinaryAvailable(binary) {
226
227
  return false
227
228
  }
228
229
 
230
+ /** Backoff between the two connect attempts (issue #188).
231
+ *
232
+ * Short on purpose: the failure being retried is a dropped SYN / unanswered
233
+ * dial, not a slow host, and a caller's read budget is usually far shorter than
234
+ * the 15s connect timeout. A re-dial after this kind of failure was measured at
235
+ * ~700ms, so 400ms of backoff is enough to land on a different path without
236
+ * making the user wait twice for nothing.
237
+ */
238
+ export const CONNECT_RETRY_DELAY_MS = 400
239
+
240
+
241
+ // Connect-stage failures that are DETERMINISTIC, so a second dial only doubles
242
+ // the wait the user stares at. Checked BEFORE the transient list: OpenSSH
243
+ // prefixes several of these with "Connection closed by ...", which would
244
+ // otherwise look retryable.
245
+ const NON_TRANSIENT_CONNECT_PATTERNS = [
246
+ /permission denied/i,
247
+ /too many authentication failures/i,
248
+ /no supported authentication/i,
249
+ /host key verification failed/i,
250
+ /remote host identification has changed/i,
251
+ /could not resolve hostname/i,
252
+ /name or service not known/i,
253
+ /connection refused/i,
254
+ /no route to host/i,
255
+ /network is unreachable/i,
256
+ /no matching (?:key exchange|host key|ciphers|mac)/i,
257
+ ]
258
+
259
+ // Connect-stage failures that are TRANSIENT: the dial or the pre-auth banner
260
+ // exchange was dropped, and the very next attempt usually succeeds.
261
+ const TRANSIENT_CONNECT_PATTERNS = [
262
+ /connection timed out/i,
263
+ /operation timed out/i,
264
+ /connection reset by peer/i,
265
+ // OpenSSH prints an address here, not the word "host":
266
+ // Connection closed by 10.0.0.1 port 22
267
+ /connection closed by /i,
268
+ /kex_exchange_identification/i,
269
+ /connection lost/i,
270
+ ]
271
+
272
+ /**
273
+ * Was this failed connect probe a transient, worth-retrying dial failure?
274
+ *
275
+ * Issue #188: on a corporate link ~6% of fresh openssh connects died with
276
+ * `Connection timed out` after the full 15s `ConnectTimeout`, and an immediate
277
+ * re-dial succeeded in ~700ms every time. The native backend has retried the
278
+ * equivalent case (`SSH_HANDSHAKE_CLOSED`) since #185; this is the same
279
+ * contract for the `ssh` CLI backend.
280
+ *
281
+ * Only the CONNECT stage is classified here. The probe is a bare
282
+ * `ssh -- <host> true`, so nothing authenticated is ever replayed, and host-key
283
+ * / handshake policy is untouched — the retry spawns the identical argv.
284
+ *
285
+ * @param {{code: number|null, signal: string|null, stderr: string}} probe
286
+ * @returns {boolean}
287
+ */
288
+ export function transientConnectFailure(probe) {
289
+ if (!probe) return false
290
+ // Our own timer fired: the host never answered within the connect budget.
291
+ if (probe.signal === 'TIMEOUT') return true
292
+ const text = String(probe.stderr || '')
293
+ if (!text) return false
294
+ if (NON_TRANSIENT_CONNECT_PATTERNS.some((re) => re.test(text))) return false
295
+ return TRANSIENT_CONNECT_PATTERNS.some((re) => re.test(text))
296
+ }
297
+
229
298
  /**
230
299
  * Options shared by every `ssh` invocation for this target.
231
300
  *
@@ -579,13 +648,54 @@ export class SystemOpenSshPool {
579
648
  if (this.client) return Promise.resolve(this.client)
580
649
  if (this.connecting) return this.connecting
581
650
  const epoch = this.epoch
582
- const pending = this._doConnect(epoch)
651
+ const pending = this._connectWithRetry(epoch)
583
652
  this.connecting = pending
584
653
  const clear = () => { if (this.epoch === epoch && this.connecting === pending) this.connecting = null }
585
654
  pending.then(clear, clear)
586
655
  return pending
587
656
  }
588
657
 
658
+ /**
659
+ * Dial, and on a TRANSIENT connect failure dial ONCE more (issue #188).
660
+ *
661
+ * The retry is shared by every concurrent caller because `connect()` memoizes
662
+ * this promise: N simultaneous reads of a dropped link cost exactly one extra
663
+ * dial, not N. Nothing authenticated is replayed — `_doConnect` only runs the
664
+ * `ssh -- <host> true` probe, and the retry spawns the identical argv, so the
665
+ * host-key and handshake policy of the first attempt still applies.
666
+ *
667
+ * A deterministic failure (bad credentials, changed host key, DNS, refused,
668
+ * unreachable) is NOT tagged transient by `transientConnectFailure`, so it
669
+ * surfaces on the first attempt with no extra wait.
670
+ */
671
+ async _connectWithRetry(epoch) {
672
+ const firstStarted = Date.now()
673
+ try {
674
+ return await this._doConnect(epoch)
675
+ } catch (error) {
676
+ if (!error || error.code !== 'SSH_CONNECT_TRANSIENT' || this.epoch !== epoch) throw error
677
+ const firstMs = Date.now() - firstStarted
678
+ await delay(CONNECT_RETRY_DELAY_MS)
679
+ if (this.epoch !== epoch) throw new Error('ssh target changed during connect retry')
680
+ const retryStarted = Date.now()
681
+ try {
682
+ return await this._doConnect(epoch)
683
+ } catch (retryError) {
684
+ const retryMs = Date.now() - retryStarted
685
+ // Both dials failed. Say so explicitly, with BOTH durations: from a
686
+ // single timeout "flaky link" and "host is down" are indistinguishable,
687
+ // and the user's next move differs (retry later vs. check the host).
688
+ const wrapped = new Error(
689
+ String((retryError && retryError.message) || retryError)
690
+ + ` (connect retried once: first attempt ${firstMs}ms, retry ${retryMs}ms)`,
691
+ )
692
+ wrapped.code = retryError && retryError.code
693
+ wrapped.cause = retryError
694
+ throw wrapped
695
+ }
696
+ }
697
+ }
698
+
589
699
  async _doConnect(epoch) {
590
700
  const isCurrent = () => this.epoch === epoch
591
701
  const sshBinary = resolveSshBinary(this.config)
@@ -607,10 +717,14 @@ export class SystemOpenSshPool {
607
717
  // dsh-remote-fix3: _runSsh reports its own timer as code -1 / signal
608
718
  // TIMEOUT with empty stderr, so the old message degraded to a bare
609
719
  // `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
- }
613
- throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
720
+ const stderrText = String(probe.stderr || '').trim()
721
+ const failure = probe.signal === 'TIMEOUT'
722
+ ? 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)`)
723
+ : new Error(`ssh failed (exit ${probe.code})${stderrText ? ': ' + stderrText : ''}`)
724
+ // Issue #188: tag the retryable class HERE, where the probe result is
725
+ // known, so the retry decision never has to sniff a message at a distance.
726
+ if (transientConnectFailure(probe)) failure.code = 'SSH_CONNECT_TRANSIENT'
727
+ throw failure
614
728
  }
615
729
  void secret
616
730
  const conn = new OpenSshConnection(this, { sshBinary, secret })
package/lib/pool.js CHANGED
@@ -7,6 +7,7 @@ import { truncate } from './paths.js'
7
7
  import { createHostKeyGuard } from './hostkey.js'
8
8
  import { buildSftpSurface } from './sftp-surface.js'
9
9
  import { friendlyMessage } from './errors.js'
10
+ import { setTimeout as delay } from 'node:timers/promises'
10
11
  import { SystemOpenSshPool, isSystemOpenSshBackend } from './openssh.js'
11
12
 
12
13
  const { Client } = ssh2
@@ -323,7 +324,7 @@ export class SshPool {
323
324
  if (this.client) return Promise.resolve(this.client)
324
325
  if (this.connecting) return this.connecting
325
326
  const epoch = this.epoch
326
- const pending = this._doConnect(epoch)
327
+ const pending = this._connectWithRetry(epoch)
327
328
  this.connecting = pending
328
329
  const clear = () => {
329
330
  if (this.epoch === epoch && this.connecting === pending) this.connecting = null
@@ -332,22 +333,48 @@ export class SshPool {
332
333
  return pending
333
334
  }
334
335
 
336
+ async _connectWithRetry(epoch) {
337
+ try { return await this._doConnect(epoch) }
338
+ catch (error) {
339
+ if (error.code !== 'SSH_HANDSHAKE_CLOSED' || this.epoch !== epoch) throw error
340
+ // MaxStartups / middlebox resets may be transient. Share ONE bounded
341
+ // retry across all callers; never replay an authenticated command.
342
+ await delay(350)
343
+ if (this.epoch !== epoch) throw new Error('ssh target changed during handshake retry')
344
+ return this._doConnect(epoch)
345
+ }
346
+ }
347
+
335
348
  async _doConnect(epoch) {
336
349
  const isCurrent = () => this.epoch === epoch
350
+ const target = { host: this.config.host, port: this.config.port }
337
351
  const knownHostsFile = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
338
352
  const guard = createHostKeyGuard(this.config, knownHostsFile)
339
353
  const client = new Client()
340
- let settled = false
354
+ this._connectingClient = client
355
+ let settled = false, handshakeCompleted = false
356
+ client.on('handshake', () => { handshakeCompleted = true })
341
357
  // Every connect-stage failure is classified HERE, at the layer that knows
342
358
  // which machine was being dialed: a bare ssh2 errno ("Timed out while
343
359
  // waiting for handshake") names no host, and on a multi-machine plugin the
344
360
  // user cannot tell WHICH box failed. friendlyMessage is idempotent, so
345
361
  // callers that classify again (rw_connect, routes) do not double-wrap.
346
- const classify = (err) => new Error(friendlyMessage(err, { host: this.config.host, port: this.config.port }))
362
+ const classify = (err) => {
363
+ const error = new Error(friendlyMessage(err, target))
364
+ error.cause = err
365
+ if (!handshakeCompleted && /^(?:Connection lost before handshake|ssh connection closed|read ECONNRESET)$/i.test(String(err.message || err))) error.code = 'SSH_HANDSHAKE_CLOSED'
366
+ return error
367
+ }
347
368
  const fail = (err) => {
348
369
  if (settled) return
349
370
  settled = true
350
371
  if (isCurrent() && this.client === client) this.client = null
372
+ if (this._connectingClient === client) this._connectingClient = null
373
+ try { client.destroy() } catch {}
374
+ if (isCurrent() && this.proxyPool) {
375
+ try { this.proxyPool.close() } catch {}
376
+ this.proxyPool = null
377
+ }
351
378
  throw classify(guard.lastError ? new Error(guard.lastError) : err)
352
379
  }
353
380
 
@@ -408,9 +435,17 @@ export class SshPool {
408
435
  if (settled) return
409
436
  settled = true
410
437
  if (isCurrent() && this.client === client) this.client = null
411
- reject(classify(guard.lastError ? new Error(guard.lastError) : err))
438
+ if (this._connectingClient === client) this._connectingClient = null
439
+ const failure = classify(guard.lastError ? new Error(guard.lastError) : err)
440
+ if (isCurrent() && this.proxyPool) {
441
+ try { this.proxyPool.close() } catch {}
442
+ this.proxyPool = null
443
+ }
444
+ try { client.destroy() } catch {}
445
+ reject(failure)
412
446
  }
413
447
  client.on('ready', () => {
448
+ if (this._connectingClient === client) this._connectingClient = null
414
449
  if (settled) return
415
450
  settled = true
416
451
  if (!isCurrent()) {
@@ -521,6 +556,7 @@ export class SshPool {
521
556
  // Convert it into a normal rejection so every caller's try/catch —
522
557
  // boot restore, test-connect, rw_connect — sees a regular failure.
523
558
  try {
559
+ if (!isCurrent() || settled) throw new Error('ssh target changed during connect')
524
560
  client.connect(opts)
525
561
  } catch (err) {
526
562
  rejectOnce(err)
@@ -982,6 +1018,9 @@ export class SshPool {
982
1018
  const client = this.client
983
1019
  this.client = null
984
1020
  this._dropSftpSession()
1021
+ const pendingClient = this._connectingClient
1022
+ this._connectingClient = null
1023
+ if (pendingClient) { try { pendingClient.destroy() } catch {} }
985
1024
  const pending = this.connecting
986
1025
  this.connecting = null
987
1026
  if (pending && typeof pending.catch === 'function') {
@@ -1008,6 +1047,9 @@ export class SshPool {
1008
1047
  const client = this.client
1009
1048
  this.client = null
1010
1049
  this._dropSftpSession()
1050
+ const pendingClient = this._connectingClient
1051
+ this._connectingClient = null
1052
+ if (pendingClient) { try { pendingClient.destroy() } catch {} }
1011
1053
  const pending = this.connecting
1012
1054
  this.connecting = null
1013
1055
  if (pending && typeof pending.catch === 'function') {
package/lib/update.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // files with the newer npm tarball. This module owns the version check and the
6
6
  // tarball apply:
7
7
  //
8
- // • checkLatestVersion() — query the npm registry for the `latest` dist-tag;
8
+ // • fetchLatestVersion() — query npm latest, falling back to an official stable GitHub release;
9
9
  // • applyUpdate() — download the tarball, extract package/{lib,package.json,
10
10
  // cordis.patch.yml} with a minimal tar reader, verify the version, then
11
11
  // replace the installed files atomically (temp file + rename, never a
@@ -27,6 +27,122 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameS
27
27
  import { createRequire } from 'node:module'
28
28
  import path from 'node:path'
29
29
  import { fileURLToPath, pathToFileURL } from 'node:url'
30
+ import http from 'node:http'
31
+ import https from 'node:https'
32
+ import tls from 'node:tls'
33
+ import { gunzipSync, inflateSync, brotliDecompressSync } from 'node:zlib'
34
+ // Update-only proxy support uses builtins so partial-install self-healing
35
+ // never needs to import an unavailable package or missing sibling module.
36
+ const CAP = 32 * 1024 * 1024
37
+
38
+ export function updateProxyFor(url, env = process.env) {
39
+ const target = new URL(url)
40
+ const bypass = env.no_proxy ?? env.NO_PROXY ?? ''
41
+ const host = target.hostname.toLowerCase()
42
+ for (const item of bypass.split(',').map(s => s.trim().toLowerCase()).filter(Boolean)) {
43
+ if (item === '*') return ''
44
+ const match = /^(.*?)(?::(\d+))?$/.exec(item)
45
+ if (match[2] && match[2] !== (target.port || '443')) continue
46
+ const domain = match[1].replace(/^\*?\./, '')
47
+ if (host === domain || host.endsWith('.' + domain)) return ''
48
+ }
49
+ return env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY || ''
50
+ }
51
+
52
+ export async function requestThroughProxy(url, options, proxyUrl) {
53
+ const target = new URL(url), proxy = new URL(proxyUrl)
54
+ if (target.protocol !== 'https:' || !['http:', 'https:'].includes(proxy.protocol)) throw new Error('Update HTTPS proxy must use http:// or https://')
55
+ if (options.signal?.aborted) throw new DOMException('Update request aborted', 'AbortError')
56
+ return new Promise((resolve, reject) => {
57
+ let socket, secure, request, agent, done = false
58
+ const cleanup = () => { options.signal?.removeEventListener('abort', abort); agent?.destroy(); request?.destroy(); secure?.destroy(); socket?.destroy(); tunnel.destroy() }
59
+ const fail = error => { if (done) return; done = true; cleanup(); reject(error) }
60
+ const abort = () => fail(new DOMException('Update request aborted', 'AbortError'))
61
+ const headers = { host: target.host }
62
+ if (proxy.username || proxy.password) headers['proxy-authorization'] = 'Basic ' + Buffer.from(decodeURIComponent(proxy.username) + ':' + decodeURIComponent(proxy.password)).toString('base64')
63
+ const transport = proxy.protocol === 'https:' ? https : http
64
+ const tunnel = transport.request({ hostname: proxy.hostname, port: proxy.port || (proxy.protocol === 'https:' ? 443 : 80), method: 'CONNECT', path: target.host.includes(':') ? target.host : target.host + ':443', headers })
65
+ tunnel.on('error', fail)
66
+ tunnel.on('connect', (response, connected, head) => {
67
+ socket = connected
68
+ if (response.statusCode !== 200) { fail(Object.assign(new Error('HTTPS proxy CONNECT returned HTTP ' + response.statusCode), { code: 'PROXY_HTTP_' + response.statusCode })); return }
69
+ if (head.length) socket.unshift(head)
70
+ secure = tls.connect({ socket, servername: target.hostname, ...(options.ca ? { ca: options.ca } : {}) })
71
+ secure.on('error', fail)
72
+ secure.once('secureConnect', () => {
73
+ agent = new https.Agent({ keepAlive: false }); agent.createConnection = () => secure
74
+ request = https.request(target, { method: options.method || 'GET', headers: options.headers, agent }, response => {
75
+ const chunks = []; let size = 0
76
+ response.on('error', fail)
77
+ response.on('aborted', () => fail(new Error('Update response interrupted')))
78
+ response.on('data', chunk => { size += chunk.length; if (size > CAP) fail(new Error('Update response exceeds size limit')); else chunks.push(chunk) })
79
+ response.on('end', () => {
80
+ if (done) return
81
+ try {
82
+ let bytes = Buffer.concat(chunks)
83
+ const encoding = response.headers['content-encoding']
84
+ if (encoding === 'gzip') bytes = gunzipSync(bytes, { maxOutputLength: CAP })
85
+ else if (encoding === 'deflate') bytes = inflateSync(bytes, { maxOutputLength: CAP })
86
+ else if (encoding === 'br') bytes = brotliDecompressSync(bytes, { maxOutputLength: CAP })
87
+ done = true; cleanup()
88
+ resolve({ ok: response.statusCode >= 200 && response.statusCode < 300, status: response.statusCode, headers: new Headers(response.headers), json: async () => JSON.parse(bytes.toString('utf8')), arrayBuffer: async () => bytes })
89
+ } catch (error) { fail(error) }
90
+ })
91
+ })
92
+ request.on('error', fail); request.end()
93
+ })
94
+ })
95
+ options.signal?.addEventListener('abort', abort, { once: true })
96
+ if (options.signal?.aborted) abort(); else tunnel.end()
97
+ })
98
+ }
99
+
100
+ export async function fetchUpdate(url, options = {}, hops = 0) {
101
+ const proxy = updateProxyFor(url)
102
+ // Unit tests retain their injected global fetch and never contact production.
103
+ if (!proxy || process.env.NODE_TEST_CONTEXT) return fetch(url, options)
104
+ const response = await requestThroughProxy(url, options, proxy)
105
+ if ([301, 302, 303, 307, 308].includes(response.status) && response.headers.get('location')) {
106
+ if (hops >= 5) throw new Error('Too many update redirects')
107
+ const next = new URL(response.headers.get('location'), url)
108
+ if (next.protocol !== 'https:') throw new Error('Update redirect must retain HTTPS')
109
+ const headers = new Headers(options.headers)
110
+ if (next.origin !== new URL(url).origin) { headers.delete('authorization'); headers.delete('cookie') }
111
+ return fetchUpdate(next.href, { ...options, headers: Object.fromEntries(headers) }, hops + 1)
112
+ }
113
+ return response
114
+ }
115
+
116
+ // Official release fallback only. Never install an unchecked mirror response.
117
+ const REPO = 'https://api.github.com/repos/flymysql/dsh-remote/releases/'
118
+ export const stableVersion = value => typeof value === 'string' && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)
119
+ export async function fetchRelease(version, fetchImpl = fetchUpdate, timeoutMs = 8000) {
120
+ if (version !== undefined && !stableVersion(version)) throw new Error('Invalid stable release version')
121
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs)
122
+ timer.unref?.()
123
+ try {
124
+ const response = await fetchImpl(REPO + (version ? 'tags/v' + version : 'latest'), { signal: controller.signal, headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-remote-updater' } })
125
+ if (!response.ok) throw new Error('GitHub Release HTTP ' + response.status)
126
+ const release = await response.json()
127
+ const found = String(release?.tag_name || '').replace(/^v/, '')
128
+ if (!stableVersion(found) || version && found !== version || release.draft !== false || release.prerelease !== false) throw new Error('GitHub Release is not the requested stable release')
129
+ const filename = 'dsh-remote-' + found + '.tgz'
130
+ const asset = release.assets?.find(a => a.name === filename && a.state === 'uploaded')
131
+ if (!asset || !/^sha256:[a-f0-9]{64}$/i.test(asset.digest || '') || !Number.isFinite(asset.size) || asset.size <= 0 || asset.size > 32 * 1024 * 1024) throw new Error('GitHub Release has no verified installation archive')
132
+ return { version: found, source: 'github', url: 'https://github.com/flymysql/dsh-remote/releases/download/v' + found + '/' + filename, integrity: 'sha256-' + Buffer.from(asset.digest.slice(7), 'hex').toString('base64') }
133
+ } finally { clearTimeout(timer) }
134
+ }
135
+
136
+ export async function downloadReleaseBytes(url, fetchImpl = fetchUpdate, timeoutMs = 60000) {
137
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs)
138
+ try {
139
+ const response = await fetchImpl(url, { signal: controller.signal })
140
+ if (!response.ok) throw new Error('download failed (HTTP ' + response.status + ')')
141
+ const bytes = Buffer.from(await response.arrayBuffer())
142
+ if (bytes.length > 32 * 1024 * 1024) throw new Error('Update archive exceeds size limit')
143
+ return bytes
144
+ } finally { clearTimeout(timer) }
145
+ }
30
146
 
31
147
  const NPM_PACKAGE = 'dsh-remote'
32
148
  const REGISTRY_URL = 'https://registry.npmjs.org/' + NPM_PACKAGE + '/latest'
@@ -109,7 +225,7 @@ export function gtVersion(a, b) {
109
225
  * 三者的处置完全不同,必须让用户看到真实原因。
110
226
  * @param timeoutMs - 超时(看门狗只负责中止,不影响进程存活)。
111
227
  */
112
- export async function fetchLatestVersion(timeoutMs = 8000) {
228
+ async function fetchNpmLatestVersion(timeoutMs = 8000, fetchImpl = fetchUpdate) {
113
229
  try {
114
230
  const controller = new AbortController()
115
231
  const timer = setTimeout(() => controller.abort(), timeoutMs)
@@ -118,29 +234,40 @@ export async function fetchLatestVersion(timeoutMs = 8000) {
118
234
  if (typeof timer.unref === 'function') timer.unref()
119
235
  let res
120
236
  try {
121
- res = await fetch(REGISTRY_URL, { signal: controller.signal, headers: { accept: 'application/json' } })
122
- } finally {
123
- clearTimeout(timer)
124
- }
125
- if (res.status === 429) {
126
- return { error: 'npm registry 限流(HTTP 429)——请求过于频繁,稍后会自动恢复', reason: 'rate-limited', status: 429 }
127
- }
128
- if (!res.ok) {
129
- return { error: `npm registry 返回 HTTP ${res.status}`, reason: 'http', status: res.status }
130
- }
131
- const data = await res.json().catch(() => null)
132
- const version = typeof data?.version === 'string' && data.version ? data.version : null
133
- if (!version) return { error: 'npm registry 响应里没有可用的版本号', reason: 'malformed' }
134
- return { version }
237
+ res = await fetchImpl(REGISTRY_URL, { signal: controller.signal, headers: { accept: 'application/json' } })
238
+ if (res.status === 429) {
239
+ return { error: 'npm registry 限流(HTTP 429)——请求过于频繁,稍后会自动恢复', reason: 'rate-limited', status: 429 }
240
+ }
241
+ if (!res.ok) {
242
+ return { error: `npm registry 返回 HTTP ${res.status}`, reason: 'http', status: res.status }
243
+ }
244
+ const data = await res.json().catch(error => { if (error?.name === 'AbortError') throw error; return null })
245
+ const version = stableVersion(data?.version) ? data.version : null
246
+ if (!version) return { error: 'npm registry 响应里没有可用的版本号', reason: 'malformed' }
247
+ return { version }
248
+ } finally { clearTimeout(timer) }
135
249
  } catch (err) {
136
250
  const aborted = err?.name === 'AbortError'
137
251
  return {
138
252
  error: aborted ? `连接 npm registry 超时(${timeoutMs}ms)` : '无法连接 npm registry',
139
253
  reason: aborted ? 'timeout' : 'network',
254
+ ...((err?.cause?.code || err?.code) ? { networkCode: String(err.cause?.code || err.code) } : {}),
140
255
  }
141
256
  }
142
257
  }
143
258
 
259
+ /** npm preferred; a registry outage does not disable official GitHub releases. */
260
+ export async function fetchLatestVersion(timeoutMs = 8000, { fetchImpl = fetchUpdate } = {}) {
261
+ const primary = await fetchNpmLatestVersion(timeoutMs, fetchImpl)
262
+ if (!primary.error) return primary
263
+ try {
264
+ const release = await fetchRelease(undefined, fetchImpl, timeoutMs)
265
+ return { version: release.version, source: release.source }
266
+ } catch (error) {
267
+ return { ...primary, error: primary.error + (primary.networkCode ? '(' + primary.networkCode + ')' : '') + ';GitHub 备用来源也不可用', fallbackError: String(error.message || error) }
268
+ }
269
+ }
270
+
144
271
  /**
145
272
  * Fetch the npm metadata for one exact published version and return its
146
273
  * `dist.integrity` (issue #169) — the SRI string the registry itself computed
@@ -152,7 +279,7 @@ export async function fetchLatestVersion(timeoutMs = 8000) {
152
279
  * @param {number} [timeoutMs] - watchdog budget; the caller does not await the timer.
153
280
  * @returns {Promise<string>} the SRI string ("sha512-…").
154
281
  */
155
- export async function fetchDistIntegrity(version, fetchImpl = fetch, timeoutMs = 15000) {
282
+ export async function fetchDistIntegrity(version, fetchImpl = fetchUpdate, timeoutMs = 15000) {
156
283
  const controller = new AbortController()
157
284
  const timer = setTimeout(() => controller.abort(), timeoutMs)
158
285
  if (typeof timer.unref === 'function') timer.unref()
@@ -162,7 +289,7 @@ export async function fetchDistIntegrity(version, fetchImpl = fetch, timeoutMs =
162
289
  headers: { accept: 'application/vnd.npm.install-v1+json' },
163
290
  })
164
291
  if (!res.ok) throw new Error(`registry metadata returned HTTP ${res.status}`)
165
- const data = await res.json().catch(() => null)
292
+ const data = await res.json().catch(error => { if (error?.name === 'AbortError') throw error; return null })
166
293
  const integrity = data?.dist?.integrity
167
294
  if (typeof integrity !== 'string' || !/^(sha512|sha256)-[A-Za-z0-9+/=]+$/.test(integrity)) {
168
295
  throw new Error('registry metadata carries no usable dist.integrity')
@@ -223,7 +350,7 @@ export async function applyUpdate(targetVersion, options = {}) {
223
350
  }
224
351
  const tarballUrl = `https://registry.npmjs.org/${NPM_PACKAGE}/-/${NPM_PACKAGE}-${targetVersion}.tgz`
225
352
  const dir = path.resolve(options.dir || selfDir())
226
- const doFetch = options.fetchImpl || fetch
353
+ const doFetch = options.fetchImpl || fetchUpdate
227
354
  const writeAtomic = options.writeFileAtomic || writeFileAtomic
228
355
  const restoreFile = options.restoreFile || copyFileSync
229
356
  const tmpRoot = path.join(dir, `.dsh-remote-update-${Date.now()}`)
@@ -235,23 +362,25 @@ export async function applyUpdate(targetVersion, options = {}) {
235
362
  // Offline repair must not contact the registry at all.
236
363
  buf = readFileSync(options.tarballPath)
237
364
  } else {
238
- // Supply-chain root (#169): take the registry's own dist.integrity for
239
- // this exact version FIRST — an unknown or garbage version fails here
240
- // without downloading anything, and the downloaded bytes must match it
241
- // before a single byte is extracted. The version check further below
242
- // reads the tarball's own package.json, which an attacker-controlled
243
- // response can simply echo back; only this hash is external.
244
- const integrity = options.integrity ?? await fetchDistIntegrity(targetVersion, doFetch)
245
- const controller = new AbortController()
246
- const timer = setTimeout(() => controller.abort(), 60000)
247
- let res
365
+ if (!stableVersion(targetVersion)) throw new Error('Invalid stable update version')
366
+ let integrity, registryFailure
248
367
  try {
249
- res = await doFetch(tarballUrl, { signal: controller.signal })
250
- } finally {
251
- clearTimeout(timer)
368
+ integrity = options.integrity ?? await fetchDistIntegrity(targetVersion, doFetch)
369
+ buf = await downloadReleaseBytes(tarballUrl, doFetch)
370
+ } catch (error) { registryFailure = error }
371
+ if (registryFailure) {
372
+ // A malformed integrity response is not a connectivity failure: do not
373
+ // turn a failed trust check into a less strict installation path.
374
+ if (/no usable dist\.integrity|unsupported dist\.integrity/i.test(registryFailure.message)) throw registryFailure
375
+ try {
376
+ const release = await fetchRelease(targetVersion, doFetch)
377
+ integrity = release.integrity
378
+ buf = await downloadReleaseBytes(release.url, doFetch)
379
+ } catch (fallback) {
380
+ throw new Error(String(registryFailure.message) + '; GitHub fallback failed: ' + String(fallback.message))
381
+ }
252
382
  }
253
- if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
254
- buf = Buffer.from(await res.arrayBuffer())
383
+ // Hash mismatches never trigger source switching and never touch files.
255
384
  assertIntegrity(buf, integrity)
256
385
  }
257
386
  // npm tarballs are gzipped tar; extract the package/ directory.