ssh-remote-p0.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /* eslint-disable max-lines -- SSH P0 helper 集中维护真实连接、远端身份、进程与 replay tunnel 生命周期,拆散会隐藏同一条安全边界。 */
  2. import { createConnection, createServer, type Server, type Socket } from "node:net";
  3. import { Client as SSHClient, type ClientChannel, type TcpConnectionDetails } from "ssh2";
  4. import {
  5. TID_COMPOSER_REMOTE_CONNECTION,
  6. TID_COMPOSER_WORKSPACE_TRIGGER,
  7. TID_REMOTE_KIND_SSH,
  8. TID_SSH_DIALOG,
  9. TID_SSH_ERROR,
  10. TID_SSH_HOST_INPUT,
  11. TID_SSH_PASSWORD_INPUT,
  12. TID_SSH_PORT_INPUT,
  13. TID_SSH_SUCCESS,
  14. TID_SSH_USERNAME_INPUT,
  15. buildRemoteWorkspaceIdentity,
  16. type RemoteTarget,
  17. } from "@zcode/shared";
  18. import {
  19. clickTestIdByWebDriver,
  20. setInputValueByTestIdDom,
  21. waitForWorkspaceApp,
  22. } from "./desktop-app.js";
  23. import { resolveSeededReplayBaseUrl } from "./custom-openai-provider-store.js";
  24. import { startNewV4Draft } from "./v4-conversation.js";
  25. import {
  26. isMainRendererUrl,
  27. isResourceManagerUrl,
  28. listHostProcessIdentities,
  29. openResourceManager,
  30. switchToElectronRendererTarget,
  31. waitForResourceManagerReady,
  32. } from "./resource-manager.js";
  33. export const SSH_CONNECT_TIMEOUT_MS = 10 * 60_000;
  34. export const SSH_WORKSPACE_READY_TIMEOUT_MS = 2 * 60_000;
  35. export interface SSHConnectionConfig {
  36. host: string;
  37. password: string;
  38. port: number;
  39. username: string;
  40. }
  41. export interface SSHRuntimeConfig extends SSHConnectionConfig {
  42. workspacePaths: readonly [string, string];
  43. }
  44. export interface SingleSSHWorkspaceRuntimeConfig extends SSHConnectionConfig {
  45. workspacePath: string;
  46. }
  47. export interface DualSSHRuntimeConfig {
  48. targets: readonly [SSHConnectionConfig, SSHConnectionConfig];
  49. workspacePath: string;
  50. }
  51. export interface RemoteTabSnapshot {
  52. activeWorkspaceIdentity: string | null;
  53. activeWorkspacePath: string | null;
  54. remoteHost: string | null;
  55. remoteKind: string | null;
  56. remoteSessionId: string | null;
  57. secretPersistedInTab: boolean;
  58. workspaceIdentity: string | null;
  59. workspacePath: string | null;
  60. }
  61. export interface ReplayTunnel {
  62. baseURL: string;
  63. close(): Promise<void>;
  64. }
  65. export interface FirstConnectionStallingSSHProxy {
  66. firstConnectionAccepted: Promise<void>;
  67. port: number;
  68. waitForFirstConnectionClosed(): Promise<void>;
  69. close(): Promise<void>;
  70. }
  71. export async function createFirstConnectionStallingSSHProxy(
  72. config: Pick<SSHRuntimeConfig, "host" | "port">,
  73. caseMarker: string,
  74. ): Promise<FirstConnectionStallingSSHProxy> {
  75. let markFirstConnectionAccepted!: () => void;
  76. const firstConnectionAccepted = new Promise<void>((resolve) => {
  77. markFirstConnectionAccepted = resolve;
  78. });
  79. let markFirstConnectionClosed!: () => void;
  80. const firstConnectionClosed = new Promise<void>((resolve) => {
  81. markFirstConnectionClosed = resolve;
  82. });
  83. const sockets = new Set<Socket>();
  84. let connectionCount = 0;
  85. const trackSocket = (socket: Socket) => {
  86. sockets.add(socket);
  87. socket.once("close", () => sockets.delete(socket));
  88. };
  89. const server = createServer((client) => {
  90. trackSocket(client);
  91. connectionCount += 1;
  92. if (connectionCount === 1) {
  93. // 第一个 TCP connection 故意不转发 SSH 握手,稳定保留 pending cancel 窗口。
  94. markFirstConnectionAccepted();
  95. client.once("error", () => client.destroy());
  96. client.once("close", markFirstConnectionClosed);
  97. return;
  98. }
  99. const upstream = createConnection({ host: config.host, port: config.port });
  100. trackSocket(upstream);
  101. const closeBoth = () => {
  102. client.destroy();
  103. upstream.destroy();
  104. };
  105. client.once("error", closeBoth);
  106. upstream.once("error", closeBoth);
  107. upstream.once("connect", () => client.pipe(upstream).pipe(client));
  108. client.once("close", () => upstream.destroy());
  109. upstream.once("close", () => client.destroy());
  110. });
  111. const port = await listenOnLoopback(server, caseMarker);
  112. return {
  113. firstConnectionAccepted,
  114. port,
  115. waitForFirstConnectionClosed: () => firstConnectionClosed,
  116. async close() {
  117. for (const socket of sockets) {
  118. socket.destroy();
  119. }
  120. await closeServer(server);
  121. },
  122. };
  123. }
  124. export function readSSHRuntimeConfig(caseMarker: string): SSHRuntimeConfig {
  125. const host = requireSecretEnv("ZCODE_E2E_SSH_HOST", caseMarker);
  126. const username = requireSecretEnv("ZCODE_E2E_SSH_USERNAME", caseMarker);
  127. const password = requireSecretEnv("ZCODE_E2E_SSH_PASSWORD", caseMarker);
  128. const portText = process.env.ZCODE_E2E_SSH_PORT?.trim() || "22";
  129. const port = Number.parseInt(portText, 10);
  130. if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
  131. throw new Error(`${caseMarker}: ZCODE_E2E_SSH_PORT 必须是 1..65535 的整数`);
  132. }
  133. const workspacePaths = (
  134. process.env.ZCODE_E2E_SSH_WORKSPACE_PATHS?.split(",") ?? ["/root", "/home"]
  135. )
  136. .map((value) => value.trim())
  137. .filter(Boolean);
  138. if (
  139. workspacePaths.length !== 2 ||
  140. workspacePaths.some((value) => !value.startsWith("/")) ||
  141. workspacePaths[0] === workspacePaths[1]
  142. ) {
  143. throw new Error(`${caseMarker}: ZCODE_E2E_SSH_WORKSPACE_PATHS 必须是两个不同的绝对路径`);
  144. }
  145. return {
  146. host,
  147. password,
  148. port,
  149. username,
  150. workspacePaths: [workspacePaths[0]!, workspacePaths[1]!],
  151. };
  152. }
  153. export function readSingleSSHWorkspaceRuntimeConfig(
  154. caseMarker: string,
  155. ): SingleSSHWorkspaceRuntimeConfig {
  156. const host = requireSecretEnv("ZCODE_E2E_SSH_HOST", caseMarker);
  157. const username = requireSecretEnv("ZCODE_E2E_SSH_USERNAME", caseMarker);
  158. const password = requireSecretEnv("ZCODE_E2E_SSH_PASSWORD", caseMarker);
  159. const port = parseSSHPort(
  160. process.env.ZCODE_E2E_SSH_PORT?.trim() || "22",
  161. `${caseMarker}: ZCODE_E2E_SSH_PORT`,
  162. );
  163. const workspacePath =
  164. process.env.ZCODE_E2E_SSH_WORKSPACE_PATH?.trim() ||
  165. process.env.ZCODE_E2E_SSH_SHARED_WORKSPACE_PATH?.trim() ||
  166. "/root/workspace";
  167. if (!workspacePath.startsWith("/")) {
  168. throw new Error(`${caseMarker}: ZCODE_E2E_SSH_WORKSPACE_PATH 必须是绝对路径`);
  169. }
  170. return { host, password, port, username, workspacePath };
  171. }
  172. export function readDualSSHRuntimeConfig(caseMarker: string): DualSSHRuntimeConfig {
  173. const commonHost = process.env.ZCODE_E2E_SSH_HOST?.trim();
  174. const commonUsername = process.env.ZCODE_E2E_SSH_USERNAME?.trim();
  175. const commonPassword = process.env.ZCODE_E2E_SSH_PASSWORD?.trim();
  176. const workspacePath = process.env.ZCODE_E2E_SSH_SHARED_WORKSPACE_PATH?.trim() || "/workspace";
  177. if (!workspacePath.startsWith("/")) {
  178. throw new Error(`${caseMarker}: ZCODE_E2E_SSH_SHARED_WORKSPACE_PATH 必须是绝对路径`);
  179. }
  180. const readTarget = (suffix: "A" | "B"): SSHConnectionConfig => {
  181. const host = process.env[`ZCODE_E2E_SSH_${suffix}_HOST`]?.trim() || commonHost;
  182. const username = process.env[`ZCODE_E2E_SSH_${suffix}_USERNAME`]?.trim() || commonUsername;
  183. const password = process.env[`ZCODE_E2E_SSH_${suffix}_PASSWORD`]?.trim() || commonPassword;
  184. const portText = process.env[`ZCODE_E2E_SSH_${suffix}_PORT`]?.trim();
  185. if (!host || !username || !password || !portText) {
  186. throw new Error(`${caseMarker}: dual SSH target ${suffix} 缺少 host/username/password/port`);
  187. }
  188. const port = parseSSHPort(portText, `${caseMarker}: target ${suffix}`);
  189. return { host, password, port, username };
  190. };
  191. const targets = [readTarget("A"), readTarget("B")] as const;
  192. if (
  193. targets[0].host === targets[1].host &&
  194. targets[0].port === targets[1].port &&
  195. targets[0].username === targets[1].username
  196. ) {
  197. throw new Error(`${caseMarker}: dual SSH target 必须产生两个不同 remote identity`);
  198. }
  199. return { targets, workspacePath };
  200. }
  201. export async function connectSSHWorkspace(options: {
  202. caseMarker: string;
  203. config: SSHConnectionConfig;
  204. workspacePath: string;
  205. }): Promise<RemoteTabSnapshot> {
  206. await startNewV4Draft();
  207. await openSSHRemoteDialog(options.caseMarker);
  208. await fillSSHPasswordSettings(options.config);
  209. await clickLastEnabledSSHDialogButton(options.caseMarker);
  210. await waitForSSHDirectoryStep(options.caseMarker);
  211. await selectSSHRemoteDirectory(options.workspacePath, options.caseMarker);
  212. await waitForWorkspaceApp(options.workspacePath, SSH_WORKSPACE_READY_TIMEOUT_MS);
  213. const target: RemoteTarget = {
  214. kind: "ssh",
  215. host: options.config.host,
  216. port: options.config.port,
  217. username: options.config.username,
  218. };
  219. return waitForRemoteTab({
  220. caseMarker: options.caseMarker,
  221. expectedIdentity: buildRemoteWorkspaceIdentity(options.workspacePath, target),
  222. expectedPath: options.workspacePath,
  223. });
  224. }
  225. export async function openSSHRemoteDialog(caseMarker: string): Promise<void> {
  226. await clickTestIdByWebDriver(TID_COMPOSER_WORKSPACE_TRIGGER, {
  227. timeout: 30_000,
  228. timeoutMsg: `${caseMarker}: 空草稿没有显示 workspace 菜单`,
  229. });
  230. await clickTestIdByWebDriver(TID_COMPOSER_REMOTE_CONNECTION, {
  231. timeout: 30_000,
  232. timeoutMsg: `${caseMarker}: workspace 菜单没有显示远程连接入口`,
  233. });
  234. await clickTestIdByWebDriver(TID_REMOTE_KIND_SSH, {
  235. timeout: 30_000,
  236. timeoutMsg: `${caseMarker}: 远程连接向导没有显示 SSH transport`,
  237. });
  238. await clickLastEnabledSSHDialogButton(caseMarker);
  239. }
  240. export async function fillSSHPasswordSettings(config: SSHConnectionConfig): Promise<void> {
  241. await setInputValueByTestIdDom(TID_SSH_HOST_INPUT, config.host);
  242. await setInputValueByTestIdDom(TID_SSH_PORT_INPUT, String(config.port));
  243. await setInputValueByTestIdDom(TID_SSH_USERNAME_INPUT, config.username);
  244. await setInputValueByTestIdDom(TID_SSH_PASSWORD_INPUT, config.password);
  245. }
  246. export async function clickLastEnabledSSHDialogButton(caseMarker: string): Promise<void> {
  247. let lastState = "dialog-missing";
  248. await browser.waitUntil(
  249. async () => {
  250. const result = await browser.execute((dialogTestId) => {
  251. const dialog = document.querySelector<HTMLElement>(`[data-testid="${dialogTestId}"]`);
  252. if (!dialog || dialog.getClientRects().length === 0) {
  253. return { clicked: false, reason: "dialog-missing" };
  254. }
  255. const button = Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"))
  256. .filter((candidate) => candidate.getClientRects().length > 0)
  257. .at(-1);
  258. if (!button) return { clicked: false, reason: "button-missing" };
  259. if (button.disabled) {
  260. return { clicked: false, reason: "button-disabled" };
  261. }
  262. button.click();
  263. return { clicked: true, reason: "clicked" };
  264. }, TID_SSH_DIALOG);
  265. lastState = result.reason;
  266. return result.clicked;
  267. },
  268. {
  269. timeout: 30_000,
  270. interval: 100,
  271. timeoutMsg: `${caseMarker}: SSH 向导主动作不可点击 (${lastState})`,
  272. },
  273. );
  274. }
  275. export async function waitForSSHError(
  276. caseMarker: string,
  277. timeout = SSH_CONNECT_TIMEOUT_MS,
  278. ): Promise<string> {
  279. let errorText = "";
  280. await browser.waitUntil(
  281. async () => {
  282. errorText = await browser.execute((errorTestId) => {
  283. const error = document.querySelector<HTMLElement>(`[data-testid="${errorTestId}"]`);
  284. return error?.getClientRects().length ? error.innerText.trim() : "";
  285. }, TID_SSH_ERROR);
  286. return Boolean(errorText);
  287. },
  288. {
  289. timeout,
  290. interval: 500,
  291. timeoutMsg: `${caseMarker}: SSH 失败后没有显示错误`,
  292. },
  293. );
  294. return errorText;
  295. }
  296. export async function waitForSSHDirectoryStep(caseMarker: string): Promise<void> {
  297. let state: { error: string; status: "connecting" | "error" | "success" } = {
  298. error: "",
  299. status: "connecting",
  300. };
  301. await browser.waitUntil(
  302. async () => {
  303. state = await browser.execute(
  304. (successTestId, errorTestId) => {
  305. const success = document.querySelector<HTMLElement>(`[data-testid="${successTestId}"]`);
  306. if (success?.getClientRects().length) {
  307. return { error: "", status: "success" as const };
  308. }
  309. const error = document.querySelector<HTMLElement>(`[data-testid="${errorTestId}"]`);
  310. if (error?.getClientRects().length) {
  311. return { error: error.innerText.trim(), status: "error" as const };
  312. }
  313. return { error: "", status: "connecting" as const };
  314. },
  315. TID_SSH_SUCCESS,
  316. TID_SSH_ERROR,
  317. );
  318. return state.status !== "connecting";
  319. },
  320. {
  321. timeout: SSH_CONNECT_TIMEOUT_MS,
  322. interval: 500,
  323. timeoutMsg: `${caseMarker}: SSH 部署/连接没有完成`,
  324. },
  325. );
  326. if (state.status === "error") {
  327. throw new Error(`${caseMarker}: SSH 连接失败: ${state.error}`);
  328. }
  329. }
  330. export async function selectSSHRemoteDirectory(
  331. workspacePath: string,
  332. caseMarker: string,
  333. ): Promise<void> {
  334. await browser.waitUntil(
  335. () =>
  336. browser.execute((successTestId) => {
  337. const success = document.querySelector<HTMLElement>(`[data-testid="${successTestId}"]`);
  338. return Boolean(success?.querySelector<HTMLInputElement>('input[type="text"]'));
  339. }, TID_SSH_SUCCESS),
  340. {
  341. timeout: 30_000,
  342. timeoutMsg: `${caseMarker}: SSH directory step 没有路径输入框`,
  343. },
  344. );
  345. const normalizedPath = workspacePath.replace(/\/+$/, "") || "/";
  346. const lastSlash = normalizedPath.lastIndexOf("/");
  347. const parentPath = lastSlash === 0 ? "/" : normalizedPath.slice(0, lastSlash);
  348. const directoryName = normalizedPath.slice(lastSlash + 1);
  349. if (!directoryName) {
  350. throw new Error(`${caseMarker}: P0 helper 暂不支持选择根目录`);
  351. }
  352. const pathInput = $(`[data-testid="${TID_SSH_SUCCESS}"] input[type="text"]`);
  353. await pathInput.setValue(parentPath);
  354. await browser.keys("Enter");
  355. // 先等父目录真实加载出目标项,再点击进入目标目录。仅等待受控 input 的值会把
  356. // inputPath 更新误判成 currentPath 已切换,导致仍然选择初始 homedir。
  357. await browser.waitUntil(
  358. async () =>
  359. browser.execute(
  360. (successTestId, expectedName) => {
  361. const success = document.querySelector<HTMLElement>(`[data-testid="${successTestId}"]`);
  362. const entry = Array.from(
  363. success?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  364. ).find((button) => button.innerText.trim() === expectedName);
  365. if (!entry) return false;
  366. entry.click();
  367. return true;
  368. },
  369. TID_SSH_SUCCESS,
  370. directoryName,
  371. ),
  372. {
  373. timeout: 30_000,
  374. interval: 100,
  375. timeoutMsg: `${caseMarker}: 父目录没有显示目标目录 ${directoryName}`,
  376. },
  377. );
  378. await browser.waitUntil(
  379. () =>
  380. browser.execute(
  381. (successTestId, expectedPath) => {
  382. const input = document
  383. .querySelector<HTMLElement>(`[data-testid="${successTestId}"]`)
  384. ?.querySelector<HTMLInputElement>('input[type="text"]');
  385. return input?.value === expectedPath;
  386. },
  387. TID_SSH_SUCCESS,
  388. normalizedPath,
  389. ),
  390. {
  391. timeout: 30_000,
  392. interval: 100,
  393. timeoutMsg: `${caseMarker}: directory browser 没有进入目标路径`,
  394. },
  395. );
  396. await clickLastEnabledSSHDialogButton(caseMarker);
  397. await browser.waitUntil(
  398. () =>
  399. browser.execute(
  400. (dialogTestId) => !document.querySelector(`[data-testid="${dialogTestId}"]`),
  401. TID_SSH_DIALOG,
  402. ),
  403. {
  404. timeout: SSH_WORKSPACE_READY_TIMEOUT_MS,
  405. interval: 250,
  406. timeoutMsg: `${caseMarker}: 选择远端目录后 SSH 向导没有关闭`,
  407. },
  408. );
  409. }
  410. export async function waitForRemoteTab(options: {
  411. caseMarker: string;
  412. expectedIdentity: string;
  413. expectedPath: string;
  414. expectedRemoteSessionId?: string | null;
  415. requireActive?: boolean;
  416. timeoutMs?: number;
  417. }): Promise<RemoteTabSnapshot> {
  418. let snapshot: RemoteTabSnapshot | null = null;
  419. try {
  420. await browser.waitUntil(
  421. async () => {
  422. snapshot = await readRemoteTabSnapshot(options.expectedIdentity);
  423. return (
  424. snapshot.workspacePath === options.expectedPath &&
  425. snapshot.workspaceIdentity === options.expectedIdentity &&
  426. Boolean(snapshot.remoteSessionId) &&
  427. (!options.expectedRemoteSessionId ||
  428. snapshot.remoteSessionId === options.expectedRemoteSessionId) &&
  429. (options.requireActive === false ||
  430. (snapshot.activeWorkspacePath === options.expectedPath &&
  431. snapshot.activeWorkspaceIdentity === options.expectedIdentity))
  432. );
  433. },
  434. {
  435. timeout: options.timeoutMs ?? SSH_WORKSPACE_READY_TIMEOUT_MS,
  436. interval: 1_000,
  437. timeoutMsg: `${options.caseMarker}: remote tab identity/session 没有收敛`,
  438. },
  439. );
  440. } catch (error) {
  441. throw new Error(
  442. `${options.caseMarker}: remote tab identity/session 没有收敛,latest=${JSON.stringify(snapshot)}`,
  443. { cause: error },
  444. );
  445. }
  446. if (!snapshot) {
  447. throw new Error(`${options.caseMarker}: remote tab snapshot 缺失`);
  448. }
  449. return snapshot;
  450. }
  451. export function readRemoteTabSnapshot(expectedIdentity: string): Promise<RemoteTabSnapshot> {
  452. return browser.execute((identity) => {
  453. type RemoteTab = {
  454. remoteSessionId?: string;
  455. remoteTarget?: Record<string, unknown>;
  456. workspaceIdentity?: string;
  457. workspacePath?: string;
  458. };
  459. const store = (
  460. window as Window & {
  461. __zcodeTabStoreE2E?: {
  462. getState?: () => {
  463. activeWorkspaceIdentity?: string | null;
  464. activeWorkspacePath?: string | null;
  465. tabs?: RemoteTab[];
  466. };
  467. };
  468. }
  469. ).__zcodeTabStoreE2E;
  470. const state = store?.getState?.();
  471. const tab = state?.tabs?.find((candidate) => candidate.workspaceIdentity === identity);
  472. const target = tab?.remoteTarget;
  473. return {
  474. activeWorkspaceIdentity: state?.activeWorkspaceIdentity ?? null,
  475. activeWorkspacePath: state?.activeWorkspacePath ?? null,
  476. remoteHost: typeof target?.host === "string" ? target.host : null,
  477. remoteKind: typeof target?.kind === "string" ? target.kind : null,
  478. remoteSessionId: tab?.remoteSessionId ?? null,
  479. secretPersistedInTab: Boolean(
  480. target && ("password" in target || "privateKeyPassphrase" in target),
  481. ),
  482. workspaceIdentity: tab?.workspaceIdentity ?? null,
  483. workspacePath: tab?.workspacePath ?? null,
  484. };
  485. }, expectedIdentity);
  486. }
  487. export async function readHostProcesses(): Promise<Array<{ name: string; pid: number }>> {
  488. await openResourceManager();
  489. await switchToElectronRendererTarget(isResourceManagerUrl);
  490. await waitForResourceManagerReady();
  491. const hosts = await listHostProcessIdentities();
  492. await switchToElectronRendererTarget(isMainRendererUrl);
  493. return hosts;
  494. }
  495. export async function runSSHCommand(
  496. config: SSHConnectionConfig,
  497. command: string,
  498. ): Promise<{ code: number | null; stderr: string; stdout: string }> {
  499. const client = await connectSSHClient(config);
  500. try {
  501. return await new Promise((resolve, reject) => {
  502. client.exec(command, (error, channel) => {
  503. if (error) {
  504. reject(error);
  505. return;
  506. }
  507. collectSSHChannel(channel).then(resolve, reject);
  508. });
  509. });
  510. } finally {
  511. client.end();
  512. }
  513. }
  514. export async function createSSHReplayTunnel(
  515. config: SSHConnectionConfig,
  516. caseMarker: string,
  517. ): Promise<ReplayTunnel> {
  518. const replayBaseURL = await resolveSeededReplayBaseUrl();
  519. if (!replayBaseURL) {
  520. throw new Error(`${caseMarker}: 没有找到本轮 replay provider URL`);
  521. }
  522. const replayURL = new URL(replayBaseURL);
  523. const replayPort = Number.parseInt(replayURL.port, 10);
  524. if (!Number.isSafeInteger(replayPort) || replayPort < 1) {
  525. throw new Error(`${caseMarker}: replay provider URL 缺少有效端口`);
  526. }
  527. const client = new SSHClient();
  528. client.on("tcp connection", (_details: TcpConnectionDetails, accept) => {
  529. const channel = accept();
  530. const socket = createConnection({
  531. host: replayURL.hostname,
  532. port: replayPort,
  533. });
  534. const closeBoth = () => {
  535. channel.destroy();
  536. socket.destroy();
  537. };
  538. channel.once("error", closeBoth);
  539. socket.once("error", closeBoth);
  540. socket.once("connect", () => channel.pipe(socket).pipe(channel));
  541. socket.once("close", () => channel.destroy());
  542. channel.once("close", () => socket.destroy());
  543. });
  544. const remotePort = await new Promise<number>((resolve, reject) => {
  545. client.once("error", reject);
  546. client.once("ready", () => {
  547. client.forwardIn("127.0.0.1", 0, (error, assignedPort) => {
  548. if (error) reject(error);
  549. else resolve(assignedPort);
  550. });
  551. });
  552. client.connect(toSSHConnectOptions(config));
  553. });
  554. return {
  555. baseURL: `http://127.0.0.1:${remotePort}`,
  556. close: () =>
  557. new Promise<void>((resolve) => {
  558. client.unforwardIn("127.0.0.1", remotePort, () => {
  559. client.end();
  560. resolve();
  561. });
  562. }),
  563. };
  564. }
  565. function listenOnLoopback(server: Server, caseMarker: string): Promise<number> {
  566. return new Promise((resolve, reject) => {
  567. const onError = (error: Error) => reject(error);
  568. server.once("error", onError);
  569. server.listen({ host: "127.0.0.1", port: 0 }, () => {
  570. server.off("error", onError);
  571. const address = server.address();
  572. if (!address || typeof address === "string") {
  573. reject(new Error(`${caseMarker}: 无法解析 SSH pending proxy 监听端口`));
  574. return;
  575. }
  576. resolve(address.port);
  577. });
  578. });
  579. }
  580. function closeServer(server: Server): Promise<void> {
  581. if (!server.listening) {
  582. return Promise.resolve();
  583. }
  584. return new Promise((resolve, reject) => {
  585. server.close((error) => {
  586. if (error) reject(error);
  587. else resolve();
  588. });
  589. });
  590. }
  591. function requireSecretEnv(name: string, caseMarker: string): string {
  592. const value = process.env[name]?.trim();
  593. if (!value) throw new Error(`${caseMarker}: 缺少 ${name}`);
  594. return value;
  595. }
  596. function parseSSHPort(portText: string, context: string): number {
  597. const port = Number.parseInt(portText, 10);
  598. if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
  599. throw new Error(`${context}: SSH port 必须是 1..65535 的整数`);
  600. }
  601. return port;
  602. }
  603. function connectSSHClient(config: SSHConnectionConfig): Promise<SSHClient> {
  604. return new Promise((resolve, reject) => {
  605. const client = new SSHClient();
  606. client.once("error", reject);
  607. client.once("ready", () => resolve(client));
  608. client.connect(toSSHConnectOptions(config));
  609. });
  610. }
  611. function toSSHConnectOptions(config: SSHConnectionConfig) {
  612. return {
  613. host: config.host,
  614. password: config.password,
  615. port: config.port,
  616. readyTimeout: SSH_CONNECT_TIMEOUT_MS,
  617. username: config.username,
  618. };
  619. }
  620. function collectSSHChannel(
  621. channel: ClientChannel,
  622. ): Promise<{ code: number | null; stderr: string; stdout: string }> {
  623. return new Promise((resolve, reject) => {
  624. let stdout = "";
  625. let stderr = "";
  626. let exitCode: number | null = null;
  627. channel.setEncoding("utf8");
  628. channel.stderr.setEncoding("utf8");
  629. channel.on("data", (chunk: string) => {
  630. stdout += chunk;
  631. });
  632. channel.stderr.on("data", (chunk: string) => {
  633. stderr += chunk;
  634. });
  635. channel.once("exit", (code: number | null) => {
  636. exitCode = code;
  637. });
  638. channel.once("error", reject);
  639. channel.once("close", () => resolve({ code: exitCode, stderr, stdout }));
  640. });
  641. }