dsh-remote 1.5.0 → 1.6.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/README.en.md +1 -1
- package/README.md +1 -1
- package/lib/binding.js +100 -84
- package/lib/client.js +107 -45
- package/lib/connect-summary.js +28 -0
- package/lib/file-reference.js +75 -7
- package/lib/forwards.js +72 -23
- package/lib/host-api.js +26 -37
- package/lib/hostkey.js +128 -10
- package/lib/http-transport.js +72 -5
- package/lib/ignore.js +64 -21
- package/lib/main.js +279 -229
- package/lib/mirror-paths.js +107 -2
- package/lib/openssh.js +51 -1
- package/lib/pool.js +9 -0
- package/lib/registry.js +47 -7
- package/lib/remote-fs.js +43 -19
- package/lib/remote-git.js +53 -5
- package/lib/routes-fs.js +33 -17
- package/lib/routes-web-attach.js +115 -43
- package/lib/routes-workspace.js +15 -9
- package/lib/search.js +96 -16
- package/lib/sftp-surface.js +5 -1
- package/lib/sshconfig.js +62 -7
- package/lib/sync-status.js +3 -2
- package/lib/sync.js +109 -48
- package/lib/terminal.js +7 -3
- package/lib/update.js +65 -10
- package/lib/web-attach.js +137 -20
- package/lib/workspace-cleanup.js +85 -60
- package/lib/workspace-files-remote.js +154 -3
- package/package.json +2 -2
package/lib/routes-web-attach.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// file only adapts the HTTP surface to it. The state it drives belongs to the
|
|
6
6
|
// plugin entry and arrives as `deps`: the live-attach map, the machine
|
|
7
7
|
// registry array, the per-identity pool resolver, and the audit sink.
|
|
8
|
-
import { WebAttach } from './web-attach.js'
|
|
8
|
+
import { WebAttach, stopRemoteReport } from './web-attach.js'
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* @param {object} deps
|
|
@@ -25,6 +25,21 @@ import { WebAttach } from './web-attach.js'
|
|
|
25
25
|
* @returns {Array<object>} route descriptors for registerHttpTransports.
|
|
26
26
|
*/
|
|
27
27
|
export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, config, webAttaches, store, machines, poolForMachine, identityOf, webAttachCommandFor, webAttachDiscoverCommandFor, audit }) {
|
|
28
|
+
// Concurrent-open gate for the `open` action: machineId → the promise of
|
|
29
|
+
// the open currently holding the slot. The factory is mounted exactly once
|
|
30
|
+
// per boot (main.js route table), so closure scope is all the state this
|
|
31
|
+
// serialization needs. Continues the web-attach lifecycle line — #54
|
|
32
|
+
// (stale client), #125 (discovery), #204 (self-reconnect): those fixes
|
|
33
|
+
// made one SESSION survive its connection; this one makes one MACHINE
|
|
34
|
+
// hold one session even when two opens are fired at it at once. Without
|
|
35
|
+
// the gate, the live-check ran before the multi-second `await
|
|
36
|
+
// attach.open()`, so both requests saw "no live tunnel" and both
|
|
37
|
+
// proceeded; the second `webAttaches.set` overwrote the first session,
|
|
38
|
+
// stranding a local listener that stayed bound but invisible (status
|
|
39
|
+
// lists map values, close touches the map entry, the unload sweeper in
|
|
40
|
+
// main.js iterates map values) — and on the launch path an extra remote
|
|
41
|
+
// `dsh web` kept running that nothing could stop.
|
|
42
|
+
const opening = new Map()
|
|
28
43
|
return [
|
|
29
44
|
{
|
|
30
45
|
kind: 'exact',
|
|
@@ -56,46 +71,85 @@ export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
56
71
|
// second remote DSH and leak the first one's process.
|
|
57
72
|
const live = webAttaches.get(machineId)
|
|
58
73
|
if (live && live.active) return sendJson(res, 200, { ok: true, attach: live.describe(), reused: true })
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
74
|
+
for (;;) {
|
|
75
|
+
const pending = opening.get(machineId)
|
|
76
|
+
if (!pending) {
|
|
77
|
+
// This request holds the slot: the WHOLE open sequence —
|
|
78
|
+
// stale teardown included — runs as one task, so a concurrent
|
|
79
|
+
// request can neither double-close a stale entry nor land its
|
|
80
|
+
// own `webAttaches.set` between the live-check above and the
|
|
81
|
+
// first one's.
|
|
82
|
+
const task = (async () => {
|
|
83
|
+
// A tunnel that is no longer listening still owns sockets and
|
|
84
|
+
// a log path; release it before this machine gets a fresh
|
|
85
|
+
// session. Its remote process is left alone — stopping it
|
|
86
|
+
// stays an explicit act. Re-read the registry: this request
|
|
87
|
+
// may have waited behind an earlier open (or its failure)
|
|
88
|
+
// that changed it in the meantime.
|
|
89
|
+
const stale = webAttaches.get(machineId)
|
|
90
|
+
if (stale) { try { await stale.close() } catch { /* already torn down */ } }
|
|
91
|
+
const machine = machines.find((m) => m.id === machineId)
|
|
92
|
+
if (!machine) return sendJson(res, 404, { ok: false, error: `机器不存在:${machineId}` })
|
|
93
|
+
const attachPool = poolForMachine(identityOf(machine))
|
|
94
|
+
const attach = new WebAttach({
|
|
95
|
+
localPortStart: config.webAttachPortStart,
|
|
96
|
+
// Issue #54: follow the chosen pool's lifecycle so a dropped
|
|
97
|
+
// SSH connection degrades to "disconnected" and then
|
|
98
|
+
// self-heals, instead of leaving a dead client that crashes
|
|
99
|
+
// the host process.
|
|
100
|
+
trackPool: true,
|
|
101
|
+
})
|
|
102
|
+
try {
|
|
103
|
+
await attach.open({
|
|
104
|
+
pool: attachPool,
|
|
105
|
+
machineId,
|
|
106
|
+
command: String(body.command || '').trim() || webAttachCommandFor(machine),
|
|
107
|
+
profile: 'web',
|
|
108
|
+
existingUrl: String(body.existingUrl || ''),
|
|
109
|
+
// Issue #125: a per-call override wins, then the machine's
|
|
110
|
+
// own setting; '' disables discovery entirely (previous
|
|
111
|
+
// behaviour).
|
|
112
|
+
discoverCommand: String(body.discoverCommand || '').trim()
|
|
113
|
+
|| (typeof webAttachDiscoverCommandFor === 'function' ? webAttachDiscoverCommandFor(machine) : ''),
|
|
114
|
+
dshHome: config.webAttachDshHome || '',
|
|
115
|
+
waitSeconds: config.webAttachWaitSeconds,
|
|
116
|
+
})
|
|
117
|
+
} catch (err) {
|
|
118
|
+
try { await attach.close() } catch { /* nothing was listening */ }
|
|
119
|
+
const msg = String((err && err.message) || err)
|
|
120
|
+
audit('web-attach', `open ${machine.host} failed: ${msg}`, 1, machine)
|
|
121
|
+
return sendJson(res, 500, { ok: false, error: msg })
|
|
122
|
+
}
|
|
123
|
+
webAttaches.set(machineId, attach)
|
|
124
|
+
// The audit line records WHICH path opened the tunnel, but
|
|
125
|
+
// never the discovered URL itself — it carries a live login
|
|
126
|
+
// token.
|
|
127
|
+
audit('web-attach', `open ${machine.host} → 127.0.0.1:${attach.localPort}`
|
|
128
|
+
+ (attach.discovery ? ` (discover: ${attach.discovery})` : ''), 0, machine)
|
|
129
|
+
return sendJson(res, 200, { ok: true, attach: attach.describe() })
|
|
130
|
+
})()
|
|
131
|
+
opening.set(machineId, task)
|
|
132
|
+
try {
|
|
133
|
+
await task
|
|
134
|
+
} finally {
|
|
135
|
+
// Hand the slot back only when it still holds THIS task: a
|
|
136
|
+
// joiner that fell through after a failure installs its own.
|
|
137
|
+
if (opening.get(machineId) === task) opening.delete(machineId)
|
|
138
|
+
}
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
// Another request is already opening this machine. Its own
|
|
142
|
+
// outcome (200 or 500) was answered on ITS response, so only
|
|
143
|
+
// "did it leave a live tunnel" matters here.
|
|
144
|
+
try { await pending } catch { /* already answered as a 500 */ }
|
|
145
|
+
const winner = webAttaches.get(machineId)
|
|
146
|
+
if (winner && winner.active) {
|
|
147
|
+
return sendJson(res, 200, { ok: true, attach: winner.describe(), reused: true })
|
|
148
|
+
}
|
|
149
|
+
// No live tunnel (the in-flight open failed, or its session was
|
|
150
|
+
// closed again): loop — join the next in-flight open if one
|
|
151
|
+
// started, or claim the slot and run it ourselves.
|
|
92
152
|
}
|
|
93
|
-
webAttaches.set(machineId, attach)
|
|
94
|
-
// The audit line records WHICH path opened the tunnel, but never
|
|
95
|
-
// the discovered URL itself — it carries a live login token.
|
|
96
|
-
audit('web-attach', `open ${machine.host} → 127.0.0.1:${attach.localPort}`
|
|
97
|
-
+ (attach.discovery ? ` (discover: ${attach.discovery})` : ''), 0, machine)
|
|
98
|
-
return sendJson(res, 200, { ok: true, attach: attach.describe() })
|
|
99
153
|
}
|
|
100
154
|
|
|
101
155
|
if (action === 'close') {
|
|
@@ -105,10 +159,28 @@ export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
105
159
|
// `close()` refuses to signal anything without a recorded PID, so a
|
|
106
160
|
// tunnel onto the user's own running instance stays hands-off.
|
|
107
161
|
const exec = (cmd) => poolForMachine(identityOf(machines.find((m) => m.id === machineId) || {})).exec(cmd, { timeoutMs: 10000 })
|
|
108
|
-
|
|
162
|
+
const managed = attach.remotePid > 0
|
|
163
|
+
const stop = await attach.close({ stopRemote, exec })
|
|
109
164
|
webAttaches.delete(machineId)
|
|
110
|
-
|
|
111
|
-
|
|
165
|
+
// Honest reporting, continuing the #271/#272 line (recursive remove
|
|
166
|
+
// reports incompleteness): `stoppedRemote` is what the stop command
|
|
167
|
+
// PROVED, never a restatement of the request. close() classifies the
|
|
168
|
+
// command's markers; the one legacy shape kept on purpose is the
|
|
169
|
+
// /proc-less remote, which cannot be checked either way — there the
|
|
170
|
+
// old `true` survives but is labelled unverified.
|
|
171
|
+
const report = !stopRemote
|
|
172
|
+
? { stoppedRemote: false, note: '' }
|
|
173
|
+
: managed
|
|
174
|
+
? stopRemoteReport(stop && stop.stopOutcome)
|
|
175
|
+
: { stoppedRemote: false, note: 'remote stop skipped: no pid of ours' }
|
|
176
|
+
const closeBody = { ok: true, closed: true, stoppedRemote: report.stoppedRemote }
|
|
177
|
+
if (report.note) closeBody.stoppedRemoteNote = report.note
|
|
178
|
+
// An honestly-failed stop is audited as a failure; the audit line
|
|
179
|
+
// used to claim "(remote stopped)" unconditionally.
|
|
180
|
+
const outcome = managed ? (stop && stop.stopOutcome) : null
|
|
181
|
+
const failedStop = outcome === 'failed' || outcome === 'refused' || outcome === 'error'
|
|
182
|
+
audit('web-attach', `close ${attach.cleanUrl}${stopRemote ? (report.note ? ` (${report.note})` : ' (remote stopped)') : ''}`, failedStop ? 1 : 0)
|
|
183
|
+
return sendJson(res, 200, closeBody)
|
|
112
184
|
}
|
|
113
185
|
|
|
114
186
|
return sendJson(res, 400, { ok: false, error: 'action must be open | close' })
|
package/lib/routes-workspace.js
CHANGED
|
@@ -24,6 +24,7 @@ import { createHostKeyGuard } from './hostkey.js'
|
|
|
24
24
|
* @param {(remotePath: string, host: string, user: string, port: number, extra?: object) => string} deps.ensureMirror
|
|
25
25
|
* @param {(m: object) => string} deps.aliasOf
|
|
26
26
|
* @param {() => object|null} deps.activeMachine
|
|
27
|
+
* @param {() => object} deps.activeMirrorOrigin
|
|
27
28
|
* @param {(localDir: string) => void} deps.startAutoPush
|
|
28
29
|
* @param {(body: object, res: object) => Promise<boolean>} deps.applyRequestedMachine - picker re-assertion (replies on mismatch).
|
|
29
30
|
* @param {(localDir: string, remotePath: string, machine: object) => Promise<void>} deps.registerMirroredWorkspace
|
|
@@ -35,7 +36,7 @@ import { createHostKeyGuard } from './hostkey.js'
|
|
|
35
36
|
* @param {() => string} deps.knownHostsFile
|
|
36
37
|
* @returns {Array<object>} route descriptors for registerHttpTransports.
|
|
37
38
|
*/
|
|
38
|
-
export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror, aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability, pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId }) {
|
|
39
|
+
export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror, aliasOf, activeMachine, activeMirrorOrigin, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability, pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId }) {
|
|
39
40
|
return [
|
|
40
41
|
{
|
|
41
42
|
kind: 'exact',
|
|
@@ -91,8 +92,9 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
91
92
|
const p = normalizeRemotePath(rawPath)
|
|
92
93
|
const okDir = await isRemoteDir(p)
|
|
93
94
|
if (!okDir) return sendJson(res, 400, { ok: false, error: `not a directory: ${p}` })
|
|
95
|
+
const { host, username, port, alias } = activeMirrorOrigin()
|
|
96
|
+
const local = ensureMirror(p, host, username, port, { alias })
|
|
94
97
|
persistWorkspace(p)
|
|
95
|
-
const local = ensureMirror(p, config.host, config.username, config.port, { alias: aliasOf(activeMachine()) })
|
|
96
98
|
startAutoPush(local)
|
|
97
99
|
return sendJson(res, 200, { ok: true, workspace: p, localMirror: local, ...status() })
|
|
98
100
|
} catch (err) {
|
|
@@ -106,11 +108,15 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
106
108
|
handler: async (req, res) => {
|
|
107
109
|
if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
|
|
108
110
|
const controller = new AbortController()
|
|
111
|
+
const signal = req.signal ? AbortSignal.any([req.signal, controller.signal]) : controller.signal
|
|
109
112
|
const cancel = () => { if (!res.writableEnded) controller.abort() }
|
|
110
113
|
res.once?.('close', cancel)
|
|
111
114
|
req.once?.('aborted', cancel)
|
|
112
115
|
try {
|
|
113
|
-
|
|
116
|
+
if (signal.aborted) return
|
|
117
|
+
const raw = await readBody(req)
|
|
118
|
+
if (signal.aborted) return
|
|
119
|
+
const payload = JSON.parse(raw || '{}')
|
|
114
120
|
// Blank-only guard: a filesystem root is a legal workspace (issue
|
|
115
121
|
// #60); the real directory probe below answers everything else.
|
|
116
122
|
const rawPath = String(payload.path || '').trim()
|
|
@@ -120,13 +126,13 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
120
126
|
// switch made elsewhere between the listing and this commit cannot
|
|
121
127
|
// mirror onto a machine the user never looked at (the picker sends
|
|
122
128
|
// /current only once per machine now, so nothing else re-applies it).
|
|
123
|
-
if (!(await applyRequestedMachine(payload, res))) return
|
|
129
|
+
if (!(await applyRequestedMachine(payload, res)) || signal.aborted) return
|
|
124
130
|
if (!config.host) return sendJson(res, 400, { ok: false, error: 'no remote host configured/connected — connect first' })
|
|
125
131
|
const selected = payload.machineId && machineForId ? machineForId(String(payload.machineId)) : activeMachine()
|
|
126
132
|
const prepared = prepareMirrorTarget
|
|
127
|
-
? await prepareMirrorTarget(p, selected,
|
|
133
|
+
? await prepareMirrorTarget(p, selected, signal)
|
|
128
134
|
: { ok: await isRemoteDir(p), machine: selected, identity: { host: config.host, username: config.username, port: config.port } }
|
|
129
|
-
if (
|
|
135
|
+
if (signal.aborted) return
|
|
130
136
|
if (!prepared.ok) return sendJson(res, 400, { ok: false, error: prepared.error || `not a directory (or unreachable): ${p}` })
|
|
131
137
|
const { machine, identity } = prepared
|
|
132
138
|
const local = ensureMirror(p, identity.host, identity.username, identity.port, { alias: aliasOf(machine) })
|
|
@@ -139,11 +145,11 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
139
145
|
// last segment. Callers that only pick a folder (settings page, Remote
|
|
140
146
|
// Files explorer) opt out with registerWorkspace:false, so no stray
|
|
141
147
|
// workspace appears in their flow.
|
|
142
|
-
if (payload.registerWorkspace !== false) await registerMirroredWorkspace(local, p, machine,
|
|
143
|
-
if (
|
|
148
|
+
if (payload.registerWorkspace !== false) await registerMirroredWorkspace(local, p, machine, signal)
|
|
149
|
+
if (signal.aborted) return
|
|
144
150
|
return sendJson(res, 200, { ok: true, ...status(), path: p, localMirror: local, machine: identity })
|
|
145
151
|
} catch (err) {
|
|
146
|
-
if (!
|
|
152
|
+
if (!signal.aborted) return sendJson(res, 500, { ok: false, error: friendlyMessage(err) })
|
|
147
153
|
} finally {
|
|
148
154
|
res.removeListener?.('close', cancel)
|
|
149
155
|
req.removeListener?.('aborted', cancel)
|
package/lib/search.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// Windows remotes). Walks the remote tree over SFTP readdir/stat/readFile with
|
|
4
4
|
// the same bounded-parallelism + ignore rules as the mirror sync.
|
|
5
5
|
import { joinRemotePath, relPathUnder, shq } from './paths.js'
|
|
6
|
+
import { parseIgnoreRule } from './ignore.js'
|
|
6
7
|
|
|
7
8
|
function mapLimit(items, limit, fn) {
|
|
8
9
|
const limitN = Math.max(1, Math.min(Math.floor(limit) || 1, items.length))
|
|
@@ -81,11 +82,21 @@ export async function searchTree(sftp, rootDir, opts = {}) {
|
|
|
81
82
|
let cancelled = false
|
|
82
83
|
const startedAt = Date.now()
|
|
83
84
|
|
|
84
|
-
/** True when the caller asked us to stop (abort,
|
|
85
|
+
/** True when the caller asked us to stop (abort, time budget, or a full cap). */
|
|
85
86
|
const shouldStop = () => {
|
|
86
87
|
if (cancelled || truncated) return true
|
|
87
88
|
if (signal && signal.aborted) { cancelled = true; return true }
|
|
88
89
|
if (maxDurationMs > 0 && Date.now() - startedAt >= maxDurationMs) { truncated = true; return true }
|
|
90
|
+
// A full cap is itself the honest truncation signal — there may be more
|
|
91
|
+
// matches beyond it in files this walk never reads. Before this branch,
|
|
92
|
+
// `truncated` was only set when a FURTHER match arrived past the cap, but
|
|
93
|
+
// the per-entry guard skips remaining files unread, so a cap filled exactly
|
|
94
|
+
// on a file's last matching line never set it: shouldStop never fired, the
|
|
95
|
+
// directory loop burned a readdir round-trip on every remaining directory,
|
|
96
|
+
// and the walk ended with truncated:false while dropping matches (or said
|
|
97
|
+
// TRUNCATED only after maxDurationMs burned). Continues the issue #44
|
|
98
|
+
// hardening: a cancellable walk must also stop for its own caps.
|
|
99
|
+
if (matches.length >= maxMatches) { truncated = true; return true }
|
|
89
100
|
return false
|
|
90
101
|
}
|
|
91
102
|
|
|
@@ -160,7 +171,18 @@ export async function searchTree(sftp, rootDir, opts = {}) {
|
|
|
160
171
|
return { matches, scanned, truncated, cancelled }
|
|
161
172
|
}
|
|
162
173
|
|
|
163
|
-
|
|
174
|
+
/**
|
|
175
|
+
* Map one reported hit back to the absolute remote path the rest of the plugin
|
|
176
|
+
* prints. The tools run with cwd = the search root (see searchViaShell) and are
|
|
177
|
+
* given '.', so they report './src/a.ts'; the SFTP walk reports the absolute
|
|
178
|
+
* path for the same file.
|
|
179
|
+
*/
|
|
180
|
+
function absoluteMatchPath(p, rootDir) {
|
|
181
|
+
const rel = String(p).replace(/^\.\//, '')
|
|
182
|
+
return rel.startsWith('/') ? rel : joinRemotePath(rootDir, rel)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function parseGrepLines(stdout, maxMatches, rootDir) {
|
|
164
186
|
const matches = []
|
|
165
187
|
let truncated = false
|
|
166
188
|
for (const line of String(stdout || '').split('\n')) {
|
|
@@ -168,14 +190,62 @@ function parseGrepLines(stdout, maxMatches) {
|
|
|
168
190
|
const m = line.match(/^(.*?):(\d+):(.*)$/)
|
|
169
191
|
if (!m) continue
|
|
170
192
|
if (matches.length >= maxMatches) { truncated = true; break }
|
|
171
|
-
matches.push({ path: m[1], line: Number(m[2]), text: m[3] })
|
|
193
|
+
matches.push({ path: absoluteMatchPath(m[1], rootDir), line: Number(m[2]), text: m[3] })
|
|
172
194
|
}
|
|
173
195
|
return { matches, truncated }
|
|
174
196
|
}
|
|
175
197
|
|
|
198
|
+
/** Number of DISTINCT files that produced a hit. NOT a scan count: the remote
|
|
199
|
+
* tool never reports how many files it opened, and inventing that number would
|
|
200
|
+
* be a lie. (The SFTP walk reports its own real scan count.) */
|
|
201
|
+
function distinctFiles(matches) {
|
|
202
|
+
return new Set(matches.map((m) => m.path)).size
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Per-tool exclude flags for the search ignore rules.
|
|
207
|
+
*
|
|
208
|
+
* The fast path must apply the SAME rules as the SFTP walk (they arrive as
|
|
209
|
+
* opts.ignorePatterns, built by lib/main.js from lib/ignore.js), but the tools
|
|
210
|
+
* do not share a vocabulary: rg takes --glob, grep takes --exclude /
|
|
211
|
+
* --exclude-dir. A basename rule maps 1:1. A rule containing a "/" (or a
|
|
212
|
+
* leading "/") is anchored to the search root: rg can express that because it
|
|
213
|
+
* runs with cwd = the search root, whereas grep's --exclude* only ever match
|
|
214
|
+
* BASENAMES. Anchored rules are therefore passed to rg only, and grep still
|
|
215
|
+
* descends into them -- a documented limitation of the grep fallback instead of
|
|
216
|
+
* pretended parity (DEFAULT_SEARCH_IGNORE's 'Library/Caches/' is one).
|
|
217
|
+
*
|
|
218
|
+
* Every flag is shq-quoted: the whole thing is one remote shell line.
|
|
219
|
+
*/
|
|
220
|
+
function shellExcludes(patterns) {
|
|
221
|
+
const rg = []
|
|
222
|
+
const grep = []
|
|
223
|
+
for (const raw of (Array.isArray(patterns) ? patterns : String(patterns || '').split('\n'))) {
|
|
224
|
+
const rule = parseIgnoreRule(raw)
|
|
225
|
+
if (!rule) continue
|
|
226
|
+
if (rule.anchored) {
|
|
227
|
+
rg.push('--glob=' + shq('!' + rule.pattern + (rule.dirOnly ? '/' : '')))
|
|
228
|
+
continue
|
|
229
|
+
}
|
|
230
|
+
if (rule.dirOnly) {
|
|
231
|
+
rg.push('--glob=' + shq('!' + rule.pattern + '/'))
|
|
232
|
+
grep.push('--exclude-dir=' + shq(rule.pattern))
|
|
233
|
+
} else {
|
|
234
|
+
rg.push('--glob=' + shq('!' + rule.pattern))
|
|
235
|
+
grep.push('--exclude=' + shq(rule.pattern))
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return { rg: rg.length ? ' ' + rg.join(' ') : '', grep: grep.length ? ' ' + grep.join(' ') : '' }
|
|
239
|
+
}
|
|
240
|
+
|
|
176
241
|
/**
|
|
177
|
-
* POSIX fast path:
|
|
178
|
-
*
|
|
242
|
+
* POSIX fast path: 'rg' then 'grep -R'. Throws when the remote has neither, so
|
|
243
|
+
* the caller can fall back to an SFTP walk (Windows / no grep).
|
|
244
|
+
*
|
|
245
|
+
* ignorePatterns (the raw lines lib/main.js compiled the SFTP walk's matcher
|
|
246
|
+
* from) become per-tool exclude flags: the two tools spell them differently and
|
|
247
|
+
* '-I' means opposite things, so the flag sets are built separately. Both tools
|
|
248
|
+
* run from the search root so anchored rules match like the walk's.
|
|
179
249
|
*/
|
|
180
250
|
export async function searchViaShell(pool, rootDir, opts = {}) {
|
|
181
251
|
const {
|
|
@@ -184,34 +254,44 @@ export async function searchViaShell(pool, rootDir, opts = {}) {
|
|
|
184
254
|
glob,
|
|
185
255
|
contextLines = 0,
|
|
186
256
|
maxMatches = 500,
|
|
257
|
+
ignorePatterns = [],
|
|
187
258
|
signal,
|
|
188
259
|
} = opts
|
|
189
260
|
// Honour an already-aborted signal before spawning a remote grep on a huge tree.
|
|
190
261
|
if (signal && signal.aborted) {
|
|
191
262
|
return { matches: [], scanned: 0, truncated: false, cancelled: true, via: 'none' }
|
|
192
263
|
}
|
|
264
|
+
const ex = shellExcludes(ignorePatterns)
|
|
193
265
|
const ic = ignoreCase ? ' -i' : ''
|
|
194
|
-
const
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const
|
|
266
|
+
const ctx = contextLines > 0 ? ' -C ' + Number(contextLines) : ''
|
|
267
|
+
const globFlag = glob ? ' --glob=' + shq(glob) : ''
|
|
268
|
+
// -I is "ignore binary files" to grep but "--no-filename" to rg. rg must NOT
|
|
269
|
+
// get it: without a file name every row is unusable and parseGrepLines drops
|
|
270
|
+
// all of them, which silently turned every POSIX search into zero matches.
|
|
271
|
+
const rg = 'rg -n --no-heading' + ic + globFlag + ctx + ex.rg + ' --max-count ' + maxMatches + ' -- ' + shq(pattern) + ' .'
|
|
272
|
+
const grepGlob = glob ? ' --include=' + shq(glob) : ''
|
|
273
|
+
const grep = 'grep -R -n -I -E' + ic + grepGlob + ctx + ex.grep + ' -- ' + shq(pattern) + ' .'
|
|
274
|
+
// Both tools run from the search root: the ignore rules are anchored there,
|
|
275
|
+
// and rg matches --glob patterns against paths relative to the cwd (with an
|
|
276
|
+
// absolute search root, --glob=!Library/Caches/ matches nothing at all).
|
|
277
|
+
const script = 'cd ' + shq(rootDir) + ' || exit 2; if command -v rg >/dev/null 2>&1; then ' + rg + '; elif command -v grep >/dev/null 2>&1; then ' + grep + '; else exit 127; fi'
|
|
200
278
|
const res = await pool.exec(script, { timeoutMs: opts.timeoutMs, signal })
|
|
201
279
|
// A cancelled call must return as cancelled (with whatever partial output the
|
|
202
280
|
// remote produced), NOT throw: throwing would make searchRemote fall through
|
|
203
281
|
// to the slower SFTP walk, i.e. keep running after the caller said stop.
|
|
204
282
|
if (res.signal === 'ABORTED') {
|
|
205
|
-
const partial = parseGrepLines(res.stdout, maxMatches)
|
|
206
|
-
return { matches: partial.matches, scanned: partial.matches
|
|
283
|
+
const partial = parseGrepLines(res.stdout, maxMatches, rootDir)
|
|
284
|
+
return { matches: partial.matches, scanned: distinctFiles(partial.matches), truncated: false, cancelled: true, via: 'none' }
|
|
207
285
|
}
|
|
208
286
|
// 0 = hits, 1 = no hits; other codes mean the tools are missing / failed.
|
|
209
287
|
if (res.signal === 'TIMEOUT') throw new Error('search timed out')
|
|
210
|
-
if (res.code !== 0 && res.code !== 1) throw new Error(res.stderr ||
|
|
211
|
-
const parsed = parseGrepLines(res.stdout, maxMatches)
|
|
288
|
+
if (res.code !== 0 && res.code !== 1) throw new Error(res.stderr || 'search exit ' + res.code)
|
|
289
|
+
const parsed = parseGrepLines(res.stdout, maxMatches, rootDir)
|
|
212
290
|
return {
|
|
213
291
|
matches: parsed.matches,
|
|
214
|
-
|
|
292
|
+
// DISTINCT files with hits, not match rows: the shell path cannot know how
|
|
293
|
+
// many files the tool opened, so this must not pretend to be a scan count.
|
|
294
|
+
scanned: distinctFiles(parsed.matches),
|
|
215
295
|
truncated: parsed.truncated || /truncated|max-count/i.test(String(res.stderr || '')),
|
|
216
296
|
via: /rg/.test(String(res.stderr || '')) ? 'rg' : 'grep',
|
|
217
297
|
}
|
package/lib/sftp-surface.js
CHANGED
|
@@ -86,7 +86,11 @@ export function buildSftpSurface(sftp, { commandTimeoutMs, onTimeout }) {
|
|
|
86
86
|
sftp.rename(a, b, (e2) => {
|
|
87
87
|
if (e2) {
|
|
88
88
|
// Roll the original back into place before reporting the failure.
|
|
89
|
-
return sftp.rename(bak, b, () =>
|
|
89
|
+
return sftp.rename(bak, b, (rollbackError) => {
|
|
90
|
+
if (!rollbackError) return cb(e2)
|
|
91
|
+
const message = `SFTP install failed (${e2.message || e2}). Rollback failed (${rollbackError.message || rollbackError}). Original file retained at ${bak}`
|
|
92
|
+
return cb(Object.assign(new AggregateError([e2, rollbackError], message), { code: e2.code }))
|
|
93
|
+
})
|
|
90
94
|
}
|
|
91
95
|
// Best effort: a leftover backup must not fail the operation.
|
|
92
96
|
sftp.unlink(bak, () => cb(null))
|
package/lib/sshconfig.js
CHANGED
|
@@ -26,6 +26,13 @@
|
|
|
26
26
|
// • `Include` directives, globbed, expanded in place, relative to ~/.ssh
|
|
27
27
|
// (falling back to the including file's directory), depth- and cycle-limited.
|
|
28
28
|
// • backslash line continuations.
|
|
29
|
+
// • `Match` lines are block boundaries exactly like Host lines — criteria are
|
|
30
|
+
// NOT evaluated here, so a Match section's options belong to NOTHING, never
|
|
31
|
+
// to the Host block above (continues the ssh-config alias line: #38 import,
|
|
32
|
+
// #211 alias backend).
|
|
33
|
+
// • `keyword=value` is accepted alongside `keyword value` (ssh_config(5)).
|
|
34
|
+
// • options BEFORE the first Host/Match line ride along as file-level defaults
|
|
35
|
+
// at lowest precedence, so a bare alias still receives them.
|
|
29
36
|
//
|
|
30
37
|
// The module is pure (I/O is injectable), so it is unit-testable without a real
|
|
31
38
|
// home directory — see test/sshconfig.test.js.
|
|
@@ -182,32 +189,74 @@ export function splitValue(value) {
|
|
|
182
189
|
|
|
183
190
|
const stripQuotes = (s) => String(s || '').replace(/^"(.*)"$/s, '$1').replace(/^'(.*)'$/s, '$1')
|
|
184
191
|
|
|
192
|
+
/** Split one config line into [keyword, value] (null when there is no value).
|
|
193
|
+
* ssh_config(5): keyword and value are separated by whitespace, or by optional
|
|
194
|
+
* whitespace and exactly one `=` — `Port=2222`, `Port = 2222` and `Port 2222`
|
|
195
|
+
* all mean the same thing to ssh, so a keyword may never contain `=`. */
|
|
196
|
+
const matchKeywordValue = (line) => String(line).match(/^([^\s=]+)(?:\s*=\s*|\s+)(.*)$/)
|
|
197
|
+
|
|
185
198
|
/**
|
|
186
199
|
* Parse OpenSSH config text into Host BLOCKS, preserving pattern lists.
|
|
200
|
+
*
|
|
201
|
+
* Three ssh facts the parser owes the resolver (continues the ssh-config alias
|
|
202
|
+
* line, issues #38 / #211):
|
|
203
|
+
* • a `Match` line ends the current block exactly as a `Host` line does —
|
|
204
|
+
* Match criteria are NOT evaluated here, so the section's options belong to
|
|
205
|
+
* nothing rather than leaking into the block above;
|
|
206
|
+
* • `keyword=value` is valid ssh_config(5) syntax (matchKeywordValue);
|
|
207
|
+
* • options BEFORE the first Host/Match line apply to every host: they are
|
|
208
|
+
* collected into one leading `global: true` block (first-obtained, exactly
|
|
209
|
+
* as ssh processes a file top-to-bottom).
|
|
187
210
|
* @param {string} text
|
|
188
|
-
* @returns {Array<{patterns: string[], values: Record<string, string|number>, line: number}>}
|
|
211
|
+
* @returns {Array<{patterns: string[], values: Record<string, string|number>, line: number, global?: true}>}
|
|
189
212
|
*/
|
|
190
213
|
export function parseHostBlocks(text) {
|
|
191
214
|
const blocks = []
|
|
192
215
|
let current = null
|
|
216
|
+
let globalBlock = null
|
|
217
|
+
let inSection = false
|
|
193
218
|
const lines = configLines(text)
|
|
194
219
|
for (let i = 0; i < lines.length; i += 1) {
|
|
195
220
|
const line = lines[i].trim()
|
|
196
221
|
if (!line || line.startsWith('#')) continue
|
|
197
|
-
const m = line
|
|
222
|
+
const m = matchKeywordValue(line)
|
|
198
223
|
if (!m) continue
|
|
199
224
|
const key = m[1].toLowerCase()
|
|
200
225
|
const value = m[2].trim()
|
|
201
226
|
if (key === 'host') {
|
|
227
|
+
inSection = true
|
|
202
228
|
current = { patterns: splitValue(value), values: {}, line: i + 1 }
|
|
203
229
|
blocks.push(current)
|
|
204
230
|
continue
|
|
205
231
|
}
|
|
206
|
-
if (
|
|
232
|
+
if (key === 'match') {
|
|
233
|
+
// The section's options are not ours to evaluate: set no target, so they
|
|
234
|
+
// are attributed to nothing instead of leaking into the block above
|
|
235
|
+
// (verified against real `ssh -G`, which never lets them leak).
|
|
236
|
+
inSection = true
|
|
237
|
+
current = null
|
|
238
|
+
continue
|
|
239
|
+
}
|
|
240
|
+
let target = current
|
|
241
|
+
if (!target && !inSection) {
|
|
242
|
+
// Before the first Host/Match line: a file-level option, global to every
|
|
243
|
+
// host in real ssh.
|
|
244
|
+
if (!globalBlock) globalBlock = { patterns: ['*'], values: {}, line: i + 1, global: true }
|
|
245
|
+
target = globalBlock
|
|
246
|
+
}
|
|
247
|
+
if (!target || !KNOWN_PARAMS.has(key)) continue
|
|
207
248
|
// First value wins inside a block too (a repeated parameter is ignored).
|
|
208
|
-
if (Object.prototype.hasOwnProperty.call(
|
|
209
|
-
|
|
249
|
+
if (Object.prototype.hasOwnProperty.call(target.values, key)) continue
|
|
250
|
+
target.values[key] = key === 'port' ? (Number(value) || value) : stripQuotes(value)
|
|
210
251
|
}
|
|
252
|
+
// File-level options sit at the TOP of the file, and ssh processes a config
|
|
253
|
+
// top-to-bottom with first-obtained-wins: a top `Port 2200` is obtained BEFORE
|
|
254
|
+
// any Host block's own port, so `ssh -G a` reports 2200 even when block a
|
|
255
|
+
// sets its own port (verified against real ssh). Unshift keeps the block
|
|
256
|
+
// array in physical file order, so the resolver's cross-block
|
|
257
|
+
// first-obtained-wins reproduces that exactly — globals are defaults for
|
|
258
|
+
// parameters no one set, and WIN for parameters they set first.
|
|
259
|
+
if (globalBlock) blocks.unshift(globalBlock)
|
|
211
260
|
return blocks
|
|
212
261
|
}
|
|
213
262
|
|
|
@@ -222,7 +271,7 @@ export function parseSshConfig(text) {
|
|
|
222
271
|
for (const raw of configLines(text)) {
|
|
223
272
|
const line = raw.trim()
|
|
224
273
|
if (!line || line.startsWith('#')) continue
|
|
225
|
-
const m = line
|
|
274
|
+
const m = matchKeywordValue(line)
|
|
226
275
|
if (!m) continue
|
|
227
276
|
const key = m[1].toLowerCase()
|
|
228
277
|
const val = m[2].trim()
|
|
@@ -231,6 +280,9 @@ export function parseSshConfig(text) {
|
|
|
231
280
|
entries.push(cur)
|
|
232
281
|
continue
|
|
233
282
|
}
|
|
283
|
+
// Same boundary as parseHostBlocks: a Match section's options are not ours
|
|
284
|
+
// to evaluate and must not leak into the entry above.
|
|
285
|
+
if (key === 'match') { cur = null; continue }
|
|
234
286
|
if (!cur) continue
|
|
235
287
|
if (key === 'hostname' && !cur.hostName) cur.hostName = stripQuotes(val)
|
|
236
288
|
else if (key === 'user' && !cur.user) cur.user = stripQuotes(val)
|
|
@@ -324,7 +376,10 @@ export function resolveSshHost(alias, text) {
|
|
|
324
376
|
if (!name) return out
|
|
325
377
|
for (const block of parseHostBlocks(text)) {
|
|
326
378
|
if (!hostBlockMatches(block.patterns, name)) continue
|
|
327
|
-
|
|
379
|
+
// File-level defaults (global: true) carry values but do not NAME the
|
|
380
|
+
// alias: an unknown host keeps matched=false, so the no-matching-block
|
|
381
|
+
// warning survives a file that merely carries global options.
|
|
382
|
+
if (!block.global) out.matched = true
|
|
328
383
|
// first obtained value wins, ACROSS blocks in file order
|
|
329
384
|
for (const [key, value] of Object.entries(block.values)) {
|
|
330
385
|
if (key === 'hostname') { if (!out.hostName) out.hostName = String(value) }
|
package/lib/sync-status.js
CHANGED
|
@@ -18,8 +18,9 @@ export function createSyncActivity() {
|
|
|
18
18
|
const result = await fn((next) => { stats = next || {} })
|
|
19
19
|
if (current()) {
|
|
20
20
|
const conflicts = Array.isArray(stats.conflicts) ? stats.conflicts.map((c) => ({ path: c.path, reason: c.reason })) : []
|
|
21
|
-
const partial = !!(stats.failed || stats.abortedError || stats.truncated || stats.skippedLarge)
|
|
22
|
-
|
|
21
|
+
const partial = !!(stats.cancelled || stats.failed || stats.abortedError || stats.truncated || stats.skippedLarge)
|
|
22
|
+
const phase = conflicts.length && !stats.cancelled ? 'conflicts' : partial ? 'partial' : 'completed'
|
|
23
|
+
entries.set(local, { token, phase, operation, updatedAt: new Date().toISOString(), files: stats.files || 0, conflicts, error: stats.abortedError || '', ...(stats.cancelled ? { cancelled: true } : {}) })
|
|
23
24
|
}
|
|
24
25
|
return result
|
|
25
26
|
} catch (err) {
|