ssh-stallable-proxy.ts 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { createConnection, createServer, type AddressInfo, type Socket } from "node:net";
  2. /** 可切换新连接停摆的 SSH TCP 代理。调用方可更新 target 端口;仅后续连接采用新地址,已有连接不改路由。 */
  3. export async function createStallableTcpProxy(target: { host: string; port: number }) {
  4. const pending = new Map<
  5. Socket,
  6. { chunks: Buffer[]; capture: (chunk: Buffer) => void; cleanup: () => void }
  7. >();
  8. const live = new Set<Socket>();
  9. let mode: "forward" | "stall" | "reject" = "forward";
  10. let accepted = 0;
  11. const attach = (client: Socket, initial: readonly Buffer[] = []) => {
  12. // 建立上游前必须暂停下游;否则 release 后、connect 回调前的新数据仍会被丢弃。
  13. client.pause();
  14. const upstream = createConnection({ host: target.host, port: target.port });
  15. live.add(client);
  16. live.add(upstream);
  17. const closeBoth = () => {
  18. client.destroy();
  19. upstream.destroy();
  20. live.delete(client);
  21. live.delete(upstream);
  22. };
  23. client.once("error", closeBoth);
  24. upstream.once("error", closeBoth);
  25. upstream.once("connect", () => {
  26. for (const chunk of initial) upstream.write(chunk);
  27. client.pipe(upstream).pipe(client);
  28. });
  29. client.once("close", closeBoth);
  30. upstream.once("close", closeBoth);
  31. };
  32. const server = createServer((client) => {
  33. accepted += 1;
  34. if (mode === "reject") {
  35. client.destroy();
  36. return;
  37. }
  38. if (mode === "stall") {
  39. const chunks: Buffer[] = [];
  40. const capture = (chunk: Buffer) => chunks.push(Buffer.from(chunk));
  41. const cleanup = () => {
  42. pending.delete(client);
  43. client.destroy();
  44. };
  45. pending.set(client, { chunks, capture, cleanup });
  46. // SSH Client 在等待期间已发送 banner。原来的 resume() 没有 data 消费者,
  47. // 会丢掉握手字节,导致每次 release 都失败,再被 case 的手动重试掩盖。
  48. client.on("data", capture);
  49. client.once("error", cleanup);
  50. client.once("close", cleanup);
  51. return;
  52. }
  53. attach(client);
  54. });
  55. await new Promise<void>((ok, bad) => {
  56. server.once("error", bad);
  57. server.listen(0, "127.0.0.1", () => ok());
  58. });
  59. return {
  60. port: (server.address() as AddressInfo).port,
  61. setStall(value: boolean) {
  62. mode = value ? "stall" : "forward";
  63. },
  64. setRejectNewConnections(value: boolean) {
  65. // 容器停机时不得尝试已释放、可能被另一夹具复用的旧端口;既有连接仍由真实远端关闭。
  66. mode = value ? "reject" : "forward";
  67. },
  68. pendingCount: () =>
  69. [...pending.keys()].filter((client) => !client.destroyed && !client.readableEnded).length,
  70. pendingByteCount: () => [...pending.keys()].reduce((sum, socket) => sum + socket.bytesRead, 0),
  71. acceptedCount: () => accepted,
  72. release() {
  73. let count = 0;
  74. for (const [client, held] of pending) {
  75. client.pause();
  76. client.off("data", held.capture);
  77. client.off("error", held.cleanup);
  78. client.off("close", held.cleanup);
  79. pending.delete(client);
  80. if (client.destroyed || client.readableEnded) {
  81. client.destroy();
  82. continue;
  83. }
  84. attach(client, held.chunks);
  85. count += 1;
  86. }
  87. return count;
  88. },
  89. async close() {
  90. for (const client of pending.keys()) client.destroy();
  91. pending.clear();
  92. for (const socket of live) socket.destroy();
  93. await new Promise<void>((ok) => server.close(() => ok()));
  94. },
  95. };
  96. }