| 23 | let sshClient: Client | null = null; |
| 24 | |
| 25 | function onFirstMessage(data: Buffer | string) { |
| 26 | ws.off("message", onFirstMessage); |
| 27 | |
| 28 | const text = typeof data === "string" ? data : data.toString("utf-8"); |
| 29 | let params: ConnectParams; |
| 30 | try { |
| 31 | params = JSON.parse(text); |
| 32 | } catch { |
| 33 | ws.send(JSON.stringify({ error: "Invalid connection parameters" })); |
| 34 | ws.close(); |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | sshClient = new Client(); |
| 39 | |
| 40 | sshClient.on("ready", () => { |
| 41 | sshClient!.shell( |
| 42 | { term: "xterm-256color", cols: 80, rows: 24 }, |
| 43 | (err, stream) => { |
| 44 | if (err) { |
| 45 | ws.send( |
| 46 | `\r\n\x1b[31mFailed to open shell: ${err.message}\x1b[0m\r\n`, |
| 47 | ); |
| 48 | ws.close(); |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | stream.on("data", (chunk: Buffer) => { |
| 53 | if (ws.readyState === WebSocket.OPEN) { |
| 54 | ws.send(chunk.toString("binary")); |
| 55 | } |
| 56 | }); |
| 57 | |
| 58 | stream.on("close", () => { |
| 59 | if (ws.readyState === WebSocket.OPEN) ws.close(); |
| 60 | }); |
| 61 | |
| 62 | ws.on("message", (msg: Buffer | string) => { |
| 63 | const input = typeof msg === "string" ? msg : msg.toString("utf-8"); |
| 64 | try { |
| 65 | stream.write(input); |
| 66 | } catch { |
| 67 | /* stream closed */ |
| 68 | } |
| 69 | }); |
| 70 | |
| 71 | ws.on("close", () => { |
| 72 | stream.end(); |
| 73 | sshClient?.end(); |
| 74 | }); |
| 75 | }, |
| 76 | ); |
| 77 | }); |
| 78 | |
| 79 | sshClient.on("error", (err) => { |
| 80 | const msg = `\r\n\x1b[31mSSH error: ${err.message}\x1b[0m\r\n`; |
| 81 | if (ws.readyState === WebSocket.OPEN) { |
| 82 | ws.send(msg); |