-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathssh-tunnel.ts
More file actions
212 lines (196 loc) · 5.68 KB
/
Copy pathssh-tunnel.ts
File metadata and controls
212 lines (196 loc) · 5.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Starts and monitors SSH tunnels for remote gateway access.
import { spawn } from "node:child_process";
import net from "node:net";
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
import { formatErrorMessage, isErrno } from "./errors.js";
import { parseStrictPositiveInteger } from "./parse-finite-number.js";
import { ensurePortAvailable } from "./ports.js";
export type SshParsedTarget = {
user?: string;
host: string;
port: number;
};
export type SshTunnel = {
parsedTarget: SshParsedTarget;
localPort: number;
remotePort: number;
pid: number | null;
stderr: string[];
stop: () => Promise<void>;
};
export function parseSshTarget(raw: string): SshParsedTarget | null {
const trimmed = raw.trim().replace(/^ssh\s+/, "");
if (!trimmed) {
return null;
}
const [userPart, hostPart] = trimmed.includes("@")
? ((): [string | undefined, string] => {
const idx = trimmed.indexOf("@");
const user = trimmed.slice(0, idx).trim();
const host = trimmed.slice(idx + 1).trim();
return [user || undefined, host];
})()
: [undefined, trimmed];
const colonIdx = hostPart.lastIndexOf(":");
if (colonIdx > 0 && colonIdx < hostPart.length - 1) {
const host = hostPart.slice(0, colonIdx).trim();
const portRaw = hostPart.slice(colonIdx + 1).trim();
const port = parseStrictPositiveInteger(portRaw);
if (!host || port === undefined || port > 65535) {
return null;
}
// Security: Reject hostnames starting with '-' to prevent argument injection
if (host.startsWith("-")) {
return null;
}
return { user: userPart, host, port };
}
if (!hostPart) {
return null;
}
// Security: Reject hostnames starting with '-' to prevent argument injection
if (hostPart.startsWith("-")) {
return null;
}
return { user: userPart, host: hostPart, port: 22 };
}
async function pickEphemeralPort(): Promise<number> {
return await new Promise<number>((resolve, reject) => {
const server = net.createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
server.close(() => {
if (!addr || typeof addr === "string") {
reject(new Error("failed to allocate a local port"));
return;
}
resolve(addr.port);
});
});
});
}
async function canConnectLocal(port: number): Promise<boolean> {
return await new Promise<boolean>((resolve) => {
const socket = net.connect({ host: "127.0.0.1", port });
const done = (ok: boolean) => {
socket.removeAllListeners();
socket.destroy();
resolve(ok);
};
socket.once("connect", () => done(true));
socket.once("error", () => done(false));
socket.setTimeout(250, () => done(false));
});
}
async function waitForLocalListener(port: number, timeoutMs: number): Promise<void> {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
if (await canConnectLocal(port)) {
return;
}
await new Promise((r) => {
setTimeout(r, 50);
});
}
throw new Error(`ssh tunnel did not start listening on localhost:${port}`);
}
export async function startSshPortForward(opts: {
target: string;
identity?: string;
localPortPreferred: number;
remotePort: number;
timeoutMs: number;
}): Promise<SshTunnel> {
const parsed = parseSshTarget(opts.target);
if (!parsed) {
throw new Error(`invalid SSH target: ${opts.target}`);
}
let localPort = opts.localPortPreferred;
try {
await ensurePortAvailable(localPort);
} catch (err) {
if (isErrno(err) && err.code === "EADDRINUSE") {
localPort = await pickEphemeralPort();
} else {
throw err;
}
}
const userHost = parsed.user ? `${parsed.user}@${parsed.host}` : parsed.host;
const args = [
"-N",
"-L",
`${localPort}:127.0.0.1:${opts.remotePort}`,
"-p",
String(parsed.port),
"-o",
"ExitOnForwardFailure=yes",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"UpdateHostKeys=yes",
"-o",
"ConnectTimeout=5",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
];
if (opts.identity?.trim()) {
args.push("-i", opts.identity.trim());
}
// Security: Use '--' to prevent userHost from being interpreted as an option
args.push("--", userHost);
const stderr: string[] = [];
const child = spawn("/usr/bin/ssh", args, {
stdio: ["ignore", "ignore", "pipe"],
});
child.stderr?.setEncoding("utf8");
child.stderr?.on("data", (chunk) => {
const lines = normalizeStringEntries(String(chunk).split("\n"));
stderr.push(...lines);
});
const stop = async () => {
if (child.killed) {
return;
}
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
const t = setTimeout(() => {
try {
child.kill("SIGKILL");
} finally {
resolve();
}
}, 1500);
child.once("exit", () => {
clearTimeout(t);
resolve();
});
});
};
try {
await Promise.race([
waitForLocalListener(localPort, Math.max(250, opts.timeoutMs)),
new Promise<void>((_, reject) => {
child.once("exit", (code, signal) => {
reject(new Error(`ssh exited (${code ?? "null"}${signal ? `/${signal}` : ""})`));
});
}),
]);
} catch (err) {
await stop();
const suffix = stderr.length > 0 ? `\n${stderr.join("\n")}` : "";
throw new Error(`${formatErrorMessage(err)}${suffix}`, { cause: err });
}
return {
parsedTarget: parsed,
localPort,
remotePort: opts.remotePort,
pid: typeof child.pid === "number" ? child.pid : null,
stderr,
stop,
};
}