dsh-remote-go 0.1.0 → 0.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.md +64 -95
- package/{client.js → dist/client.js} +7805 -5486
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/dist/src/constants.js +67 -0
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +40 -21
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/src/api.js +0 -340
- package/src/atomic-json.js +0 -208
- package/src/bootstrap.js +0 -100
- package/src/connect-log.js +0 -39
- package/src/connect-pipeline.js +0 -463
- package/src/connect-progress.js +0 -135
- package/src/constants.js +0 -31
- package/src/diagnostics.js +0 -157
- package/src/download-jobs.js +0 -217
- package/src/errors.js +0 -316
- package/src/host-lifecycle.js +0 -187
- package/src/host-registry.js +0 -145
- package/src/host-runtime.js +0 -53
- package/src/host-view.js +0 -51
- package/src/index.js +0 -162
- package/src/key-files.js +0 -49
- package/src/known-hosts.js +0 -94
- package/src/layout.js +0 -35
- package/src/local-download.js +0 -162
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -89
- package/src/prompts.js +0 -132
- package/src/redact.js +0 -54
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -73
- package/src/remote-proc.js +0 -208
- package/src/remote-web.js +0 -300
- package/src/secrets.js +0 -79
- package/src/service.js +0 -250
- package/src/settings.js +0 -135
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -652
- package/src/store.js +0 -143
- package/src/tunnel.js +0 -73
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -28
- package/vendor/ssh2-entry.mjs +0 -12
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local download writer. Every download (single file or folder) is streamed from
|
|
3
|
+
* SFTP directly to a user-selected local directory. Nothing is archived or held in
|
|
4
|
+
* memory, and there is no byte or entry cap. Existing target names are renamed with
|
|
5
|
+
* a ` (2)`, ` (3)` suffix so a download never overwrites local data.
|
|
6
|
+
*
|
|
7
|
+
* The destination is a **write primitive that a remote host chooses the contents of** (the
|
|
8
|
+
* file or folder name comes from the remote tree), so it is fenced like one: only folders
|
|
9
|
+
* under the local user's home, and never a system, autorun or credential folder. Without this
|
|
10
|
+
* fence a compromised remote could ask the GUI to save its tree into
|
|
11
|
+
* `…\Start Menu\Programs\Startup` (or `~/.ssh/authorized_keys`) and run code on this machine at
|
|
12
|
+
* the next logon.
|
|
13
|
+
*/
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { mkdir, open, rm, stat } from 'node:fs/promises';
|
|
17
|
+
import { errors, isRemoteGoError } from './errors.js';
|
|
18
|
+
import { remoteFileName, safeLocalSegment } from './remote-path.js';
|
|
19
|
+
/**
|
|
20
|
+
* Path segments that execute something when the user logs in, or that authorize a login.
|
|
21
|
+
* Matched case-insensitively as a whole segment anywhere below the home directory, so both
|
|
22
|
+
* `…\Start Menu\Programs\Startup` and `~/.config/autostart` are covered. Shell startup files
|
|
23
|
+
* and the per-user containers that hold them (`~/.config`, `~/.local`, whose `bin` is on PATH in
|
|
24
|
+
* many distributions) are refused for the same reason, as are the macOS login-item folders
|
|
25
|
+
* (`~/Library/LaunchAgents`, `LaunchDaemons`, `StartupItems`) and the X session files.
|
|
26
|
+
*/
|
|
27
|
+
const FORBIDDEN_SEGMENTS = new Map([
|
|
28
|
+
['startup', 'autorun'],
|
|
29
|
+
['startupfolder', 'autorun'],
|
|
30
|
+
['startupitems', 'autorun'],
|
|
31
|
+
['autostart', 'autorun'],
|
|
32
|
+
['systemd', 'autorun'],
|
|
33
|
+
['launchagents', 'autorun'],
|
|
34
|
+
['launchdaemons', 'autorun'],
|
|
35
|
+
['.ssh', 'credentials'],
|
|
36
|
+
['.gnupg', 'credentials'],
|
|
37
|
+
['.config', 'login'],
|
|
38
|
+
['.local', 'login'],
|
|
39
|
+
['.bashrc', 'login'],
|
|
40
|
+
['.bash_profile', 'login'],
|
|
41
|
+
['.bash_login', 'login'],
|
|
42
|
+
['.bash_logout', 'login'],
|
|
43
|
+
['.profile', 'login'],
|
|
44
|
+
['.zshrc', 'login'],
|
|
45
|
+
['.zprofile', 'login'],
|
|
46
|
+
['.zshenv', 'login'],
|
|
47
|
+
['.zlogin', 'login'],
|
|
48
|
+
['.zlogout', 'login'],
|
|
49
|
+
['.kshrc', 'login'],
|
|
50
|
+
['.cshrc', 'login'],
|
|
51
|
+
['.tcshrc', 'login'],
|
|
52
|
+
['.login', 'login'],
|
|
53
|
+
['.logout', 'login'],
|
|
54
|
+
['.xsessionrc', 'login'],
|
|
55
|
+
['.xprofile', 'login'],
|
|
56
|
+
['.xinitrc', 'login'],
|
|
57
|
+
]);
|
|
58
|
+
/** `shell:startup` / `shell:common startup` name an autorun folder without spelling a path. */
|
|
59
|
+
const SHELL_FOLDER_RE = /^\s*shell\s*:/i;
|
|
60
|
+
/** Directories that belong to the OS; never a download target even if home somehow covers them. */
|
|
61
|
+
const SYSTEM_ROOTS = Object.freeze(process.platform === 'win32'
|
|
62
|
+
? ['C:\\Windows', 'C:\\Program Files', 'C:\\Program Files (x86)', 'C:\\ProgramData']
|
|
63
|
+
: ['/etc', '/usr', '/bin', '/sbin', '/lib', '/lib64', '/boot', '/opt', '/var', '/dev', '/proc', '/sys']);
|
|
64
|
+
/** A stronger reason wins when several segments of one path match (most specific first). */
|
|
65
|
+
const REASON_PRIORITY = ['autorun', 'credentials', 'login', 'system'];
|
|
66
|
+
/**
|
|
67
|
+
* One resolved path, comparable on this platform. Windows and macOS both have a
|
|
68
|
+
* case-insensitive default filesystem, so a case-insensitive compare is the one the OS itself
|
|
69
|
+
* would do (`C:\Users` vs `c:\users`, `/Users/Me` vs `/Users/me`).
|
|
70
|
+
*/
|
|
71
|
+
function comparable(value) {
|
|
72
|
+
return process.platform === 'win32' || process.platform === 'darwin' ? value.toLowerCase() : value;
|
|
73
|
+
}
|
|
74
|
+
function segmentsOf(resolved) {
|
|
75
|
+
return resolved.split(/[\\/]+/).filter((segment) => segment !== '');
|
|
76
|
+
}
|
|
77
|
+
function isInside(root, target) {
|
|
78
|
+
const base = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
|
|
79
|
+
return target === root || target.startsWith(base);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Locations whose *contents* run or authenticate at logon. A download may neither land inside
|
|
83
|
+
* one of them nor create one of their ancestors: a remote folder named `Microsoft` under
|
|
84
|
+
* `~/AppData/Roaming` would otherwise put a whole `Windows\Start Menu\Programs\Startup` tree on
|
|
85
|
+
* disk without any single path segment looking suspicious (macOS has the same shape under
|
|
86
|
+
* `~/Library`).
|
|
87
|
+
* @param home - resolved home directory.
|
|
88
|
+
* @returns resolved sensitive roots that exist by definition (not on disk).
|
|
89
|
+
*/
|
|
90
|
+
function sensitiveRoots(home) {
|
|
91
|
+
const roots = ['.config', '.local', '.ssh', '.gnupg'].map((name) => path.join(home, name));
|
|
92
|
+
roots.push(path.join(home, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu'));
|
|
93
|
+
for (const name of ['LaunchAgents', 'LaunchDaemons', 'StartupItems']) {
|
|
94
|
+
roots.push(path.join(home, 'Library', name));
|
|
95
|
+
}
|
|
96
|
+
const appData = typeof process.env.APPDATA === 'string' && process.env.APPDATA.trim() !== '';
|
|
97
|
+
if (appData)
|
|
98
|
+
roots.push(path.join(process.env.APPDATA, 'Microsoft', 'Windows', 'Start Menu'));
|
|
99
|
+
return roots;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Whether a path is a sensitive location, inside one, or an ancestor of one.
|
|
103
|
+
* @param target - resolved candidate path.
|
|
104
|
+
* @param home - resolved home directory.
|
|
105
|
+
*/
|
|
106
|
+
function isProtectedLocation(target, home) {
|
|
107
|
+
const resolved = comparable(target);
|
|
108
|
+
for (const root of sensitiveRoots(home)) {
|
|
109
|
+
const sensitive = comparable(path.resolve(root));
|
|
110
|
+
if (isInside(sensitive, resolved) || isInside(resolved, sensitive))
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
/** The concrete home directory a policy call is judged against. */
|
|
116
|
+
function homeOf(options = {}) {
|
|
117
|
+
return path.resolve(options.home ?? homedir());
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Whether one local folder may receive a remote download.
|
|
121
|
+
* @param destination - the folder the client asked to save into.
|
|
122
|
+
* @param options - the local user's home (defaults to the OS home).
|
|
123
|
+
* @returns a refusal reason, or null when the folder is acceptable. Pure: no filesystem
|
|
124
|
+
* access, so it is testable.
|
|
125
|
+
*/
|
|
126
|
+
export function destinationPolicy(destination, options = {}) {
|
|
127
|
+
if (typeof destination !== 'string' || destination.trim() === '' || destination.includes('\0'))
|
|
128
|
+
return 'invalid';
|
|
129
|
+
if (SHELL_FOLDER_RE.test(destination))
|
|
130
|
+
return 'autorun';
|
|
131
|
+
const home = comparable(homeOf(options));
|
|
132
|
+
const target = comparable(path.resolve(destination));
|
|
133
|
+
if (!isInside(home, target))
|
|
134
|
+
return 'outside-home';
|
|
135
|
+
const segments = segmentsOf(target);
|
|
136
|
+
const reasons = new Set();
|
|
137
|
+
for (const segment of segments) {
|
|
138
|
+
const reason = FORBIDDEN_SEGMENTS.get(segment.toLowerCase());
|
|
139
|
+
if (reason !== undefined)
|
|
140
|
+
reasons.add(reason);
|
|
141
|
+
}
|
|
142
|
+
// `…\Start Menu\Programs`: a two-segment location whose entries appear in the Start menu.
|
|
143
|
+
for (let at = 1; at < segments.length; at += 1) {
|
|
144
|
+
if (segments[at - 1].toLowerCase() === 'start menu' && segments[at].toLowerCase() === 'programs') {
|
|
145
|
+
reasons.add('autorun');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const root of SYSTEM_ROOTS) {
|
|
149
|
+
if (isInside(comparable(path.resolve(root)), target))
|
|
150
|
+
reasons.add('system');
|
|
151
|
+
}
|
|
152
|
+
for (const reason of REASON_PRIORITY)
|
|
153
|
+
if (reasons.has(reason))
|
|
154
|
+
return reason;
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
/** The client-facing refusal for one destination policy result. */
|
|
158
|
+
function destinationRefusal(reason) {
|
|
159
|
+
if (reason === 'outside-home') {
|
|
160
|
+
return errors.invalidInput('destination', {
|
|
161
|
+
zh: '只能保存到本机用户主目录下的文件夹(防止写入系统或自启动位置)。',
|
|
162
|
+
en: 'Downloads must go to a folder under this machine’s home directory (system and autorun locations are refused).',
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
if (reason === 'autorun') {
|
|
166
|
+
return errors.invalidInput('destination', {
|
|
167
|
+
zh: '不能保存到自启动目录(例如 Startup / autostart / shell:startup)。',
|
|
168
|
+
en: 'An autorun folder (for example Startup / autostart / shell:startup) cannot be a download target.',
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
if (reason === 'credentials') {
|
|
172
|
+
return errors.invalidInput('destination', {
|
|
173
|
+
zh: '不能保存到 SSH / GPG 配置目录(例如 .ssh)。',
|
|
174
|
+
en: 'An SSH / GPG configuration folder (for example .ssh) cannot be a download target.',
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
if (reason === 'login') {
|
|
178
|
+
return errors.invalidInput('destination', {
|
|
179
|
+
zh: '不能保存到登录脚本或用户配置目录(例如 .bashrc / .profile / .config / .local)。',
|
|
180
|
+
en: 'A login script or user configuration folder (for example .bashrc / .profile / .config / .local) cannot be a download target.',
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
if (reason === 'protected') {
|
|
184
|
+
return errors.invalidInput('destination', {
|
|
185
|
+
zh: '不能保存到会在登录或启动时生效的位置(自启动、登录脚本或凭据目录及其上级目录)。',
|
|
186
|
+
en: 'A location that runs or authenticates at logon (autorun, login scripts, credentials, or one of their parent folders) cannot be a download target.',
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
if (reason === 'system') {
|
|
190
|
+
return errors.invalidInput('destination', {
|
|
191
|
+
zh: '不能保存到系统目录。',
|
|
192
|
+
en: 'A system directory cannot be a download target.',
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return errors.invalidInput('destination', {
|
|
196
|
+
zh: '请选择本机的保存文件夹。',
|
|
197
|
+
en: 'Choose a destination folder on this machine.',
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Refuse a path the remote host named inside an already-accepted destination.
|
|
202
|
+
*
|
|
203
|
+
* The destination is chosen locally, but the *name* below it comes from the remote tree
|
|
204
|
+
* (`~/Downloads/…`, `~/.config` + a remote folder called `autostart`, `~` + a remote file called
|
|
205
|
+
* `.bash_login`). This is the check that turns those combinations into a refusal.
|
|
206
|
+
* @param candidate - resolved folder or file path about to be created.
|
|
207
|
+
* @throws `invalid-input` when the path is protected.
|
|
208
|
+
*/
|
|
209
|
+
function assertCandidateAllowed(candidate, options = {}) {
|
|
210
|
+
const refusal = destinationPolicy(candidate, options);
|
|
211
|
+
if (refusal !== null)
|
|
212
|
+
throw destinationRefusal(refusal);
|
|
213
|
+
if (isProtectedLocation(candidate, homeOf(options)))
|
|
214
|
+
throw destinationRefusal('protected');
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Resolve and check one download destination.
|
|
218
|
+
* @param destination - absolute local folder.
|
|
219
|
+
* @param options - the local user's home, for tests.
|
|
220
|
+
* @returns the resolved folder.
|
|
221
|
+
*/
|
|
222
|
+
async function requireDestination(destination, options = {}) {
|
|
223
|
+
const refusal = destinationPolicy(destination, options);
|
|
224
|
+
if (refusal !== null)
|
|
225
|
+
throw destinationRefusal(refusal);
|
|
226
|
+
// `destinationPolicy` accepts only a non-empty string path, so by here the unknown is a
|
|
227
|
+
// string; the `as` restates that narrowing instead of adding a second runtime check.
|
|
228
|
+
const base = path.resolve(destination);
|
|
229
|
+
try {
|
|
230
|
+
const info = await stat(base);
|
|
231
|
+
if (!info.isDirectory()) {
|
|
232
|
+
throw errors.invalidInput('destination', {
|
|
233
|
+
zh: '选择的保存位置不是文件夹。',
|
|
234
|
+
en: 'The selected destination is not a folder.',
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
if (isRemoteGoError(error))
|
|
240
|
+
throw error;
|
|
241
|
+
throw errors.invalidInput('destination', {
|
|
242
|
+
zh: '选择的保存文件夹不存在或不可写。',
|
|
243
|
+
en: 'The selected destination folder does not exist or cannot be written.',
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return base;
|
|
247
|
+
}
|
|
248
|
+
async function createUniqueFolder(base, name, options = {}) {
|
|
249
|
+
const safeName = safeLocalSegment(name) || 'download';
|
|
250
|
+
for (let index = 1; index <= 999; index += 1) {
|
|
251
|
+
const candidate = path.join(base, index === 1 ? safeName : `${safeName} (${index})`);
|
|
252
|
+
// The root's name comes from the remote tree, so it is judged before anything is created:
|
|
253
|
+
// `~/.config` + a remote folder called `autostart` must fail here, with zero writes.
|
|
254
|
+
assertCandidateAllowed(candidate, options);
|
|
255
|
+
try {
|
|
256
|
+
await mkdir(candidate);
|
|
257
|
+
return candidate;
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
// Only EEXIST means "this name is taken, try the next suffix"; a thrown value is
|
|
261
|
+
// `unknown`, and the `as` restates the one field this branch reads.
|
|
262
|
+
if (error?.code !== 'EEXIST')
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
throw errors.invalidInput('destination', {
|
|
267
|
+
zh: '目标目录里已经有太多同名文件夹,请换一个目录。',
|
|
268
|
+
en: 'The destination already contains too many folders with this name; choose another directory.',
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
async function createUniqueFile(base, name, options = {}) {
|
|
272
|
+
const safeName = safeLocalSegment(name) || 'download';
|
|
273
|
+
const extension = path.extname(safeName);
|
|
274
|
+
const stem = path.basename(safeName, extension) || 'download';
|
|
275
|
+
for (let index = 1; index <= 999; index += 1) {
|
|
276
|
+
const fileName = index === 1 ? safeName : `${stem} (${index})${extension}`;
|
|
277
|
+
const candidate = path.join(base, fileName);
|
|
278
|
+
// The remote names the file: `~` + `.bash_login` is a login script, not a download.
|
|
279
|
+
assertCandidateAllowed(candidate, options);
|
|
280
|
+
try {
|
|
281
|
+
const handle = await open(candidate, 'wx', 0o600);
|
|
282
|
+
await handle.close();
|
|
283
|
+
return candidate;
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
// Same EEXIST-only contract as the folder name search above.
|
|
287
|
+
if (error?.code !== 'EEXIST')
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
throw errors.invalidInput('destination', {
|
|
292
|
+
zh: '目标目录里已经有太多同名文件,请换一个目录。',
|
|
293
|
+
en: 'The destination already contains too many files with this name; choose another directory.',
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
function toDownloadError(error) {
|
|
297
|
+
// `isRemoteGoError` only declares a boolean (it lives in the P1a set); the `as` restates
|
|
298
|
+
// the narrowing its `instanceof` proves at runtime.
|
|
299
|
+
if (isRemoteGoError(error))
|
|
300
|
+
return error;
|
|
301
|
+
return errors.remoteFileUnavailable(undefined, {
|
|
302
|
+
technical: String(error?.message ?? error ?? '').slice(0, 300),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Stream one remote file into `destination`, creating an auto-renamed local file.
|
|
307
|
+
* @param runtime - connected host runtime.
|
|
308
|
+
* @param remotePath - normalized absolute remote path.
|
|
309
|
+
* @param destination - absolute local directory.
|
|
310
|
+
*/
|
|
311
|
+
export async function saveHostFile(runtime, remotePath, destination, options = {}) {
|
|
312
|
+
if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
|
|
313
|
+
throw errors.remoteFileUnavailable({
|
|
314
|
+
zh: '这台主机还没有连接,无法读取远端文件。',
|
|
315
|
+
en: 'This host is not connected, so the remote file cannot be read.',
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
if (typeof runtime.ssh.saveRemoteFile !== 'function') {
|
|
319
|
+
throw errors.internal('the SSH transport does not support file saves');
|
|
320
|
+
}
|
|
321
|
+
const base = await requireDestination(destination, options);
|
|
322
|
+
const name = remoteFileName(remotePath);
|
|
323
|
+
let localPath = null;
|
|
324
|
+
try {
|
|
325
|
+
localPath = await createUniqueFile(base, name, options);
|
|
326
|
+
const result = await runtime.ssh.saveRemoteFile(remotePath, localPath, options);
|
|
327
|
+
return {
|
|
328
|
+
path: remotePath,
|
|
329
|
+
kind: 'file',
|
|
330
|
+
name: path.basename(localPath),
|
|
331
|
+
destination: localPath,
|
|
332
|
+
totalBytes: Number(result?.size ?? 0),
|
|
333
|
+
files: 1,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
if (localPath)
|
|
338
|
+
await rm(localPath, { force: true }).catch(() => { });
|
|
339
|
+
throw toDownloadError(error);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Copy one remote folder into `destination` as individual local files.
|
|
344
|
+
* @param runtime - connected host runtime.
|
|
345
|
+
* @param remotePath - normalized absolute remote folder path.
|
|
346
|
+
* @param destination - absolute local directory.
|
|
347
|
+
*/
|
|
348
|
+
export async function saveHostFolder(runtime, remotePath, destination, options = {}) {
|
|
349
|
+
if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
|
|
350
|
+
throw errors.remoteFileUnavailable({
|
|
351
|
+
zh: '这台主机还没有连接,无法读取远端文件夹。',
|
|
352
|
+
en: 'This host is not connected, so the remote folder cannot be read.',
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
if (typeof runtime.ssh.saveRemoteTree !== 'function') {
|
|
356
|
+
throw errors.internal('the SSH transport does not support folder saves');
|
|
357
|
+
}
|
|
358
|
+
const base = await requireDestination(destination, options);
|
|
359
|
+
const name = remoteFileName(remotePath);
|
|
360
|
+
let root = null;
|
|
361
|
+
try {
|
|
362
|
+
root = await createUniqueFolder(base, name, options);
|
|
363
|
+
const result = await runtime.ssh.saveRemoteTree(remotePath, root, options);
|
|
364
|
+
return {
|
|
365
|
+
path: remotePath,
|
|
366
|
+
kind: 'folder',
|
|
367
|
+
name,
|
|
368
|
+
destination: result?.destination ?? root,
|
|
369
|
+
totalBytes: Number(result?.totalBytes ?? 0),
|
|
370
|
+
files: Number(result?.totalFiles ?? 0),
|
|
371
|
+
...(result?.cancelled === true ? { cancelled: true } : {}),
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
if (root)
|
|
376
|
+
await rm(root, { recursive: true, force: true }).catch(() => { });
|
|
377
|
+
throw toDownloadError(error);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
export { requireDestination };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local SSH material (read-only): `~/.ssh/config` and `~/.ssh/known_hosts`; never writes, never prompts.
|
|
3
|
+
*/
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { readFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
export async function loadLocalSshMaterial(input) {
|
|
8
|
+
const sshDir = path.join(input.home, '.ssh');
|
|
9
|
+
const configPath = path.join(sshDir, 'config');
|
|
10
|
+
const knownHostsPath = path.join(sshDir, 'known_hosts');
|
|
11
|
+
const exists = input.exists ?? existsSync;
|
|
12
|
+
const read = input.readFileImpl ?? readFile;
|
|
13
|
+
let configText = '';
|
|
14
|
+
let knownHostsText = '';
|
|
15
|
+
try {
|
|
16
|
+
if (exists(configPath))
|
|
17
|
+
configText = await read(configPath, 'utf8');
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
configText = '';
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
if (exists(knownHostsPath))
|
|
24
|
+
knownHostsText = await read(knownHostsPath, 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
knownHostsText = '';
|
|
28
|
+
}
|
|
29
|
+
return { sshDir, configText, knownHostsText, configPath, knownHostsPath };
|
|
30
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detect the DSH version of the local installation; the remote runtime is pinned to this exact version, never to npm `latest`.
|
|
3
|
+
*/
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { readFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { createKernelAdapter } from './kernel-adapter.js';
|
|
8
|
+
import { isPlainObject } from './util.js';
|
|
9
|
+
import { normalizeVersion, parseVersion } from './version.js';
|
|
10
|
+
export async function detectLocalVersion(input = {}) {
|
|
11
|
+
const env = input.env ?? process.env;
|
|
12
|
+
const explicit = env.DSH_VERSION || env.DSH_RUNTIME_VERSION;
|
|
13
|
+
if (explicit && parseVersion(normalizeVersion(explicit))) {
|
|
14
|
+
return { version: normalizeVersion(explicit), source: 'env' };
|
|
15
|
+
}
|
|
16
|
+
// The web client-module registry publishes the Host release identity, which
|
|
17
|
+
// releases share with the CLI package version.
|
|
18
|
+
const release = createKernelAdapter(input.ctx).clientModuleRelease();
|
|
19
|
+
if (release.state === 'ok' && release.value !== null) {
|
|
20
|
+
const version = release.value.version;
|
|
21
|
+
if (version !== null && parseVersion(normalizeVersion(version))) {
|
|
22
|
+
return { version: normalizeVersion(version), source: 'client-modules' };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
else if (release.state === 'changed') {
|
|
26
|
+
// A moved release identity is a kernel this probe does not recognize: keep the package.json
|
|
27
|
+
// fallback, but say so — a silently wrong pin breaks every connect that follows.
|
|
28
|
+
input.logger?.warn?.('[dsh-remote-go] the client-module release identity changed shape; falling back to package.json:', release.detail);
|
|
29
|
+
}
|
|
30
|
+
for (const candidate of candidatePackageJsons(input)) {
|
|
31
|
+
try {
|
|
32
|
+
if (!existsSync(candidate))
|
|
33
|
+
continue;
|
|
34
|
+
const text = await readFile(candidate, 'utf8');
|
|
35
|
+
// A package.json on disk is untrusted input: narrow it before reading fields.
|
|
36
|
+
const parsed = JSON.parse(text);
|
|
37
|
+
if (isPlainObject(parsed) &&
|
|
38
|
+
parsed.name === '@deepseek-ai/dsh' &&
|
|
39
|
+
typeof parsed.version === 'string' &&
|
|
40
|
+
parseVersion(normalizeVersion(parsed.version))) {
|
|
41
|
+
return { version: normalizeVersion(parsed.version), source: `package.json:${candidate}` };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// swallow-ok: a candidate that is absent or unparsable is skipped by design
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return { version: null, source: 'unknown' };
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The local DSH build's Node engine range (`engines.node`). It is the source of
|
|
52
|
+
* truth for the managed Node version the plugin installs on the remote: the
|
|
53
|
+
* remote runs this exact DSH version, so it must satisfy this declaration.
|
|
54
|
+
*
|
|
55
|
+
* Best-effort like the version probe: an unreadable or missing package yields
|
|
56
|
+
* `range: null` and the caller falls back to the plugin's own floor.
|
|
57
|
+
*/
|
|
58
|
+
export async function detectLocalEnginesNode(input = {}) {
|
|
59
|
+
for (const candidate of candidatePackageJsons(input)) {
|
|
60
|
+
try {
|
|
61
|
+
if (!existsSync(candidate))
|
|
62
|
+
continue;
|
|
63
|
+
const parsed = JSON.parse(await readFile(candidate, 'utf8'));
|
|
64
|
+
const engines = isPlainObject(parsed) && isPlainObject(parsed.engines) ? parsed.engines : null;
|
|
65
|
+
const range = engines?.node;
|
|
66
|
+
if (typeof range === 'string' && range.trim() !== '') {
|
|
67
|
+
return { range: range.trim(), source: `package.json:${candidate}` };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// swallow-ok: the same candidate scan as the version probe above
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { range: null, source: 'unknown' };
|
|
75
|
+
}
|
|
76
|
+
export function candidatePackageJsons(input = {}) {
|
|
77
|
+
const out = [];
|
|
78
|
+
const argv1 = input.argv1 ?? process.argv[1] ?? '';
|
|
79
|
+
const marker = `${path.sep}@deepseek-ai${path.sep}dsh${path.sep}`;
|
|
80
|
+
const markerIndex = argv1.indexOf(marker);
|
|
81
|
+
if (markerIndex >= 0) {
|
|
82
|
+
out.push(path.join(argv1.slice(0, markerIndex + marker.length), 'package.json'));
|
|
83
|
+
}
|
|
84
|
+
// Electron's `resourcesPath` is not on the standard Process type; it is read duck-typed.
|
|
85
|
+
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
|
|
86
|
+
if (typeof resourcesPath === 'string' && resourcesPath !== '') {
|
|
87
|
+
out.push(path.join(resourcesPath, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'));
|
|
88
|
+
out.push(path.join(resourcesPath, 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'));
|
|
89
|
+
out.push(path.join(resourcesPath, 'app', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'));
|
|
90
|
+
}
|
|
91
|
+
// Walk up from the CLI entry looking for a nested package.
|
|
92
|
+
let dir = argv1 ? path.dirname(argv1) : (input.cwd ?? process.cwd());
|
|
93
|
+
for (let i = 0; i < 8; i += 1) {
|
|
94
|
+
out.push(path.join(dir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'));
|
|
95
|
+
const parent = path.dirname(dir);
|
|
96
|
+
if (parent === dir)
|
|
97
|
+
break;
|
|
98
|
+
dir = parent;
|
|
99
|
+
}
|
|
100
|
+
return [...new Set(out)];
|
|
101
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { shellQuote } from '../util.js';
|
|
2
|
+
export const NODE_DIST_BASES = Object.freeze([
|
|
3
|
+
'https://nodejs.org/dist',
|
|
4
|
+
'https://npmmirror.com/mirrors/node',
|
|
5
|
+
]);
|
|
6
|
+
/**
|
|
7
|
+
* Pick the downloader both install scripts share: curl when present, else wget.
|
|
8
|
+
* Exit 9 is the "neither tool" contract the caller maps to `no-fetch`.
|
|
9
|
+
*/
|
|
10
|
+
const FETCH_PROLOGUE = `if command -v curl >/dev/null 2>&1; then
|
|
11
|
+
FETCH=curl
|
|
12
|
+
elif command -v wget >/dev/null 2>&1; then
|
|
13
|
+
FETCH=wget
|
|
14
|
+
else
|
|
15
|
+
printf 'FAILED\\tno-fetch\\n'
|
|
16
|
+
exit 9
|
|
17
|
+
fi`;
|
|
18
|
+
export function buildNodeChecksumScript(input) {
|
|
19
|
+
const bases = (input.bases ?? NODE_DIST_BASES).map((base) => shellQuote(base)).join(' ');
|
|
20
|
+
return `set -u
|
|
21
|
+
DL=${shellQuote(input.downloadDir)}
|
|
22
|
+
VERSION=${shellQuote(input.version)}
|
|
23
|
+
FILE="node-v$VERSION-linux-${input.arch}.tar.gz"
|
|
24
|
+
mkdir -p "$DL" || exit 3
|
|
25
|
+
${FETCH_PROLOGUE}
|
|
26
|
+
fetch() {
|
|
27
|
+
URL=$1
|
|
28
|
+
OUT=$2
|
|
29
|
+
if [ "$FETCH" = curl ]; then
|
|
30
|
+
curl -fsSL --connect-timeout 10 --max-time 60 -o "$OUT" "$URL" 2>/dev/null
|
|
31
|
+
else
|
|
32
|
+
wget -q -T 30 -t 1 -O "$OUT" "$URL" 2>/dev/null
|
|
33
|
+
fi
|
|
34
|
+
}
|
|
35
|
+
for BASE in ${bases}; do
|
|
36
|
+
TMP="$DL/.shasums.$$"
|
|
37
|
+
if fetch "$BASE/v$VERSION/SHASUMS256.txt" "$TMP"; then
|
|
38
|
+
LINE=$(grep -F " $FILE" "$TMP" | head -n 1 || true)
|
|
39
|
+
if [ -n "$LINE" ]; then
|
|
40
|
+
SHA=$(printf '%s\\n' "$LINE" | awk '{print $1}')
|
|
41
|
+
if [ "\${#SHA}" -eq 64 ]; then
|
|
42
|
+
printf 'CHECKSUM\\t%s\\t%s\\n' "$BASE" "$SHA"
|
|
43
|
+
rm -f "$TMP"
|
|
44
|
+
exit 0
|
|
45
|
+
fi
|
|
46
|
+
fi
|
|
47
|
+
fi
|
|
48
|
+
rm -f "$TMP"
|
|
49
|
+
done
|
|
50
|
+
exit 5
|
|
51
|
+
`;
|
|
52
|
+
}
|
|
53
|
+
export function parseNodeChecksumOutput(stdout, input) {
|
|
54
|
+
const file = `node-v${input.version}-linux-${input.arch}.tar.gz`;
|
|
55
|
+
const allowed = input.bases ?? NODE_DIST_BASES;
|
|
56
|
+
for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
|
|
57
|
+
const parts = rawLine.split('\t');
|
|
58
|
+
if (parts[0] !== 'CHECKSUM' || parts.length < 3)
|
|
59
|
+
continue;
|
|
60
|
+
const [, base, sha256] = parts;
|
|
61
|
+
if (!allowed.includes(base))
|
|
62
|
+
continue;
|
|
63
|
+
if (!/^[0-9a-f]{64}$/.test(sha256))
|
|
64
|
+
continue;
|
|
65
|
+
return { base, version: input.version, sha256, file };
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
export function buildNodeInstallScript(input) {
|
|
70
|
+
const bases = (input.bases ?? NODE_DIST_BASES).map((base) => shellQuote(base)).join(' ');
|
|
71
|
+
const { release } = input;
|
|
72
|
+
return `set -eu
|
|
73
|
+
NODE_DIR=${shellQuote(input.layout.nodeDir)}
|
|
74
|
+
DL=${shellQuote(input.layout.downloadDir)}
|
|
75
|
+
VERSION=${shellQuote(release.version)}
|
|
76
|
+
SHA=${shellQuote(release.sha256)}
|
|
77
|
+
FILE=${shellQuote(release.file)}
|
|
78
|
+
BINDIR="$NODE_DIR/v$VERSION"
|
|
79
|
+
mkdir -p "$NODE_DIR" "$DL" || exit 3
|
|
80
|
+
if [ -x "$BINDIR/bin/node" ] && [ "$("$BINDIR/bin/node" -v 2>/dev/null || true)" = "v$VERSION" ]; then
|
|
81
|
+
printf 'READY\\t%s\\n' "$BINDIR"
|
|
82
|
+
exit 0
|
|
83
|
+
fi
|
|
84
|
+
${FETCH_PROLOGUE}
|
|
85
|
+
verify() {
|
|
86
|
+
TARGET=$1
|
|
87
|
+
if command -v sha256sum >/dev/null 2>&1; then
|
|
88
|
+
printf '%s %s\\n' "$SHA" "$TARGET" | sha256sum -c - >/dev/null 2>&1
|
|
89
|
+
elif command -v shasum >/dev/null 2>&1; then
|
|
90
|
+
printf '%s %s\\n' "$SHA" "$TARGET" | shasum -a 256 -c - >/dev/null 2>&1
|
|
91
|
+
elif command -v openssl >/dev/null 2>&1; then
|
|
92
|
+
GOT=$(openssl dgst -sha256 "$TARGET" 2>/dev/null | sed 's/.*= //')
|
|
93
|
+
[ "$GOT" = "$SHA" ]
|
|
94
|
+
else
|
|
95
|
+
return 127
|
|
96
|
+
fi
|
|
97
|
+
}
|
|
98
|
+
TARBALL="$DL/$FILE"
|
|
99
|
+
if [ -f "$TARBALL" ] && verify "$TARBALL"; then
|
|
100
|
+
echo "STEP\\treuse"
|
|
101
|
+
else
|
|
102
|
+
OK=0
|
|
103
|
+
for BASE in ${bases}; do
|
|
104
|
+
PART="$TARBALL.part.$$"
|
|
105
|
+
rm -f "$PART"
|
|
106
|
+
printf 'STEP\\tdownload\\t%s\\n' "$BASE"
|
|
107
|
+
if [ "$FETCH" = curl ]; then
|
|
108
|
+
curl -fsSL --connect-timeout 15 --max-time 600 -o "$PART" "$BASE/v$VERSION/$FILE" &
|
|
109
|
+
else
|
|
110
|
+
wget -q -T 60 -t 3 -O "$PART" "$BASE/v$VERSION/$FILE" &
|
|
111
|
+
fi
|
|
112
|
+
PID=$!
|
|
113
|
+
while kill -0 "$PID" 2>/dev/null; do
|
|
114
|
+
printf 'BYTES\\t%s\\n' "$(wc -c < "$PART" 2>/dev/null || echo 0)"
|
|
115
|
+
sleep 2
|
|
116
|
+
done
|
|
117
|
+
if wait "$PID" && verify "$PART"; then
|
|
118
|
+
mv "$PART" "$TARBALL"
|
|
119
|
+
OK=1
|
|
120
|
+
break
|
|
121
|
+
fi
|
|
122
|
+
printf 'FAILED\\tchecksum\\t%s\\n' "$BASE"
|
|
123
|
+
rm -f "$PART"
|
|
124
|
+
done
|
|
125
|
+
if [ "$OK" -ne 1 ]; then
|
|
126
|
+
echo "FAILED\\tdownload"
|
|
127
|
+
exit 6
|
|
128
|
+
fi
|
|
129
|
+
fi
|
|
130
|
+
echo "STEP\\textract"
|
|
131
|
+
TMPX="$NODE_DIR/.extract.$$"
|
|
132
|
+
rm -rf "$TMPX"
|
|
133
|
+
mkdir -p "$TMPX"
|
|
134
|
+
if ! tar -xzf "$TARBALL" -C "$TMPX" --strip-components=1; then
|
|
135
|
+
echo "FAILED\\textract"
|
|
136
|
+
rm -rf "$TMPX"
|
|
137
|
+
exit 7
|
|
138
|
+
fi
|
|
139
|
+
if [ ! -x "$TMPX/bin/node" ]; then
|
|
140
|
+
echo "FAILED\\textract"
|
|
141
|
+
rm -rf "$TMPX"
|
|
142
|
+
exit 7
|
|
143
|
+
fi
|
|
144
|
+
GOT=$("$TMPX/bin/node" -v 2>/dev/null || true)
|
|
145
|
+
if [ "$GOT" != "v$VERSION" ]; then
|
|
146
|
+
echo "FAILED\\tverify"
|
|
147
|
+
rm -rf "$TMPX"
|
|
148
|
+
exit 8
|
|
149
|
+
fi
|
|
150
|
+
rm -rf "$BINDIR"
|
|
151
|
+
mv "$TMPX" "$BINDIR"
|
|
152
|
+
rm -f "$TARBALL"
|
|
153
|
+
for OLD in "$NODE_DIR"/v*; do
|
|
154
|
+
[ -d "$OLD" ] || continue
|
|
155
|
+
[ "$OLD" = "$BINDIR" ] && continue
|
|
156
|
+
rm -rf "$OLD"
|
|
157
|
+
done
|
|
158
|
+
printf 'READY\\t%s\\n' "$BINDIR"
|
|
159
|
+
`;
|
|
160
|
+
}
|