dsh-remote 1.2.0 → 1.3.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/README.en.md +11 -3
- package/README.md +11 -3
- package/lib/binding.js +112 -28
- package/lib/boot.js +4 -31
- package/lib/client.js +807 -197
- package/lib/connect-summary.js +52 -0
- package/lib/forwards.js +297 -35
- package/lib/index.js +20 -4615
- package/lib/main.js +4693 -0
- package/lib/mirror-paths.js +17 -0
- package/lib/openssh.js +59 -8
- package/lib/registry.js +6 -1
- package/lib/routes-forwards.js +95 -4
- package/lib/self-heal.js +58 -5
- package/lib/sshconfig.js +6 -0
- package/lib/update.js +150 -33
- package/lib/vendor/jsdiff/SOURCE.md +1 -1
- package/lib/vendor/jsdiff/diff/base.js +1 -1
- package/lib/vendor/jsdiff/diff/line.js +1 -1
- package/lib/vendor/jsdiff/patch/create.js +147 -18
- package/lib/vendor/jsdiff/util/params.js +1 -1
- package/package.json +4 -4
package/lib/mirror-paths.js
CHANGED
|
@@ -32,3 +32,20 @@ export function assertDownloadHasNoSymlinks(base, target) {
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
|
|
36
|
+
// An explicit `localPath` argument (the rw_download tool surface) must land
|
|
37
|
+
// inside the same mirror the HTTP route writes into. Resolve it in the local
|
|
38
|
+
// grammar and refuse anything that would escape the root, alias the meta
|
|
39
|
+
// record, or smuggle Windows-unusable names — the same guarantees the
|
|
40
|
+
// remote-derived form gets from mirrorDownloadTarget.
|
|
41
|
+
export function mirrorConstrainLocalTarget(base, localPathArg, localPathApi = path) {
|
|
42
|
+
const root = localPathApi.resolve(base)
|
|
43
|
+
const target = localPathApi.resolve(String(localPathArg || ''))
|
|
44
|
+
const within = localPathApi.relative(root, target)
|
|
45
|
+
if (!within || localPathApi.isAbsolute(within) || within.split(localPathApi.sep).some(part => part === '..')) throw unsafeDownload()
|
|
46
|
+
const parts = within.split(localPathApi.sep)
|
|
47
|
+
// This local-only record determines the session's remote identity.
|
|
48
|
+
if (parts.length === 1 && (localPathApi.sep === '\\' ? parts[0].toLowerCase() : parts[0]) === '.dsh-remote-meta.json') throw unsafeDownload()
|
|
49
|
+
if (localPathApi.sep === '\\' && parts.some(part => /[<>:"|?*\\\x00-\x1f]/.test(part) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw unsafeDownload()
|
|
50
|
+
return target
|
|
51
|
+
}
|
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`
|
|
331
|
-
//
|
|
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
|
-
|
|
344
|
-
|
|
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 (
|
|
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
|
-
|
|
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/registry.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// Keeping this logic in one module makes the guarantee unit-testable and
|
|
11
11
|
// shared between the HTTP routes and the tools (rw_connect).
|
|
12
12
|
|
|
13
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs'
|
|
14
14
|
import path from 'node:path'
|
|
15
15
|
|
|
16
16
|
/** Load { list, currentId, explicitNone } from the registry file. */
|
|
@@ -56,6 +56,11 @@ export function saveMachines(file, list, currentId, keepCurrentKey = true) {
|
|
|
56
56
|
const payload = { list }
|
|
57
57
|
if (hasStored) payload.currentId = stored
|
|
58
58
|
writeFileSync(file, JSON.stringify(payload, null, 2))
|
|
59
|
+
// This file can carry plaintext credentials (password / passphrase under
|
|
60
|
+
// the default 'plain' backend), so keep it user-private — the same rule
|
|
61
|
+
// term-secret.json (main.js) and the ssh-config writer (routes-machines.js)
|
|
62
|
+
// already follow. A pre-existing looser mode is tightened on every save.
|
|
63
|
+
try { chmodSync(file, 0o600) } catch { /* Windows: the parent dir is already user-private */ }
|
|
59
64
|
}
|
|
60
65
|
|
|
61
66
|
/**
|
package/lib/routes-forwards.js
CHANGED
|
@@ -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',
|
|
@@ -37,24 +37,115 @@ export function createForwardRoutes({ sendJson, readBody, forwards, store }) {
|
|
|
37
37
|
if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535) {
|
|
38
38
|
return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' })
|
|
39
39
|
}
|
|
40
|
+
// Which host the tunnel belongs to. The settings form names it
|
|
41
|
+
// explicitly (`machineId`): a forward can be DEFINED for a host that
|
|
42
|
+
// is not connected right now — it simply cannot start until that host
|
|
43
|
+
// is. Omitting the field keeps the historical behaviour: tag what the
|
|
44
|
+
// ACTIVE POOL is actually on (ephemeral included), not the registry's
|
|
45
|
+
// currentId, because rw_connect(save:false) keeps currentId on the old
|
|
46
|
+
// machine while the pool talks to the new one.
|
|
47
|
+
//
|
|
48
|
+
// An explicit id must be a real registry record: persisting a typo
|
|
49
|
+
// would create a forward that no machine can ever start and that no
|
|
50
|
+
// UI row can explain.
|
|
51
|
+
let machineId = typeof activeMachineId === 'function' ? activeMachineId() : store.currentId
|
|
52
|
+
if (Object.prototype.hasOwnProperty.call(body, 'machineId') && body.machineId !== null && body.machineId !== '') {
|
|
53
|
+
const wanted = String(body.machineId)
|
|
54
|
+
const known = Array.isArray(store.list) && store.list.some((m) => m && m.id === wanted)
|
|
55
|
+
if (!known) return sendJson(res, 404, { ok: false, error: 'machine not found', forwards: forwards.list() })
|
|
56
|
+
machineId = wanted
|
|
57
|
+
}
|
|
40
58
|
const d = forwards.define({
|
|
41
59
|
direction: body.direction === 'reverse' ? 'reverse' : 'local',
|
|
42
60
|
listenPort,
|
|
43
61
|
targetHost: body.targetHost || '127.0.0.1',
|
|
44
62
|
targetPort,
|
|
45
63
|
autoStart: !!body.autoStart,
|
|
46
|
-
machineId
|
|
64
|
+
machineId,
|
|
47
65
|
})
|
|
48
66
|
return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
|
|
49
67
|
}
|
|
68
|
+
if (action === 'update') {
|
|
69
|
+
// Partial patch: the row's 自动重连 checkbox sends only `autoStart`,
|
|
70
|
+
// the edit form sends the whole definition. Every field that IS
|
|
71
|
+
// present is validated; a missing field is left untouched (it must
|
|
72
|
+
// not silently reset anything). `autoStart`, when present, still has
|
|
73
|
+
// to be a real boolean.
|
|
74
|
+
const has = (k) => Object.prototype.hasOwnProperty.call(body, k)
|
|
75
|
+
const id = String(body.id || '')
|
|
76
|
+
const current = forwards.list().find((f) => f.id === id)
|
|
77
|
+
if (!current) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() })
|
|
78
|
+
const patch = {}
|
|
79
|
+
if (has('autoStart')) {
|
|
80
|
+
if (typeof body.autoStart !== 'boolean') {
|
|
81
|
+
return sendJson(res, 400, { ok: false, error: 'autoStart 必须是布尔值' })
|
|
82
|
+
}
|
|
83
|
+
patch.autoStart = body.autoStart
|
|
84
|
+
}
|
|
85
|
+
if (has('direction')) {
|
|
86
|
+
if (body.direction !== 'local' && body.direction !== 'reverse') {
|
|
87
|
+
return sendJson(res, 400, { ok: false, error: 'direction 只能是 local 或 reverse' })
|
|
88
|
+
}
|
|
89
|
+
patch.direction = body.direction
|
|
90
|
+
}
|
|
91
|
+
if (has('listenPort')) {
|
|
92
|
+
const p = Number(body.listenPort)
|
|
93
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) {
|
|
94
|
+
return sendJson(res, 400, { ok: false, error: 'listenPort 必须是 1–65535 的整数' })
|
|
95
|
+
}
|
|
96
|
+
patch.listenPort = p
|
|
97
|
+
}
|
|
98
|
+
if (has('targetPort')) {
|
|
99
|
+
// An empty target port means "same as the listen port", exactly
|
|
100
|
+
// like the add form.
|
|
101
|
+
const p = body.targetPort === '' || body.targetPort == null
|
|
102
|
+
? (patch.listenPort !== undefined ? patch.listenPort : current.listenPort)
|
|
103
|
+
: Number(body.targetPort)
|
|
104
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) {
|
|
105
|
+
return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' })
|
|
106
|
+
}
|
|
107
|
+
patch.targetPort = p
|
|
108
|
+
}
|
|
109
|
+
if (has('targetHost')) {
|
|
110
|
+
const host = String(body.targetHost || '').trim() || '127.0.0.1'
|
|
111
|
+
patch.targetHost = host
|
|
112
|
+
}
|
|
113
|
+
if (has('machineId')) {
|
|
114
|
+
if (body.machineId === null || body.machineId === '') {
|
|
115
|
+
patch.machineId = null
|
|
116
|
+
} else {
|
|
117
|
+
const wanted = String(body.machineId)
|
|
118
|
+
const known = Array.isArray(store.list) && store.list.some((m) => m && m.id === wanted)
|
|
119
|
+
if (!known) return sendJson(res, 404, { ok: false, error: 'machine not found', forwards: forwards.list() })
|
|
120
|
+
patch.machineId = wanted
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// A live tunnel keeps its OLD bind until it is torn down; editing it
|
|
124
|
+
// in place would show one port while the socket listens on another.
|
|
125
|
+
// Only the bind matters — 自动重连 may still be toggled while running.
|
|
126
|
+
const bindChanged = ['direction', 'listenPort', 'targetHost', 'targetPort', 'machineId']
|
|
127
|
+
.some((k) => k in patch && patch[k] !== (current[k] === undefined ? null : current[k]))
|
|
128
|
+
if (current.active && bindChanged) {
|
|
129
|
+
return sendJson(res, 409, { ok: false, error: '先停止这条转发再修改监听/目标/主机', forwards: forwards.list() })
|
|
130
|
+
}
|
|
131
|
+
const d = forwards.update(id, patch)
|
|
132
|
+
if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() })
|
|
133
|
+
return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
|
|
134
|
+
}
|
|
50
135
|
if (action === 'start' || action === 'stop') {
|
|
51
136
|
const d = forwards.list().find((f) => f.id === body.id)
|
|
52
137
|
if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found' })
|
|
53
138
|
if (action === 'start') {
|
|
54
139
|
const r = await forwards.start(d)
|
|
55
|
-
|
|
140
|
+
// Always return the CURRENT list, even on failure: a start that
|
|
141
|
+
// lost a race but found the tunnel already listening (see
|
|
142
|
+
// ForwardManager.start) must let the UI leave 启动 instead of
|
|
143
|
+
// staying on a stale row until the next click.
|
|
144
|
+
if (!r.ok) return sendJson(res, 500, { ok: false, error: r.error, forwards: forwards.list() })
|
|
56
145
|
} else {
|
|
57
|
-
|
|
146
|
+
// A user stop is intentional: clear the persisted "was running"
|
|
147
|
+
// flag so 自动重连 does not bring it back on the next connect.
|
|
148
|
+
forwards.stop(d.id, { forget: true })
|
|
58
149
|
}
|
|
59
150
|
return sendJson(res, 200, { ok: true, forwards: forwards.list() })
|
|
60
151
|
}
|
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 {
|
|
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
|
|
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
|
-
|
|
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/update.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
// Every failure aborts without touching the installed files (a bad download or
|
|
23
23
|
// a version mismatch must never break the running plugin).
|
|
24
24
|
|
|
25
|
+
import { createHash } from 'node:crypto'
|
|
25
26
|
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
26
27
|
import { createRequire } from 'node:module'
|
|
27
28
|
import path from 'node:path'
|
|
@@ -140,6 +141,52 @@ export async function fetchLatestVersion(timeoutMs = 8000) {
|
|
|
140
141
|
}
|
|
141
142
|
}
|
|
142
143
|
|
|
144
|
+
/**
|
|
145
|
+
* Fetch the npm metadata for one exact published version and return its
|
|
146
|
+
* `dist.integrity` (issue #169) — the SRI string the registry itself computed
|
|
147
|
+
* over the tarball bytes. This is the root of trust `applyUpdate` verifies
|
|
148
|
+
* the downloaded bytes against: TLS protects the transport, not the content.
|
|
149
|
+
*
|
|
150
|
+
* @param {string} version - exact published version.
|
|
151
|
+
* @param {Function} [fetchImpl] - fetch stand-in (tests inject here).
|
|
152
|
+
* @param {number} [timeoutMs] - watchdog budget; the caller does not await the timer.
|
|
153
|
+
* @returns {Promise<string>} the SRI string ("sha512-…").
|
|
154
|
+
*/
|
|
155
|
+
export async function fetchDistIntegrity(version, fetchImpl = fetch, timeoutMs = 15000) {
|
|
156
|
+
const controller = new AbortController()
|
|
157
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
158
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
159
|
+
try {
|
|
160
|
+
const res = await fetchImpl(`https://registry.npmjs.org/${NPM_PACKAGE}/${encodeURIComponent(version)}`, {
|
|
161
|
+
signal: controller.signal,
|
|
162
|
+
headers: { accept: 'application/vnd.npm.install-v1+json' },
|
|
163
|
+
})
|
|
164
|
+
if (!res.ok) throw new Error(`registry metadata returned HTTP ${res.status}`)
|
|
165
|
+
const data = await res.json().catch(() => null)
|
|
166
|
+
const integrity = data?.dist?.integrity
|
|
167
|
+
if (typeof integrity !== 'string' || !/^(sha512|sha256)-[A-Za-z0-9+/=]+$/.test(integrity)) {
|
|
168
|
+
throw new Error('registry metadata carries no usable dist.integrity')
|
|
169
|
+
}
|
|
170
|
+
return integrity
|
|
171
|
+
} finally { clearTimeout(timer) }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Verify downloaded bytes against an npm `dist.integrity` SRI string.
|
|
176
|
+
* Throws (never returns false) so a mismatch aborts the update before the
|
|
177
|
+
* tar is even gunzipped.
|
|
178
|
+
* @param {Buffer} buf - the downloaded tarball bytes.
|
|
179
|
+
* @param {string} integrity - SRI string from the registry metadata.
|
|
180
|
+
*/
|
|
181
|
+
export function assertIntegrity(buf, integrity) {
|
|
182
|
+
const [alg, expected] = String(integrity || '').split('-')
|
|
183
|
+
if ((alg !== 'sha512' && alg !== 'sha256') || !expected) {
|
|
184
|
+
throw new Error(`unsupported dist.integrity: ${integrity}`)
|
|
185
|
+
}
|
|
186
|
+
const actual = createHash(alg).update(buf).digest('base64')
|
|
187
|
+
if (actual !== expected) throw new Error(`tarball integrity mismatch: expected ${alg}-${expected}, got ${alg}-${actual}`)
|
|
188
|
+
}
|
|
189
|
+
|
|
143
190
|
/** Minimal POSIX ustar reader (regular files only) — npm tarballs are gzipped tar. */
|
|
144
191
|
function parseTar(buf) {
|
|
145
192
|
const files = []
|
|
@@ -175,21 +222,38 @@ export async function applyUpdate(targetVersion, options = {}) {
|
|
|
175
222
|
throw new Error('refusing to self-update: this copy is not under node_modules (link/dev install) — update it from its source repo instead')
|
|
176
223
|
}
|
|
177
224
|
const tarballUrl = `https://registry.npmjs.org/${NPM_PACKAGE}/-/${NPM_PACKAGE}-${targetVersion}.tgz`
|
|
178
|
-
const dir = options.dir || selfDir()
|
|
225
|
+
const dir = path.resolve(options.dir || selfDir())
|
|
179
226
|
const doFetch = options.fetchImpl || fetch
|
|
227
|
+
const writeAtomic = options.writeFileAtomic || writeFileAtomic
|
|
228
|
+
const restoreFile = options.restoreFile || copyFileSync
|
|
180
229
|
const tmpRoot = path.join(dir, `.dsh-remote-update-${Date.now()}`)
|
|
181
230
|
const tmpPkg = path.join(tmpRoot, 'package')
|
|
231
|
+
let preserveBackup = false
|
|
182
232
|
try {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
233
|
+
let buf
|
|
234
|
+
if (options.tarballPath) {
|
|
235
|
+
// Offline repair must not contact the registry at all.
|
|
236
|
+
buf = readFileSync(options.tarballPath)
|
|
237
|
+
} 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
|
|
248
|
+
try {
|
|
249
|
+
res = await doFetch(tarballUrl, { signal: controller.signal })
|
|
250
|
+
} finally {
|
|
251
|
+
clearTimeout(timer)
|
|
252
|
+
}
|
|
253
|
+
if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
|
|
254
|
+
buf = Buffer.from(await res.arrayBuffer())
|
|
255
|
+
assertIntegrity(buf, integrity)
|
|
190
256
|
}
|
|
191
|
-
if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
|
|
192
|
-
const buf = Buffer.from(await res.arrayBuffer())
|
|
193
257
|
// npm tarballs are gzipped tar; extract the package/ directory.
|
|
194
258
|
const { gunzipSync } = await import('node:zlib')
|
|
195
259
|
const tar = gunzipSync(buf)
|
|
@@ -197,10 +261,15 @@ export async function applyUpdate(targetVersion, options = {}) {
|
|
|
197
261
|
mkdirSync(tmpPkg, { recursive: true })
|
|
198
262
|
let extracted = 0
|
|
199
263
|
for (const f of files) {
|
|
200
|
-
const rel = f.name.replace(/^package\//, '')
|
|
264
|
+
const rel = f.name.replace(/^package\//, '').replace(/\\/g, '/')
|
|
201
265
|
if (!rel || rel === 'package/' || rel.endsWith('/')) continue
|
|
202
266
|
if (rel !== 'package.json' && rel !== 'cordis.patch.yml' && !rel.startsWith('lib/')) continue
|
|
203
|
-
const
|
|
267
|
+
const unsafe = rel.startsWith('/') || /^[a-zA-Z]:/.test(rel) || rel.split('/').includes('..')
|
|
268
|
+
if (unsafe) throw new Error(`unsafe tarball path: ${f.name}`)
|
|
269
|
+
const dest = path.resolve(tmpPkg, rel)
|
|
270
|
+
if (dest !== tmpPkg && !dest.startsWith(tmpPkg + path.sep)) {
|
|
271
|
+
throw new Error(`unsafe tarball path: ${f.name}`)
|
|
272
|
+
}
|
|
204
273
|
mkdirSync(path.dirname(dest), { recursive: true })
|
|
205
274
|
writeFileSync(dest, f.data)
|
|
206
275
|
extracted++
|
|
@@ -213,41 +282,89 @@ export async function applyUpdate(targetVersion, options = {}) {
|
|
|
213
282
|
// break the next boot — check the file size and that it is not empty).
|
|
214
283
|
const newIndex = path.join(tmpPkg, 'lib', 'index.js')
|
|
215
284
|
if (!existsSync(newIndex) || statSize(newIndex) < 100) throw new Error('tarball missing lib/index.js')
|
|
216
|
-
// Swap the installed files one at a time: atomic, and idempotent.
|
|
217
|
-
//
|
|
218
|
-
//
|
|
219
|
-
// half
|
|
220
|
-
// every 500 ms, a torn write would be re-hashed and served mid-copy.
|
|
221
|
-
// Skipping byte-identical files keeps a re-apply of the same version from
|
|
222
|
-
// churning mtimes (and the host half from reloading for nothing).
|
|
285
|
+
// Swap the installed files one at a time: atomic, and idempotent. The
|
|
286
|
+
// manifest also makes the whole operation transactional: a failed write or
|
|
287
|
+
// a silent content mismatch restores the previous tree instead of leaving
|
|
288
|
+
// a half-applied package that cannot import itself.
|
|
223
289
|
const installLib = path.join(dir, 'lib')
|
|
224
290
|
const tmpLib = path.join(tmpPkg, 'lib')
|
|
291
|
+
const manifest = []
|
|
292
|
+
for (const rel of listFilesRecursive(tmpLib)) {
|
|
293
|
+
manifest.push({ src: path.join(tmpLib, rel), dest: path.join(installLib, rel) })
|
|
294
|
+
}
|
|
295
|
+
for (const rel of ['package.json', 'cordis.patch.yml']) {
|
|
296
|
+
const src = path.join(tmpPkg, rel)
|
|
297
|
+
if (existsSync(src)) manifest.push({ src, dest: path.join(dir, rel) })
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const backupRoot = path.join(tmpRoot, 'backup')
|
|
301
|
+
const backups = new Map()
|
|
225
302
|
const changed = []
|
|
303
|
+
let mutationStarted = false
|
|
304
|
+
let rollbackError = ''
|
|
305
|
+
const backup = (dest) => {
|
|
306
|
+
if (backups.has(dest)) return
|
|
307
|
+
const existed = existsSync(dest)
|
|
308
|
+
let backupPath = ''
|
|
309
|
+
if (existed) {
|
|
310
|
+
backupPath = path.join(backupRoot, String(backups.size))
|
|
311
|
+
mkdirSync(path.dirname(backupPath), { recursive: true })
|
|
312
|
+
copyFileSync(dest, backupPath)
|
|
313
|
+
}
|
|
314
|
+
backups.set(dest, { existed, path: backupPath })
|
|
315
|
+
}
|
|
226
316
|
const install = (src, dest) => {
|
|
227
317
|
const bytes = readFileSync(src)
|
|
318
|
+
backup(dest)
|
|
228
319
|
if (sameFileContent(dest, bytes)) return
|
|
229
320
|
try { mkdirSync(path.dirname(dest), { recursive: true }) } catch {}
|
|
230
|
-
|
|
321
|
+
mutationStarted = true
|
|
322
|
+
writeAtomic(dest, bytes)
|
|
231
323
|
changed.push(path.relative(dir, dest).split(path.sep).join('/'))
|
|
232
324
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
325
|
+
const rollback = () => {
|
|
326
|
+
if (!mutationStarted) return
|
|
327
|
+
for (const [dest, saved] of [...backups].reverse()) {
|
|
328
|
+
try {
|
|
329
|
+
try { mkdirSync(path.dirname(dest), { recursive: true }) } catch {}
|
|
330
|
+
if (saved.existed) restoreFile(saved.path, dest)
|
|
331
|
+
else rmSync(dest, { force: true })
|
|
332
|
+
} catch (error) {
|
|
333
|
+
rollbackError = `rollback failed at ${path.relative(dir, dest)}: ${(error && error.message) || error}; backup retained at ${backupRoot}`
|
|
334
|
+
break
|
|
335
|
+
}
|
|
336
|
+
}
|
|
240
337
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
338
|
+
|
|
339
|
+
try {
|
|
340
|
+
for (const { src, dest } of manifest) install(src, dest)
|
|
341
|
+
// Do not trust the writes alone: verify every selected tarball file after
|
|
342
|
+
// the install, including nested .cjs/.js files and package metadata.
|
|
343
|
+
for (const { src, dest } of manifest) {
|
|
344
|
+
const expected = readFileSync(src)
|
|
345
|
+
let actual
|
|
346
|
+
try { actual = readFileSync(dest) } catch (error) {
|
|
347
|
+
throw new Error(`applied file missing: ${path.relative(dir, dest)} (${(error && error.message) || error})`)
|
|
348
|
+
}
|
|
349
|
+
if (!actual.equals(expected)) throw new Error(`applied file mismatch: ${path.relative(dir, dest)}`)
|
|
350
|
+
}
|
|
351
|
+
const marker = path.join(dir, '.dsh-remote-updated')
|
|
352
|
+
backup(marker)
|
|
353
|
+
mutationStarted = true
|
|
354
|
+
writeAtomic(marker, Buffer.from(String(targetVersion)))
|
|
355
|
+
return { ok: true, to: targetVersion, changed }
|
|
356
|
+
} catch (error) {
|
|
357
|
+
rollback()
|
|
358
|
+
if (rollbackError) {
|
|
359
|
+
preserveBackup = true
|
|
360
|
+
throw new Error(`${(error && error.message) || error}; ${rollbackError}`)
|
|
361
|
+
}
|
|
362
|
+
throw error
|
|
244
363
|
}
|
|
245
|
-
writeFileSync(path.join(dir, '.dsh-remote-updated'), String(targetVersion))
|
|
246
|
-
return { ok: true, to: targetVersion, changed }
|
|
247
364
|
} catch (err) {
|
|
248
365
|
throw new Error('update failed: ' + ((err && err.message) || err))
|
|
249
366
|
} finally {
|
|
250
|
-
try { rmSync(tmpRoot, { recursive: true, force: true }) } catch {}
|
|
367
|
+
if (!preserveBackup) { try { rmSync(tmpRoot, { recursive: true, force: true }) } catch {} }
|
|
251
368
|
}
|
|
252
369
|
}
|
|
253
370
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Vendored unchanged from jsdiff
|
|
1
|
+
// Vendored unchanged from jsdiff 9.0.0; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
|
|
2
2
|
export default class Diff {
|
|
3
3
|
diff(oldStr, newStr,
|
|
4
4
|
// Type below is not accurate/complete - see above for full possibilities - but it compiles
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Vendored unchanged from jsdiff
|
|
1
|
+
// Vendored unchanged from jsdiff 9.0.0; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
|
|
2
2
|
import Diff from './base.js';
|
|
3
3
|
import { generateOptions } from '../util/params.js';
|
|
4
4
|
class LineDiff extends Diff {
|