@jwjp/ftp-mcp 0.2.1 → 0.3.1

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/src/workspace.js CHANGED
@@ -1,31 +1,120 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { Writable } from 'node:stream';
4
+ import { Readable, Writable } from 'node:stream';
5
5
  import { FileType } from 'basic-ftp';
6
+ import { DEFAULT_IDLE_TIMEOUT_MS } from './config.js';
6
7
  import { localPath, safePath, UserError } from './paths.js';
7
8
  import { createTransport } from './transports.js';
8
9
 
9
- const sha256 = data => createHash('sha256').update(data).digest('hex');
10
+ const CHUNK_BYTES = 64 * 1024;
11
+ const LOCAL_HASH_CHUNK_BYTES = 1024 * 1024;
12
+ export const LIST_LIMIT = 200;
13
+
14
+ // Closing a connection cannot undo a completed transfer. Do not turn a
15
+ // successful upload into a failure that prompts an unsafe retry.
16
+ async function closeQuietly(client) {
17
+ try { await client.close(); }
18
+ catch { /* The operation result is more useful than a close error. */ }
19
+ }
20
+
21
+ // FileHandle.write() may write fewer bytes than asked; finish the chunk.
22
+ async function writeAll(handle, chunk) {
23
+ for (let offset = 0; offset < chunk.length;) {
24
+ const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset);
25
+ offset += bytesWritten;
26
+ }
27
+ }
10
28
 
11
29
  export class FtpWorkspace {
30
+ #clientQueue = Promise.resolve();
31
+ #idle = null;
32
+ #closed = false;
33
+
12
34
  constructor(config, clientFactory = () => createTransport(config)) {
13
35
  this.config = config;
14
36
  this.clientFactory = clientFactory;
15
37
  this.previews = new Map();
38
+ this.pendingWrite = Promise.resolve();
39
+ }
40
+
41
+ #withWrite(action) {
42
+ const operation = this.pendingWrite.then(action);
43
+ this.pendingWrite = operation.catch(() => {});
44
+ return operation;
45
+ }
46
+
47
+ // One remote connection serves one operation at a time: an FTP control
48
+ // connection cannot run two commands at once, and a shared SFTP session
49
+ // would interleave a listing with an upload's verification.
50
+ withClient(action) {
51
+ const operation = this.#clientQueue.then(() => this.#useClient(action));
52
+ this.#clientQueue = operation.catch(() => {});
53
+ return operation;
54
+ }
55
+
56
+ async #useClient(action) {
57
+ const client = await this.#acquire();
58
+ let result;
59
+ try {
60
+ result = await action(client);
61
+ } catch (error) {
62
+ // A failed operation can leave a transfer half done or the connection
63
+ // in an unknown state. Never hand that connection to the next caller.
64
+ await closeQuietly(client);
65
+ throw error;
66
+ }
67
+ await this.#release(client);
68
+ return result;
16
69
  }
17
70
 
18
- async withClient(action) {
71
+ async #acquire() {
72
+ const idle = this.#idle;
73
+ this.#idle = null;
74
+ if (idle) {
75
+ clearTimeout(idle.timer);
76
+ // The server may have closed an idle connection. Check before reuse so
77
+ // the caller's operation does not fail on a stale connection.
78
+ try {
79
+ await idle.client.ping();
80
+ return idle.client;
81
+ } catch {
82
+ await closeQuietly(idle.client);
83
+ }
84
+ }
19
85
  const client = this.clientFactory();
20
86
  try {
21
87
  await client.access();
22
88
  await client.cd(this.config.remoteRoot);
23
- return await action(client);
24
- } finally {
25
- // Closing a connection cannot undo a completed transfer. Do not turn a
26
- // successful upload into a failure that prompts an unsafe retry.
27
- try { await client.close(); }
28
- catch { /* The operation result is more useful than a close error. */ }
89
+ } catch (error) {
90
+ await closeQuietly(client);
91
+ throw error;
92
+ }
93
+ return client;
94
+ }
95
+
96
+ async #release(client) {
97
+ const idleMs = this.config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
98
+ if (this.#closed || idleMs === 0) return closeQuietly(client);
99
+ const timer = setTimeout(() => {
100
+ if (this.#idle?.client !== client) return;
101
+ this.#idle = null;
102
+ closeQuietly(client);
103
+ }, idleMs);
104
+ // An idle connection must not keep the process alive on its own timer.
105
+ timer.unref();
106
+ this.#idle = { client, timer };
107
+ }
108
+
109
+ // Close the idle connection and stop keeping new ones. An operation in
110
+ // progress finishes and then closes its connection.
111
+ async close() {
112
+ this.#closed = true;
113
+ const idle = this.#idle;
114
+ this.#idle = null;
115
+ if (idle) {
116
+ clearTimeout(idle.timer);
117
+ await closeQuietly(idle.client);
29
118
  }
30
119
  }
31
120
 
@@ -45,139 +134,231 @@ export class FtpWorkspace {
45
134
  }
46
135
  }
47
136
 
48
- async list(relative = '') {
137
+ async list(relative = '', cursor = '') {
49
138
  relative = safePath(relative, this.config.extra, { allowRoot: true });
50
139
  return this.withClient(async client => {
51
140
  if (relative) {
52
141
  const entry = await this.entry(client, relative);
53
142
  if (!entry || entry.type !== FileType.Directory) throw new UserError('Remote directory does not exist.');
54
143
  }
55
- const entries = await client.list(relative || '.');
56
- return entries.filter(item => !item.name.includes('/') && !safeExcluded(relative, item.name, this.config.extra) && item.type !== FileType.SymbolicLink)
57
- .slice(0, 200).map(item => ({ name: item.name, type: item.type === FileType.Directory ? 'directory' : 'file', size: item.size, modifiedAt: item.modifiedAt?.toISOString() ?? null }));
144
+ const allowed = (await client.list(relative || '.'))
145
+ .filter(item => item.name > cursor && !item.name.includes('/') && !safeExcluded(relative, item.name, this.config.extra) && item.type !== FileType.SymbolicLink)
146
+ .sort((a, b) => a.name < b.name ? -1 : Number(a.name > b.name));
147
+ const page = allowed.slice(0, LIST_LIMIT);
148
+ const truncated = allowed.length > LIST_LIMIT;
149
+ return {
150
+ entries: page.map(item => ({ name: item.name, type: item.type === FileType.Directory ? 'directory' : 'file', size: item.size, modifiedAt: item.modifiedAt?.toISOString() ?? null })),
151
+ truncated,
152
+ nextCursor: truncated ? page.at(-1).name : null
153
+ };
58
154
  });
59
155
  }
60
156
 
61
- async readRemote(client, relative) {
157
+ async #remoteEntry(client, relative) {
62
158
  const entry = await this.entry(client, relative);
63
159
  if (!entry) return null;
64
160
  if (entry.type !== FileType.File) throw new UserError('Remote path is not a regular file.');
65
161
  if (entry.size > this.config.maxBytes) throw new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.');
66
- const chunks = [];
162
+ return entry;
163
+ }
164
+
165
+ async #readRemote(client, relative, entry, destination) {
166
+ const hash = createHash('sha256');
67
167
  let bytes = 0;
68
168
  const limit = this.config.maxBytes;
69
169
  const sink = new Writable({
70
170
  write(chunk, _encoding, callback) {
71
171
  bytes += chunk.length;
72
172
  if (bytes > limit) return callback(new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.'));
73
- chunks.push(chunk);
74
- callback();
173
+ hash.update(chunk);
174
+ if (destination) writeAll(destination, chunk).then(() => callback(), callback);
175
+ else callback();
75
176
  }
76
177
  });
77
- await client.downloadTo(sink, relative);
78
- return Buffer.concat(chunks, bytes);
178
+ try { await client.downloadTo(sink, relative); }
179
+ finally { sink.destroy(); }
180
+ if (Number.isSafeInteger(entry.size) && bytes < entry.size) {
181
+ throw new UserError('Remote transfer ended before the listed file size; inspect it before retrying.');
182
+ }
183
+ return { sha256: hash.digest('hex'), bytes };
79
184
  }
80
185
 
81
- async localFile(relative) {
82
- const file = await localPath(this.config.localRoot, relative);
186
+ async readRemote(client, relative) {
187
+ const entry = await this.#remoteEntry(client, relative);
188
+ return entry ? this.#readRemote(client, relative, entry) : null;
189
+ }
190
+
191
+ async #openLocal(relative) {
192
+ const file = await localPath(this.config.localRoot, relative, this.config.extra);
83
193
  const stat = await fs.stat(file).catch(error => {
84
194
  if (error.code === 'ENOENT') return null;
85
195
  throw error;
86
196
  });
87
- if (!stat) return { file, data: null };
197
+ if (!stat) return { file, handle: null };
88
198
  if (!stat.isFile()) throw new UserError('Local path is not a regular file.');
89
199
  if (stat.size > this.config.maxBytes) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
90
- const data = await fs.readFile(file);
91
- if (data.length > this.config.maxBytes) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
92
- return { file, data };
200
+ return { file, handle: await fs.open(file, 'r'), mode: stat.mode & 0o777 };
201
+ }
202
+
203
+ async *#localChunks(handle, { reuseBuffer = false } = {}) {
204
+ let remaining = this.config.maxBytes;
205
+ const chunkBytes = reuseBuffer ? LOCAL_HASH_CHUNK_BYTES : CHUNK_BYTES;
206
+ const scratch = reuseBuffer ? Buffer.allocUnsafe(Math.min(chunkBytes, remaining + 1)) : null;
207
+ for (;;) {
208
+ const length = Math.min(chunkBytes, remaining + 1);
209
+ const chunk = scratch ?? Buffer.allocUnsafe(length);
210
+ const { bytesRead } = await handle.read(chunk, 0, length);
211
+ if (bytesRead === 0) return;
212
+ if (bytesRead > remaining) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
213
+ remaining -= bytesRead;
214
+ yield chunk.subarray(0, bytesRead);
215
+ }
216
+ }
217
+
218
+ async localFile(relative) {
219
+ const { file, handle, mode } = await this.#openLocal(relative);
220
+ if (!handle) return { file, sha256: null };
221
+ const hash = createHash('sha256');
222
+ let bytes = 0;
223
+ try {
224
+ for await (const chunk of this.#localChunks(handle, { reuseBuffer: true })) {
225
+ hash.update(chunk);
226
+ bytes += chunk.length;
227
+ }
228
+ } finally {
229
+ await handle.close();
230
+ }
231
+ return { file, sha256: hash.digest('hex'), bytes, mode };
93
232
  }
94
233
 
95
234
  async download(relative, expectedLocalSha256) {
96
235
  relative = safePath(relative, this.config.extra);
97
- return this.withClient(async client => {
98
- const remote = await this.readRemote(client, relative);
99
- if (!remote) throw new UserError('Remote file does not exist.');
236
+ return this.#withWrite(() => this.withClient(async client => {
237
+ const entry = await this.#remoteEntry(client, relative);
238
+ if (!entry) throw new UserError('Remote file does not exist.');
100
239
  const local = await this.localFile(relative);
101
- const remoteSha256 = sha256(remote);
102
- const localSha256 = local.data === null ? null : sha256(local.data);
103
- if (localSha256 === remoteSha256) return { path: relative, status: 'unchanged', sha256: remoteSha256, bytes: remote.length };
104
- if (localSha256 !== null && expectedLocalSha256 !== localSha256) {
105
- throw new UserError(`Local file differs. Its SHA-256 is ${localSha256}; supply expectedLocalSha256 to replace it.`);
240
+ if (local.sha256 !== null && expectedLocalSha256 !== local.sha256) {
241
+ const remote = await this.#readRemote(client, relative, entry);
242
+ const latest = await this.localFile(relative);
243
+ if (latest.sha256 === remote.sha256) return { path: relative, status: 'unchanged', ...remote };
244
+ if (latest.sha256 === null) throw new UserError('Local file changed during download; retry after reviewing it.');
245
+ throw new UserError(`Local file differs. Its SHA-256 is ${latest.sha256}; supply expectedLocalSha256 to replace it.`);
106
246
  }
107
247
  await fs.mkdir(path.dirname(local.file), { recursive: true });
108
- await localPath(this.config.localRoot, relative);
109
- const temp = `${local.file}.${randomUUID()}.tmp`;
248
+ await localPath(this.config.localRoot, relative, this.config.extra);
249
+ const temp = path.join(path.dirname(local.file), `.mcp-download-${randomUUID()}.tmp`);
250
+ const handle = await fs.open(temp, 'wx', 0o600);
251
+ let unchanged;
110
252
  try {
111
- await fs.writeFile(temp, remote, { flag: 'wx' });
253
+ let remote;
254
+ try { remote = await this.#readRemote(client, relative, entry, handle); }
255
+ finally { await handle.close(); }
112
256
  const latest = await this.localFile(relative);
113
- if ((latest.data === null ? null : sha256(latest.data)) !== localSha256) {
114
- throw new UserError('Local file changed during download; retry after reviewing it.');
257
+ if (latest.sha256 === remote.sha256) {
258
+ unchanged = { path: relative, status: 'unchanged', ...remote };
259
+ } else {
260
+ if (latest.sha256 !== local.sha256) {
261
+ throw new UserError('Local file changed during download; retry after reviewing it.');
262
+ }
263
+ if (latest.mode !== undefined && process.platform !== 'win32') await fs.chmod(temp, latest.mode);
264
+ await fs.rename(temp, local.file);
265
+ return { path: relative, status: 'downloaded', ...remote };
115
266
  }
116
- await fs.rename(temp, local.file);
117
- } finally {
118
- await fs.rm(temp, { force: true });
267
+ } catch (error) {
268
+ try { await fs.rm(temp, { force: true }); }
269
+ catch { throw new UserError(`Download failed and temporary local file may remain at ${path.basename(temp)}.`); }
270
+ throw error;
119
271
  }
120
- return { path: relative, status: 'downloaded', sha256: remoteSha256, bytes: remote.length };
121
- });
272
+ // The local file already matches. A leftover copy does not change that
273
+ // result, so report it instead of failing the call.
274
+ try { await fs.rm(temp, { force: true }); }
275
+ catch { return { ...unchanged, warning: `Temporary local file may remain at ${path.basename(temp)}; remove it manually.` }; }
276
+ return unchanged;
277
+ }));
122
278
  }
123
279
 
124
280
  async previewUpload(relative) {
125
281
  relative = safePath(relative, this.config.extra);
126
282
  const local = await this.localFile(relative);
127
- if (!local.data) throw new UserError('Local file does not exist.');
283
+ if (local.sha256 === null) throw new UserError('Local file does not exist.');
128
284
  return this.withClient(async client => {
129
285
  const remote = await this.readRemote(client, relative);
130
- const localSha256 = sha256(local.data);
131
- const remoteSha256 = remote === null ? null : sha256(remote);
286
+ const localSha256 = local.sha256;
287
+ const remoteSha256 = remote?.sha256 ?? null;
132
288
  const changed = localSha256 !== remoteSha256;
133
289
  const token = changed ? randomUUID() : null;
134
290
  if (token) {
135
291
  if (this.previews.size >= 100) this.previews.delete(this.previews.keys().next().value);
136
- this.previews.set(token, { relative, localSha256, remoteSha256, expires: Date.now() + 10 * 60_000 });
292
+ this.previews.set(token, { relative, localSha256, remoteSha256, remoteBytes: remote?.bytes ?? null, expires: Date.now() + 10 * 60_000 });
137
293
  }
138
- return { path: relative, changed, localSha256, remoteSha256, localBytes: local.data.length, remoteBytes: remote?.length ?? null, uploadToken: token };
294
+ return { path: relative, changed, localSha256, remoteSha256, localBytes: local.bytes, remoteBytes: remote?.bytes ?? null, uploadToken: token };
139
295
  });
140
296
  }
141
297
 
142
298
  async upload(relative, token) {
143
299
  relative = safePath(relative, this.config.extra);
300
+ return this.#withWrite(() => this.#commitUpload(relative, token));
301
+ }
302
+
303
+ async #commitUpload(relative, token) {
144
304
  const preview = this.previews.get(token);
145
305
  if (!preview || preview.relative !== relative || preview.expires < Date.now()) throw new UserError('Run remote_preview_upload again; its token is missing or expired.');
146
306
  this.previews.delete(token);
147
307
  const local = await this.localFile(relative);
148
- if (!local.data || sha256(local.data) !== preview.localSha256) throw new UserError('Local file changed since the preview.');
308
+ if (local.sha256 !== preview.localSha256) throw new UserError('Local file changed since the preview.');
149
309
  return this.withClient(async client => {
150
- const remote = await this.readRemote(client, relative);
151
- if ((remote === null ? null : sha256(remote)) !== preview.remoteSha256) throw new UserError('Remote file changed since the preview.');
310
+ // A listing catches a remote file that appeared, disappeared, or changed
311
+ // size before any bytes are sent. A same-size change is caught by the
312
+ // full comparison right before the rename.
313
+ const current = await this.#remoteEntry(client, relative);
314
+ if ((current === null) !== (preview.remoteSha256 === null) || (current && Number.isSafeInteger(current.size) && current.size !== preview.remoteBytes)) {
315
+ throw new UserError('Remote file changed since the preview.');
316
+ }
152
317
  const parent = path.posix.dirname(relative);
153
318
  const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
154
- let committed = false;
155
- let stageAttempted = false;
156
- let warning = null;
319
+ let backup = null;
320
+ let stagedFile;
157
321
  try {
158
- stageAttempted = true;
159
- await client.uploadFrom(local.data, staged);
160
- const stagedData = await this.readRemote(client, staged);
161
- if (!stagedData || sha256(stagedData) !== preview.localSha256) throw new UserError('Staged upload verification failed.');
322
+ const { handle } = await this.#openLocal(relative);
323
+ if (!handle) throw new UserError('Local file changed during upload.');
324
+ const source = Readable.from(this.#localChunks(handle), { objectMode: false });
325
+ try { await client.uploadFrom(source, staged); }
326
+ finally {
327
+ source.destroy();
328
+ await handle.close();
329
+ }
330
+ stagedFile = await this.readRemote(client, staged);
331
+ if (stagedFile?.sha256 !== preview.localSha256) throw new UserError('Staged upload verification failed.');
162
332
  const latestLocal = await this.localFile(relative);
163
- if (!latestLocal.data || sha256(latestLocal.data) !== preview.localSha256) throw new UserError('Local file changed during upload.');
333
+ if (latestLocal.sha256 !== preview.localSha256) throw new UserError('Local file changed during upload.');
164
334
  const latestRemote = await this.readRemote(client, relative);
165
- if ((latestRemote === null ? null : sha256(latestRemote)) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
166
- warning = await client.rename(staged, relative, latestRemote !== null);
167
- committed = true;
168
- } finally {
169
- if (!committed && stageAttempted) {
170
- try {
171
- if (await this.entry(client, staged)) await client.remove(staged);
172
- }
173
- catch { throw new UserError(`Upload failed and temporary remote file may remain at ${staged}.`); }
335
+ if ((latestRemote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
336
+ backup = await client.rename(staged, relative, latestRemote !== null);
337
+ } catch (error) {
338
+ try {
339
+ if (await this.entry(client, staged)) await client.remove(staged);
340
+ } catch {
341
+ const reason = error instanceof UserError ? error.message : 'Upload failed.';
342
+ throw new UserError(`${reason} Temporary remote file may remain at ${staged}.`);
174
343
  }
344
+ throw error;
175
345
  }
346
+ const recovery = backup ? ` The previous version remains at ${backup}.` : '';
347
+ // The staged bytes were verified by hash, and a rename does not change
348
+ // them. Confirm the rename put a file of that size in place; another
349
+ // full read could not exclude a writer that changes it afterwards.
176
350
  let uploaded;
177
- try { uploaded = await this.readRemote(client, relative); }
178
- catch { throw new UserError('Upload rename completed, but verification failed; inspect the remote file before retrying.'); }
179
- if (!uploaded || sha256(uploaded) !== preview.localSha256) throw new UserError('Upload verification failed; inspect the remote file before retrying.');
180
- return { path: relative, status: 'uploaded', sha256: preview.localSha256, bytes: local.data.length, ...(warning ? { warning } : {}) };
351
+ try { uploaded = await this.entry(client, relative); }
352
+ catch { throw new UserError(`Upload rename completed, but verification failed; inspect the remote file before retrying.${recovery}`); }
353
+ if (uploaded?.type !== FileType.File || (Number.isSafeInteger(uploaded.size) && uploaded.size !== stagedFile.bytes)) {
354
+ throw new UserError(`Upload verification failed; inspect the remote file before retrying.${recovery}`);
355
+ }
356
+ let warning;
357
+ if (backup) {
358
+ try { await client.remove(backup); }
359
+ catch { warning = `Upload succeeded, but the previous version remains at ${backup}; remove it manually.`; }
360
+ }
361
+ return { path: relative, status: 'uploaded', ...stagedFile, ...(warning ? { warning } : {}) };
181
362
  });
182
363
  }
183
364
  }