@myrialabs/clopen 0.4.32 → 0.4.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/chat/stream-manager.ts +4 -1
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +8 -1
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +33 -4
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/stream.ts +1 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +7 -0
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/nested-repos.test.ts +108 -5
- package/backend/git/nested-repos.ts +103 -18
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +16 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +309 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/index.ts +4 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-DSvGoxp2.js → index-BF4buYmI.js} +1 -1
- package/dist/assets/{index-hu17G6tX.js → index-BW0DA8NV.js} +1 -1
- package/dist/assets/{main-BccclZsC.js → main-BbwWLJRN.js} +499 -473
- package/dist/assets/main-CCvRMXlP.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-Ciuw0wF0.css +0 -1
|
@@ -0,0 +1,967 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh-client — remote file operations over SFTP.
|
|
3
|
+
*
|
|
4
|
+
* Every call leases the host's shared ssh2 client (see client-pool) and opens
|
|
5
|
+
* an SFTP subsystem on it, so browsing files costs a channel rather than a
|
|
6
|
+
* second handshake. Paths are remote POSIX paths and are always resolved
|
|
7
|
+
* against the server's `realpath`, never joined on the Clopen host — a Windows
|
|
8
|
+
* Clopen must not turn `/var/log` into `\var\log`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Readable, Writable } from 'node:stream';
|
|
12
|
+
import type { Client as SshClient, FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2';
|
|
13
|
+
import { sshClientPool } from './client-pool';
|
|
14
|
+
import { runCommandOrThrow, shellQuote } from './connect';
|
|
15
|
+
import { readDiskUsage } from './disk-usage';
|
|
16
|
+
import type {
|
|
17
|
+
SftpArchiveFormat,
|
|
18
|
+
SftpArchiveInfo,
|
|
19
|
+
SftpBulkResult,
|
|
20
|
+
SftpCompressResult,
|
|
21
|
+
SftpConflict,
|
|
22
|
+
SftpConflictStrategy,
|
|
23
|
+
SftpDiskUsage,
|
|
24
|
+
SftpEntry,
|
|
25
|
+
SftpEntryType,
|
|
26
|
+
SftpExtractOptions,
|
|
27
|
+
SftpExtractResult,
|
|
28
|
+
SftpFileContent,
|
|
29
|
+
SftpListing
|
|
30
|
+
} from '$shared/types/ssh';
|
|
31
|
+
import { debug } from '$shared/utils/logger';
|
|
32
|
+
|
|
33
|
+
/** Largest file the inline text editor will open. Bigger files must be downloaded. */
|
|
34
|
+
export const SFTP_TEXT_READ_LIMIT = 2 * 1024 * 1024;
|
|
35
|
+
|
|
36
|
+
/** Refuse to recurse past this depth when deleting a directory tree. */
|
|
37
|
+
const MAX_DELETE_DEPTH = 64;
|
|
38
|
+
|
|
39
|
+
/** How many `name (2)`, `name (3)`… candidates to try before giving up. */
|
|
40
|
+
const MAX_RENAME_ATTEMPTS = 500;
|
|
41
|
+
|
|
42
|
+
/** How many archive entries to read when previewing what an archive holds. */
|
|
43
|
+
const ARCHIVE_LIST_LIMIT = 2000;
|
|
44
|
+
|
|
45
|
+
const S_IFMT = 0o170000;
|
|
46
|
+
const S_IFDIR = 0o040000;
|
|
47
|
+
const S_IFLNK = 0o120000;
|
|
48
|
+
const S_IFREG = 0o100000;
|
|
49
|
+
|
|
50
|
+
function openSftp(client: SshClient): Promise<SFTPWrapper> {
|
|
51
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
52
|
+
client.sftp((error, sftp) => {
|
|
53
|
+
if (error) {
|
|
54
|
+
rejectPromise(new Error(`Could not open SFTP: ${error.message}`));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
resolvePromise(sftp);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Lease the host, open SFTP, run `operation`, then close the subsystem. */
|
|
63
|
+
async function withSftp<T>(connectionId: string, operation: (sftp: SFTPWrapper) => Promise<T>): Promise<T> {
|
|
64
|
+
return sshClientPool.use(connectionId, async (client) => {
|
|
65
|
+
const sftp = await openSftp(client);
|
|
66
|
+
try {
|
|
67
|
+
return await operation(sftp);
|
|
68
|
+
} finally {
|
|
69
|
+
sftp.end();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Promisify one ssh2 SFTP call, whose callbacks are all `(err, value?)`. */
|
|
75
|
+
function callSftp<T>(
|
|
76
|
+
run: (done: (error: Error | null | undefined, value?: T) => void) => void
|
|
77
|
+
): Promise<T> {
|
|
78
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
79
|
+
run((error, value) => {
|
|
80
|
+
if (error) {
|
|
81
|
+
rejectPromise(error);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
resolvePromise(value as T);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function typeFromMode(mode: number): SftpEntryType {
|
|
90
|
+
switch (mode & S_IFMT) {
|
|
91
|
+
case S_IFDIR:
|
|
92
|
+
return 'directory';
|
|
93
|
+
case S_IFLNK:
|
|
94
|
+
return 'symlink';
|
|
95
|
+
case S_IFREG:
|
|
96
|
+
return 'file';
|
|
97
|
+
default:
|
|
98
|
+
return 'other';
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Render mode bits the way `ls -l` does, minus the leading type character. */
|
|
103
|
+
function permissionString(mode: number): string {
|
|
104
|
+
const bits = ['r', 'w', 'x'];
|
|
105
|
+
let rendered = '';
|
|
106
|
+
for (let group = 0; group < 3; group++) {
|
|
107
|
+
for (let bit = 0; bit < 3; bit++) {
|
|
108
|
+
const mask = 1 << (8 - (group * 3 + bit));
|
|
109
|
+
rendered += mode & mask ? bits[bit] : '-';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// setuid / setgid / sticky replace the matching execute slot, as in ls.
|
|
113
|
+
if (mode & 0o4000) rendered = `${rendered.slice(0, 2)}${mode & 0o100 ? 's' : 'S'}${rendered.slice(3)}`;
|
|
114
|
+
if (mode & 0o2000) rendered = `${rendered.slice(0, 5)}${mode & 0o010 ? 's' : 'S'}${rendered.slice(6)}`;
|
|
115
|
+
if (mode & 0o1000) rendered = `${rendered.slice(0, 8)}${mode & 0o001 ? 't' : 'T'}`;
|
|
116
|
+
return rendered;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function toIsoTime(seconds: number): string {
|
|
120
|
+
// SFTP reports seconds; a host with a broken clock can report 0 or garbage.
|
|
121
|
+
const millis = seconds > 0 ? seconds * 1000 : 0;
|
|
122
|
+
const date = new Date(millis);
|
|
123
|
+
return Number.isNaN(date.getTime()) ? new Date(0).toISOString() : date.toISOString();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Join a remote POSIX directory and child name. `..` resolves one level up. */
|
|
127
|
+
export function joinRemote(directory: string, name: string): string {
|
|
128
|
+
if (name.startsWith('/')) return normalizeRemote(name);
|
|
129
|
+
const base = directory.endsWith('/') ? directory.slice(0, -1) : directory;
|
|
130
|
+
return normalizeRemote(`${base}/${name}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Collapse `.`, `..` and duplicate slashes in a remote POSIX path. */
|
|
134
|
+
export function normalizeRemote(path: string): string {
|
|
135
|
+
const isAbsolute = path.startsWith('/');
|
|
136
|
+
const parts: string[] = [];
|
|
137
|
+
for (const segment of path.split('/')) {
|
|
138
|
+
if (!segment || segment === '.') continue;
|
|
139
|
+
if (segment === '..') {
|
|
140
|
+
if (parts.length > 0 && parts[parts.length - 1] !== '..') {
|
|
141
|
+
parts.pop();
|
|
142
|
+
} else if (!isAbsolute) {
|
|
143
|
+
parts.push('..');
|
|
144
|
+
}
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
parts.push(segment);
|
|
148
|
+
}
|
|
149
|
+
const joined = parts.join('/');
|
|
150
|
+
if (isAbsolute) return `/${joined}`;
|
|
151
|
+
return joined || '.';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function parentOfRemote(path: string): string {
|
|
155
|
+
const normalized = normalizeRemote(path);
|
|
156
|
+
if (normalized === '/') return '/';
|
|
157
|
+
const cut = normalized.lastIndexOf('/');
|
|
158
|
+
if (cut <= 0) return '/';
|
|
159
|
+
return normalized.slice(0, cut);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Describe one directory entry. Symlinks are reported as symlinks but also
|
|
164
|
+
* carry where they point and what type the target is, so the browser can let
|
|
165
|
+
* the user step into a linked directory.
|
|
166
|
+
*/
|
|
167
|
+
async function describeEntry(
|
|
168
|
+
sftp: SFTPWrapper,
|
|
169
|
+
directory: string,
|
|
170
|
+
item: FileEntryWithStats
|
|
171
|
+
): Promise<SftpEntry> {
|
|
172
|
+
const path = joinRemote(directory, item.filename);
|
|
173
|
+
const attrs = item.attrs;
|
|
174
|
+
const type = typeFromMode(attrs.mode);
|
|
175
|
+
|
|
176
|
+
let linkTarget: string | null = null;
|
|
177
|
+
let targetType: SftpEntryType | null = null;
|
|
178
|
+
if (type === 'symlink') {
|
|
179
|
+
try {
|
|
180
|
+
linkTarget = await callSftp<string>((done) => sftp.readlink(path, done));
|
|
181
|
+
} catch {
|
|
182
|
+
linkTarget = null;
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const targetStats = await callSftp<Stats>((done) => sftp.stat(path, done));
|
|
186
|
+
targetType = typeFromMode(targetStats.mode);
|
|
187
|
+
} catch {
|
|
188
|
+
// A dangling symlink — leave the target type unknown.
|
|
189
|
+
targetType = null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
name: item.filename,
|
|
195
|
+
path,
|
|
196
|
+
type,
|
|
197
|
+
size: attrs.size,
|
|
198
|
+
mode: attrs.mode & 0o7777,
|
|
199
|
+
permissions: permissionString(attrs.mode),
|
|
200
|
+
uid: attrs.uid,
|
|
201
|
+
gid: attrs.gid,
|
|
202
|
+
modifiedAt: toIsoTime(attrs.mtime),
|
|
203
|
+
linkTarget,
|
|
204
|
+
targetType
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The shell command that archives `paths` into `archivePath`.
|
|
210
|
+
*
|
|
211
|
+
* Both tools are run from the items' common parent so the archive stores plain
|
|
212
|
+
* names — extracting it recreates `subject/`, not `home/user/subject/`.
|
|
213
|
+
*
|
|
214
|
+
* A name starting with `-` would otherwise be read as an option. tar accepts
|
|
215
|
+
* `--` to end its options; zip does not ("can't use -- before archive name"),
|
|
216
|
+
* so there the names are prefixed with `./`, which zip strips back out.
|
|
217
|
+
*/
|
|
218
|
+
export function buildCompressCommand(
|
|
219
|
+
paths: string[],
|
|
220
|
+
archivePath: string,
|
|
221
|
+
format: SftpArchiveFormat
|
|
222
|
+
): string {
|
|
223
|
+
const parent = parentOfRemote(paths[0]);
|
|
224
|
+
const bareNames = paths.map((path) => path.split('/').pop() || path);
|
|
225
|
+
|
|
226
|
+
if (format === 'zip') {
|
|
227
|
+
const names = bareNames.map((name) => shellQuote(`./${name}`)).join(' ');
|
|
228
|
+
return `cd ${shellQuote(parent)} && zip -r -q ${shellQuote(archivePath)} ${names}`;
|
|
229
|
+
}
|
|
230
|
+
const names = bareNames.map((name) => shellQuote(name)).join(' ');
|
|
231
|
+
return `cd ${shellQuote(parent)} && tar -czf ${shellQuote(archivePath)} -- ${names}`;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Suffixes that name an archive, longest compound first — `.tar.gz` has to be
|
|
236
|
+
* recognised before `.gz`, or `site.tar.gz` would unwrap to `site.tar`.
|
|
237
|
+
*/
|
|
238
|
+
const ARCHIVE_SUFFIXES = [
|
|
239
|
+
'.tar.gz',
|
|
240
|
+
'.tar.bz2',
|
|
241
|
+
'.tar.xz',
|
|
242
|
+
'.tgz',
|
|
243
|
+
'.tbz2',
|
|
244
|
+
'.txz',
|
|
245
|
+
'.zip',
|
|
246
|
+
'.tar',
|
|
247
|
+
'.gz'
|
|
248
|
+
];
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Split a name into the part a `(2)` marker goes after and the extension that
|
|
252
|
+
* has to stay at the end. `notes.txt` splits, `.bashrc` does not — a leading
|
|
253
|
+
* dot is part of the name, not the start of a suffix — and `site.tar.gz` keeps
|
|
254
|
+
* both halves of its compound suffix together.
|
|
255
|
+
*/
|
|
256
|
+
export function splitRemoteName(name: string): { stem: string; suffix: string } {
|
|
257
|
+
const lowerName = name.toLowerCase();
|
|
258
|
+
for (const compound of ['.tar.gz', '.tar.bz2', '.tar.xz', '.tar.zst']) {
|
|
259
|
+
if (lowerName.endsWith(compound) && name.length > compound.length) {
|
|
260
|
+
return { stem: name.slice(0, -compound.length), suffix: name.slice(-compound.length) };
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const cut = name.lastIndexOf('.');
|
|
264
|
+
if (cut <= 0) return { stem: name, suffix: '' };
|
|
265
|
+
return { stem: name.slice(0, cut), suffix: name.slice(cut) };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The nth free-name candidate for `name`: `notes.txt` → `notes (2).txt`. */
|
|
269
|
+
export function buildCandidateName(name: string, attempt: number): string {
|
|
270
|
+
const { stem, suffix } = splitRemoteName(name);
|
|
271
|
+
return `${stem} (${attempt})${suffix}`;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The name an archive suggests for a wrapper folder: its own, minus the suffix. */
|
|
275
|
+
export function archiveBaseName(archivePath: string): string {
|
|
276
|
+
const name = archivePath.split('/').pop() || 'archive';
|
|
277
|
+
const lowerName = name.toLowerCase();
|
|
278
|
+
for (const suffix of ARCHIVE_SUFFIXES) {
|
|
279
|
+
if (lowerName.endsWith(suffix) && name.length > suffix.length) {
|
|
280
|
+
return name.slice(0, -suffix.length);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return name;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The shell command that unpacks `archivePath`, chosen by its suffix.
|
|
288
|
+
*
|
|
289
|
+
* `keepExisting` is the "don't touch what is already there" half of the
|
|
290
|
+
* conflict choice. unzip has a flag for each side of it; tar only overwrites by
|
|
291
|
+
* default, and the flag that makes it skip quietly (`--skip-old-files`) is GNU
|
|
292
|
+
* tar's — the tar on a BSD or macOS host understands only `-k`. Trying the
|
|
293
|
+
* quiet flag first and falling back covers both, and because the fallback runs
|
|
294
|
+
* whenever the first attempt fails, a genuine failure still surfaces its own
|
|
295
|
+
* error rather than being swallowed by the probe.
|
|
296
|
+
*/
|
|
297
|
+
export function buildExtractCommand(
|
|
298
|
+
archivePath: string,
|
|
299
|
+
destinationDirectory: string,
|
|
300
|
+
keepExisting = false
|
|
301
|
+
): string {
|
|
302
|
+
const lowerName = archivePath.toLowerCase();
|
|
303
|
+
const archive = shellQuote(archivePath);
|
|
304
|
+
const destination = shellQuote(destinationDirectory);
|
|
305
|
+
|
|
306
|
+
const untar = (flag: string): string => {
|
|
307
|
+
const base = `tar -x${flag}f ${archive} -C ${destination}`;
|
|
308
|
+
if (!keepExisting) return base;
|
|
309
|
+
return `${base} --skip-old-files 2>/dev/null || ${base} -k`;
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
if (lowerName.endsWith('.zip')) {
|
|
313
|
+
return `unzip ${keepExisting ? '-n' : '-o'} -q ${archive} -d ${destination}`;
|
|
314
|
+
}
|
|
315
|
+
if (lowerName.endsWith('.tar.gz') || lowerName.endsWith('.tgz')) return untar('z');
|
|
316
|
+
if (lowerName.endsWith('.tar.bz2') || lowerName.endsWith('.tbz2')) return untar('j');
|
|
317
|
+
if (lowerName.endsWith('.tar.xz') || lowerName.endsWith('.txz')) return untar('J');
|
|
318
|
+
if (lowerName.endsWith('.tar')) return untar('');
|
|
319
|
+
if (lowerName.endsWith('.gz')) {
|
|
320
|
+
// A bare .gz holds one file; decompress it into the destination.
|
|
321
|
+
const stem = (archivePath.split('/').pop() || 'file').replace(/\.gz$/i, '');
|
|
322
|
+
const target = shellQuote(joinRemote(destinationDirectory, stem));
|
|
323
|
+
const decompress = `gunzip -c ${archive} > ${target}`;
|
|
324
|
+
return keepExisting ? `[ -e ${target} ] || ${decompress}` : decompress;
|
|
325
|
+
}
|
|
326
|
+
throw new Error('Clopen does not know how to extract that file type');
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* The shell command that lists an archive's entries without unpacking it. The
|
|
331
|
+
* output is capped: a listing is only used to work out what the archive would
|
|
332
|
+
* create at the top level, and reading a million paths to learn that is waste.
|
|
333
|
+
*/
|
|
334
|
+
export function buildArchiveListCommand(archivePath: string, limit = ARCHIVE_LIST_LIMIT): string {
|
|
335
|
+
const lowerName = archivePath.toLowerCase();
|
|
336
|
+
const archive = shellQuote(archivePath);
|
|
337
|
+
const head = `head -n ${limit}`;
|
|
338
|
+
|
|
339
|
+
if (lowerName.endsWith('.zip')) return `unzip -Z1 ${archive} | ${head}`;
|
|
340
|
+
if (lowerName.endsWith('.tar.gz') || lowerName.endsWith('.tgz')) return `tar -tzf ${archive} | ${head}`;
|
|
341
|
+
if (lowerName.endsWith('.tar.bz2') || lowerName.endsWith('.tbz2')) return `tar -tjf ${archive} | ${head}`;
|
|
342
|
+
if (lowerName.endsWith('.tar.xz') || lowerName.endsWith('.txz')) return `tar -tJf ${archive} | ${head}`;
|
|
343
|
+
if (lowerName.endsWith('.tar')) return `tar -tf ${archive} | ${head}`;
|
|
344
|
+
if (lowerName.endsWith('.gz')) {
|
|
345
|
+
// A bare .gz has no index; the one file it holds is named after itself.
|
|
346
|
+
return `echo ${shellQuote(archiveBaseName(archivePath))}`;
|
|
347
|
+
}
|
|
348
|
+
throw new Error('Clopen does not know how to extract that file type');
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Reduce an archive listing to the names it would create in the destination.
|
|
353
|
+
* Only the first path segment of each entry matters: `site/index.html` and
|
|
354
|
+
* `site/css/app.css` both land in the same `site/`.
|
|
355
|
+
*/
|
|
356
|
+
export function parseArchiveTopLevelNames(listing: string): string[] {
|
|
357
|
+
const names: string[] = [];
|
|
358
|
+
const seen = new Set<string>();
|
|
359
|
+
for (const line of listing.split('\n')) {
|
|
360
|
+
// tar writes `./site/index.html` when the archive was made from `.`.
|
|
361
|
+
const entry = line.trim().replace(/^\.\//, '');
|
|
362
|
+
if (!entry || entry === '.') continue;
|
|
363
|
+
const top = entry.split('/')[0];
|
|
364
|
+
if (!top || seen.has(top)) continue;
|
|
365
|
+
seen.add(top);
|
|
366
|
+
names.push(top);
|
|
367
|
+
}
|
|
368
|
+
return names;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Whether anything at all sits at `path` — a dangling symlink counts. */
|
|
372
|
+
async function existsOn(sftp: SFTPWrapper, path: string): Promise<boolean> {
|
|
373
|
+
try {
|
|
374
|
+
await callSftp<Stats>((done) => sftp.lstat(path, done));
|
|
375
|
+
return true;
|
|
376
|
+
} catch {
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The first `name (n)` inside `directory` that nothing is using yet. */
|
|
382
|
+
async function findFreeName(sftp: SFTPWrapper, directory: string, name: string): Promise<string> {
|
|
383
|
+
for (let attempt = 2; attempt <= MAX_RENAME_ATTEMPTS; attempt++) {
|
|
384
|
+
const candidate = buildCandidateName(name, attempt);
|
|
385
|
+
if (!(await existsOn(sftp, joinRemote(directory, candidate)))) return candidate;
|
|
386
|
+
}
|
|
387
|
+
throw new Error(`Could not find a free name for ${name}`);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Delete a tree over one open SFTP subsystem, refusing to follow symlinks. */
|
|
391
|
+
async function removeTreeOn(sftp: SFTPWrapper, path: string, depth = 0): Promise<void> {
|
|
392
|
+
if (depth > MAX_DELETE_DEPTH) {
|
|
393
|
+
throw new Error(`Refusing to delete deeper than ${MAX_DELETE_DEPTH} levels`);
|
|
394
|
+
}
|
|
395
|
+
const stats = await callSftp<Stats>((done) => sftp.lstat(path, done));
|
|
396
|
+
// A symlink is removed as a link — never followed, or deleting a link to
|
|
397
|
+
// /etc would delete /etc.
|
|
398
|
+
if (typeFromMode(stats.mode) !== 'directory') {
|
|
399
|
+
await callSftp<void>((done) => sftp.unlink(path, done));
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const items = await callSftp<FileEntryWithStats[]>((done) => sftp.readdir(path, done));
|
|
403
|
+
for (const item of items) {
|
|
404
|
+
await removeTreeOn(sftp, joinRemote(path, item.filename), depth + 1);
|
|
405
|
+
}
|
|
406
|
+
await callSftp<void>((done) => sftp.rmdir(path, done));
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* What one step of a bulk operation did: nothing special, nothing at all, or a
|
|
411
|
+
* landing under a different name.
|
|
412
|
+
*/
|
|
413
|
+
type BulkOutcome = void | undefined | 'skipped' | { renamedTo: string };
|
|
414
|
+
|
|
415
|
+
/** Where one item lands, and what has to happen first. `null` means leave it. */
|
|
416
|
+
interface TransferPlan {
|
|
417
|
+
targetPath: string;
|
|
418
|
+
/** True when something is in the way and has to be deleted first. */
|
|
419
|
+
replaceExisting: boolean;
|
|
420
|
+
/** True when the item had to take a different name to fit. */
|
|
421
|
+
renamed: boolean;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Work out where `sourcePath` lands inside `destinationDirectory`, applying
|
|
426
|
+
* `strategy` when the name is taken. Returns null when the item is to be left
|
|
427
|
+
* alone — either the user chose to skip it, or a move would put it back exactly
|
|
428
|
+
* where it already is, which is not a conflict at all.
|
|
429
|
+
*/
|
|
430
|
+
async function planTransfer(
|
|
431
|
+
sftp: SFTPWrapper,
|
|
432
|
+
sourcePath: string,
|
|
433
|
+
destinationDirectory: string,
|
|
434
|
+
strategy: SftpConflictStrategy,
|
|
435
|
+
isMove: boolean
|
|
436
|
+
): Promise<TransferPlan | null> {
|
|
437
|
+
const name = sourcePath.split('/').pop() || sourcePath;
|
|
438
|
+
const targetPath = joinRemote(destinationDirectory, name);
|
|
439
|
+
const isSelf = targetPath === sourcePath;
|
|
440
|
+
|
|
441
|
+
if (isSelf && isMove) return null;
|
|
442
|
+
if (!isSelf && !(await existsOn(sftp, targetPath))) {
|
|
443
|
+
return { targetPath, replaceExisting: false, renamed: false };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
switch (strategy) {
|
|
447
|
+
case 'skip':
|
|
448
|
+
return null;
|
|
449
|
+
case 'rename': {
|
|
450
|
+
const freeName = await findFreeName(sftp, destinationDirectory, name);
|
|
451
|
+
return {
|
|
452
|
+
targetPath: joinRemote(destinationDirectory, freeName),
|
|
453
|
+
replaceExisting: false,
|
|
454
|
+
renamed: true
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
default:
|
|
458
|
+
// Overwriting an item with itself would delete it and then copy nothing.
|
|
459
|
+
if (isSelf) throw new Error('Source and destination are the same');
|
|
460
|
+
return { targetPath, replaceExisting: true, renamed: false };
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
export const sftpService = {
|
|
465
|
+
/** The absolute path a relative path (or `.`) resolves to on the host. */
|
|
466
|
+
async realpath(connectionId: string, path: string): Promise<string> {
|
|
467
|
+
return withSftp(connectionId, (sftp) =>
|
|
468
|
+
callSftp<string>((done) => sftp.realpath(path || '.', done))
|
|
469
|
+
);
|
|
470
|
+
},
|
|
471
|
+
|
|
472
|
+
async list(connectionId: string, path: string): Promise<SftpListing> {
|
|
473
|
+
return withSftp(connectionId, async (sftp) => {
|
|
474
|
+
const resolved = await callSftp<string>((done) => sftp.realpath(path || '.', done));
|
|
475
|
+
const items = await callSftp<FileEntryWithStats[]>((done) => sftp.readdir(resolved, done));
|
|
476
|
+
const entries = await Promise.all(items.map((item) => describeEntry(sftp, resolved, item)));
|
|
477
|
+
entries.sort((left, right) => {
|
|
478
|
+
// Directories first, then case-insensitive by name — the ordering
|
|
479
|
+
// every file browser uses, and one the client never has to redo.
|
|
480
|
+
const leftIsDir = left.type === 'directory' || left.targetType === 'directory';
|
|
481
|
+
const rightIsDir = right.type === 'directory' || right.targetType === 'directory';
|
|
482
|
+
if (leftIsDir !== rightIsDir) return leftIsDir ? -1 : 1;
|
|
483
|
+
return left.name.localeCompare(right.name, undefined, { sensitivity: 'base' });
|
|
484
|
+
});
|
|
485
|
+
return { path: resolved, entries };
|
|
486
|
+
});
|
|
487
|
+
},
|
|
488
|
+
|
|
489
|
+
async stat(connectionId: string, path: string): Promise<SftpEntry> {
|
|
490
|
+
return withSftp(connectionId, async (sftp) => {
|
|
491
|
+
const resolved = await callSftp<string>((done) => sftp.realpath(path, done));
|
|
492
|
+
const stats = await callSftp<Stats>((done) => sftp.lstat(resolved, done));
|
|
493
|
+
const name = resolved.split('/').pop() || resolved;
|
|
494
|
+
return describeEntry(sftp, parentOfRemote(resolved), {
|
|
495
|
+
filename: name,
|
|
496
|
+
longname: name,
|
|
497
|
+
attrs: stats
|
|
498
|
+
});
|
|
499
|
+
});
|
|
500
|
+
},
|
|
501
|
+
|
|
502
|
+
async makeDirectory(connectionId: string, path: string): Promise<void> {
|
|
503
|
+
await withSftp(connectionId, (sftp) => callSftp<void>((done) => sftp.mkdir(path, done)));
|
|
504
|
+
},
|
|
505
|
+
|
|
506
|
+
/** Create an empty file, failing if something is already there. */
|
|
507
|
+
async createFile(connectionId: string, path: string): Promise<void> {
|
|
508
|
+
await withSftp(connectionId, async (sftp) => {
|
|
509
|
+
// 'wx' is exclusive-create: an existing path is an error, not a truncate.
|
|
510
|
+
const handle = await callSftp<Buffer>((done) => sftp.open(path, 'wx', done));
|
|
511
|
+
await callSftp<void>((done) => sftp.close(handle, done));
|
|
512
|
+
});
|
|
513
|
+
},
|
|
514
|
+
|
|
515
|
+
async rename(connectionId: string, fromPath: string, toPath: string): Promise<void> {
|
|
516
|
+
await withSftp(connectionId, (sftp) =>
|
|
517
|
+
callSftp<void>((done) => sftp.rename(fromPath, toPath, done))
|
|
518
|
+
);
|
|
519
|
+
},
|
|
520
|
+
|
|
521
|
+
async chmod(connectionId: string, path: string, mode: number): Promise<void> {
|
|
522
|
+
await withSftp(connectionId, (sftp) => callSftp<void>((done) => sftp.chmod(path, mode, done)));
|
|
523
|
+
},
|
|
524
|
+
|
|
525
|
+
async remove(connectionId: string, path: string, recursive: boolean): Promise<void> {
|
|
526
|
+
await withSftp(connectionId, async (sftp) => {
|
|
527
|
+
if (recursive) {
|
|
528
|
+
await removeTreeOn(sftp, path);
|
|
529
|
+
debug.log('ssh', `removed remote tree ${path}`);
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const stats = await callSftp<Stats>((done) => sftp.lstat(path, done));
|
|
534
|
+
if (typeFromMode(stats.mode) === 'directory') {
|
|
535
|
+
await callSftp<void>((done) => sftp.rmdir(path, done));
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
await callSftp<void>((done) => sftp.unlink(path, done));
|
|
539
|
+
});
|
|
540
|
+
},
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Read a file as UTF-8 for the inline editor. Files above the limit are
|
|
544
|
+
* truncated rather than refused, so a large log is still previewable.
|
|
545
|
+
*/
|
|
546
|
+
async readText(connectionId: string, path: string): Promise<SftpFileContent> {
|
|
547
|
+
return withSftp(connectionId, async (sftp) => {
|
|
548
|
+
const stats = await callSftp<Stats>((done) => sftp.stat(path, done));
|
|
549
|
+
if (typeFromMode(stats.mode) === 'directory') {
|
|
550
|
+
throw new Error('That path is a directory');
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const truncated = stats.size > SFTP_TEXT_READ_LIMIT;
|
|
554
|
+
const chunks: Buffer[] = [];
|
|
555
|
+
let read = 0;
|
|
556
|
+
|
|
557
|
+
await new Promise<void>((resolvePromise, rejectPromise) => {
|
|
558
|
+
const stream = sftp.createReadStream(path, { start: 0, end: SFTP_TEXT_READ_LIMIT - 1 });
|
|
559
|
+
stream.on('data', (chunk: Buffer) => {
|
|
560
|
+
chunks.push(chunk);
|
|
561
|
+
read += chunk.length;
|
|
562
|
+
});
|
|
563
|
+
stream.on('error', rejectPromise);
|
|
564
|
+
stream.on('close', () => resolvePromise());
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
return {
|
|
568
|
+
path,
|
|
569
|
+
text: Buffer.concat(chunks).toString('utf8'),
|
|
570
|
+
size: read,
|
|
571
|
+
truncated
|
|
572
|
+
};
|
|
573
|
+
});
|
|
574
|
+
},
|
|
575
|
+
|
|
576
|
+
async writeText(connectionId: string, path: string, text: string): Promise<void> {
|
|
577
|
+
await withSftp(connectionId, async (sftp) => {
|
|
578
|
+
await new Promise<void>((resolvePromise, rejectPromise) => {
|
|
579
|
+
const stream = sftp.createWriteStream(path);
|
|
580
|
+
stream.on('error', rejectPromise);
|
|
581
|
+
stream.on('close', () => resolvePromise());
|
|
582
|
+
stream.end(Buffer.from(text, 'utf8'));
|
|
583
|
+
});
|
|
584
|
+
});
|
|
585
|
+
},
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Stream a remote file out. The lease is held until the returned stream ends,
|
|
589
|
+
* so the pool cannot close the transport mid-download.
|
|
590
|
+
*/
|
|
591
|
+
async openDownload(
|
|
592
|
+
connectionId: string,
|
|
593
|
+
path: string
|
|
594
|
+
): Promise<{ stream: Readable; size: number; name: string }> {
|
|
595
|
+
const lease = await sshClientPool.acquire(connectionId);
|
|
596
|
+
try {
|
|
597
|
+
const sftp = await openSftp(lease.client);
|
|
598
|
+
const stats = await callSftp<Stats>((done) => sftp.stat(path, done));
|
|
599
|
+
if (typeFromMode(stats.mode) === 'directory') {
|
|
600
|
+
throw new Error('That path is a directory');
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const stream = sftp.createReadStream(path);
|
|
604
|
+
const finish = (): void => {
|
|
605
|
+
sftp.end();
|
|
606
|
+
lease.release();
|
|
607
|
+
};
|
|
608
|
+
stream.on('close', finish);
|
|
609
|
+
stream.on('error', finish);
|
|
610
|
+
|
|
611
|
+
return { stream, size: stats.size, name: path.split('/').pop() || 'download' };
|
|
612
|
+
} catch (error) {
|
|
613
|
+
lease.release();
|
|
614
|
+
throw error;
|
|
615
|
+
}
|
|
616
|
+
},
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Stream bytes into a remote file. Resolves once the remote side has the whole
|
|
620
|
+
* body, so the HTTP route can only report success after the write landed.
|
|
621
|
+
*/
|
|
622
|
+
async openUpload(connectionId: string, path: string): Promise<{ stream: Writable; done: Promise<void> }> {
|
|
623
|
+
const lease = await sshClientPool.acquire(connectionId);
|
|
624
|
+
try {
|
|
625
|
+
const sftp = await openSftp(lease.client);
|
|
626
|
+
const stream = sftp.createWriteStream(path);
|
|
627
|
+
const done = new Promise<void>((resolvePromise, rejectPromise) => {
|
|
628
|
+
stream.on('error', (error: Error) => {
|
|
629
|
+
sftp.end();
|
|
630
|
+
lease.release();
|
|
631
|
+
rejectPromise(error);
|
|
632
|
+
});
|
|
633
|
+
stream.on('close', () => {
|
|
634
|
+
sftp.end();
|
|
635
|
+
lease.release();
|
|
636
|
+
resolvePromise();
|
|
637
|
+
});
|
|
638
|
+
});
|
|
639
|
+
return { stream, done };
|
|
640
|
+
} catch (error) {
|
|
641
|
+
lease.release();
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
644
|
+
},
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* How much space the account has. Not part of SFTP, so this runs commands —
|
|
648
|
+
* see disk-usage.ts for why `df` alone is the wrong answer on shared hosting.
|
|
649
|
+
*/
|
|
650
|
+
async diskUsage(connectionId: string, path: string): Promise<SftpDiskUsage> {
|
|
651
|
+
return sshClientPool.use(connectionId, (client) => readDiskUsage(client, path));
|
|
652
|
+
},
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Apply `operation` to every path, collecting per-path outcomes instead of
|
|
656
|
+
* stopping at the first failure — deleting twenty files should not abort
|
|
657
|
+
* because one of them is read-only, and the user needs to know which one.
|
|
658
|
+
*
|
|
659
|
+
* An operation reports what it did: nothing for a plain success, `skipped`
|
|
660
|
+
* for an item it deliberately left alone, or the name the item ended up
|
|
661
|
+
* with when a conflict pushed it onto a different one.
|
|
662
|
+
*/
|
|
663
|
+
async runBulk(
|
|
664
|
+
paths: string[],
|
|
665
|
+
operation: (path: string) => Promise<BulkOutcome>
|
|
666
|
+
): Promise<SftpBulkResult> {
|
|
667
|
+
const succeeded: string[] = [];
|
|
668
|
+
const skipped: string[] = [];
|
|
669
|
+
const renamed: Array<{ path: string; toPath: string }> = [];
|
|
670
|
+
const failed: Array<{ path: string; error: string }> = [];
|
|
671
|
+
for (const path of paths) {
|
|
672
|
+
try {
|
|
673
|
+
const outcome = await operation(path);
|
|
674
|
+
if (outcome === 'skipped') {
|
|
675
|
+
skipped.push(path);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
succeeded.push(path);
|
|
679
|
+
if (outcome && typeof outcome === 'object') {
|
|
680
|
+
renamed.push({ path, toPath: outcome.renamedTo });
|
|
681
|
+
}
|
|
682
|
+
} catch (error) {
|
|
683
|
+
failed.push({ path, error: error instanceof Error ? error.message : String(error) });
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
return { succeeded, skipped, renamed, failed };
|
|
687
|
+
},
|
|
688
|
+
|
|
689
|
+
async removeMany(connectionId: string, paths: string[], recursive: boolean): Promise<SftpBulkResult> {
|
|
690
|
+
return this.runBulk(paths, (path) => this.remove(connectionId, path, recursive));
|
|
691
|
+
},
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* The names in `paths` that are already taken inside `destinationDirectory`.
|
|
695
|
+
* Asked before a copy or a move so the user is offered a choice instead of
|
|
696
|
+
* being told afterwards that a file they wanted was replaced — or worse, not
|
|
697
|
+
* being told at all.
|
|
698
|
+
*
|
|
699
|
+
* A move onto an item's own directory is not a conflict: it is a no-op. A
|
|
700
|
+
* copy onto it is, because duplicating in place is a real thing to want.
|
|
701
|
+
*/
|
|
702
|
+
async findConflicts(
|
|
703
|
+
connectionId: string,
|
|
704
|
+
paths: string[],
|
|
705
|
+
destinationDirectory: string,
|
|
706
|
+
operation: 'move' | 'copy'
|
|
707
|
+
): Promise<SftpConflict[]> {
|
|
708
|
+
return withSftp(connectionId, async (sftp) => {
|
|
709
|
+
const destination = await callSftp<string>((done) =>
|
|
710
|
+
sftp.realpath(destinationDirectory, done)
|
|
711
|
+
);
|
|
712
|
+
const conflicts: SftpConflict[] = [];
|
|
713
|
+
for (const path of paths) {
|
|
714
|
+
const name = path.split('/').pop() || path;
|
|
715
|
+
const targetPath = joinRemote(destination, name);
|
|
716
|
+
if (targetPath === path && operation === 'move') continue;
|
|
717
|
+
try {
|
|
718
|
+
const stats = await callSftp<Stats>((done) => sftp.lstat(targetPath, done));
|
|
719
|
+
conflicts.push({ path, name, targetPath, targetType: typeFromMode(stats.mode) });
|
|
720
|
+
} catch {
|
|
721
|
+
// Nothing there — nothing to ask about.
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return conflicts;
|
|
725
|
+
});
|
|
726
|
+
},
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Move paths into `destinationDirectory`. SFTP rename is tried first because
|
|
730
|
+
* it needs no shell; it fails across filesystems, so `mv` is the fallback.
|
|
731
|
+
*/
|
|
732
|
+
async move(
|
|
733
|
+
connectionId: string,
|
|
734
|
+
paths: string[],
|
|
735
|
+
destinationDirectory: string,
|
|
736
|
+
onConflict: SftpConflictStrategy = 'skip'
|
|
737
|
+
): Promise<SftpBulkResult> {
|
|
738
|
+
return withSftp(connectionId, async (sftp) => {
|
|
739
|
+
const destination = await callSftp<string>((done) =>
|
|
740
|
+
sftp.realpath(destinationDirectory, done)
|
|
741
|
+
);
|
|
742
|
+
return this.runBulk(paths, async (path) => {
|
|
743
|
+
const plan = await planTransfer(sftp, path, destination, onConflict, true);
|
|
744
|
+
if (!plan) return 'skipped';
|
|
745
|
+
// Both rename and `mv` would put the source *inside* an existing
|
|
746
|
+
// directory of the same name rather than replacing it, so what is
|
|
747
|
+
// in the way has to be deleted first.
|
|
748
|
+
if (plan.replaceExisting) await removeTreeOn(sftp, plan.targetPath);
|
|
749
|
+
try {
|
|
750
|
+
await callSftp<void>((done) => sftp.rename(path, plan.targetPath, done));
|
|
751
|
+
} catch {
|
|
752
|
+
await sshClientPool.use(connectionId, (client) =>
|
|
753
|
+
runCommandOrThrow(
|
|
754
|
+
client,
|
|
755
|
+
`mv -f -- ${shellQuote(path)} ${shellQuote(plan.targetPath)}`,
|
|
756
|
+
`Could not move ${path}`
|
|
757
|
+
)
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
debug.log('ssh', `moved ${path} to ${plan.targetPath}`);
|
|
761
|
+
return plan.renamed ? { renamedTo: plan.targetPath } : undefined;
|
|
762
|
+
});
|
|
763
|
+
});
|
|
764
|
+
},
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Copy paths into `destinationDirectory`. SFTP has no copy operation at all,
|
|
768
|
+
* so this is `cp -a` — which also preserves modes and timestamps.
|
|
769
|
+
*/
|
|
770
|
+
async copy(
|
|
771
|
+
connectionId: string,
|
|
772
|
+
paths: string[],
|
|
773
|
+
destinationDirectory: string,
|
|
774
|
+
onConflict: SftpConflictStrategy = 'skip'
|
|
775
|
+
): Promise<SftpBulkResult> {
|
|
776
|
+
return withSftp(connectionId, async (sftp) => {
|
|
777
|
+
const destination = await callSftp<string>((done) =>
|
|
778
|
+
sftp.realpath(destinationDirectory, done)
|
|
779
|
+
);
|
|
780
|
+
return this.runBulk(paths, async (path) => {
|
|
781
|
+
const plan = await planTransfer(sftp, path, destination, onConflict, false);
|
|
782
|
+
if (!plan) return 'skipped';
|
|
783
|
+
// `cp -a src dir` copies *into* dir when dir exists, so an item being
|
|
784
|
+
// replaced is removed first — otherwise "overwrite" would silently
|
|
785
|
+
// nest the source inside its namesake.
|
|
786
|
+
if (plan.replaceExisting) await removeTreeOn(sftp, plan.targetPath);
|
|
787
|
+
await sshClientPool.use(connectionId, (client) =>
|
|
788
|
+
runCommandOrThrow(
|
|
789
|
+
client,
|
|
790
|
+
`cp -a -- ${shellQuote(path)} ${shellQuote(plan.targetPath)}`,
|
|
791
|
+
`Could not copy ${path}`
|
|
792
|
+
)
|
|
793
|
+
);
|
|
794
|
+
return plan.renamed ? { renamedTo: plan.targetPath } : undefined;
|
|
795
|
+
});
|
|
796
|
+
});
|
|
797
|
+
},
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Archive `paths` into `archivePath`. The archive stores plain names rather
|
|
801
|
+
* than full paths, so extracting it does not recreate `/home/user/...` — the
|
|
802
|
+
* `cd` into the common parent is what makes that true.
|
|
803
|
+
*
|
|
804
|
+
* An archive name already in use is resolved the same way a copy's is, and
|
|
805
|
+
* for the same reason: `zip` *adds to* an archive that already exists rather
|
|
806
|
+
* than replacing it, so "compress these two files" silently inherits
|
|
807
|
+
* whatever the old archive of that name held.
|
|
808
|
+
*/
|
|
809
|
+
async compress(
|
|
810
|
+
connectionId: string,
|
|
811
|
+
paths: string[],
|
|
812
|
+
archivePath: string,
|
|
813
|
+
format: SftpArchiveFormat,
|
|
814
|
+
onConflict: SftpConflictStrategy = 'skip'
|
|
815
|
+
): Promise<SftpCompressResult> {
|
|
816
|
+
if (paths.length === 0) throw new Error('Nothing selected to compress');
|
|
817
|
+
|
|
818
|
+
const requestedName = archivePath.split('/').pop() || archivePath;
|
|
819
|
+
const plan = await withSftp(connectionId, async (sftp) => {
|
|
820
|
+
const directory = await callSftp<string>((done) =>
|
|
821
|
+
sftp.realpath(parentOfRemote(archivePath), done)
|
|
822
|
+
);
|
|
823
|
+
let target = joinRemote(directory, requestedName);
|
|
824
|
+
let renamed = false;
|
|
825
|
+
|
|
826
|
+
if (await existsOn(sftp, target)) {
|
|
827
|
+
// Writing the archive over one of its own inputs would compress a
|
|
828
|
+
// file that is being replaced as it is read.
|
|
829
|
+
if (paths.includes(target) && onConflict === 'overwrite') {
|
|
830
|
+
throw new Error('The archive cannot replace one of the items being compressed');
|
|
831
|
+
}
|
|
832
|
+
switch (onConflict) {
|
|
833
|
+
case 'skip':
|
|
834
|
+
throw new Error(`“${requestedName}” already exists here`);
|
|
835
|
+
case 'rename': {
|
|
836
|
+
const freeName = await findFreeName(sftp, directory, requestedName);
|
|
837
|
+
target = joinRemote(directory, freeName);
|
|
838
|
+
renamed = true;
|
|
839
|
+
break;
|
|
840
|
+
}
|
|
841
|
+
default:
|
|
842
|
+
await removeTreeOn(sftp, target);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
return { target, renamed };
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
await sshClientPool.use(connectionId, (client) =>
|
|
849
|
+
runCommandOrThrow(
|
|
850
|
+
client,
|
|
851
|
+
buildCompressCommand(paths, plan.target, format),
|
|
852
|
+
'Could not create the archive',
|
|
853
|
+
10 * 60_000
|
|
854
|
+
)
|
|
855
|
+
);
|
|
856
|
+
debug.log('ssh', `compressed ${paths.length} item(s) into ${plan.target}`);
|
|
857
|
+
return { archivePath: plan.target, renamed: plan.renamed };
|
|
858
|
+
},
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Read what an archive would create without unpacking it: the names it puts
|
|
862
|
+
* at the top level of the destination, and which of those are already taken.
|
|
863
|
+
* The extract dialog is built out of this — "one folder, extract it here" and
|
|
864
|
+
* "eleven loose files, wrap them" are different answers, and only the archive
|
|
865
|
+
* itself knows which one applies.
|
|
866
|
+
*/
|
|
867
|
+
async inspectArchive(
|
|
868
|
+
connectionId: string,
|
|
869
|
+
archivePath: string,
|
|
870
|
+
destinationDirectory: string
|
|
871
|
+
): Promise<SftpArchiveInfo> {
|
|
872
|
+
const listing = await sshClientPool.use(connectionId, (client) =>
|
|
873
|
+
runCommandOrThrow(
|
|
874
|
+
client,
|
|
875
|
+
buildArchiveListCommand(archivePath),
|
|
876
|
+
'Could not read the archive',
|
|
877
|
+
60_000
|
|
878
|
+
)
|
|
879
|
+
);
|
|
880
|
+
const lines = listing ? listing.split('\n').length : 0;
|
|
881
|
+
const topLevelNames = parseArchiveTopLevelNames(listing);
|
|
882
|
+
const truncated = lines >= ARCHIVE_LIST_LIMIT;
|
|
883
|
+
|
|
884
|
+
const destinationEntries = await this.list(connectionId, destinationDirectory);
|
|
885
|
+
const existingNames = new Set(destinationEntries.entries.map((entry) => entry.name));
|
|
886
|
+
|
|
887
|
+
return {
|
|
888
|
+
path: archivePath,
|
|
889
|
+
topLevelNames,
|
|
890
|
+
truncated,
|
|
891
|
+
suggestedFolderName: archiveBaseName(archivePath),
|
|
892
|
+
conflictingNames: topLevelNames.filter((name) => existingNames.has(name)),
|
|
893
|
+
// A single top-level entry already contains itself; wrapping it would
|
|
894
|
+
// only add a directory the user has to click through. Anything else —
|
|
895
|
+
// including a listing too long to be sure about — is wrapped.
|
|
896
|
+
smartMode: topLevelNames.length === 1 && !truncated ? 'here' : 'folder'
|
|
897
|
+
};
|
|
898
|
+
},
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Extract an archive, either straight into `destinationDirectory` or into a
|
|
902
|
+
* folder of its own. The tool is picked by suffix; what happens to names
|
|
903
|
+
* already in use is the caller's choice.
|
|
904
|
+
*/
|
|
905
|
+
async extract(
|
|
906
|
+
connectionId: string,
|
|
907
|
+
archivePath: string,
|
|
908
|
+
destinationDirectory: string,
|
|
909
|
+
options: SftpExtractOptions = { mode: 'smart', onConflict: 'rename' }
|
|
910
|
+
): Promise<SftpExtractResult> {
|
|
911
|
+
const strategy = options.onConflict;
|
|
912
|
+
let mode = options.mode;
|
|
913
|
+
if (mode === 'smart') {
|
|
914
|
+
const info = await this.inspectArchive(connectionId, archivePath, destinationDirectory);
|
|
915
|
+
mode = info.smartMode;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
let destination = destinationDirectory;
|
|
919
|
+
let createdFolder = false;
|
|
920
|
+
|
|
921
|
+
if (mode === 'folder') {
|
|
922
|
+
const requestedName = (options.folderName || '').trim() || archiveBaseName(archivePath);
|
|
923
|
+
if (requestedName.includes('/')) {
|
|
924
|
+
throw new Error('A folder name cannot contain a slash');
|
|
925
|
+
}
|
|
926
|
+
destination = await withSftp(connectionId, async (sftp) => {
|
|
927
|
+
const parent = await callSftp<string>((done) =>
|
|
928
|
+
sftp.realpath(destinationDirectory, done)
|
|
929
|
+
);
|
|
930
|
+
let folderName = requestedName;
|
|
931
|
+
if (await existsOn(sftp, joinRemote(parent, folderName))) {
|
|
932
|
+
if (strategy === 'skip') {
|
|
933
|
+
throw new Error(`“${folderName}” already exists here`);
|
|
934
|
+
}
|
|
935
|
+
if (strategy === 'rename') {
|
|
936
|
+
folderName = await findFreeName(sftp, parent, folderName);
|
|
937
|
+
}
|
|
938
|
+
// Overwrite unpacks into the folder that is already there rather
|
|
939
|
+
// than deleting it, so an interrupted extract cannot take the
|
|
940
|
+
// user's directory with it.
|
|
941
|
+
}
|
|
942
|
+
const target = joinRemote(parent, folderName);
|
|
943
|
+
if (!(await existsOn(sftp, target))) {
|
|
944
|
+
await callSftp<void>((done) => sftp.mkdir(target, done));
|
|
945
|
+
createdFolder = true;
|
|
946
|
+
}
|
|
947
|
+
return target;
|
|
948
|
+
});
|
|
949
|
+
} else if (strategy === 'rename') {
|
|
950
|
+
// Nothing to rename around: unpacking into a directory that is already
|
|
951
|
+
// populated merges the two, one file at a time, and neither tar nor
|
|
952
|
+
// unzip can be told to sidestep a name.
|
|
953
|
+
throw new Error('Extracting here can only replace or keep the existing files');
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
await sshClientPool.use(connectionId, (client) =>
|
|
957
|
+
runCommandOrThrow(
|
|
958
|
+
client,
|
|
959
|
+
buildExtractCommand(archivePath, destination, strategy === 'skip'),
|
|
960
|
+
'Could not extract the archive',
|
|
961
|
+
10 * 60_000
|
|
962
|
+
)
|
|
963
|
+
);
|
|
964
|
+
debug.log('ssh', `extracted ${archivePath} into ${destination}`);
|
|
965
|
+
return { destination, createdFolder };
|
|
966
|
+
}
|
|
967
|
+
};
|