pi-web-ui 0.102.0 → 0.103.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/CHANGELOG.md +29 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/dist/server/agent-service-daemon.js +17 -10
- package/dist/server/agent-service.js +125 -49
- package/dist/server/bash-tool.js +19 -1
- package/dist/server/client-state.js +9 -1
- package/dist/server/dispatch-domain-handlers.js +66 -0
- package/dist/server/edit-soft-tool.js +15 -3
- package/dist/server/files-service.js +636 -14
- package/dist/server/index.js +7 -1
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/read-tool.js +11 -4
- package/dist/server/remote-ssh-service.js +1314 -0
- package/dist/server/scm.js +16 -0
- package/dist/server/terminals.js +65 -21
- package/dist/server/tool-guards.js +18 -6
- package/dist/server/virtual-tui.js +258 -0
- package/dist/server/webui-context.js +109 -4
- package/package.json +7 -1
- package/web/dist/assets/TerminalPanel-Dk8E4DaC.js +3 -0
- package/web/dist/assets/index-CYQdZEbx.css +1 -0
- package/web/dist/assets/index-Pl0V0tEL.js +680 -0
- package/web/dist/index.html +4 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/TerminalPanel-CYGOzbPT.js +0 -3
- package/web/dist/assets/index-CP71PHb6.js +0 -680
- package/web/dist/assets/index-ytRwL6j0.css +0 -1
|
@@ -0,0 +1,1314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* remote-ssh-service.ts — 远程 SSH 连接管理、环境探针、SFTP 文件系统与远程命令/终端服务。
|
|
3
|
+
*
|
|
4
|
+
* 职责:
|
|
5
|
+
* 1. 维护远程 SSH 连接池(按 user@host:port 复用、并发单飞握手、断线自动重连、空闲超时回收);
|
|
6
|
+
* 2. 远程环境探针(Probe):检测系统架构、基础依赖(git/node/bash/python)及包管理器;
|
|
7
|
+
* 3. 远程目录浏览与文件操作(SFTP):为右栏文件树、文件预览/编辑、上传及 AI 工具提供远程读写;
|
|
8
|
+
* 4. 远程命令执行与虚拟 PTY 终端:通过已鉴权的 ssh2 连接直接开启交互式 Shell 与命令执行;
|
|
9
|
+
* 5. SSH Profiles 本地安全持久化:凭据使用 AES-256-GCM 加密,支持按 URI 自动提取凭据重连;
|
|
10
|
+
* 6. 远程工作区本地会话目录映射:对话 JSONL 保存在本地 `<dataDir>/remote-workspaces/<slug>`。
|
|
11
|
+
*/
|
|
12
|
+
import { Client } from "ssh2";
|
|
13
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, promises as fs } from "node:fs";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 连接空闲 30 分钟自动断开
|
|
18
|
+
const PROBE_TIMEOUT_MS = 25_000;
|
|
19
|
+
const DEFAULT_KEY_CANDIDATES = ["~/.ssh/id_ed25519", "~/.ssh/id_ecdsa", "~/.ssh/id_rsa", "~/.ssh/id_dsa"];
|
|
20
|
+
/** `~` 路径展开 */
|
|
21
|
+
export function expandHome(p) {
|
|
22
|
+
if (p === undefined)
|
|
23
|
+
return undefined;
|
|
24
|
+
const s = p.trim();
|
|
25
|
+
if (!s)
|
|
26
|
+
return s;
|
|
27
|
+
if (s === "~")
|
|
28
|
+
return os.homedir();
|
|
29
|
+
if (s.startsWith("~/") || s.startsWith("~\\")) {
|
|
30
|
+
return path.join(os.homedir(), s.slice(2));
|
|
31
|
+
}
|
|
32
|
+
return s;
|
|
33
|
+
}
|
|
34
|
+
/** 判断路径是否为 ssh:// 远程工作区 URI */
|
|
35
|
+
export function isRemoteWorkspaceUri(uri) {
|
|
36
|
+
return Boolean(uri && uri.trim().startsWith("ssh://"));
|
|
37
|
+
}
|
|
38
|
+
/** 解析 ssh://user@host:port/remote/path */
|
|
39
|
+
export function parseRemoteWorkspaceUri(uri) {
|
|
40
|
+
if (!isRemoteWorkspaceUri(uri))
|
|
41
|
+
return null;
|
|
42
|
+
const trimmed = uri.trim();
|
|
43
|
+
const m = /^ssh:\/\/([^@]+)@([^:/]+)(?::(\d+))?(\/.*)?$/.exec(trimmed);
|
|
44
|
+
if (!m)
|
|
45
|
+
return null;
|
|
46
|
+
const username = m[1];
|
|
47
|
+
const host = m[2];
|
|
48
|
+
const port = m[3] ? parseInt(m[3], 10) || 22 : 22;
|
|
49
|
+
const rawPath = m[4] ? m[4].replace(/\\/g, "/") : "/";
|
|
50
|
+
const remotePath = path.posix.normalize(rawPath).replace(/\/+$/, "") || "/";
|
|
51
|
+
return {
|
|
52
|
+
username,
|
|
53
|
+
host,
|
|
54
|
+
port,
|
|
55
|
+
remotePath,
|
|
56
|
+
hostKey: `${username}@${host}:${port}`,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** 构造规范的 ssh://user@host:port/remote/path */
|
|
60
|
+
export function formatRemoteWorkspaceUri(username, host, port, remotePath) {
|
|
61
|
+
const cleanPath = path.posix.normalize((remotePath || "/").replace(/\\/g, "/"));
|
|
62
|
+
const normPath = cleanPath.startsWith("/") ? cleanPath : `/${cleanPath}`;
|
|
63
|
+
return `ssh://${username}@${host}:${port || 22}${normPath !== "/" ? normPath.replace(/\/+$/, "") : "/"}`;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* 在远程工作区根 remoteRoot 下解析相对或绝对路径,防止 `..` 越界。
|
|
67
|
+
* 返回 { abs: 远程 posix 绝对路径, rel: 相对工作区根的 posix 相对路径(根自身为 "") }
|
|
68
|
+
*/
|
|
69
|
+
export function resolveRemoteWorkspacePath(remoteRoot, rawPath) {
|
|
70
|
+
const root = path.posix.normalize(remoteRoot.replace(/\\/g, "/")).replace(/\/+$/, "") || "/";
|
|
71
|
+
const cleaned = (rawPath || "").replace(/\\/g, "/").trim();
|
|
72
|
+
if (!cleaned || cleaned === ".") {
|
|
73
|
+
return { abs: root, rel: "" };
|
|
74
|
+
}
|
|
75
|
+
const abs = cleaned.startsWith("/") ? path.posix.normalize(cleaned) : path.posix.resolve(root, cleaned);
|
|
76
|
+
const rel = path.posix.relative(root, abs);
|
|
77
|
+
if (rel.startsWith("..") || rel.includes("/..") || path.posix.isAbsolute(rel)) {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
return { abs, rel: rel === "." ? "" : rel };
|
|
81
|
+
}
|
|
82
|
+
const REMOTE_URI_MARKER_FILE = ".pi-remote-uri";
|
|
83
|
+
/**
|
|
84
|
+
* 将工作区路径(本地目录或 ssh:// URI)映射到本地会话物理存储目录。
|
|
85
|
+
* - 本地工作区原样返回;
|
|
86
|
+
* - 远程 ssh:// 工作区映射到 `<dataDir>/remote-workspaces/<slug>`,并在其中写入 `.pi-remote-uri` 标记文件,
|
|
87
|
+
* 使得所有的会话 JSONL、计划、草稿全部 100% 存储在本地磁盘。
|
|
88
|
+
*/
|
|
89
|
+
export function resolveWorkspaceSessionDir(dataDir, cwdOrUri) {
|
|
90
|
+
const trimmed = (cwdOrUri || "").trim();
|
|
91
|
+
if (!isRemoteWorkspaceUri(trimmed)) {
|
|
92
|
+
return trimmed;
|
|
93
|
+
}
|
|
94
|
+
const safeDataDir = dataDir || process.env.PI_WEB_DATA_DIR || path.join(os.homedir(), ".pi-web");
|
|
95
|
+
const parsed = parseRemoteWorkspaceUri(trimmed);
|
|
96
|
+
const hash = createHash("sha1").update(trimmed).digest("hex").slice(0, 10);
|
|
97
|
+
const baseName = parsed
|
|
98
|
+
? `${parsed.username}_${parsed.host}_${parsed.port}_${parsed.remotePath.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/^_+|_+$/g, "")}`.slice(0, 72)
|
|
99
|
+
: trimmed.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 72);
|
|
100
|
+
const dir = path.resolve(safeDataDir, "remote-workspaces", `${baseName}_${hash}`);
|
|
101
|
+
try {
|
|
102
|
+
mkdirSync(dir, { recursive: true });
|
|
103
|
+
const markerPath = path.join(dir, REMOTE_URI_MARKER_FILE);
|
|
104
|
+
if (!existsSync(markerPath)) {
|
|
105
|
+
writeFileSync(markerPath, trimmed, "utf8");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
// ignore mkdir error in read-only edge cases
|
|
110
|
+
}
|
|
111
|
+
return dir;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* 从本地会话物理存储目录还原出工作区标识:
|
|
115
|
+
* 若目录下含有 `.pi-remote-uri` 标记文件,则返回原始 `ssh://...` URI;否则原样返回本地路径。
|
|
116
|
+
*/
|
|
117
|
+
export function restoreWorkspaceUriFromSessionDir(dir) {
|
|
118
|
+
if (!dir || isRemoteWorkspaceUri(dir))
|
|
119
|
+
return dir;
|
|
120
|
+
try {
|
|
121
|
+
const markerPath = path.join(dir, REMOTE_URI_MARKER_FILE);
|
|
122
|
+
if (existsSync(markerPath)) {
|
|
123
|
+
const uri = readFileSync(markerPath, "utf8").trim();
|
|
124
|
+
if (isRemoteWorkspaceUri(uri))
|
|
125
|
+
return uri;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// ignore
|
|
130
|
+
}
|
|
131
|
+
return dir;
|
|
132
|
+
}
|
|
133
|
+
/** Shell 安全单引号转义 */
|
|
134
|
+
export function shellQuotePosix(s) {
|
|
135
|
+
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* 将 SDK resolveToCwd 产生的本地路径(或原始输入路径)映射为远程工作区的 posix 绝对路径。
|
|
139
|
+
*/
|
|
140
|
+
export function mapResolvedPathToRemote(resolvedOrRawPath, localSessionDir, remoteWorkspaceUri) {
|
|
141
|
+
const parsed = parseRemoteWorkspaceUri(remoteWorkspaceUri);
|
|
142
|
+
const remoteRoot = parsed?.remotePath || "/";
|
|
143
|
+
const raw = (resolvedOrRawPath || "").trim();
|
|
144
|
+
if (!raw || raw === ".")
|
|
145
|
+
return remoteRoot;
|
|
146
|
+
try {
|
|
147
|
+
const rel = path.relative(path.resolve(localSessionDir), path.resolve(raw));
|
|
148
|
+
if (rel === "")
|
|
149
|
+
return remoteRoot;
|
|
150
|
+
if (!rel.startsWith("..") && !path.isAbsolute(rel)) {
|
|
151
|
+
return path.posix.join(remoteRoot, rel.split(path.sep).join("/"));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
catch { }
|
|
155
|
+
const stripped = raw
|
|
156
|
+
.replace(/^[A-Za-z]:/, "")
|
|
157
|
+
.split(path.sep)
|
|
158
|
+
.join("/");
|
|
159
|
+
return stripped.startsWith("/") ? path.posix.normalize(stripped) : path.posix.resolve(remoteRoot, stripped);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* 生成面向 AI 的远程工作区身份与工具透明桥接提示词。
|
|
163
|
+
* 在远程工作区下替代本地 WINDOWS_PERSONA 的平台身份描述,同时完整保留防挂死(timeout / 禁前台长驻 / TTY 禁交互 / GBK 编码)核心规则。
|
|
164
|
+
*/
|
|
165
|
+
export function buildRemoteWorkspacePersona(remoteUri) {
|
|
166
|
+
const parsed = parseRemoteWorkspaceUri(remoteUri);
|
|
167
|
+
const hostDesc = parsed ? `${parsed.username}@${parsed.host}:${parsed.port}` : remoteUri;
|
|
168
|
+
const remoteDir = parsed ? parsed.remotePath : remoteUri;
|
|
169
|
+
return [
|
|
170
|
+
`You are operating inside a REMOTE SSH workspace (${remoteUri}).`,
|
|
171
|
+
`- Target host: ${hostDesc}`,
|
|
172
|
+
`- Remote working directory: ${remoteDir}`,
|
|
173
|
+
`- All built-in workspace tools (bash, read, write, edit, edit_soft, ls, find, grep) and interactive terminals are ALREADY transparently bridged to execute directly on the remote host in "${remoteDir}".`,
|
|
174
|
+
`- Use normal POSIX relative paths (e.g. "src/index.ts") or remote absolute paths (e.g. "${remoteDir}/src/index.ts") directly in read/write/edit/bash/ls/find/grep. Do NOT wrap bash commands in "ssh ..." and do NOT treat this workspace as the local client OS.`,
|
|
175
|
+
``,
|
|
176
|
+
`Follow these rules to avoid hanging the session:`,
|
|
177
|
+
`- ALWAYS pass a timeout parameter to the bash tool (in seconds). There is NO default timeout — a command that never finishes (servers, watchers, infinite loops, slow downloads/installs) will hang the entire conversation indefinitely. Pick a generous timeout for long-running work, but never omit it.`,
|
|
178
|
+
`- NEVER run interactive or foreground long-running commands through the bash tool (vi, less, top, python -, node -, npm run dev, sleep 10000). For servers/daemons use background execution with output redirected to a log file, then poll the log; stop them when done.`,
|
|
179
|
+
`- In the interactive terminal (TTY) — NEVER use heredocs (<<'EOF' ... EOF) or here-strings, and NEVER start interactive programs (vi, less, python -, node -, npm init): they wait for keyboard input that never arrives and hang the terminal forever. Prefer writing a temp script file (e.g. .pi-tmp.sh) and running it non-interactively. ALWAYS pass a timeout to long-running commands (e.g. \`timeout 120 npm run dev\`).`,
|
|
180
|
+
`- Many legacy Chinese text files (.html/.txt/.md/.log, exported documents) are GBK/GB2312 encoded: the read tool decodes UTF-8 only and will show mojibake (乱码) for them. If a file's content looks garbled, read it through the terminal or bash using \`iconv -f GBK -t UTF-8 file\`. Never paste mojibake into your reasoning or answer — describe the decoded content instead.`,
|
|
181
|
+
].join("\n");
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* 将会话 cwd 格式化为系统提示词里的 Current working directory 展示文本。
|
|
185
|
+
* 若为远程工作区,展示远程真实目录与 SSH URI,绝不向模型暴露本地缓存路径。
|
|
186
|
+
*/
|
|
187
|
+
export function formatCwdForPrompt(cwdOrSessionDir) {
|
|
188
|
+
const real = restoreWorkspaceUriFromSessionDir(cwdOrSessionDir);
|
|
189
|
+
if (isRemoteWorkspaceUri(real)) {
|
|
190
|
+
const parsed = parseRemoteWorkspaceUri(real);
|
|
191
|
+
return parsed ? `${parsed.remotePath} (remote SSH: ${real})` : real;
|
|
192
|
+
}
|
|
193
|
+
return cwdOrSessionDir;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* 若当前会话目录对应远程 ssh:// 工作区,构造供 SDK 内置工具(read/write/edit/ls/find/grep)使用的远程 operations。
|
|
197
|
+
* 若为普通本地工作区则返回 null。
|
|
198
|
+
*/
|
|
199
|
+
export function createRemoteSdkOperations(localSessionDir) {
|
|
200
|
+
const remoteUri = restoreWorkspaceUriFromSessionDir(localSessionDir);
|
|
201
|
+
if (!isRemoteWorkspaceUri(remoteUri))
|
|
202
|
+
return null;
|
|
203
|
+
const toRemote = (p) => mapResolvedPathToRemote(p, localSessionDir, remoteUri);
|
|
204
|
+
const getSvc = () => {
|
|
205
|
+
const svc = getGlobalRemoteSshService();
|
|
206
|
+
if (!svc)
|
|
207
|
+
throw new Error("Remote SSH service is not initialized");
|
|
208
|
+
return svc;
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
remoteUri,
|
|
212
|
+
toRemote,
|
|
213
|
+
isDirectory: async (p) => {
|
|
214
|
+
try {
|
|
215
|
+
const st = await getSvc().sftpStat(remoteUri, toRemote(p));
|
|
216
|
+
return st.isDirectory;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
read: {
|
|
223
|
+
readFile: async (p) => {
|
|
224
|
+
const { data } = await getSvc().sftpReadFile(remoteUri, toRemote(p));
|
|
225
|
+
return data;
|
|
226
|
+
},
|
|
227
|
+
access: async (p) => {
|
|
228
|
+
await getSvc().sftpStat(remoteUri, toRemote(p));
|
|
229
|
+
},
|
|
230
|
+
},
|
|
231
|
+
write: {
|
|
232
|
+
writeFile: async (p, content) => {
|
|
233
|
+
await getSvc().sftpWriteFile(remoteUri, toRemote(p), content, { createParents: true });
|
|
234
|
+
},
|
|
235
|
+
mkdir: async (dir) => {
|
|
236
|
+
await getSvc().sftpMkdirRecursive(remoteUri, toRemote(dir));
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
edit: {
|
|
240
|
+
readFile: async (p) => {
|
|
241
|
+
const { data } = await getSvc().sftpReadFile(remoteUri, toRemote(p));
|
|
242
|
+
return data;
|
|
243
|
+
},
|
|
244
|
+
writeFile: async (p, content) => {
|
|
245
|
+
await getSvc().sftpWriteFile(remoteUri, toRemote(p), content, { createParents: true });
|
|
246
|
+
},
|
|
247
|
+
access: async (p) => {
|
|
248
|
+
await getSvc().sftpStat(remoteUri, toRemote(p));
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
ls: {
|
|
252
|
+
exists: async (p) => {
|
|
253
|
+
try {
|
|
254
|
+
await getSvc().sftpStat(remoteUri, toRemote(p));
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
stat: async (p) => {
|
|
262
|
+
const st = await getSvc().sftpStat(remoteUri, toRemote(p));
|
|
263
|
+
return { isDirectory: () => st.isDirectory };
|
|
264
|
+
},
|
|
265
|
+
readdir: async (p) => {
|
|
266
|
+
const entries = await getSvc().sftpReaddir(remoteUri, toRemote(p));
|
|
267
|
+
return entries.map((e) => e.name);
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
find: {
|
|
271
|
+
exists: async (p) => {
|
|
272
|
+
try {
|
|
273
|
+
await getSvc().sftpStat(remoteUri, toRemote(p));
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
glob: async (pattern, searchPath, options) => {
|
|
281
|
+
const remoteDir = toRemote(searchPath);
|
|
282
|
+
const limit = Math.max(1, options.limit || 1000);
|
|
283
|
+
const namePat = pattern.includes("/") ? pattern.split("/").pop() || "*" : pattern;
|
|
284
|
+
const cmd = `find . \\( -name node_modules -o -name .git \\) -prune -o -name ${shellQuotePosix(namePat)} -print 2>/dev/null | head -n ${limit}`;
|
|
285
|
+
const res = await getSvc().execInWorkspace(remoteUri, cmd, { cwd: remoteDir, timeoutMs: 15_000 });
|
|
286
|
+
return res.stdout
|
|
287
|
+
.split(/\r?\n/)
|
|
288
|
+
.map((l) => l.trim().replace(/^\.\//, ""))
|
|
289
|
+
.filter((l) => l && l !== ".");
|
|
290
|
+
},
|
|
291
|
+
},
|
|
292
|
+
grepExecute: async (params) => {
|
|
293
|
+
const remoteTarget = toRemote(params.path || ".");
|
|
294
|
+
const limit = Math.max(1, params.limit ?? 100);
|
|
295
|
+
const flags = ["-rnI", "--exclude-dir=node_modules", "--exclude-dir=.git"];
|
|
296
|
+
if (params.ignoreCase)
|
|
297
|
+
flags.push("-i");
|
|
298
|
+
if (params.literal)
|
|
299
|
+
flags.push("-F");
|
|
300
|
+
else
|
|
301
|
+
flags.push("-E");
|
|
302
|
+
if (params.context && params.context > 0)
|
|
303
|
+
flags.push(`-C ${Math.floor(params.context)}`);
|
|
304
|
+
if (params.glob)
|
|
305
|
+
flags.push(`--include=${shellQuotePosix(params.glob)}`);
|
|
306
|
+
const cmd = `grep ${flags.join(" ")} -- ${shellQuotePosix(params.pattern)} ${shellQuotePosix(remoteTarget)} 2>/dev/null | head -n ${limit}`;
|
|
307
|
+
const res = await getSvc().execInWorkspace(remoteUri, cmd, { timeoutMs: 15_000 });
|
|
308
|
+
const out = res.stdout.trim();
|
|
309
|
+
return out || "No matches found";
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
let globalRemoteSshService = null;
|
|
314
|
+
export function setGlobalRemoteSshService(svc) {
|
|
315
|
+
globalRemoteSshService = svc;
|
|
316
|
+
}
|
|
317
|
+
export function getGlobalRemoteSshService() {
|
|
318
|
+
return globalRemoteSshService;
|
|
319
|
+
}
|
|
320
|
+
export class RemoteSshService {
|
|
321
|
+
dataDir;
|
|
322
|
+
connections = new Map();
|
|
323
|
+
hostConnections = new Map(); // hostKey -> connectionId
|
|
324
|
+
inflightConnects = new Map();
|
|
325
|
+
credentialCache = new Map(); // hostKey -> hydrated params
|
|
326
|
+
secretKey = null;
|
|
327
|
+
constructor(dataDir) {
|
|
328
|
+
this.dataDir = dataDir;
|
|
329
|
+
}
|
|
330
|
+
/** 获取或初始化本地凭据加密密钥(32 字节 AES 密钥) */
|
|
331
|
+
async getSecretKey() {
|
|
332
|
+
if (this.secretKey)
|
|
333
|
+
return this.secretKey;
|
|
334
|
+
const keyPath = path.join(this.dataDir, ".remote-ssh.key");
|
|
335
|
+
try {
|
|
336
|
+
if (existsSync(keyPath)) {
|
|
337
|
+
const buf = await fs.readFile(keyPath);
|
|
338
|
+
if (buf.length === 32) {
|
|
339
|
+
this.secretKey = buf;
|
|
340
|
+
return buf;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
catch { }
|
|
345
|
+
const generated = randomBytes(32);
|
|
346
|
+
try {
|
|
347
|
+
await fs.mkdir(this.dataDir, { recursive: true });
|
|
348
|
+
await fs.writeFile(keyPath, generated, { mode: 0o600 });
|
|
349
|
+
this.secretKey = generated;
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
this.secretKey = generated;
|
|
353
|
+
}
|
|
354
|
+
return this.secretKey;
|
|
355
|
+
}
|
|
356
|
+
async seal(text) {
|
|
357
|
+
const key = await this.getSecretKey();
|
|
358
|
+
const iv = randomBytes(12);
|
|
359
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
360
|
+
const ct = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
|
|
361
|
+
return {
|
|
362
|
+
iv: iv.toString("hex"),
|
|
363
|
+
tag: cipher.getAuthTag().toString("hex"),
|
|
364
|
+
ct: ct.toString("hex"),
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async unseal(blob) {
|
|
368
|
+
if (!blob)
|
|
369
|
+
return undefined;
|
|
370
|
+
try {
|
|
371
|
+
const key = await this.getSecretKey();
|
|
372
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(blob.iv, "hex"));
|
|
373
|
+
decipher.setAuthTag(Buffer.from(blob.tag, "hex"));
|
|
374
|
+
const pt = Buffer.concat([decipher.update(Buffer.from(blob.ct, "hex")), decipher.final()]);
|
|
375
|
+
return pt.toString("utf8");
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
get profilesFilePath() {
|
|
382
|
+
return path.join(this.dataDir, "ssh-profiles.json");
|
|
383
|
+
}
|
|
384
|
+
async loadProfilesData() {
|
|
385
|
+
try {
|
|
386
|
+
if (existsSync(this.profilesFilePath)) {
|
|
387
|
+
const content = await fs.readFile(this.profilesFilePath, "utf8");
|
|
388
|
+
const parsed = JSON.parse(content);
|
|
389
|
+
if (parsed && parsed.version === 1 && typeof parsed.profiles === "object") {
|
|
390
|
+
return parsed;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
catch { }
|
|
395
|
+
return { version: 1, profiles: {} };
|
|
396
|
+
}
|
|
397
|
+
async saveProfilesData(data) {
|
|
398
|
+
try {
|
|
399
|
+
await fs.mkdir(this.dataDir, { recursive: true });
|
|
400
|
+
await fs.writeFile(this.profilesFilePath, JSON.stringify(data, null, 2), "utf8");
|
|
401
|
+
}
|
|
402
|
+
catch (err) {
|
|
403
|
+
console.error("[remote-ssh] 无法保存 profiles 文件:", err);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/** 列出所有已保存的 SSH profiles */
|
|
407
|
+
async listProfiles() {
|
|
408
|
+
const data = await this.loadProfilesData();
|
|
409
|
+
return Object.values(data.profiles)
|
|
410
|
+
.map((p) => ({
|
|
411
|
+
name: p.name,
|
|
412
|
+
host: p.host,
|
|
413
|
+
port: p.port,
|
|
414
|
+
username: p.username,
|
|
415
|
+
authType: p.authType,
|
|
416
|
+
privateKeyPath: p.privateKeyPath,
|
|
417
|
+
lastConnected: p.lastConnected,
|
|
418
|
+
}))
|
|
419
|
+
.sort((a, b) => (b.lastConnected ?? 0) - (a.lastConnected ?? 0));
|
|
420
|
+
}
|
|
421
|
+
/** 删除一个已保存的 profile */
|
|
422
|
+
async deleteProfile(name) {
|
|
423
|
+
const data = await this.loadProfilesData();
|
|
424
|
+
if (data.profiles[name]) {
|
|
425
|
+
delete data.profiles[name];
|
|
426
|
+
await this.saveProfilesData(data);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** 记录或更新一个 profile */
|
|
430
|
+
async saveProfile(name, params) {
|
|
431
|
+
const data = await this.loadProfilesData();
|
|
432
|
+
const existing = data.profiles[name];
|
|
433
|
+
const auth = params.auth;
|
|
434
|
+
const stored = {
|
|
435
|
+
name,
|
|
436
|
+
host: params.host,
|
|
437
|
+
port: params.port ?? 22,
|
|
438
|
+
username: params.username,
|
|
439
|
+
authType: auth.type,
|
|
440
|
+
privateKeyPath: auth.type === "key" ? auth.privateKeyPath : undefined,
|
|
441
|
+
lastConnected: Date.now(),
|
|
442
|
+
};
|
|
443
|
+
if (auth.type === "password") {
|
|
444
|
+
if (auth.password) {
|
|
445
|
+
stored.encryptedPassword = await this.seal(auth.password);
|
|
446
|
+
}
|
|
447
|
+
else if (existing?.encryptedPassword) {
|
|
448
|
+
stored.encryptedPassword = existing.encryptedPassword;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
else if (auth.type === "key") {
|
|
452
|
+
if (auth.passphrase) {
|
|
453
|
+
stored.encryptedPassphrase = await this.seal(auth.passphrase);
|
|
454
|
+
}
|
|
455
|
+
else if (existing?.encryptedPassphrase) {
|
|
456
|
+
stored.encryptedPassphrase = existing.encryptedPassphrase;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
data.profiles[name] = stored;
|
|
460
|
+
await this.saveProfilesData(data);
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* 从内存缓存或磁盘已保存的 profile 中补全缺失的密码/私钥口令。
|
|
464
|
+
* 例如用户在界面点击已保存的 profile 时前端未持有明文密码,此处自动解密填充。
|
|
465
|
+
*/
|
|
466
|
+
async hydrateAuthParams(params) {
|
|
467
|
+
const port = params.port ?? 22;
|
|
468
|
+
const hostKey = `${params.username}@${params.host}:${port}`;
|
|
469
|
+
const cloned = {
|
|
470
|
+
...params,
|
|
471
|
+
port,
|
|
472
|
+
auth: { ...params.auth },
|
|
473
|
+
};
|
|
474
|
+
const data = await this.loadProfilesData();
|
|
475
|
+
const matchedProfile = (params.profileName ? data.profiles[params.profileName] : undefined) ??
|
|
476
|
+
Object.values(data.profiles).find((p) => p.host === params.host && (p.port || 22) === port && p.username === params.username);
|
|
477
|
+
if (cloned.auth.type === "password" && !cloned.auth.password) {
|
|
478
|
+
const cached = this.credentialCache.get(hostKey);
|
|
479
|
+
if (cached?.auth.type === "password" && cached.auth.password) {
|
|
480
|
+
cloned.auth.password = cached.auth.password;
|
|
481
|
+
}
|
|
482
|
+
else if (matchedProfile?.encryptedPassword) {
|
|
483
|
+
const decrypted = await this.unseal(matchedProfile.encryptedPassword);
|
|
484
|
+
if (decrypted)
|
|
485
|
+
cloned.auth.password = decrypted;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
else if (cloned.auth.type === "key") {
|
|
489
|
+
if (!cloned.auth.privateKeyPath && matchedProfile?.privateKeyPath) {
|
|
490
|
+
cloned.auth.privateKeyPath = matchedProfile.privateKeyPath;
|
|
491
|
+
}
|
|
492
|
+
if (!cloned.auth.passphrase && matchedProfile?.encryptedPassphrase) {
|
|
493
|
+
const decrypted = await this.unseal(matchedProfile.encryptedPassphrase);
|
|
494
|
+
if (decrypted)
|
|
495
|
+
cloned.auth.passphrase = decrypted;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return cloned;
|
|
499
|
+
}
|
|
500
|
+
/** 关闭某个连接 */
|
|
501
|
+
closeConnection(id) {
|
|
502
|
+
const conn = this.connections.get(id);
|
|
503
|
+
if (conn) {
|
|
504
|
+
conn.alive = false;
|
|
505
|
+
clearTimeout(conn.timer);
|
|
506
|
+
if (this.hostConnections.get(conn.hostKey) === id) {
|
|
507
|
+
this.hostConnections.delete(conn.hostKey);
|
|
508
|
+
}
|
|
509
|
+
try {
|
|
510
|
+
conn.client.end();
|
|
511
|
+
}
|
|
512
|
+
catch { }
|
|
513
|
+
this.connections.delete(id);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
refreshConnectionTimer(conn) {
|
|
517
|
+
clearTimeout(conn.timer);
|
|
518
|
+
conn.timer = setTimeout(() => {
|
|
519
|
+
this.closeConnection(conn.id);
|
|
520
|
+
}, IDLE_TIMEOUT_MS);
|
|
521
|
+
conn.timer.unref?.();
|
|
522
|
+
}
|
|
523
|
+
/** 建立底层 ssh2 Client 连接 */
|
|
524
|
+
async createClient(rawParams) {
|
|
525
|
+
const params = await this.hydrateAuthParams(rawParams);
|
|
526
|
+
const client = new Client();
|
|
527
|
+
const connectConfig = {
|
|
528
|
+
host: params.host,
|
|
529
|
+
port: params.port ?? 22,
|
|
530
|
+
username: params.username,
|
|
531
|
+
readyTimeout: PROBE_TIMEOUT_MS,
|
|
532
|
+
keepaliveInterval: 10_000,
|
|
533
|
+
keepaliveCountMax: 3,
|
|
534
|
+
};
|
|
535
|
+
const auth = params.auth;
|
|
536
|
+
if (auth.type === "password") {
|
|
537
|
+
connectConfig.password = auth.password;
|
|
538
|
+
// 同时支持 keyboard-interactive(许多 Linux OpenSSH 默认用 keyboard-interactive 验证密码)
|
|
539
|
+
connectConfig.tryKeyboard = true;
|
|
540
|
+
client.on("keyboard-interactive", (_name, _instructions, _instructionsLang, prompts, finish) => {
|
|
541
|
+
finish(prompts.map(() => auth.password ?? ""));
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
else if (auth.type === "key") {
|
|
545
|
+
if (auth.privateKey) {
|
|
546
|
+
connectConfig.privateKey = auth.privateKey;
|
|
547
|
+
}
|
|
548
|
+
else {
|
|
549
|
+
let keyFile = expandHome(auth.privateKeyPath);
|
|
550
|
+
if (!keyFile || !existsSync(keyFile)) {
|
|
551
|
+
for (const cand of DEFAULT_KEY_CANDIDATES) {
|
|
552
|
+
const exp = expandHome(cand);
|
|
553
|
+
if (exp && existsSync(exp)) {
|
|
554
|
+
keyFile = exp;
|
|
555
|
+
break;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (keyFile) {
|
|
560
|
+
connectConfig.privateKey = await fs.readFile(keyFile);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (auth.passphrase) {
|
|
564
|
+
connectConfig.passphrase = auth.passphrase;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
else if (auth.type === "agent") {
|
|
568
|
+
const sock = process.env.SSH_AUTH_SOCK || (process.platform === "win32" ? "\\\\.\\pipe\\openssh-ssh-agent" : "");
|
|
569
|
+
if (sock)
|
|
570
|
+
connectConfig.agent = sock;
|
|
571
|
+
}
|
|
572
|
+
return new Promise((resolve, reject) => {
|
|
573
|
+
const cleanup = () => {
|
|
574
|
+
client.removeListener("ready", onReady);
|
|
575
|
+
client.removeListener("error", onError);
|
|
576
|
+
};
|
|
577
|
+
const onReady = () => {
|
|
578
|
+
cleanup();
|
|
579
|
+
resolve({ client, hydrated: params });
|
|
580
|
+
};
|
|
581
|
+
const onError = (err) => {
|
|
582
|
+
cleanup();
|
|
583
|
+
reject(err);
|
|
584
|
+
};
|
|
585
|
+
client.once("ready", onReady);
|
|
586
|
+
client.once("error", onError);
|
|
587
|
+
try {
|
|
588
|
+
client.connect(connectConfig);
|
|
589
|
+
}
|
|
590
|
+
catch (err) {
|
|
591
|
+
cleanup();
|
|
592
|
+
reject(err);
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
/** 注册活跃连接并监听断开事件 */
|
|
597
|
+
registerConnection(client, hydrated) {
|
|
598
|
+
const connId = randomUUID();
|
|
599
|
+
const hostKey = `${hydrated.username}@${hydrated.host}:${hydrated.port ?? 22}`;
|
|
600
|
+
const conn = {
|
|
601
|
+
id: connId,
|
|
602
|
+
hostKey,
|
|
603
|
+
client,
|
|
604
|
+
params: hydrated,
|
|
605
|
+
alive: true,
|
|
606
|
+
timer: setTimeout(() => this.closeConnection(connId), IDLE_TIMEOUT_MS),
|
|
607
|
+
};
|
|
608
|
+
conn.timer.unref?.();
|
|
609
|
+
const markDead = () => {
|
|
610
|
+
conn.alive = false;
|
|
611
|
+
if (this.hostConnections.get(hostKey) === connId) {
|
|
612
|
+
this.hostConnections.delete(hostKey);
|
|
613
|
+
}
|
|
614
|
+
this.connections.delete(connId);
|
|
615
|
+
clearTimeout(conn.timer);
|
|
616
|
+
};
|
|
617
|
+
client.once("close", markDead);
|
|
618
|
+
client.once("end", markDead);
|
|
619
|
+
client.on("error", () => {
|
|
620
|
+
markDead();
|
|
621
|
+
});
|
|
622
|
+
this.connections.set(connId, conn);
|
|
623
|
+
this.hostConnections.set(hostKey, connId);
|
|
624
|
+
this.credentialCache.set(hostKey, hydrated);
|
|
625
|
+
return conn;
|
|
626
|
+
}
|
|
627
|
+
/** 执行远端 shell 命令并获取 stdout */
|
|
628
|
+
async execCommand(client, cmd) {
|
|
629
|
+
return new Promise((resolve, reject) => {
|
|
630
|
+
client.exec(cmd, (err, stream) => {
|
|
631
|
+
if (err)
|
|
632
|
+
return reject(err);
|
|
633
|
+
let stdout = "";
|
|
634
|
+
let stderr = "";
|
|
635
|
+
stream.on("data", (chunk) => {
|
|
636
|
+
stdout += chunk.toString("utf8");
|
|
637
|
+
});
|
|
638
|
+
stream.stderr.on("data", (chunk) => {
|
|
639
|
+
stderr += chunk.toString("utf8");
|
|
640
|
+
});
|
|
641
|
+
stream.on("close", (code) => {
|
|
642
|
+
if (code === 0) {
|
|
643
|
+
resolve(stdout);
|
|
644
|
+
}
|
|
645
|
+
else {
|
|
646
|
+
resolve(stdout || stderr);
|
|
647
|
+
}
|
|
648
|
+
});
|
|
649
|
+
stream.on("error", (e) => reject(e));
|
|
650
|
+
});
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
/** 远程环境深度探针(Probe) */
|
|
654
|
+
async probe(params) {
|
|
655
|
+
let client;
|
|
656
|
+
let hydrated;
|
|
657
|
+
try {
|
|
658
|
+
const res = await this.createClient(params);
|
|
659
|
+
client = res.client;
|
|
660
|
+
hydrated = res.hydrated;
|
|
661
|
+
}
|
|
662
|
+
catch (err) {
|
|
663
|
+
return {
|
|
664
|
+
ok: false,
|
|
665
|
+
error: err.message || String(err),
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
const conn = this.registerConnection(client, hydrated);
|
|
669
|
+
// 无论是否显式勾选,连接成功都持久化凭据以便打开远程工作区后能够跨请求/跨重启自动重连
|
|
670
|
+
if (params.saveProfile !== false) {
|
|
671
|
+
const pName = params.profileName?.trim() || `${hydrated.username}@${hydrated.host}`;
|
|
672
|
+
await this.saveProfile(pName, hydrated);
|
|
673
|
+
}
|
|
674
|
+
const probeScript = `
|
|
675
|
+
echo "===SYSTEM==="
|
|
676
|
+
uname -s
|
|
677
|
+
uname -m
|
|
678
|
+
uname -n
|
|
679
|
+
echo "$USER"
|
|
680
|
+
echo "$HOME"
|
|
681
|
+
echo "===GIT==="
|
|
682
|
+
which git 2>/dev/null && git --version 2>/dev/null || echo "NONE"
|
|
683
|
+
echo "===NODE==="
|
|
684
|
+
which node 2>/dev/null && node -v 2>/dev/null || echo "NONE"
|
|
685
|
+
echo "===BASH==="
|
|
686
|
+
which bash 2>/dev/null || echo "NONE"
|
|
687
|
+
echo "===PYTHON==="
|
|
688
|
+
(which python3 2>/dev/null && python3 --version 2>/dev/null) || (which python 2>/dev/null && python --version 2>/dev/null) || echo "NONE"
|
|
689
|
+
echo "===PKG==="
|
|
690
|
+
for p in apt-get dnf yum apk pacman brew; do
|
|
691
|
+
if command -v $p >/dev/null 2>&1; then echo "$p"; break; fi
|
|
692
|
+
done
|
|
693
|
+
`;
|
|
694
|
+
try {
|
|
695
|
+
const output = await this.execCommand(client, probeScript);
|
|
696
|
+
const parsed = this.parseProbeOutput(output);
|
|
697
|
+
conn.system = parsed.system;
|
|
698
|
+
return {
|
|
699
|
+
ok: true,
|
|
700
|
+
connectionId: conn.id,
|
|
701
|
+
system: parsed.system,
|
|
702
|
+
tools: parsed.tools,
|
|
703
|
+
packageManager: parsed.packageManager,
|
|
704
|
+
suggestedInstall: parsed.suggestedInstall,
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
catch (err) {
|
|
708
|
+
return {
|
|
709
|
+
ok: false,
|
|
710
|
+
connectionId: conn.id,
|
|
711
|
+
error: `探针执行失败: ${err.message}`,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
parseProbeOutput(raw) {
|
|
716
|
+
const lines = raw.split(/\r?\n/).map((l) => l.trim());
|
|
717
|
+
const sections = {};
|
|
718
|
+
let currentSection = "INIT";
|
|
719
|
+
for (const line of lines) {
|
|
720
|
+
if (line.startsWith("===") && line.endsWith("===")) {
|
|
721
|
+
currentSection = line.slice(3, -3);
|
|
722
|
+
sections[currentSection] = [];
|
|
723
|
+
}
|
|
724
|
+
else if (currentSection) {
|
|
725
|
+
sections[currentSection] = sections[currentSection] || [];
|
|
726
|
+
sections[currentSection].push(line);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
const sysLines = (sections["SYSTEM"] || []).filter(Boolean);
|
|
730
|
+
const osName = sysLines[0] || "Unknown";
|
|
731
|
+
const arch = sysLines[1] || "Unknown";
|
|
732
|
+
const hostname = sysLines[2] || "";
|
|
733
|
+
const user = sysLines[3] || "";
|
|
734
|
+
const homeDir = sysLines[4] || "/";
|
|
735
|
+
const gitLines = (sections["GIT"] || []).filter(Boolean);
|
|
736
|
+
const gitInstalled = gitLines.length > 0 && gitLines[0] !== "NONE";
|
|
737
|
+
const gitVersion = gitInstalled ? gitLines.join(" ") : undefined;
|
|
738
|
+
const nodeLines = (sections["NODE"] || []).filter(Boolean);
|
|
739
|
+
const nodeInstalled = nodeLines.length > 0 && nodeLines[0] !== "NONE";
|
|
740
|
+
const nodeVersion = nodeInstalled ? nodeLines.join(" ") : undefined;
|
|
741
|
+
const bashLines = (sections["BASH"] || []).filter(Boolean);
|
|
742
|
+
const bashInstalled = bashLines.length > 0 && bashLines[0] !== "NONE";
|
|
743
|
+
const bashPath = bashInstalled ? bashLines[0] : undefined;
|
|
744
|
+
const pyLines = (sections["PYTHON"] || []).filter(Boolean);
|
|
745
|
+
const pyInstalled = pyLines.length > 0 && pyLines[0] !== "NONE";
|
|
746
|
+
const pyVersion = pyInstalled ? pyLines.join(" ") : undefined;
|
|
747
|
+
const pkgLines = (sections["PKG"] || []).filter(Boolean);
|
|
748
|
+
const packageManager = pkgLines[0] || "unknown";
|
|
749
|
+
const suggestedInstall = [];
|
|
750
|
+
if (!gitInstalled)
|
|
751
|
+
suggestedInstall.push("git");
|
|
752
|
+
if (!bashInstalled)
|
|
753
|
+
suggestedInstall.push("bash");
|
|
754
|
+
return {
|
|
755
|
+
system: {
|
|
756
|
+
os: osName,
|
|
757
|
+
arch,
|
|
758
|
+
hostname,
|
|
759
|
+
user,
|
|
760
|
+
homeDir,
|
|
761
|
+
},
|
|
762
|
+
tools: {
|
|
763
|
+
git: { installed: gitInstalled, version: gitVersion },
|
|
764
|
+
node: { installed: nodeInstalled, version: nodeVersion },
|
|
765
|
+
bash: { installed: bashInstalled, path: bashPath },
|
|
766
|
+
python: { installed: pyInstalled, version: pyVersion },
|
|
767
|
+
},
|
|
768
|
+
packageManager,
|
|
769
|
+
suggestedInstall,
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
/** 取得指定连接并重置其空闲计时器 */
|
|
773
|
+
getConnection(connectionId) {
|
|
774
|
+
const conn = this.connections.get(connectionId);
|
|
775
|
+
if (!conn || !conn.alive) {
|
|
776
|
+
throw new Error(`连接已断开或不存在 (ID: ${connectionId}),请重新发起探针连接`);
|
|
777
|
+
}
|
|
778
|
+
this.refreshConnectionTimer(conn);
|
|
779
|
+
return conn;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* 按 host/port/username 获取存活连接;若已断开或服务刚重启,自动从缓存或 ssh-profiles.json
|
|
783
|
+
* 提取加密保存的凭据重连(并发请求单飞合并)。
|
|
784
|
+
*/
|
|
785
|
+
async getOrConnectHost(host, port, username) {
|
|
786
|
+
const hostKey = `${username}@${host}:${port}`;
|
|
787
|
+
const existingId = this.hostConnections.get(hostKey);
|
|
788
|
+
if (existingId) {
|
|
789
|
+
const conn = this.connections.get(existingId);
|
|
790
|
+
if (conn && conn.alive) {
|
|
791
|
+
this.refreshConnectionTimer(conn);
|
|
792
|
+
return conn;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
const inflight = this.inflightConnects.get(hostKey);
|
|
796
|
+
if (inflight)
|
|
797
|
+
return inflight;
|
|
798
|
+
const run = (async () => {
|
|
799
|
+
let params = this.credentialCache.get(hostKey);
|
|
800
|
+
if (!params) {
|
|
801
|
+
const data = await this.loadProfilesData();
|
|
802
|
+
const profile = Object.values(data.profiles).find((p) => p.host === host && (p.port || 22) === port && p.username === username);
|
|
803
|
+
if (profile) {
|
|
804
|
+
if (profile.authType === "password") {
|
|
805
|
+
const password = (await this.unseal(profile.encryptedPassword)) ?? "";
|
|
806
|
+
params = { host, port, username, auth: { type: "password", password } };
|
|
807
|
+
}
|
|
808
|
+
else if (profile.authType === "key") {
|
|
809
|
+
const passphrase = await this.unseal(profile.encryptedPassphrase);
|
|
810
|
+
params = {
|
|
811
|
+
host,
|
|
812
|
+
port,
|
|
813
|
+
username,
|
|
814
|
+
auth: { type: "key", privateKeyPath: profile.privateKeyPath, passphrase },
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
else {
|
|
818
|
+
params = { host, port, username, auth: { type: "agent" } };
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
else {
|
|
822
|
+
// 回退尝试默认 SSH 密钥
|
|
823
|
+
params = { host, port, username, auth: { type: "key" } };
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
const { client, hydrated } = await this.createClient(params);
|
|
827
|
+
return this.registerConnection(client, hydrated);
|
|
828
|
+
})();
|
|
829
|
+
this.inflightConnects.set(hostKey, run);
|
|
830
|
+
try {
|
|
831
|
+
return await run;
|
|
832
|
+
}
|
|
833
|
+
finally {
|
|
834
|
+
this.inflightConnects.delete(hostKey);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
/** 按远程工作区 URI 获取活跃连接与 SFTP 会话 */
|
|
838
|
+
async getOrConnectByUri(uri) {
|
|
839
|
+
const parsed = parseRemoteWorkspaceUri(uri);
|
|
840
|
+
if (!parsed) {
|
|
841
|
+
throw new Error(`无效的远程工作区 URI: ${uri}`);
|
|
842
|
+
}
|
|
843
|
+
const conn = await this.getOrConnectHost(parsed.host, parsed.port, parsed.username);
|
|
844
|
+
const sftp = await this.getSftp(conn);
|
|
845
|
+
return { conn, sftp, parsed };
|
|
846
|
+
}
|
|
847
|
+
/** 获取 SFTP 会话 */
|
|
848
|
+
async getSftp(conn) {
|
|
849
|
+
if (conn.sftp)
|
|
850
|
+
return conn.sftp;
|
|
851
|
+
return new Promise((resolve, reject) => {
|
|
852
|
+
conn.client.sftp((err, sftp) => {
|
|
853
|
+
if (err)
|
|
854
|
+
return reject(err);
|
|
855
|
+
sftp.once("close", () => {
|
|
856
|
+
if (conn.sftp === sftp)
|
|
857
|
+
conn.sftp = undefined;
|
|
858
|
+
});
|
|
859
|
+
sftp.once("end", () => {
|
|
860
|
+
if (conn.sftp === sftp)
|
|
861
|
+
conn.sftp = undefined;
|
|
862
|
+
});
|
|
863
|
+
conn.sftp = sftp;
|
|
864
|
+
resolve(sftp);
|
|
865
|
+
});
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
/** 浏览远程目录 */
|
|
869
|
+
async listDir(connectionId, reqPath) {
|
|
870
|
+
let conn;
|
|
871
|
+
try {
|
|
872
|
+
conn = this.getConnection(connectionId);
|
|
873
|
+
}
|
|
874
|
+
catch (err) {
|
|
875
|
+
return {
|
|
876
|
+
ok: false,
|
|
877
|
+
connectionId,
|
|
878
|
+
path: reqPath || "/",
|
|
879
|
+
items: [],
|
|
880
|
+
error: err.message,
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
try {
|
|
884
|
+
const sftp = await this.getSftp(conn);
|
|
885
|
+
const targetPath = (reqPath && reqPath.trim()) || conn.system?.homeDir || "/";
|
|
886
|
+
return await new Promise((resolve) => {
|
|
887
|
+
sftp.readdir(targetPath, (err, list) => {
|
|
888
|
+
if (err) {
|
|
889
|
+
return resolve({
|
|
890
|
+
ok: false,
|
|
891
|
+
connectionId,
|
|
892
|
+
path: targetPath,
|
|
893
|
+
items: [],
|
|
894
|
+
error: `无法读取远程目录 ${targetPath}: ${err.message}`,
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
const items = [];
|
|
898
|
+
for (const item of list) {
|
|
899
|
+
if (item.filename === "." || item.filename === "..")
|
|
900
|
+
continue;
|
|
901
|
+
const isDir = Boolean(item.attrs.isDirectory());
|
|
902
|
+
const fullPath = targetPath === "/" ? `/${item.filename}` : `${targetPath.replace(/\/+$/, "")}/${item.filename}`;
|
|
903
|
+
items.push({
|
|
904
|
+
name: item.filename,
|
|
905
|
+
path: fullPath,
|
|
906
|
+
type: isDir ? "dir" : "file",
|
|
907
|
+
size: item.attrs.size,
|
|
908
|
+
mtime: item.attrs.mtime ? item.attrs.mtime * 1000 : undefined,
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
items.sort((a, b) => {
|
|
912
|
+
if (a.type !== b.type) {
|
|
913
|
+
return a.type === "dir" ? -1 : 1;
|
|
914
|
+
}
|
|
915
|
+
return a.name.localeCompare(b.name);
|
|
916
|
+
});
|
|
917
|
+
let parentPath = null;
|
|
918
|
+
if (targetPath !== "/" && targetPath !== "") {
|
|
919
|
+
const idx = targetPath.lastIndexOf("/");
|
|
920
|
+
parentPath = idx <= 0 ? "/" : targetPath.slice(0, idx);
|
|
921
|
+
}
|
|
922
|
+
resolve({
|
|
923
|
+
ok: true,
|
|
924
|
+
connectionId,
|
|
925
|
+
path: targetPath,
|
|
926
|
+
parentPath,
|
|
927
|
+
items,
|
|
928
|
+
});
|
|
929
|
+
});
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
catch (err) {
|
|
933
|
+
return {
|
|
934
|
+
ok: false,
|
|
935
|
+
connectionId,
|
|
936
|
+
path: reqPath || "/",
|
|
937
|
+
items: [],
|
|
938
|
+
error: err.message,
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
/** 在远端执行工具一键安装 */
|
|
943
|
+
async installTools(connectionId, tools) {
|
|
944
|
+
const conn = this.getConnection(connectionId);
|
|
945
|
+
const tool = tools[0] || "git";
|
|
946
|
+
const installScript = `
|
|
947
|
+
if command -v apt-get >/dev/null 2>&1; then
|
|
948
|
+
export DEBIAN_FRONTEND=noninteractive
|
|
949
|
+
( [ "$(id -u)" -eq 0 ] && apt-get update -y && apt-get install -y ${tool} ) || ( sudo -n apt-get update -y && sudo -n apt-get install -y ${tool} )
|
|
950
|
+
elif command -v dnf >/dev/null 2>&1; then
|
|
951
|
+
( [ "$(id -u)" -eq 0 ] && dnf install -y ${tool} ) || sudo -n dnf install -y ${tool}
|
|
952
|
+
elif command -v yum >/dev/null 2>&1; then
|
|
953
|
+
( [ "$(id -u)" -eq 0 ] && yum install -y ${tool} ) || sudo -n yum install -y ${tool}
|
|
954
|
+
elif command -v apk >/dev/null 2>&1; then
|
|
955
|
+
( [ "$(id -u)" -eq 0 ] && apk add ${tool} ) || sudo -n apk add ${tool}
|
|
956
|
+
elif command -v pacman >/dev/null 2>&1; then
|
|
957
|
+
( [ "$(id -u)" -eq 0 ] && pacman -S --noconfirm ${tool} ) || sudo -n pacman -S --noconfirm ${tool}
|
|
958
|
+
elif command -v brew >/dev/null 2>&1; then
|
|
959
|
+
brew install ${tool}
|
|
960
|
+
else
|
|
961
|
+
echo "未检测到支持的包管理器 (apt/dnf/yum/apk/pacman/brew),请手动安装 ${tool}"
|
|
962
|
+
exit 1
|
|
963
|
+
fi
|
|
964
|
+
`;
|
|
965
|
+
try {
|
|
966
|
+
const output = await this.execCommand(conn.client, installScript);
|
|
967
|
+
const verifyOutput = await this.execCommand(conn.client, `which ${tool} 2>/dev/null`);
|
|
968
|
+
const installed = Boolean(verifyOutput.trim());
|
|
969
|
+
return {
|
|
970
|
+
ok: installed,
|
|
971
|
+
connectionId,
|
|
972
|
+
tool,
|
|
973
|
+
output,
|
|
974
|
+
error: installed ? undefined : `执行完成但未检测到 ${tool} 二进制文件,可能需要 sudo 密码权限`,
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
catch (err) {
|
|
978
|
+
return {
|
|
979
|
+
ok: false,
|
|
980
|
+
connectionId,
|
|
981
|
+
tool,
|
|
982
|
+
error: err.message,
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
// =========================================================================
|
|
987
|
+
// 面向远程工作区 (ssh://...) 的文件、命令与终端操作 API
|
|
988
|
+
// =========================================================================
|
|
989
|
+
/** 在远程工作区执行 Shell 命令(支持流式输出回调、超时与 AbortSignal) */
|
|
990
|
+
async execInWorkspace(uri, command, opts) {
|
|
991
|
+
const { conn, parsed } = await this.getOrConnectByUri(uri);
|
|
992
|
+
const targetDir = opts?.cwd || parsed.remotePath || "/";
|
|
993
|
+
const fullCmd = `cd ${shellQuotePosix(targetDir)} && ${command}`;
|
|
994
|
+
return new Promise((resolve, reject) => {
|
|
995
|
+
if (opts?.signal?.aborted) {
|
|
996
|
+
return reject(new Error("Command aborted"));
|
|
997
|
+
}
|
|
998
|
+
conn.client.exec(fullCmd, (err, stream) => {
|
|
999
|
+
if (err)
|
|
1000
|
+
return reject(err);
|
|
1001
|
+
let stdout = "";
|
|
1002
|
+
let stderr = "";
|
|
1003
|
+
let settled = false;
|
|
1004
|
+
let timer = null;
|
|
1005
|
+
const finish = (res, error) => {
|
|
1006
|
+
if (settled)
|
|
1007
|
+
return;
|
|
1008
|
+
settled = true;
|
|
1009
|
+
if (timer)
|
|
1010
|
+
clearTimeout(timer);
|
|
1011
|
+
opts?.signal?.removeEventListener("abort", onAbort);
|
|
1012
|
+
if (error)
|
|
1013
|
+
reject(error);
|
|
1014
|
+
else
|
|
1015
|
+
resolve(res);
|
|
1016
|
+
};
|
|
1017
|
+
const onAbort = () => {
|
|
1018
|
+
try {
|
|
1019
|
+
stream.signal("TERM");
|
|
1020
|
+
stream.close();
|
|
1021
|
+
}
|
|
1022
|
+
catch { }
|
|
1023
|
+
finish({ stdout, stderr, exitCode: 130 }, new Error("Command aborted"));
|
|
1024
|
+
};
|
|
1025
|
+
opts?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1026
|
+
if (opts?.timeoutMs && opts.timeoutMs > 0) {
|
|
1027
|
+
timer = setTimeout(() => {
|
|
1028
|
+
try {
|
|
1029
|
+
stream.signal("KILL");
|
|
1030
|
+
stream.close();
|
|
1031
|
+
}
|
|
1032
|
+
catch { }
|
|
1033
|
+
finish({ stdout, stderr, exitCode: 124 }, new Error(`Command timed out after ${opts.timeoutMs}ms`));
|
|
1034
|
+
}, opts.timeoutMs);
|
|
1035
|
+
}
|
|
1036
|
+
stream.on("data", (chunk) => {
|
|
1037
|
+
stdout += chunk.toString("utf8");
|
|
1038
|
+
opts?.onData?.(chunk);
|
|
1039
|
+
});
|
|
1040
|
+
stream.stderr.on("data", (chunk) => {
|
|
1041
|
+
stderr += chunk.toString("utf8");
|
|
1042
|
+
opts?.onData?.(chunk);
|
|
1043
|
+
});
|
|
1044
|
+
stream.on("close", (code) => {
|
|
1045
|
+
finish({ stdout, stderr, exitCode: typeof code === "number" ? code : 0 });
|
|
1046
|
+
});
|
|
1047
|
+
stream.on("error", (e) => {
|
|
1048
|
+
finish({ stdout, stderr, exitCode: 1 }, e);
|
|
1049
|
+
});
|
|
1050
|
+
});
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
/** SFTP stat(跟随软链) */
|
|
1054
|
+
async sftpStat(uri, remoteAbsPath) {
|
|
1055
|
+
const { sftp } = await this.getOrConnectByUri(uri);
|
|
1056
|
+
return new Promise((resolve, reject) => {
|
|
1057
|
+
sftp.stat(remoteAbsPath, (err, stats) => {
|
|
1058
|
+
if (err)
|
|
1059
|
+
return reject(err);
|
|
1060
|
+
resolve({
|
|
1061
|
+
isDirectory: Boolean(stats.isDirectory()),
|
|
1062
|
+
isFile: Boolean(stats.isFile()),
|
|
1063
|
+
size: stats.size ?? 0,
|
|
1064
|
+
mtime: (stats.mtime ?? 0) * 1000,
|
|
1065
|
+
});
|
|
1066
|
+
});
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
/** SFTP readdir(跟随符号链接判断目录) */
|
|
1070
|
+
async sftpReaddir(uri, remoteAbsPath) {
|
|
1071
|
+
const { sftp } = await this.getOrConnectByUri(uri);
|
|
1072
|
+
const list = await new Promise((resolve, reject) => {
|
|
1073
|
+
sftp.readdir(remoteAbsPath, (err, entries) => {
|
|
1074
|
+
if (err)
|
|
1075
|
+
return reject(err);
|
|
1076
|
+
resolve(entries || []);
|
|
1077
|
+
});
|
|
1078
|
+
});
|
|
1079
|
+
const out = [];
|
|
1080
|
+
for (const item of list) {
|
|
1081
|
+
if (item.filename === "." || item.filename === "..")
|
|
1082
|
+
continue;
|
|
1083
|
+
let isDir = Boolean(item.attrs.isDirectory());
|
|
1084
|
+
if (item.attrs.isSymbolicLink()) {
|
|
1085
|
+
try {
|
|
1086
|
+
const target = path.posix.join(remoteAbsPath, item.filename);
|
|
1087
|
+
const st = await this.sftpStat(uri, target);
|
|
1088
|
+
isDir = st.isDirectory;
|
|
1089
|
+
}
|
|
1090
|
+
catch {
|
|
1091
|
+
isDir = false;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
out.push({
|
|
1095
|
+
name: item.filename,
|
|
1096
|
+
type: isDir ? "dir" : "file",
|
|
1097
|
+
size: item.attrs.size ?? 0,
|
|
1098
|
+
mtime: (item.attrs.mtime ?? 0) * 1000,
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
return out;
|
|
1102
|
+
}
|
|
1103
|
+
/** SFTP 读取远程文件 Buffer(可选限制最大读取字节数) */
|
|
1104
|
+
async sftpReadFile(uri, remoteAbsPath, maxBytes) {
|
|
1105
|
+
const { sftp } = await this.getOrConnectByUri(uri);
|
|
1106
|
+
const st = await this.sftpStat(uri, remoteAbsPath);
|
|
1107
|
+
if (!st.isFile) {
|
|
1108
|
+
const err = new Error(`Not a file: ${remoteAbsPath}`);
|
|
1109
|
+
err.code = "EISDIR";
|
|
1110
|
+
throw err;
|
|
1111
|
+
}
|
|
1112
|
+
const toRead = maxBytes !== undefined ? Math.min(st.size, maxBytes) : st.size;
|
|
1113
|
+
if (toRead <= 0) {
|
|
1114
|
+
return { data: Buffer.alloc(0), size: st.size };
|
|
1115
|
+
}
|
|
1116
|
+
return new Promise((resolve, reject) => {
|
|
1117
|
+
const chunks = [];
|
|
1118
|
+
const stream = sftp.createReadStream(remoteAbsPath, { start: 0, end: toRead - 1 });
|
|
1119
|
+
stream.on("data", (chunk) => chunks.push(chunk));
|
|
1120
|
+
stream.on("error", (err) => reject(err));
|
|
1121
|
+
stream.on("end", () => {
|
|
1122
|
+
resolve({ data: Buffer.concat(chunks), size: st.size });
|
|
1123
|
+
});
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
/** SFTP 写入远程文件 */
|
|
1127
|
+
async sftpWriteFile(uri, remoteAbsPath, content, opts) {
|
|
1128
|
+
if (opts?.createParents) {
|
|
1129
|
+
const parentDir = path.posix.dirname(remoteAbsPath);
|
|
1130
|
+
if (parentDir && parentDir !== "/") {
|
|
1131
|
+
await this.sftpMkdirRecursive(uri, parentDir);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
const { sftp } = await this.getOrConnectByUri(uri);
|
|
1135
|
+
const buf = typeof content === "string" ? Buffer.from(content, "utf8") : content;
|
|
1136
|
+
return new Promise((resolve, reject) => {
|
|
1137
|
+
const stream = sftp.createWriteStream(remoteAbsPath, opts?.flag ? { flags: opts.flag } : undefined);
|
|
1138
|
+
stream.on("error", (err) => reject(err));
|
|
1139
|
+
stream.on("close", () => resolve());
|
|
1140
|
+
stream.end(buf);
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
/** 递归创建远程目录 (mkdir -p) */
|
|
1144
|
+
async sftpMkdirRecursive(uri, remoteAbsPath) {
|
|
1145
|
+
await this.execInWorkspace(uri, `mkdir -p ${shellQuotePosix(remoteAbsPath)}`, { cwd: "/" });
|
|
1146
|
+
}
|
|
1147
|
+
/** 重命名或移动远程文件/目录 */
|
|
1148
|
+
async sftpRename(uri, oldRemoteAbs, newRemoteAbs) {
|
|
1149
|
+
const { sftp } = await this.getOrConnectByUri(uri);
|
|
1150
|
+
return new Promise((resolve, reject) => {
|
|
1151
|
+
sftp.rename(oldRemoteAbs, newRemoteAbs, (err) => {
|
|
1152
|
+
if (err)
|
|
1153
|
+
return reject(err);
|
|
1154
|
+
resolve();
|
|
1155
|
+
});
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
/** 删除远程文件或目录 (rm -rf) */
|
|
1159
|
+
async sftpRemove(uri, remoteAbsPath) {
|
|
1160
|
+
if (!remoteAbsPath || remoteAbsPath === "/") {
|
|
1161
|
+
throw new Error("Refusing to remove root directory");
|
|
1162
|
+
}
|
|
1163
|
+
await this.execInWorkspace(uri, `rm -rf ${shellQuotePosix(remoteAbsPath)}`, { cwd: "/" });
|
|
1164
|
+
}
|
|
1165
|
+
/** 复制或移动远程文件/目录 */
|
|
1166
|
+
async sftpCopy(uri, srcRemoteAbs, destRemoteAbs, move) {
|
|
1167
|
+
const cmd = move
|
|
1168
|
+
? `mv ${shellQuotePosix(srcRemoteAbs)} ${shellQuotePosix(destRemoteAbs)}`
|
|
1169
|
+
: `cp -R ${shellQuotePosix(srcRemoteAbs)} ${shellQuotePosix(destRemoteAbs)}`;
|
|
1170
|
+
const res = await this.execInWorkspace(uri, cmd, { cwd: "/" });
|
|
1171
|
+
if (res.exitCode !== 0) {
|
|
1172
|
+
throw new Error(res.stderr || res.stdout || "Remote copy/move failed");
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* 为内置终端(terminals.ts)创建基于 ssh2 Channel 的虚拟 IPty 实例。
|
|
1177
|
+
* 直接复用已鉴权(含密码/私钥)的 SSH 连接开启交互式 PTY Shell,100% 免二次输入密码。
|
|
1178
|
+
*/
|
|
1179
|
+
createVirtualPty(uri, cols, rows) {
|
|
1180
|
+
const dataListeners = [];
|
|
1181
|
+
const exitListeners = [];
|
|
1182
|
+
let channel = null;
|
|
1183
|
+
let pendingWrites = [];
|
|
1184
|
+
let currentCols = Math.max(2, Math.floor(cols) || 80);
|
|
1185
|
+
let currentRows = Math.max(2, Math.floor(rows) || 24);
|
|
1186
|
+
let killed = false;
|
|
1187
|
+
const emitData = (str) => {
|
|
1188
|
+
for (const fn of dataListeners) {
|
|
1189
|
+
try {
|
|
1190
|
+
fn(str);
|
|
1191
|
+
}
|
|
1192
|
+
catch { }
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
const emitExit = (exitCode) => {
|
|
1196
|
+
for (const fn of exitListeners) {
|
|
1197
|
+
try {
|
|
1198
|
+
fn({ exitCode });
|
|
1199
|
+
}
|
|
1200
|
+
catch { }
|
|
1201
|
+
}
|
|
1202
|
+
};
|
|
1203
|
+
void (async () => {
|
|
1204
|
+
try {
|
|
1205
|
+
const { conn, parsed } = await this.getOrConnectByUri(uri);
|
|
1206
|
+
if (killed)
|
|
1207
|
+
return;
|
|
1208
|
+
conn.client.shell({
|
|
1209
|
+
term: "xterm-256color",
|
|
1210
|
+
cols: currentCols,
|
|
1211
|
+
rows: currentRows,
|
|
1212
|
+
}, (err, stream) => {
|
|
1213
|
+
if (err || killed) {
|
|
1214
|
+
if (err)
|
|
1215
|
+
emitData(`\r\n[SSH Terminal Error: ${err.message}]\r\n`);
|
|
1216
|
+
emitExit(1);
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
channel = stream;
|
|
1220
|
+
stream.on("data", (chunk) => {
|
|
1221
|
+
emitData(chunk.toString("utf8"));
|
|
1222
|
+
});
|
|
1223
|
+
stream.stderr.on("data", (chunk) => {
|
|
1224
|
+
emitData(chunk.toString("utf8"));
|
|
1225
|
+
});
|
|
1226
|
+
stream.on("close", (code) => {
|
|
1227
|
+
channel = null;
|
|
1228
|
+
emitExit(typeof code === "number" ? code : 0);
|
|
1229
|
+
});
|
|
1230
|
+
// 自动进入远程项目工作目录
|
|
1231
|
+
if (parsed.remotePath && parsed.remotePath !== "~") {
|
|
1232
|
+
stream.write(`cd ${shellQuotePosix(parsed.remotePath)} && clear\r`);
|
|
1233
|
+
}
|
|
1234
|
+
if (pendingWrites.length > 0) {
|
|
1235
|
+
for (const w of pendingWrites)
|
|
1236
|
+
stream.write(w);
|
|
1237
|
+
pendingWrites = [];
|
|
1238
|
+
}
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
catch (err) {
|
|
1242
|
+
emitData(`\r\n[Failed to connect remote SSH terminal: ${err.message}]\r\n`);
|
|
1243
|
+
emitExit(1);
|
|
1244
|
+
}
|
|
1245
|
+
})();
|
|
1246
|
+
const virtualPty = {
|
|
1247
|
+
pid: Math.floor(10000 + Math.random() * 80000),
|
|
1248
|
+
cols: currentCols,
|
|
1249
|
+
rows: currentRows,
|
|
1250
|
+
process: "ssh-remote",
|
|
1251
|
+
handleFlowControl: false,
|
|
1252
|
+
onData(listener) {
|
|
1253
|
+
dataListeners.push(listener);
|
|
1254
|
+
return {
|
|
1255
|
+
dispose: () => {
|
|
1256
|
+
const idx = dataListeners.indexOf(listener);
|
|
1257
|
+
if (idx >= 0)
|
|
1258
|
+
dataListeners.splice(idx, 1);
|
|
1259
|
+
},
|
|
1260
|
+
};
|
|
1261
|
+
},
|
|
1262
|
+
onExit(listener) {
|
|
1263
|
+
exitListeners.push(listener);
|
|
1264
|
+
return {
|
|
1265
|
+
dispose: () => {
|
|
1266
|
+
const idx = exitListeners.indexOf(listener);
|
|
1267
|
+
if (idx >= 0)
|
|
1268
|
+
exitListeners.splice(idx, 1);
|
|
1269
|
+
},
|
|
1270
|
+
};
|
|
1271
|
+
},
|
|
1272
|
+
write(data) {
|
|
1273
|
+
if (killed)
|
|
1274
|
+
return;
|
|
1275
|
+
if (channel) {
|
|
1276
|
+
channel.write(data);
|
|
1277
|
+
}
|
|
1278
|
+
else {
|
|
1279
|
+
pendingWrites.push(data);
|
|
1280
|
+
}
|
|
1281
|
+
},
|
|
1282
|
+
resize(newCols, newRows) {
|
|
1283
|
+
currentCols = Math.max(2, Math.floor(newCols) || 80);
|
|
1284
|
+
currentRows = Math.max(2, Math.floor(newRows) || 24);
|
|
1285
|
+
if (channel) {
|
|
1286
|
+
try {
|
|
1287
|
+
channel.setWindow(currentRows, currentCols, 0, 0);
|
|
1288
|
+
}
|
|
1289
|
+
catch { }
|
|
1290
|
+
}
|
|
1291
|
+
},
|
|
1292
|
+
clear() { },
|
|
1293
|
+
kill(_signal) {
|
|
1294
|
+
if (killed)
|
|
1295
|
+
return;
|
|
1296
|
+
killed = true;
|
|
1297
|
+
if (channel) {
|
|
1298
|
+
try {
|
|
1299
|
+
channel.close();
|
|
1300
|
+
}
|
|
1301
|
+
catch { }
|
|
1302
|
+
channel = null;
|
|
1303
|
+
}
|
|
1304
|
+
},
|
|
1305
|
+
pause() {
|
|
1306
|
+
channel?.pause();
|
|
1307
|
+
},
|
|
1308
|
+
resume() {
|
|
1309
|
+
channel?.resume();
|
|
1310
|
+
},
|
|
1311
|
+
};
|
|
1312
|
+
return virtualPty;
|
|
1313
|
+
}
|
|
1314
|
+
}
|