dsh-remote-go 0.2.0 → 0.3.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.
Files changed (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,257 @@
1
+ /** Read-only `~/.ssh/config` parsing and alias discovery for the `ssh_config(5)` subset; `Include`, `Match` and
2
+ * `ProxyCommand` are reported, never guessed. */
3
+ const KNOWN_OPTIONS = new Set([
4
+ 'hostname',
5
+ 'user',
6
+ 'port',
7
+ 'identityfile',
8
+ 'certificatefile',
9
+ 'proxyjump',
10
+ 'proxycommand',
11
+ 'serveraliveinterval',
12
+ 'serveralivecountmax',
13
+ 'connecttimeout',
14
+ 'identitiesonly',
15
+ 'preferredauthentications',
16
+ ]);
17
+ // `Host = x` keeps `= x` as its value: the first whitespace wins unless `=` comes before it.
18
+ function parseLine(line) {
19
+ const trimmed = line.trim();
20
+ if (trimmed === '' || trimmed.startsWith('#'))
21
+ return null;
22
+ const eq = trimmed.indexOf('=');
23
+ const space = trimmed.search(/\s/);
24
+ let keyword;
25
+ let value;
26
+ if (eq >= 0 && (space < 0 || eq < space)) {
27
+ keyword = trimmed.slice(0, eq);
28
+ value = trimmed.slice(eq + 1);
29
+ }
30
+ else if (space >= 0) {
31
+ keyword = trimmed.slice(0, space);
32
+ value = trimmed.slice(space + 1);
33
+ }
34
+ else {
35
+ keyword = trimmed;
36
+ value = '';
37
+ }
38
+ value = value.trim();
39
+ if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
40
+ (value.startsWith("'") && value.endsWith("'") && value.length >= 2)) {
41
+ value = value.slice(1, -1);
42
+ }
43
+ return { keyword: keyword.trim(), value };
44
+ }
45
+ function splitPatterns(value) {
46
+ const patterns = [];
47
+ const negated = [];
48
+ for (const token of value.split(/\s+/)) {
49
+ if (token === '')
50
+ continue;
51
+ if (token.startsWith('!'))
52
+ negated.push(token.slice(1));
53
+ else
54
+ patterns.push(token);
55
+ }
56
+ return { patterns, negated };
57
+ }
58
+ export function parseSshConfig(text) {
59
+ const entries = [];
60
+ const globals = {};
61
+ const unsupported = [];
62
+ const malformed = [];
63
+ // A repeated keyword appends: `IdentityFile` may legitimately appear several times in one block.
64
+ const appendOption = (target, key, value) => {
65
+ target[key] ??= [];
66
+ target[key].push(value);
67
+ };
68
+ let current = null;
69
+ const lines = String(text ?? '').split(/\r?\n/);
70
+ for (let index = 0; index < lines.length; index += 1) {
71
+ const lineNo = index + 1;
72
+ const parsed = parseLine(lines[index]);
73
+ if (!parsed)
74
+ continue;
75
+ const keyword = parsed.keyword.toLowerCase();
76
+ if (keyword === 'host') {
77
+ const { patterns, negated } = splitPatterns(parsed.value);
78
+ current = { patterns, negated, options: {}, line: lineNo };
79
+ if (patterns.length === 0)
80
+ malformed.push({ line: lineNo, text: lines[index] });
81
+ else
82
+ entries.push(current);
83
+ continue;
84
+ }
85
+ if (keyword === 'match') {
86
+ unsupported.push({ line: lineNo, keyword: 'Match' });
87
+ // Options inside a Match block only apply under conditions we cannot evaluate; skip to the next Host.
88
+ current = { patterns: ['__dsh_remote_go_match_block__'], negated: [], options: {}, line: lineNo };
89
+ entries.push(current);
90
+ continue;
91
+ }
92
+ if (keyword === 'include') {
93
+ unsupported.push({ line: lineNo, keyword: 'Include' });
94
+ continue;
95
+ }
96
+ if (!KNOWN_OPTIONS.has(keyword)) {
97
+ // Unknown-but-harmless options are ignored; only flag keywords that would change meaning if misread.
98
+ if (keyword === 'proxycommand' || keyword === 'certificatefile')
99
+ unsupported.push({ line: lineNo, keyword: parsed.keyword });
100
+ continue;
101
+ }
102
+ if (parsed.value === '') {
103
+ malformed.push({ line: lineNo, text: lines[index] });
104
+ continue;
105
+ }
106
+ appendOption(current ? current.options : globals, keyword, parsed.value);
107
+ }
108
+ return { entries, globals, unsupported, malformed };
109
+ }
110
+ export function matchHostPattern(pattern, value) {
111
+ if (pattern === '*')
112
+ return true;
113
+ const escaped = pattern
114
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
115
+ .replace(/\*/g, '.*')
116
+ .replace(/\?/g, '.');
117
+ return new RegExp(`^${escaped}$`, 'i').test(value);
118
+ }
119
+ export function entryMatches(entry, alias) {
120
+ if (entry.patterns.includes('__dsh_remote_go_match_block__'))
121
+ return false;
122
+ if (!entry.patterns.some((pattern) => matchHostPattern(pattern, alias)))
123
+ return false;
124
+ return !entry.negated.some((pattern) => matchHostPattern(pattern, alias));
125
+ }
126
+ const ADDITIVE_OPTIONS = new Set(['identityfile', 'certificatefile']);
127
+ function effectiveOptions(globals, entries, alias, tokens) {
128
+ const out = {};
129
+ const apply = (options) => {
130
+ for (const [key, values] of Object.entries(options)) {
131
+ const expanded = values.map((value) => expandTokens(value, tokens));
132
+ if (ADDITIVE_OPTIONS.has(key))
133
+ out[key] = [...(out[key] ?? []), ...expanded];
134
+ else if (out[key] === undefined)
135
+ out[key] = expanded;
136
+ }
137
+ };
138
+ apply(globals);
139
+ for (const entry of entries) {
140
+ if (entryMatches(entry, alias))
141
+ apply(entry.options);
142
+ }
143
+ return out;
144
+ }
145
+ export function expandTokens(value, tokens) {
146
+ return String(value).replace(/%([hprd%])/g, (match, token) => {
147
+ if (token === '%')
148
+ return '%';
149
+ return tokens[token] ?? match;
150
+ });
151
+ }
152
+ function expandTilde(value, home) {
153
+ if (value === '~')
154
+ return home;
155
+ if (value.startsWith('~/'))
156
+ return `${home.replace(/[\\/]+$/, '')}/${value.slice(2)}`;
157
+ return value;
158
+ }
159
+ export function resolveSshAlias(parsed, alias, options = {}) {
160
+ const home = options.home ?? '~';
161
+ const baseTokens = { h: alias, r: '~', p: '22', d: home };
162
+ const firstPass = effectiveOptions(parsed.globals, parsed.entries, alias, baseTokens);
163
+ const host = firstPass.hostname?.[0] ?? alias;
164
+ const user = firstPass.user?.[0] ?? null;
165
+ const rawPort = firstPass.port?.[0] ?? '22';
166
+ const port = /^\d+$/.test(rawPort) ? Number(rawPort) : 22;
167
+ // Second pass: `%h`/`%p` now resolve to the values the first pass found.
168
+ const tokens = { h: host, r: user ?? '~', p: String(port), d: home };
169
+ const resolved = effectiveOptions(parsed.globals, parsed.entries, alias, tokens);
170
+ const identityFiles = (resolved.identityfile ?? []).map((value) => expandTilde(value, home));
171
+ const proxyJump = resolved.proxyjump?.[0] ?? null;
172
+ return { alias, host, user, port, identityFiles, proxyJump, source: 'config' };
173
+ }
174
+ /** List concrete, manually-dialable aliases: a wildcard or negated pattern cannot resolve without a real target. */
175
+ export function discoverSshAliases(parsed, options = {}) {
176
+ const out = [];
177
+ const seen = new Set();
178
+ for (const entry of parsed.entries) {
179
+ for (const pattern of entry.patterns) {
180
+ if (pattern.includes('*') || pattern.includes('?') || pattern.startsWith('__dsh_remote_go_'))
181
+ continue;
182
+ if (seen.has(pattern))
183
+ continue;
184
+ seen.add(pattern);
185
+ const resolved = resolveSshAlias(parsed, pattern, options);
186
+ out.push({ alias: pattern, host: resolved.host, user: resolved.user, port: resolved.port, source: 'config' });
187
+ }
188
+ }
189
+ return out;
190
+ }
191
+ export function resolveDestination(destination, options = {}) {
192
+ const text = String(destination ?? '').trim();
193
+ const literal = parseDestinationLiteral(text);
194
+ const parsed = parseSshConfig(options.configText ?? '');
195
+ const home = options.home ?? '~';
196
+ const alias = discoverSshAliases(parsed, { home }).find((item) => item.alias === text);
197
+ if (alias) {
198
+ const resolved = resolveSshAlias(parsed, text, { home });
199
+ return {
200
+ input: text,
201
+ alias: text,
202
+ host: resolved.host,
203
+ user: literal.user ?? resolved.user,
204
+ port: literal.port ?? resolved.port,
205
+ identityFiles: resolved.identityFiles,
206
+ proxyJump: resolved.proxyJump,
207
+ source: 'config',
208
+ };
209
+ }
210
+ // Literal destination: inherit globals (e.g. a global IdentityFile) but not Host blocks that do not match
211
+ // the literal text, which is why the entries list passed below is empty.
212
+ const tokens = { h: literal.host, r: literal.user ?? '~', p: String(literal.port ?? 22), d: home };
213
+ const globals = effectiveOptions(parsed.globals, [], text, tokens);
214
+ const identityFiles = (globals.identityfile ?? []).map((value) => expandTilde(value, home));
215
+ return {
216
+ input: text,
217
+ alias: null,
218
+ host: literal.host,
219
+ user: literal.user,
220
+ port: literal.port ?? 22,
221
+ identityFiles,
222
+ proxyJump: globals.proxyjump?.[0] ?? null,
223
+ source: 'manual',
224
+ };
225
+ }
226
+ function parseDestinationLiteral(text) {
227
+ let user = null;
228
+ let rest = text;
229
+ const at = rest.lastIndexOf('@');
230
+ if (at >= 0) {
231
+ user = rest.slice(0, at);
232
+ rest = rest.slice(at + 1);
233
+ }
234
+ let host = rest;
235
+ let port = null;
236
+ if (rest.startsWith('[')) {
237
+ const close = rest.indexOf(']');
238
+ if (close > 0) {
239
+ host = rest.slice(1, close);
240
+ const tail = rest.slice(close + 1);
241
+ if (/^:\d+$/.test(tail))
242
+ port = Number(tail.slice(1));
243
+ }
244
+ }
245
+ else {
246
+ const colon = rest.lastIndexOf(':');
247
+ // Only an unbracketed `host:port`: a bare IPv6 literal keeps every colon.
248
+ if (colon > 0 && rest.indexOf(':') === colon) {
249
+ const maybePort = rest.slice(colon + 1);
250
+ if (/^\d{1,5}$/.test(maybePort)) {
251
+ host = rest.slice(0, colon);
252
+ port = Number(maybePort);
253
+ }
254
+ }
255
+ }
256
+ return { user: user || null, host, port };
257
+ }
@@ -0,0 +1,71 @@
1
+ /** SSH failure classification: the one place that turns a transport failure into the coded, bilingual error the Client
2
+ * renders; both adapters share it, so "which code and which sentence" has one answer. The table pins three details:
3
+ * `network`/`auth` are retryable but `host-key-changed` is not, `exec` deadlines are results (`timedOut`) never
4
+ * exceptions, and a coded error passes through. */
5
+ import { errors, RemoteGoError } from './errors.js';
6
+ import { headTail } from './util.js';
7
+ /** The three message shapes the rules below recognise, in the order they are tried. */
8
+ const HOST_KEY_MESSAGE = /host key|hostkey|verification/i;
9
+ const AUTH_MESSAGE = /authentication|All configured authentication methods failed|Permission denied/i;
10
+ const TRANSPORT_MESSAGE = /ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|timed out|timeout|Cannot connect|connect failed/i;
11
+ /** The typed "the transport is gone" failure: retryable network, never a bare internal error. The wording and the
12
+ * `reason=ssh-closed` technical string are frozen: `exec`, `forwardOut` and the SFTP entry points have raised this
13
+ * exact sentence since the first release, and callers (plus tests) match on it. */
14
+ export function closedError() {
15
+ return errors.network({
16
+ zh: 'SSH 连接已断开,本次操作没有完成;如果主机仍在线,重连即可继续。',
17
+ en: 'SSH connection is not open; the transport closed before this step finished.',
18
+ }, { technical: 'reason=ssh-closed' });
19
+ }
20
+ /** The host-key failure an adapter reports when it has no more specific factory to call. */
21
+ function hostKeyFailure(context) {
22
+ const endpoint = `${context.host ?? 'the host'}:${context.port ?? 22}`;
23
+ return errors.network({
24
+ zh: `主机密钥校验未通过(${endpoint})。`,
25
+ en: `Host key verification failed for ${endpoint}.`,
26
+ });
27
+ }
28
+ function failureOfKind(kind, context) {
29
+ if (kind === 'closed')
30
+ return closedError();
31
+ if (kind === 'auth')
32
+ return errors.auth();
33
+ if (kind === 'hostkey')
34
+ return hostKeyFailure(context);
35
+ // `transport` and `timeout` are the same client-visible failure: a retryable network error. The timeout
36
+ // row only lets an adapter label a handshake deadline without inventing a second sentence for it.
37
+ return errors.network();
38
+ }
39
+ /** Turn any thrown value into the error the contract may expose. The order decides: an already-coded error passes
40
+ * through, then an explicit `kind` wins over the message, then host-key, auth, transport, and anything left becomes
41
+ * `network` naming `headTail(message, 300)`. */
42
+ export function classifySshFailure(error, context = {}) {
43
+ if (error instanceof RemoteGoError)
44
+ return error;
45
+ if (context.kind !== undefined)
46
+ return failureOfKind(context.kind, context);
47
+ if (!error)
48
+ return errors.internal('unknown ssh error');
49
+ // A thrown value is `unknown`: the `as` restates the two fields a node/ssh2 transport error carries.
50
+ const message = String(error.message ?? error);
51
+ const code = String(error.code ?? '');
52
+ if (HOST_KEY_MESSAGE.test(message))
53
+ return hostKeyFailure(context);
54
+ if (AUTH_MESSAGE.test(message))
55
+ return errors.auth();
56
+ if (TRANSPORT_MESSAGE.test(`${code} ${message}`))
57
+ return errors.network();
58
+ return errors.network({
59
+ zh: `SSH 连接失败:${headTail(message, 300)}`,
60
+ en: `SSH connection failed: ${headTail(message, 300)}`,
61
+ });
62
+ }
63
+ /** The historical name for {@link classifySshFailure}; an alias, not a copy, so the two cannot drift. */
64
+ export function toSshError(error, host, port) {
65
+ return classifySshFailure(error, { host, port });
66
+ }
67
+ /** Whether one thrown value is a host-key refusal: `connect()` must rethrow it, not try the next credential. */
68
+ export function isHostKeyError(error) {
69
+ const code = error?.code;
70
+ return code === 'host-key-changed' || code === 'host-key-unknown';
71
+ }
@@ -0,0 +1,4 @@
1
+ /** `exec`'s default deadline; `timeoutMs <= 0` disables the timer. */
2
+ export const DEFAULT_EXEC_TIMEOUT_MS = 30_000;
3
+ /** `exec`'s default capture cap, applied to stdout and stderr separately. */
4
+ export const DEFAULT_EXEC_MAX_BYTES = 2 * 1024 * 1024;
@@ -0,0 +1,258 @@
1
+ /** The SFTP download capability of the ssh2 adapter: one session, stat/list, and streaming one file or a whole tree
2
+ * into a local path. `ssh.ts` delegates here to stay inside the 600-line budget, and because ssh2's SFTP details are a
3
+ * capability — optional on `SshPort` (`saveRemoteFile`/`saveRemoteTree`/`inspectRemotePath`) — rather than part of
4
+ * "opening a connection"; nothing outside the adapter imports this module. Deliberately unchanged: the disk is the only
5
+ * bound (cancellation deletes), symlinks are skipped so a loop cannot cycle, Windows metadata names are special only
6
+ * there and reported, and a throwing listener never aborts the transfer. */
7
+ import { createWriteStream } from 'node:fs';
8
+ import { mkdir, rm } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { pipeline } from 'node:stream/promises';
11
+ import { errors } from './errors.js';
12
+ import { isIgnoredLocalName, localPathKey, safeLocalSegment, uniqueLocalPath } from './remote-path.js';
13
+ /** Wrap one node-style ssh2 callback as a promise (the vendor surface has no promise variant). */
14
+ const call = (run) => new Promise((resolve, reject) => run((error, value) => (error ? reject(error) : resolve(value))));
15
+ /** Open one SFTP session on an established transport. */
16
+ export function openSftpSession(client) {
17
+ return call((done) => client.sftp(done));
18
+ }
19
+ /** Close one SFTP session, ignoring a session that is already gone. */
20
+ export function endSftp(sftp) {
21
+ try {
22
+ sftp.end();
23
+ }
24
+ catch {
25
+ // swallow-ok: the SFTP session may already be gone
26
+ }
27
+ }
28
+ /** Stream one remote file into a local path. Nothing is buffered; cancellation destroys both streams and removes the
29
+ * partial file. */
30
+ export async function saveSftpFile(sftp, remotePath, localPath, options = {}) {
31
+ const stats = await call((done) => sftp.stat(remotePath, done));
32
+ assertReadableFile(stats);
33
+ const totalBytes = Number(stats?.size ?? 0);
34
+ let doneBytes = 0;
35
+ try {
36
+ await copySftpFileToLocal(sftp, remotePath, localPath, (bytes) => {
37
+ doneBytes += bytes;
38
+ try {
39
+ options.onProgress?.({ doneBytes, totalBytes, doneFiles: 0, totalFiles: 1 });
40
+ }
41
+ catch {
42
+ // swallow-ok: progress listeners must not break the transfer
43
+ }
44
+ }, options.isCancelled);
45
+ }
46
+ catch (error) {
47
+ await rm(localPath, { force: true }).catch(() => { });
48
+ throw error;
49
+ }
50
+ return { size: doneBytes || totalBytes };
51
+ }
52
+ export async function inspectSftpPath(sftp, remotePath) {
53
+ const stats = await call((done) => sftp.stat(remotePath, done));
54
+ return {
55
+ isFile: Boolean(stats?.isFile?.()),
56
+ isDirectory: Boolean(stats?.isDirectory?.()),
57
+ size: Number(stats?.size ?? 0),
58
+ mtime: Number(stats?.mtime ?? 0),
59
+ };
60
+ }
61
+ /** Copy a remote directory to a local directory, one file at a time: directories are created locally (empty ones
62
+ * included), symlinks are skipped and there is no byte/count cap; `onIgnored` reports the skipped names. */
63
+ export async function saveSftpTree(sftp, remotePath, targetRoot, options = {}) {
64
+ const rootStats = await call((done) => sftp.stat(remotePath, done));
65
+ if (!rootStats?.isDirectory?.()) {
66
+ throw errors.remoteFileUnavailable({
67
+ zh: '这个远端路径不是目录,无法按文件夹下载。',
68
+ en: 'This remote path is not a directory and cannot be downloaded as a folder.',
69
+ });
70
+ }
71
+ const localRoot = path.resolve(targetRoot);
72
+ // Case-insensitive local filesystems map `Report.md` and `report.md` to one file: the download would silently lose
73
+ // one of them. The default follows the platform (Windows and macOS both default to case-insensitive volumes);
74
+ // tests can force it either way.
75
+ const caseInsensitive = options.caseInsensitive ?? (process.platform === 'win32' || process.platform === 'darwin');
76
+ // The Windows metadata / shortcut names are only special on Windows: on Linux/macOS `*.lnk` or `desktop.ini` are
77
+ // ordinary files and must be downloaded like any other.
78
+ const ignoreWindowsNames = options.ignoreWindowsNames ?? process.platform === 'win32';
79
+ const insideRoot = (candidate) => {
80
+ const resolved = path.resolve(candidate);
81
+ if (resolved === localRoot || resolved.startsWith(localRoot + path.sep))
82
+ return resolved;
83
+ throw errors.remoteFileUnavailable({
84
+ zh: '远端文件名无法安全映射到本地目录。',
85
+ en: 'A remote file name cannot be mapped safely into the local directory.',
86
+ });
87
+ };
88
+ const members = [];
89
+ const ignoredNames = [];
90
+ let totalBytes = 0;
91
+ let totalFiles = 0;
92
+ let renamedFiles = 0;
93
+ const walk = async (directory, relative, localDir) => {
94
+ const listing = await call((done) => sftp.readdir(directory, done));
95
+ const items = Array.isArray(listing) ? listing.slice() : [];
96
+ items.sort((left, right) => String(left?.filename ?? '').localeCompare(String(right?.filename ?? '')));
97
+ // Names are claimed per directory, so a renamed member keeps its own children.
98
+ const used = new Set();
99
+ for (const item of items) {
100
+ const filename = String(item?.filename ?? '');
101
+ if (filename === '' || filename === '.' || filename === '..')
102
+ continue;
103
+ const attrs = item?.attrs ?? {};
104
+ if (attrs.isSymbolicLink?.() === true)
105
+ continue;
106
+ // Windows metadata and shell entries are never planted in a local download; the skipped names are reported in
107
+ // the result so nothing disappears silently.
108
+ if (ignoreWindowsNames && isIgnoredLocalName(filename)) {
109
+ ignoredNames.push(relative === '' ? filename : `${relative}/${filename}`);
110
+ continue;
111
+ }
112
+ const childRelative = relative === '' ? filename : relative + '/' + filename;
113
+ const childPath = path.posix.join(directory, filename);
114
+ const desired = insideRoot(path.join(localDir, safeLocalSegment(filename)));
115
+ const localPath = insideRoot(uniqueLocalPath(desired, used, { caseInsensitive }));
116
+ used.add(localPathKey(localPath, { caseInsensitive }));
117
+ if (attrs.isDirectory?.() === true) {
118
+ members.push({ relative: childRelative, isDirectory: true, localPath });
119
+ await walk(childPath, childRelative, localPath);
120
+ }
121
+ else if (attrs.isFile?.() === true) {
122
+ const size = Number(attrs.size ?? 0);
123
+ if (!Number.isFinite(size) || size < 0)
124
+ continue;
125
+ if (localPath !== desired)
126
+ renamedFiles += 1;
127
+ totalFiles += 1;
128
+ totalBytes += size;
129
+ members.push({ relative: childRelative, remotePath: childPath, size, localPath });
130
+ }
131
+ }
132
+ };
133
+ await walk(remotePath, '', localRoot);
134
+ if (typeof options.onInventory === 'function') {
135
+ try {
136
+ options.onInventory({ totalBytes, totalFiles });
137
+ }
138
+ catch {
139
+ // swallow-ok: inventory listeners must not break the download
140
+ }
141
+ }
142
+ if (ignoredNames.length > 0 && typeof options.onIgnored === 'function') {
143
+ try {
144
+ options.onIgnored(ignoredNames.slice());
145
+ }
146
+ catch {
147
+ // swallow-ok: the ignored-name listener must not break the download
148
+ }
149
+ }
150
+ await mkdir(localRoot, { recursive: true });
151
+ for (const member of members) {
152
+ if (member.isDirectory)
153
+ await mkdir(member.localPath, { recursive: true });
154
+ }
155
+ let doneBytes = 0;
156
+ let doneFiles = 0;
157
+ const report = () => {
158
+ try {
159
+ options.onProgress?.({ doneBytes, totalBytes, doneFiles, totalFiles });
160
+ }
161
+ catch {
162
+ // swallow-ok: progress listeners must not break the download
163
+ }
164
+ };
165
+ const cancelled = async () => {
166
+ await rm(localRoot, { recursive: true, force: true }).catch(() => { });
167
+ return { destination: localRoot, totalBytes, totalFiles, cancelled: true };
168
+ };
169
+ for (const member of members) {
170
+ if (member.isDirectory || typeof member.remotePath !== 'string')
171
+ continue;
172
+ if (options.isCancelled?.())
173
+ return cancelled();
174
+ await mkdir(path.dirname(member.localPath), { recursive: true });
175
+ try {
176
+ await copySftpFileToLocal(sftp, member.remotePath, member.localPath, (bytes) => {
177
+ doneBytes += bytes;
178
+ report();
179
+ }, options.isCancelled);
180
+ }
181
+ catch (error) {
182
+ if (options.isCancelled?.())
183
+ return cancelled();
184
+ throw error;
185
+ }
186
+ doneFiles += 1;
187
+ report();
188
+ }
189
+ return { destination: localRoot, totalBytes, totalFiles, renamedFiles, ignoredNames };
190
+ }
191
+ function assertReadableFile(stats) {
192
+ if (stats?.isDirectory?.()) {
193
+ throw errors.remoteFileUnavailable({
194
+ zh: '这是一个远端目录,不能作为文件下载。',
195
+ en: 'This remote path is a directory, not a downloadable file.',
196
+ });
197
+ }
198
+ }
199
+ /** Pipe one SFTP file into a local file, reporting bytes as they arrive. */
200
+ function copySftpFileToLocal(sftp, remotePath, localPath, onChunk, shouldCancel) {
201
+ return new Promise((resolve, reject) => {
202
+ let input;
203
+ try {
204
+ input = sftp.createReadStream(remotePath);
205
+ }
206
+ catch (error) {
207
+ reject(error);
208
+ return;
209
+ }
210
+ if (!input || typeof input.on !== 'function') {
211
+ reject(new Error('SFTP read stream is unavailable'));
212
+ return;
213
+ }
214
+ const output = createWriteStream(localPath, { flags: 'w' });
215
+ let settled = false;
216
+ const fail = (error) => {
217
+ if (settled)
218
+ return;
219
+ settled = true;
220
+ try {
221
+ input.destroy();
222
+ }
223
+ catch {
224
+ // swallow-ok: the read stream is already destroyed
225
+ }
226
+ const finish = () => reject(error);
227
+ try {
228
+ if (output.closed === true)
229
+ finish();
230
+ else {
231
+ output.once('close', finish);
232
+ output.destroy();
233
+ }
234
+ }
235
+ catch {
236
+ finish();
237
+ }
238
+ };
239
+ input.on('data', (chunk) => {
240
+ if (shouldCancel?.()) {
241
+ fail(new Error('download-cancelled'));
242
+ return;
243
+ }
244
+ try {
245
+ onChunk(Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk));
246
+ }
247
+ catch {
248
+ // swallow-ok: the progress listener must not break the transfer
249
+ }
250
+ });
251
+ pipeline(input, output).then(() => {
252
+ if (settled)
253
+ return;
254
+ settled = true;
255
+ resolve();
256
+ }, fail);
257
+ });
258
+ }