-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscp.ts
More file actions
288 lines (256 loc) · 7.88 KB
/
Copy pathscp.ts
File metadata and controls
288 lines (256 loc) · 7.88 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
* SCP files to/from devbox command
*
* Supports standard SCP-like syntax where the devbox ID (dbx_*) is used as a hostname:
* rli devbox scp dbx_abc123:/remote/path ./local/path # download
* rli devbox scp ./local/path dbx_abc123:/remote/path # upload
* rli devbox scp root@dbx_abc123:/remote/path ./local/path # explicit user
* rli devbox scp dbx_src:/file dbx_dst:/file # devbox-to-devbox
*
* If no user is specified for a remote path, the devbox's configured user is used.
* Paths without a dbx_ hostname are treated as local paths.
*
* Devbox-to-devbox transfers use scp -3 to route data through the local machine,
* with a temporary SSH config so each devbox uses its own key.
*/
import { exec } from "child_process";
import { promisify } from "util";
import { writeFile, unlink, mkdir } from "fs/promises";
import { join } from "path";
import { tmpdir } from "os";
import { getClient } from "../../utils/client.js";
import { output, outputError } from "../../utils/output.js";
import {
getSSHKey,
getProxyCommand,
checkSSHTools,
SSHKeyInfo,
} from "../../utils/ssh.js";
const execAsync = promisify(exec);
export interface SCPOptions {
scpOptions?: string;
output?: string;
}
export interface ParsedSCPPath {
user?: string;
host?: string;
path: string;
isRemote: boolean;
}
/**
* Resolved info for a remote devbox endpoint.
*/
export interface ResolvedRemote {
devboxId: string;
defaultUser: string;
sshInfo: SSHKeyInfo;
}
/**
* Parse an SCP-style path into its components.
*
* Supported formats:
* user@dbx_id:path -> remote with explicit user
* dbx_id:path -> remote with default user
* /local/path -> local (absolute)
* ./relative -> local (relative)
* filename -> local (bare filename, no colon)
*/
export function parseSCPPath(input: string): ParsedSCPPath {
// Match [user@]host:path where host is a devbox ID (dbx_*).
// This avoids false positives on local paths that happen to contain colons.
const match = input.match(/^(?:([^@/:]+)@)?(dbx_[^@/:]+):(.*)$/);
if (match) {
return {
user: match[1] || undefined,
host: match[2],
path: match[3],
isRemote: true,
};
}
return { path: input, isRemote: false };
}
/**
* Resolve a devbox ID to its SSH info and default user.
*/
async function resolveRemote(devboxId: string): Promise<ResolvedRemote> {
const client = getClient();
const devbox = await client.devboxes.retrieve(devboxId);
const defaultUser =
devbox.launch_parameters?.user_parameters?.username || "user";
const sshInfo = await getSSHKey(devboxId);
if (!sshInfo) {
throw new Error(`Failed to create SSH key for ${devboxId}`);
}
return { devboxId, defaultUser, sshInfo };
}
/**
* Build the SCP command for a single-remote transfer (local <-> devbox).
*/
export function buildSCPCommand(opts: {
sshInfo: { keyfilePath: string; url: string };
proxyCommand: string;
parsedSrc: ParsedSCPPath;
parsedDst: ParsedSCPPath;
defaultUser: string;
scpOptions?: string;
}): string[] {
const scpCommand = [
"scp",
"-i",
opts.sshInfo.keyfilePath,
"-o",
`ProxyCommand=${opts.proxyCommand}`,
"-o",
"StrictHostKeyChecking=no",
];
if (opts.scpOptions) {
scpCommand.push(...opts.scpOptions.split(" "));
}
// Build src argument
if (opts.parsedSrc.isRemote) {
const user = opts.parsedSrc.user || opts.defaultUser;
scpCommand.push(`${user}@${opts.sshInfo.url}:${opts.parsedSrc.path}`);
} else {
scpCommand.push(opts.parsedSrc.path);
}
// Build dst argument
if (opts.parsedDst.isRemote) {
const user = opts.parsedDst.user || opts.defaultUser;
scpCommand.push(`${user}@${opts.sshInfo.url}:${opts.parsedDst.path}`);
} else {
scpCommand.push(opts.parsedDst.path);
}
return scpCommand;
}
/**
* Build the SCP command for a dual-remote transfer (devbox -> devbox).
* Uses scp -3 to route data through the local machine and a temporary
* SSH config file so each devbox resolves to its own key/proxy.
*/
export function buildDualRemoteSCPCommand(opts: {
srcRemote: ResolvedRemote;
dstRemote: ResolvedRemote;
proxyCommand: string;
parsedSrc: ParsedSCPPath;
parsedDst: ParsedSCPPath;
sshConfigPath: string;
scpOptions?: string;
}): string[] {
const scpCommand = [
"scp",
"-3",
"-F",
opts.sshConfigPath,
"-o",
"StrictHostKeyChecking=no",
];
if (opts.scpOptions) {
scpCommand.push(...opts.scpOptions.split(" "));
}
const srcUser = opts.parsedSrc.user || opts.srcRemote.defaultUser;
scpCommand.push(
`${srcUser}@${opts.srcRemote.sshInfo.url}:${opts.parsedSrc.path}`,
);
const dstUser = opts.parsedDst.user || opts.dstRemote.defaultUser;
scpCommand.push(
`${dstUser}@${opts.dstRemote.sshInfo.url}:${opts.parsedDst.path}`,
);
return scpCommand;
}
/**
* Generate a temporary SSH config file for dual-remote transfers.
* Maps each devbox URL to its identity file and proxy command.
*/
export function generateSCPConfig(
remotes: ResolvedRemote[],
proxyCommand: string,
): string {
return remotes
.map(
(r) =>
`Host ${r.sshInfo.url}\n` +
` IdentityFile ${r.sshInfo.keyfilePath}\n` +
` ProxyCommand ${proxyCommand}\n` +
` StrictHostKeyChecking no`,
)
.join("\n\n");
}
export async function scpFiles(src: string, dst: string, options: SCPOptions) {
try {
// Check if SSH tools are available
const sshToolsAvailable = await checkSSHTools();
if (!sshToolsAvailable) {
outputError(
"SSH tools (ssh, scp, openssl) are not available on this system",
);
}
const parsedSrc = parseSCPPath(src);
const parsedDst = parseSCPPath(dst);
if (!parsedSrc.isRemote && !parsedDst.isRemote) {
outputError(
"At least one of src or dst must be a remote devbox path (e.g. dbx_<id>:/path)",
);
}
const proxyCommand = getProxyCommand();
const dualRemote = parsedSrc.isRemote && parsedDst.isRemote;
let scpCommand: string[];
if (dualRemote) {
// Both sides are remote devboxes — resolve both in parallel
const [srcRemote, dstRemote] = await Promise.all([
resolveRemote(parsedSrc.host!),
resolveRemote(parsedDst.host!),
]);
// Write a temporary SSH config so scp can find the right key per host
const configContent = generateSCPConfig(
[srcRemote, dstRemote],
proxyCommand,
);
const configDir = join(tmpdir(), "runloop-scp");
await mkdir(configDir, { recursive: true });
const configPath = join(configDir, `scp-${Date.now()}.conf`);
await writeFile(configPath, configContent, { mode: 0o600 });
try {
scpCommand = buildDualRemoteSCPCommand({
srcRemote,
dstRemote,
proxyCommand,
parsedSrc,
parsedDst,
sshConfigPath: configPath,
scpOptions: options.scpOptions,
});
await execAsync(scpCommand.join(" "));
} finally {
// Clean up temp config
await unlink(configPath).catch(() => {});
}
} else {
// Single remote — one side is local
const devboxId = parsedSrc.isRemote ? parsedSrc.host! : parsedDst.host!;
const remote = await resolveRemote(devboxId);
scpCommand = buildSCPCommand({
sshInfo: remote.sshInfo,
proxyCommand,
parsedSrc,
parsedDst,
defaultUser: remote.defaultUser,
scpOptions: options.scpOptions,
});
await execAsync(scpCommand.join(" "));
}
// Default: just output the destination for easy scripting
if (!options.output || options.output === "text") {
console.log(dst);
} else {
output(
{
source: src,
destination: dst,
},
{ format: options.output, defaultFormat: "json" },
);
}
} catch (error) {
outputError("SCP operation failed", error);
}
}