ssh-backend.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /* eslint-disable max-lines -- SSH backend 集中维护连接、exec、SFTP 上传和 fallback 进度链路;集中维护以避免拆分引入远端连接回归。 */
  2. import { Client as SSHClient } from "ssh2";
  3. import type { ConnectConfig } from "ssh2";
  4. import { createReadStream } from "node:fs";
  5. import type { Duplex } from "node:stream";
  6. import { posix } from "node:path";
  7. import { Emitter } from "@zcode/rpc";
  8. import { resolveZCodeRuntimeEnv } from "@zcode/shared";
  9. import type {
  10. IRemoteBackend,
  11. RemoteDisconnectEvent,
  12. RemoteDisconnectReason,
  13. RemoteEnvironment,
  14. RemoteUploadOptions,
  15. StdioStream,
  16. } from "@zcode/server/remote/backend.js";
  17. import {
  18. normalizeRemoteArch,
  19. normalizeRemotePlatform,
  20. resolveRemotePlatform,
  21. } from "@zcode/server/remote/detectEnv.js";
  22. import {
  23. createCloseEventController,
  24. resolveRemoteExitCode,
  25. } from "@zcode/server/remote/closeEvent.js";
  26. import {
  27. buildPosixShellExecCommand,
  28. quotePosixShellArg,
  29. resolvePosixHomePath,
  30. } from "@zcode/server/remote/posixShell.js";
  31. import {
  32. buildSSHConnectConfig,
  33. createKeyboardInteractiveResponder,
  34. normalizeSSHConnectError,
  35. } from "@zcode/server/remote/sshAuth.js";
  36. import {
  37. createSSHUploadProgressReporter,
  38. formatSSHUploadError,
  39. formatSSHUploadLabel,
  40. readLocalFileSize,
  41. } from "@zcode/server/remote/sshUploadProgress.js";
  42. export interface SSHBackendOptions {
  43. host: string;
  44. port?: number;
  45. username: string;
  46. privateKeyPath?: string;
  47. privateKey?: string | Buffer;
  48. privateKeyPassphrase?: string;
  49. password?: string;
  50. agent?: string;
  51. }
  52. type SSHUploadFailureKind = "sftp-session" | "sftp-write" | "local-read" | "aborted";
  53. type SSHUploadFailure = Error & {
  54. uploadFailureKind?: SSHUploadFailureKind;
  55. };
  56. function normalizeUnknownError(error: unknown, fallbackMessage: string): Error {
  57. if (error instanceof Error) {
  58. return error;
  59. }
  60. if (typeof error === "string" && error.length > 0) {
  61. return new Error(error);
  62. }
  63. return new Error(fallbackMessage);
  64. }
  65. function markSSHUploadFailure(
  66. error: unknown,
  67. kind: SSHUploadFailureKind,
  68. fallbackMessage: string,
  69. ): SSHUploadFailure {
  70. const normalizedError = normalizeUnknownError(error, fallbackMessage) as SSHUploadFailure;
  71. normalizedError.uploadFailureKind = kind;
  72. return normalizedError;
  73. }
  74. function shouldLogSSHDebugMessage(message: string): boolean {
  75. return !/\bCHANNEL_(?:DATA|EXTENDED_DATA|WINDOW_ADJUST)\b/u.test(message);
  76. }
  77. function createUploadAbortError(): Error {
  78. const error = new Error("Remote upload canceled");
  79. error.name = "AbortError";
  80. return error;
  81. }
  82. function throwIfUploadAborted(signal?: AbortSignal): void {
  83. if (signal?.aborted) throw createUploadAbortError();
  84. }
  85. export class SSHBackend implements IRemoteBackend {
  86. private client: SSHClient;
  87. private connected = false;
  88. private readonly config: ConnectConfig;
  89. private homeDirPromise: Promise<string> | null = null;
  90. private execUploadOnly = false;
  91. private disposed = false;
  92. private hasEverConnected = false;
  93. private disconnectReported = false;
  94. /** 本次连接尝试中 keyboard-interactive 提示明确要求动态口令;每次 connect 前清零,只用于认证失败的分类。 */
  95. private additionalVerificationPrompted = false;
  96. /** 在途连接尝试的失败出口;dispose 用它让等待中的 ensureConnected 立即结束。 */
  97. private failPendingConnect: ((error: Error) => void) | undefined;
  98. private readonly disconnectEmitter = new Emitter<RemoteDisconnectEvent>();
  99. readonly onDidDisconnect = this.disconnectEmitter.event;
  100. private readonly onClientError = (error: unknown): void => {
  101. if (this.disposed) {
  102. // ssh2 在 ready timeout 后销毁 socket 时,close/end 阶段可能再次发出 error。
  103. // dispose 期间保留监听器只为吸收这类迟到事件,不能再向上层重复报告或触发未捕获异常。
  104. return;
  105. }
  106. // 先读取 connected:reportDisconnect 会把它清零,而 ready 后的 client-timeout 只来自 Keepalive。
  107. const normalizedError = normalizeSSHConnectError(error, {
  108. established: this.connected,
  109. additionalVerificationPrompted: this.additionalVerificationPrompted,
  110. });
  111. // ready 之后如果底层连接抖动,ssh2 仍会发出 "error" 事件。
  112. // 若没有常驻监听,Node 会把它当成未捕获异常直接抛出,可能导致 host 进程崩溃。
  113. // 这里先记录错误详情再上报断连;上层收到断连后会退出 host,反过来会丢掉真实 error 文案。
  114. console.error("[ssh] client error:", normalizedError);
  115. this.reportDisconnect("error", normalizedError);
  116. };
  117. private readonly onClientClose = (): void => {
  118. this.reportDisconnect("close");
  119. };
  120. private readonly onClientEnd = (): void => {
  121. this.reportDisconnect("end");
  122. };
  123. constructor(options: SSHBackendOptions) {
  124. this.client = new SSHClient();
  125. this.client.on("error", this.onClientError);
  126. this.client.on("close", this.onClientClose);
  127. this.client.on("end", this.onClientEnd);
  128. this.config = buildSSHConnectConfig({
  129. host: options.host,
  130. port: options.port,
  131. username: options.username,
  132. privateKey: options.privateKey,
  133. passphrase: options.privateKeyPassphrase,
  134. password: options.password,
  135. agent: options.agent,
  136. });
  137. if (resolveZCodeRuntimeEnv(process.env) === "development") {
  138. this.config.debug = (message: string) => {
  139. // SSH ready 超时只暴露 client-timeout 时无法判断卡在 TCP、协商还是认证。
  140. // 仅开发环境输出 ssh2 握手细节;CHANNEL_DATA / EXTENDED_DATA 是命令 stdout/stderr 数据包,
  141. // 下载阶段会按 chunk 高频刷屏,过滤掉它们,避免连接窗口和 electron 日志被底层传输事件淹没。
  142. if (!shouldLogSSHDebugMessage(message)) {
  143. return;
  144. }
  145. console.debug(`[ssh2] ${message}`);
  146. };
  147. }
  148. if (typeof options.password === "string" && options.password.length > 0) {
  149. // `ssh2` 类型定义遗漏了 keyboard-interactive 事件,但运行时确实支持。
  150. // 这里局部转成 EventEmitter 接口,避免为了一个事件把整段代码降级到 any。
  151. (
  152. this.client as unknown as {
  153. on(event: string, listener: (...args: unknown[]) => void): void;
  154. }
  155. ).on(
  156. "keyboard-interactive",
  157. createKeyboardInteractiveResponder(options.password, () => {
  158. this.additionalVerificationPrompted = true;
  159. }) as unknown as (...args: unknown[]) => void,
  160. );
  161. }
  162. }
  163. private assertNotDisposed(): void {
  164. if (this.disposed) {
  165. throw new Error("SSH backend 已释放,无法重新建立连接");
  166. }
  167. }
  168. private async ensureConnected(): Promise<void> {
  169. // 连接取消会先释放 backend,但迟到的 deploy/cleanup continuation 仍可能
  170. // 调用 ensureConnected。ssh2 Client 支持 end 后再次 connect,必须在 backend 边界阻止旧凭据复活。
  171. this.assertNotDisposed();
  172. if (this.connected) return;
  173. return new Promise((resolve, reject) => {
  174. const settle = () => {
  175. this.client.off("ready", handleReady);
  176. this.client.off("error", handleConnectError);
  177. this.failPendingConnect = undefined;
  178. };
  179. const handleReady = () => {
  180. settle();
  181. this.connected = true;
  182. this.hasEverConnected = true;
  183. this.disconnectReported = false;
  184. resolve();
  185. };
  186. const handleConnectError = (error: unknown) => {
  187. settle();
  188. reject(
  189. normalizeSSHConnectError(error, {
  190. additionalVerificationPrompted: this.additionalVerificationPrompted,
  191. }),
  192. );
  193. };
  194. // Bug 原因:ssh2 收到服务端 banner 后,若认证完成前 dispose 调用 end() 关闭连接,ssh2 既不发
  195. // ready 也不发 error,还会清掉 60 秒 readyTimeout。旧逻辑只等 ready/error,Promise 永不结束:
  196. // 启动重连 10 秒超时释放 backend 后,设备一直停在“连接中”,之后的手动连接都 join 到这次
  197. // 永不结束的尝试上(ZCT-2112827425880723456)。修复:dispose 通过这个出口让在途尝试立即失败,
  198. // manager 随之写回 failed 并移除 flight。不改用 close 事件判定,是因为同一 ssh2 Client 重连时
  199. // 旧连接的 close 可能晚到,无法与本次尝试区分。
  200. this.failPendingConnect = (error) => {
  201. settle();
  202. reject(error);
  203. };
  204. this.client.once("ready", handleReady);
  205. this.client.once("error", handleConnectError);
  206. this.additionalVerificationPrompted = false;
  207. this.client.connect(this.config);
  208. });
  209. }
  210. private reportDisconnect(reason: RemoteDisconnectReason, error?: Error): void {
  211. const shouldReport =
  212. !this.disposed && !this.disconnectReported && (this.connected || this.hasEverConnected);
  213. this.connected = false;
  214. this.homeDirPromise = null;
  215. if (!shouldReport) {
  216. return;
  217. }
  218. this.disconnectReported = true;
  219. this.disconnectEmitter.fire(error ? { reason, error } : { reason });
  220. }
  221. async detect(): Promise<RemoteEnvironment> {
  222. await this.ensureConnected();
  223. // Bug 原因:冷启动曾为 platform、arch、kernel ostype 串行创建三个 SSH exec channel,
  224. // 仅环境探测就占掉大部分 10 秒恢复预算。保持一个 POSIX channel 可同时避免首次多 channel 竞态。
  225. const output = await this.execSimple(
  226. "printf 'platform='; uname -s; printf 'arch='; uname -m; printf 'kernel='; " +
  227. "if [ -r /proc/sys/kernel/ostype ]; then cat /proc/sys/kernel/ostype; else printf '\\n'; fi",
  228. );
  229. const readField = (name: string): string =>
  230. output
  231. .split(/\r?\n/u)
  232. .find((line) => line.startsWith(`${name}=`))
  233. ?.slice(name.length + 1)
  234. .trim() ?? "";
  235. const reportedPlatform = normalizeRemotePlatform(readField("platform"));
  236. const arch = normalizeRemoteArch(readField("arch"));
  237. const kernelOstype = readField("kernel");
  238. const platform = resolveRemotePlatform(reportedPlatform, kernelOstype);
  239. if (platform !== reportedPlatform) {
  240. console.warn(
  241. `[ssh] detect: uname reported ${reportedPlatform}, but kernel ostype is ${kernelOstype}; fallback to ${platform}`,
  242. );
  243. }
  244. return { platform, arch };
  245. }
  246. async upload(
  247. localPath: string,
  248. remotePath: string,
  249. options?: RemoteUploadOptions,
  250. ): Promise<void> {
  251. throwIfUploadAborted(options?.signal);
  252. await this.ensureConnected();
  253. this.assertNotDisposed();
  254. const resolved = await this.resolveRemotePath(remotePath);
  255. throwIfUploadAborted(options?.signal);
  256. this.assertNotDisposed();
  257. const uploadLabel = formatSSHUploadLabel(resolved);
  258. console.log(`[ssh] upload: resolved ${uploadLabel} to ${resolved}`);
  259. const dir = posix.dirname(resolved);
  260. await this.execSimple(`mkdir -p ${quotePosixShellArg(dir)}`);
  261. if (this.execUploadOnly) {
  262. // exec-only 只缓存传输能力,不能丢掉每次上传独立的取消信号与进度回调;
  263. // 否则首次 SFTP 降级后的后续资源会脱离连接取消流程,并让 UI 停止更新进度。
  264. await this.uploadViaExec(localPath, resolved, options);
  265. return;
  266. }
  267. try {
  268. await this.uploadViaSftp(localPath, resolved, options);
  269. } catch (error) {
  270. if (!this.shouldFallbackToExecUpload(error)) {
  271. throw error;
  272. }
  273. // 某些网关 / 跳板 SSH 会把 exec 与 SFTP 落到不同的文件系统视图。
  274. // 这类场景下,前面的 `mkdir -p` 已经证明 shell 视图可写,但 SFTP 往同一路径写文件仍会报 NO_SUCH_FILE。
  275. // 这里回退到 `cat > file`,强制复用已验证可用的 shell 通道,避免把“网关不支持 SFTP 直写”误判成连接失败。
  276. // 同一个 backend 后续继续试 SFTP 只会重复失败并刷日志,因此在首次能力失败后记住 exec-only 状态;
  277. // 新连接会创建新的 backend,自然会重新探测 SFTP 能力。
  278. this.execUploadOnly = true;
  279. console.warn(
  280. `[ssh] upload: switching ${uploadLabel} from sftp to exec pipe after ${this.describeUploadFailure(error)}`,
  281. );
  282. await this.uploadViaExec(localPath, resolved, options);
  283. }
  284. }
  285. async exec(command: string): Promise<StdioStream> {
  286. await this.ensureConnected();
  287. // ensureConnected 的 await 与真正创建 channel 之间允许取消屏障插入,必须再次校验。
  288. this.assertNotDisposed();
  289. return new Promise((resolve, reject) => {
  290. // SSH exec 会先交给远端用户的默认 shell;fish 会把部署脚本里的 `download=` 等 POSIX 语法当成错误。
  291. // 在 SSH 边界统一进入 /bin/sh,保证 remote deploy、preflight 和 server 启动脚本都按项目声明的 POSIX shell 语义执行。
  292. this.client.exec(buildPosixShellExecCommand(command), (err, channel) => {
  293. if (err) return reject(err);
  294. const onClose = createCloseEventController();
  295. let fired = false;
  296. const fireOnce = (code: number) => {
  297. if (fired) return;
  298. fired = true;
  299. // remote deploy 会执行大量短命令,成功退出的 code=0 日志没有排查价值且会刷屏。
  300. // 这里只保留失败退出码,正常流程由上层的阶段日志和进度日志表达。
  301. if (code !== 0) {
  302. console.warn(`[ssh] exec channel failed: code=${code}`);
  303. }
  304. onClose.fire(code);
  305. };
  306. // ssh2 channels may fire 'exit' before 'close', or sometimes
  307. // only one of them. Listen to both to be safe.
  308. // ssh2 收到 exit-signal 时 code 为 null;没有收到任何退出信息时 close 不带参数。
  309. // 两种情况都不是成功,见 resolveRemoteExitCode。
  310. channel.on("exit", (code: number | null, signal?: string) => {
  311. fireOnce(resolveRemoteExitCode(code, signal));
  312. });
  313. channel.on("close", (code?: number | null, signal?: string) => {
  314. fireOnce(resolveRemoteExitCode(code, signal));
  315. });
  316. resolve({
  317. stdin: channel.stdin,
  318. stdout: channel,
  319. stderr: channel.stderr,
  320. onClose: onClose.event,
  321. });
  322. });
  323. });
  324. }
  325. async openDirectTcpChannel(port: number): Promise<Duplex> {
  326. if (!Number.isInteger(port) || port <= 0 || port > 65_535) {
  327. throw new Error(`Invalid remote TCP port: ${port}`);
  328. }
  329. await this.ensureConnected();
  330. return await new Promise<Duplex>((resolve, reject) => {
  331. this.client.forwardOut("127.0.0.1", 0, "127.0.0.1", port, (error, channel) => {
  332. if (error) reject(error);
  333. else resolve(channel);
  334. });
  335. });
  336. }
  337. async exists(remotePath: string): Promise<boolean> {
  338. try {
  339. const resolvedRemotePath = await this.resolveRemotePath(remotePath);
  340. const result = await this.execSimple(
  341. `test -f ${quotePosixShellArg(resolvedRemotePath)} && printf OK`,
  342. );
  343. return result.trim() === "OK";
  344. } catch {
  345. return false;
  346. }
  347. }
  348. async readFile(remotePath: string): Promise<string> {
  349. const resolvedRemotePath = await this.resolveRemotePath(remotePath);
  350. return this.execSimple(`cat ${quotePosixShellArg(resolvedRemotePath)}`);
  351. }
  352. /** Execute a simple command and return stdout as string */
  353. private execSimple(command: string): Promise<string> {
  354. this.assertNotDisposed();
  355. return new Promise((resolve, reject) => {
  356. // execSimple 同样会执行 POSIX 片段(例如 `[ -r ... ]`、变量展开)。
  357. // 这里和 exec 保持同一层 shell 策略,避免 detect/exists/readFile 在 fish 默认 shell 下先于部署失败。
  358. this.client.exec(buildPosixShellExecCommand(command), (err, channel) => {
  359. if (err) return reject(err);
  360. let stdout = "";
  361. let stderr = "";
  362. let done = false;
  363. let exitCode: number | null = null;
  364. channel.on("data", (chunk: Buffer) => {
  365. stdout += chunk.toString();
  366. });
  367. channel.stderr.on("data", (chunk: Buffer) => {
  368. stderr += chunk.toString();
  369. });
  370. const finish = (code: number) => {
  371. if (done) return;
  372. done = true;
  373. if (code !== 0) {
  374. reject(new Error(`Command failed (code ${code}): ${stderr || stdout}`));
  375. } else {
  376. resolve(stdout);
  377. }
  378. };
  379. // ssh2 在短命令场景下可能先发 exit,再异步派发 stdout data。
  380. // 不能在 exit 事件直接 finish:会把后续 data 丢掉,导致 platform/arch 偶发识别为空。
  381. // 这里改为只在 close 统一收尾,并优先使用 exit 记录的真实退出码,避免误判成功。
  382. channel.on("exit", (code: number | null, signal?: string) => {
  383. exitCode = resolveRemoteExitCode(code, signal);
  384. });
  385. channel.on("close", (code?: number | null, signal?: string) => {
  386. finish(exitCode ?? resolveRemoteExitCode(code, signal));
  387. });
  388. });
  389. });
  390. }
  391. private async resolveHomeDir(): Promise<string> {
  392. if (this.homeDirPromise) {
  393. return this.homeDirPromise;
  394. }
  395. this.homeDirPromise = this.execSimple('printf %s "$HOME"').then((homeDir) => homeDir.trim());
  396. return this.homeDirPromise;
  397. }
  398. private shouldFallbackToExecUpload(error: unknown): boolean {
  399. const uploadFailureKind = (error as SSHUploadFailure | undefined)?.uploadFailureKind;
  400. return uploadFailureKind === "sftp-session" || uploadFailureKind === "sftp-write";
  401. }
  402. private describeUploadFailure(error: unknown): string {
  403. const uploadFailureKind = (error as SSHUploadFailure | undefined)?.uploadFailureKind;
  404. const errorLabel = formatSSHUploadError(error);
  405. return uploadFailureKind ? `${uploadFailureKind} failure (${errorLabel})` : errorLabel;
  406. }
  407. private async uploadViaSftp(
  408. localPath: string,
  409. resolvedRemotePath: string,
  410. options?: RemoteUploadOptions,
  411. ): Promise<void> {
  412. throwIfUploadAborted(options?.signal);
  413. this.assertNotDisposed();
  414. const uploadLabel = formatSSHUploadLabel(resolvedRemotePath);
  415. const totalBytes = await readLocalFileSize(localPath);
  416. const progressReporter = createSSHUploadProgressReporter("sftp", uploadLabel, totalBytes);
  417. const reportProgress = (uploadedBytes: number, force: boolean) => {
  418. progressReporter(uploadedBytes, force);
  419. options?.onProgress?.({ uploadedBytes, totalBytes: totalBytes ?? 0 });
  420. };
  421. return new Promise((resolve, reject) => {
  422. this.client.sftp((err, sftp) => {
  423. if (err) {
  424. // session/write 失败会由 upload() 统一降级并记录一次 warn;这里若先记 error,
  425. // 同一个可恢复事件会同时出现 error + warn,误导为部署失败。
  426. reject(markSSHUploadFailure(err, "sftp-session", "Failed to open SFTP session"));
  427. return;
  428. }
  429. console.log(
  430. `[ssh] upload: started via sftp for ${uploadLabel} (${localPath} -> ${resolvedRemotePath})`,
  431. );
  432. const readStream = createReadStream(localPath);
  433. const writeStream = sftp.createWriteStream(resolvedRemotePath);
  434. let transferredBytes = 0;
  435. let settled = false;
  436. let suppressFollowupStreamErrors = false;
  437. const resolveOnce = () => {
  438. if (settled) {
  439. return;
  440. }
  441. settled = true;
  442. options?.signal?.removeEventListener("abort", abortOnce);
  443. reportProgress(transferredBytes, true);
  444. console.log(`[ssh] upload: completed via sftp for ${uploadLabel}`);
  445. sftp.end();
  446. resolve();
  447. };
  448. const rejectOnce = (error: unknown, kind: SSHUploadFailureKind, message: string) => {
  449. if (settled) {
  450. return;
  451. }
  452. settled = true;
  453. options?.signal?.removeEventListener("abort", abortOnce);
  454. suppressFollowupStreamErrors = true;
  455. // SFTP 失败后如果不立刻停掉本地 read stream,它仍会继续把文件读到 100%,
  456. // UI 就会在已经切到 exec pipe 之后还刷出一串虚假的 `[sftp] upload progress`。
  457. // 这里在失败瞬间主动停掉两端 stream,保证第一种上传方式的进度日志立即停止。
  458. // 注意不要把原始 error 再次喂给 destroy,否则清理路径本身会再冒出一轮重复 error 日志。
  459. readStream.unpipe(writeStream);
  460. readStream.destroy();
  461. const destroyableWriteStream = writeStream as NodeJS.WritableStream & {
  462. destroy?: (error?: Error) => void;
  463. };
  464. if (typeof destroyableWriteStream.destroy === "function") {
  465. destroyableWriteStream.destroy();
  466. }
  467. sftp.end();
  468. reject(markSSHUploadFailure(error, kind, message));
  469. };
  470. const abortOnce = () => {
  471. rejectOnce(createUploadAbortError(), "aborted", "Remote upload canceled");
  472. };
  473. if (options?.signal?.aborted) {
  474. abortOnce();
  475. return;
  476. }
  477. options?.signal?.addEventListener("abort", abortOnce, { once: true });
  478. readStream.on("data", (chunk: Buffer) => {
  479. if (settled) {
  480. return;
  481. }
  482. transferredBytes += chunk.length;
  483. reportProgress(transferredBytes, false);
  484. });
  485. writeStream.on("close", resolveOnce);
  486. writeStream.on("error", (error: Error) => {
  487. if (settled || suppressFollowupStreamErrors) {
  488. return;
  489. }
  490. rejectOnce(error, "sftp-write", `Failed to write ${resolvedRemotePath} over SFTP`);
  491. });
  492. readStream.on("error", (error: Error) => {
  493. if (settled || suppressFollowupStreamErrors) {
  494. return;
  495. }
  496. console.error(
  497. `[ssh] upload: local read failed for ${uploadLabel}: ${formatSSHUploadError(error)}`,
  498. );
  499. rejectOnce(error, "local-read", `Failed to read local file ${localPath}`);
  500. });
  501. readStream.pipe(writeStream);
  502. });
  503. });
  504. }
  505. private async uploadViaExec(
  506. localPath: string,
  507. resolvedRemotePath: string,
  508. options?: RemoteUploadOptions,
  509. ): Promise<void> {
  510. const uploadLabel = formatSSHUploadLabel(resolvedRemotePath);
  511. const totalBytes = await readLocalFileSize(localPath);
  512. const progressReporter = createSSHUploadProgressReporter("exec", uploadLabel, totalBytes);
  513. const reportProgress = (uploadedBytes: number, force: boolean) => {
  514. progressReporter(uploadedBytes, force);
  515. options?.onProgress?.({ uploadedBytes, totalBytes: totalBytes ?? 0 });
  516. };
  517. throwIfUploadAborted(options?.signal);
  518. const parentDir = posix.dirname(resolvedRemotePath);
  519. const command = `mkdir -p ${quotePosixShellArg(parentDir)} && cat > ${quotePosixShellArg(resolvedRemotePath)}`;
  520. console.log(
  521. `[ssh] upload: started via exec pipe for ${uploadLabel} (${localPath} -> ${resolvedRemotePath})`,
  522. );
  523. const stream = await this.exec(command);
  524. await new Promise<void>((resolve, reject) => {
  525. const readStream = createReadStream(localPath);
  526. const stdin = stream.stdin;
  527. let transferredBytes = 0;
  528. let settled = false;
  529. const finishWithError = (error: Error) => {
  530. if (settled) {
  531. return;
  532. }
  533. settled = true;
  534. options?.signal?.removeEventListener("abort", abortOnce);
  535. readStream.destroy();
  536. const destroyableStdin = stdin as NodeJS.WritableStream & {
  537. destroy?: (reason?: Error) => void;
  538. };
  539. if (typeof destroyableStdin.destroy === "function") {
  540. destroyableStdin.destroy(error);
  541. } else {
  542. stdin.end();
  543. }
  544. reject(error);
  545. };
  546. const abortOnce = () => finishWithError(createUploadAbortError());
  547. if (options?.signal?.aborted) {
  548. abortOnce();
  549. return;
  550. }
  551. options?.signal?.addEventListener("abort", abortOnce, { once: true });
  552. readStream.on("error", (error) => finishWithError(error));
  553. readStream.on("data", (chunk: Buffer) => {
  554. transferredBytes += chunk.length;
  555. reportProgress(transferredBytes, false);
  556. });
  557. stdin.on("error", (error: Error) => finishWithError(error));
  558. readStream.pipe(stdin);
  559. stream.onClose((code) => {
  560. if (settled) {
  561. return;
  562. }
  563. settled = true;
  564. options?.signal?.removeEventListener("abort", abortOnce);
  565. reportProgress(transferredBytes, true);
  566. if (code !== 0) {
  567. console.error(`[ssh] upload: exec pipe failed for ${uploadLabel}: exit code ${code}`);
  568. reject(new Error(`SSH exec upload failed with exit code ${code}`));
  569. return;
  570. }
  571. console.log(`[ssh] upload: completed via exec pipe for ${uploadLabel}`);
  572. resolve();
  573. });
  574. });
  575. }
  576. private async resolveRemotePath(remotePath: string): Promise<string> {
  577. const homeDir = await this.resolveHomeDir();
  578. return resolvePosixHomePath(remotePath, homeDir);
  579. }
  580. dispose(): void {
  581. if (this.disposed) {
  582. return;
  583. }
  584. this.disposed = true;
  585. // 在途连接先失败并摘掉 ready 监听:迟到的 ready 不会再用已取消连接的旧凭据标记 connected,
  586. // 也不必等 socket 关闭(TCP 未建立时可能要等系统连接超时)。
  587. this.failPendingConnect?.(new Error("SSH backend 已释放,无法重新建立连接"));
  588. // 首次握手失败后,ssh2 可能在 socket end/close 之后继续发出 error。
  589. // dispose 后保留 onClientError 作为 no-op sink,不能按 end/close 事件时序提前移除,
  590. // 否则迟到事件会逃逸为 uncaughtException,让共享 Window Host 连带退出其它 workspace。
  591. // client 只由当前 backend 持有,监听器会随 client 一起回收;此处优先保证退役阶段不崩溃。
  592. this.client.off("close", this.onClientClose);
  593. this.client.off("end", this.onClientEnd);
  594. this.client.end();
  595. this.connected = false;
  596. this.disconnectEmitter.dispose();
  597. }
  598. }