-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathssh.ts
More file actions
244 lines (215 loc) · 7.44 KB
/
ssh.ts
File metadata and controls
244 lines (215 loc) · 7.44 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import child_process from "node:child_process";
import console from "node:console";
import process from "node:process";
import { Command } from "@commander-js/extra-typings";
import chalk from "chalk";
import ora from "ora";
import { Shescape } from "shescape";
import { apiClient } from "../../apiClient.ts";
import { getAuthToken, loadConfig } from "../../helpers/config.ts";
import {
logAndQuit,
logSessionTokenExpiredAndQuit,
} from "../../helpers/errors.ts";
import { handleNodesError, nodesClient } from "../../nodesClient.ts";
import { jsonOption } from "./utils.ts";
// Canonical SSH info shape (v2 NodeSshInfo format)
type SshInfo = {
hostname: string;
port: number;
host_keys: { key_type: string; key: string }[];
last_successful_key_update: number | null;
last_attempted_key_update: number | null;
};
const ssh = new Command("ssh")
.description(`SSH into a VM on a node.
Runs \`ssh\` with host keys from the API, forgoing the need to manually accept keys on first connect.
Keys are fetched asynchronously from the VM's SSH server and may take a moment to populate.
Standard \`ssh\` behavior applies (e.g. defaults to your current username).`)
.showHelpAfterError()
.option("-q, --quiet", "Quiet mode", false)
.option(
"--use-host-keys [value]",
"Use API provided SSH server host keys if known",
true,
)
.addOption(jsonOption)
.argument(
"<destination>",
"Node name, Node ID, or VM ID to SSH into.\nFollows `ssh` behavior (i.e. root@node or jenson@node).",
)
.usage("[options] [user@]<destination>")
.allowExcessArguments(false)
.addHelpText(
"after",
`
Examples:
\x1b[2m# SSH into a node's current VM\x1b[0m
$ sf nodes ssh root@my-node
\x1b[2m# SSH with a specific username\x1b[0m
$ sf nodes ssh jenson@my-node
\x1b[2m# SSH directly to a VM ID\x1b[0m
$ sf nodes ssh root@vm_xxxxxxxxxxxxxxxxxxxxx
`,
)
.action(async (destination, options) => {
try {
const splitDestination = destination.split("@");
let nodeOrVmId: string;
let sshUsername: string | undefined;
if (splitDestination.length === 1) {
sshUsername = undefined;
nodeOrVmId = splitDestination[0];
} else if (splitDestination.length === 2) {
sshUsername = splitDestination[0];
nodeOrVmId = splitDestination[1];
} else {
logAndQuit(`Invalid SSH destination string: ${destination}`);
}
const sshSpinner = ora("Fetching SSH information...").start();
const config = await loadConfig();
const token = await getAuthToken();
let hostKeyAlias = "";
let data: SshInfo | undefined;
// Try v2 endpoint for non-vm_ IDs
if (!nodeOrVmId.startsWith("vm_")) {
const v2Response = await fetch(
`${config.api_url}/v2/nodes/${nodeOrVmId}/ssh`,
{
method: "GET",
headers: { Authorization: `Bearer ${token}` },
},
);
if (v2Response.ok) {
data = (await v2Response.json()) as SshInfo;
hostKeyAlias = `${nodeOrVmId}.v2.nodes.sfcompute.dev`;
}
}
// Fall back to v0 flow if v2 didn't resolve
if (!data) {
let vmId: string;
if (!nodeOrVmId.startsWith("vm_")) {
const client = await nodesClient();
try {
const node = await client.nodes.get(nodeOrVmId);
if (!node?.current_vm) {
sshSpinner.fail(
`Node ${chalk.cyan(
nodeOrVmId,
)} does not have a current VM. VMs can take up to 5-10 minutes to spin up.`,
);
process.exit(1);
}
vmId = node.current_vm.id;
} catch {
vmId = nodeOrVmId;
}
} else {
vmId = nodeOrVmId;
}
const client = await apiClient(token);
const { response, data: sshData } = await client.GET("/v0/vms/ssh", {
params: { query: { vm_id: vmId } },
});
if (response.status === 401) {
sshSpinner.stop();
logSessionTokenExpiredAndQuit();
}
if (!response.ok || !sshData) {
sshSpinner.fail(
`Failed to retrieve SSH information for ${chalk.cyan(
vmId,
)}: ${response.statusText}`,
);
process.exit(1);
}
// Coerce v0 response to v2 shape
data = {
hostname: sshData.ssh_hostname,
port: sshData.ssh_port,
host_keys: (sshData.ssh_host_keys ?? []).map((k) => ({
key_type: k.key_type,
key: k.base64_encoded_key,
})),
last_successful_key_update:
sshData.last_successful_key_update ?? null,
last_attempted_key_update: sshData.last_attempted_key_update ?? null,
};
hostKeyAlias = `${vmId}.vms.sfcompute.dev`;
}
sshSpinner.succeed("SSH information fetched successfully.");
if (options.json) {
console.log(JSON.stringify(data, null, 2));
return;
}
const sshHostname = data.hostname;
const sshPort = data.port;
const sshHostKeys = data.host_keys;
let sshDestination = sshHostname;
if (sshUsername !== undefined) {
sshDestination = `${sshUsername}@${sshDestination}`;
}
if (sshPort !== undefined) {
sshDestination = `${sshDestination}:${sshPort}`;
}
sshDestination = `ssh://${sshDestination}`;
let cmd = ["ssh"];
if (sshHostKeys.length > 0 && options.useHostKeys) {
let knownHostsCommand = ["/usr/bin/env", "printf", "%s %s %s\\n"];
for (const sshHostKey of sshHostKeys) {
knownHostsCommand = knownHostsCommand.concat([
hostKeyAlias,
sshHostKey.key_type,
sshHostKey.key,
]);
}
// Escape all characters for proper pass through
for (const i in knownHostsCommand) {
knownHostsCommand[i] = knownHostsCommand[i].replaceAll("%", "%%");
knownHostsCommand[i] = knownHostsCommand[i].replaceAll('"', '\\"');
knownHostsCommand[i] = '"' + knownHostsCommand[i] + '"';
}
const knownHostsCommand_str = knownHostsCommand.join(" ");
cmd = cmd.concat(["-o", `KnownHostsCommand=${knownHostsCommand_str}`]);
}
cmd = cmd.concat(["-o", `HostKeyAlias=${hostKeyAlias}`]);
cmd = cmd.concat([sshDestination]);
let shescape: undefined | Shescape;
let shell: undefined | string;
if (process.env.SHELL !== undefined) {
try {
shescape = new Shescape({
flagProtection: false,
shell: process.env.SHELL,
});
shell = process.env.SHELL;
} catch {
// shescape will stay undefined
}
}
if (shescape === undefined) {
shescape = new Shescape({
flagProtection: false,
shell: "/bin/sh",
});
shell = "/bin/sh";
}
const shell_cmd = shescape.quoteAll(cmd).join(" ");
if (!options.quiet) {
console.log(`Executing (${shell} style output): ${shell_cmd}`);
}
// Ideally this would use `@alphahydrae/exec` but `pkg` doesn't
// support ffi modules.
const result = child_process.spawnSync(cmd[0], cmd.slice(1), {
stdio: "inherit",
});
if (result.status !== undefined) {
process.exit(result.status);
} else {
process.exit(128);
}
} catch (err) {
handleNodesError(err);
}
});
export default ssh;