@pyrokine/mcp-ssh 2.3.2 → 2.4.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.
@@ -4,12 +4,14 @@
4
4
  * ssh_upload, ssh_download, ssh_read_file, ssh_write_file,
5
5
  * ssh_list_dir, ssh_file_info, ssh_mkdir, ssh_sync
6
6
  */
7
- import { createHash } from 'crypto';
7
+ import { createHash, randomBytes } from 'crypto';
8
8
  import * as fs from 'fs';
9
9
  import * as path from 'path';
10
10
  import { z } from 'zod';
11
+ import { buildRemoteDirectoryManifestCommand, compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, parseRemoteDirectoryManifest, } from '../directory-verification.js';
11
12
  import * as fileOps from '../file-ops.js';
12
13
  import { sessionManager } from '../session-manager.js';
14
+ import { buildTransferOutcome } from '../transfer-outcome.js';
13
15
  import { escapeShellArg, formatError, formatResult } from './utils.js';
14
16
  // ========== Schemas ==========
15
17
  const uploadSchema = z.object({
@@ -75,11 +77,75 @@ const syncSchema = z.object({
75
77
  .boolean()
76
78
  .optional()
77
79
  .describe('upload 时是否跟随本地 symlink,默认 false(跳过 symlink 并 warn,避免上传链接目标内容)'),
80
+ preflightTimeout: z.number().int().positive().max(60000).optional().describe('传输能力预检超时,默认 10000ms'),
81
+ connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
82
+ operationTimeout: z.number().int().positive().max(3600000).optional().describe('同步操作超时,默认 600000ms'),
78
83
  verifyOwner: z.union([z.string(), z.number()]).optional().describe('upload 后校验远端 owner(用户名或 uid)'),
79
84
  verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644 或 -rw-r--r--'),
85
+ verify: z
86
+ .object({
87
+ count: z.boolean().optional().describe('校验目录条目数'),
88
+ sha256: z.boolean().optional().describe('校验 SHA-256 root manifest'),
89
+ owner: z.boolean().optional().describe('逐项校验 owner'),
90
+ mode: z.boolean().optional().describe('逐项校验 mode'),
91
+ deletions: z.boolean().optional().describe('校验请求删除后没有额外条目'),
92
+ staleFiles: z.boolean().optional().describe('校验没有旧文件残留'),
93
+ maxEntries: z
94
+ .number()
95
+ .int()
96
+ .positive()
97
+ .max(DIRECTORY_VERIFY_MAX_ENTRIES)
98
+ .optional()
99
+ .describe('目录校验最大条目数,默认 10000,最大 50000'),
100
+ maxFileBytes: z
101
+ .number()
102
+ .int()
103
+ .positive()
104
+ .max(DIRECTORY_VERIFY_MAX_FILE_BYTES)
105
+ .optional()
106
+ .describe('SHA-256 校验的单文件字节上限,默认 256MB,最大 4GB'),
107
+ maxTotalBytes: z
108
+ .number()
109
+ .int()
110
+ .positive()
111
+ .max(DIRECTORY_VERIFY_MAX_TOTAL_BYTES)
112
+ .optional()
113
+ .describe('SHA-256 校验的总字节上限,默认 1GB,最大 16GB'),
114
+ })
115
+ .optional()
116
+ .describe('有界目录校验;未传时不执行额外远端扫描'),
80
117
  });
81
118
  // ========== Handlers ==========
82
119
  const LARGE_UPLOAD_THRESHOLD = 100 * 1024 * 1024;
120
+ class VerificationStageError extends Error {
121
+ failureStage;
122
+ retryable;
123
+ details;
124
+ constructor(failureStage, message, retryable, details) {
125
+ super(message);
126
+ this.failureStage = failureStage;
127
+ this.retryable = retryable;
128
+ this.details = details;
129
+ this.name = 'VerificationStageError';
130
+ }
131
+ }
132
+ function verificationErrorDetails(error) {
133
+ if (error instanceof VerificationStageError) {
134
+ return {
135
+ kind: 'error',
136
+ failureStage: error.failureStage,
137
+ error: error.message,
138
+ retryable: error.retryable,
139
+ ...error.details,
140
+ };
141
+ }
142
+ return {
143
+ kind: 'error',
144
+ failureStage: 'remote_probe',
145
+ error: error instanceof Error ? error.message : String(error),
146
+ retryable: false,
147
+ };
148
+ }
83
149
  function summarizeLocalPathProbe(probe) {
84
150
  const summary = {
85
151
  exists: probe.exists,
@@ -115,23 +181,16 @@ function uploadPathError(code, message, diagnostics) {
115
181
  }
116
182
  async function probeRemoteParent(alias, remotePath) {
117
183
  const parent = path.posix.dirname(remotePath);
118
- const escapedParent = escapeShellArg(parent);
119
- const command = [
120
- `if [ -d ${escapedParent} ]; then`,
121
- `if [ -w ${escapedParent} ]; then printf writable; else printf not-writable; fi;`,
122
- 'else printf missing; fi',
123
- ].join(' ');
124
184
  try {
125
- const result = await sessionManager.exec(alias, command, {
126
- timeout: 10000,
127
- useLoginUser: true,
128
- maxOutputSize: 4096,
129
- });
130
- const status = result.stdout.trim();
131
- return { exists: status !== 'missing', writable: status === 'writable' };
185
+ const result = await probeRemoteFile(alias, parent);
186
+ return {
187
+ exists: result.exists,
188
+ isDirectory: result.exists ? result.isDirectory : false,
189
+ probeMethod: 'sftp',
190
+ };
132
191
  }
133
192
  catch (error) {
134
- return { error: error instanceof Error ? error.message : String(error) };
193
+ return { error: error instanceof Error ? error.message : String(error), probeMethod: 'sftp' };
135
194
  }
136
195
  }
137
196
  function hashLocalFileMd5(filePath) {
@@ -143,14 +202,59 @@ function hashLocalFileMd5(filePath) {
143
202
  stream.on('end', () => resolve(hash.digest('hex')));
144
203
  });
145
204
  }
205
+ function boundedDiagnostic(value, maxBytes = 2048) {
206
+ const buffer = Buffer.from(value, 'utf8');
207
+ if (buffer.length <= maxBytes) {
208
+ return { text: value, bytes: buffer.length, truncated: false };
209
+ }
210
+ return {
211
+ text: buffer.subarray(0, maxBytes).toString('utf8'),
212
+ bytes: buffer.length,
213
+ truncated: true,
214
+ };
215
+ }
216
+ function commandFailureDetails(result) {
217
+ const stderr = boundedDiagnostic(result.stderr);
218
+ const stdout = boundedDiagnostic(result.stdout);
219
+ return {
220
+ exitCode: result.exitCode,
221
+ failureKind: result.failureKind,
222
+ timedOut: result.timedOut,
223
+ stdout: stdout.text || undefined,
224
+ stdoutBytes: result.stdoutBytes ?? stdout.bytes,
225
+ stdoutTruncated: result.stdoutTruncated || stdout.truncated || undefined,
226
+ stderr: stderr.text || undefined,
227
+ stderrBytes: result.stderrBytes ?? stderr.bytes,
228
+ stderrTruncated: result.stderrTruncated || stderr.truncated || undefined,
229
+ };
230
+ }
146
231
  async function hashRemoteFileMd5(alias, remotePath) {
147
- const result = await sessionManager.exec(alias, `md5sum ${escapeShellArg(remotePath)} | awk '{print $1}'`, {
148
- timeout: 30000,
232
+ try {
233
+ return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5');
234
+ }
235
+ catch (error) {
236
+ throw new VerificationStageError('remote_probe', `Remote SFTP MD5 read failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'md5', probeMethod: 'sftp' });
237
+ }
238
+ }
239
+ async function resolveExpectedOwnerId(alias, owner) {
240
+ const ownerText = String(owner);
241
+ if (/^\d+$/.test(ownerText)) {
242
+ return ownerText;
243
+ }
244
+ const result = await sessionManager.exec(alias, `id -u ${escapeShellArg(ownerText)}`, {
245
+ timeout: 10000,
149
246
  useLoginUser: true,
150
247
  maxOutputSize: 4096,
151
248
  });
152
- const digest = result.stdout.trim().split(/\s+/)[0];
153
- return /^[a-fA-F0-9]{32}$/.test(digest) ? digest : undefined;
249
+ const ownerId = result.stdout.trim();
250
+ if (!result.success || !/^\d+$/.test(ownerId)) {
251
+ const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.exitCode}`;
252
+ throw new VerificationStageError('remote_probe', `Remote owner lookup failed: ${detail}`, true, {
253
+ operation: 'owner_lookup',
254
+ ...commandFailureDetails(result),
255
+ });
256
+ }
257
+ return ownerId;
154
258
  }
155
259
  function permissionStringToOctal(permissions) {
156
260
  const bits = permissions.slice(-9);
@@ -172,59 +276,58 @@ function permissionStringToOctal(permissions) {
172
276
  });
173
277
  return `0${values.join('')}`;
174
278
  }
175
- async function probeRemoteFile(alias, remotePath) {
176
- const escapedRemotePath = escapeShellArg(remotePath);
177
- const command = [
178
- `if [ -e ${escapedRemotePath} ]; then`,
179
- `stat -c '%U\t%u\t%G\t%g\t%a\t%s\t%Y\t%F' ${escapedRemotePath};`,
180
- 'else printf missing; fi',
181
- ].join(' ');
182
- try {
183
- const result = await sessionManager.exec(alias, command, {
184
- timeout: 10000,
185
- useLoginUser: true,
186
- maxOutputSize: 4096,
187
- });
188
- if (result.stdout.trim() === 'missing') {
189
- return { exists: false, remotePath };
190
- }
191
- const [ownerName, ownerId, groupName, groupId, mode, size, mtimeSeconds, fileType] = result.stdout
192
- .trim()
193
- .split('\t');
194
- return {
195
- exists: true,
196
- remotePath,
197
- ownerName,
198
- ownerId: Number(ownerId),
199
- groupName,
200
- groupId: Number(groupId),
201
- mode: mode ? `0${mode}` : undefined,
202
- size: Number(size),
203
- mtimeMs: Number(mtimeSeconds) * 1000,
204
- fileType,
205
- isDirectory: fileType === 'directory',
206
- isFile: fileType?.startsWith('regular ') ?? false,
207
- };
279
+ function isRemoteMissingError(error) {
280
+ if (!error || typeof error !== 'object') {
281
+ return false;
208
282
  }
209
- catch {
283
+ const code = 'code' in error ? error.code : undefined;
284
+ const message = error instanceof Error ? error.message : String(error);
285
+ return code === 2 || code === 'ENOENT' || /no such file|not found/i.test(message);
286
+ }
287
+ async function probeRemoteFile(alias, remotePath, _timeout = 10000) {
288
+ try {
210
289
  const info = await fileOps.getFileInfo(alias, remotePath);
290
+ const mode = permissionStringToOctal(info.permissions);
291
+ if (!mode) {
292
+ throw new VerificationStageError('remote_probe', 'Remote SFTP stat returned invalid mode metadata', false, {
293
+ operation: 'stat',
294
+ probeMethod: 'sftp',
295
+ });
296
+ }
211
297
  return {
212
298
  exists: true,
213
299
  remotePath,
300
+ probeMethod: 'sftp',
301
+ ownerName: undefined,
214
302
  ownerId: info.owner,
303
+ groupName: undefined,
215
304
  groupId: info.group,
216
- mode: permissionStringToOctal(info.permissions),
217
- permissions: info.permissions,
305
+ mode,
218
306
  size: info.size,
219
307
  mtimeMs: info.mtime.getTime(),
308
+ fileType: info.isDirectory
309
+ ? 'directory'
310
+ : info.isFile
311
+ ? 'regular file'
312
+ : info.isSymlink
313
+ ? 'symbolic link'
314
+ : 'other',
220
315
  isDirectory: info.isDirectory,
221
316
  isFile: info.isFile,
222
- isSymlink: info.isSymlink,
223
317
  };
224
318
  }
319
+ catch (error) {
320
+ if (isRemoteMissingError(error)) {
321
+ return { exists: false, remotePath, probeMethod: 'sftp' };
322
+ }
323
+ if (error instanceof VerificationStageError) {
324
+ throw error;
325
+ }
326
+ throw new VerificationStageError('remote_probe', `Remote SFTP stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod: 'sftp' });
327
+ }
225
328
  }
226
- async function buildUploadVerification(args, local) {
227
- const remote = await probeRemoteFile(args.alias, args.remotePath);
329
+ async function buildUploadVerification(args, local, verificationRemotePath = args.remotePath) {
330
+ const remote = await probeRemoteFile(args.alias, verificationRemotePath);
228
331
  const checks = {};
229
332
  if (args.verifySize) {
230
333
  checks.size = local.exists && remote.exists ? local.size === remote.size : false;
@@ -233,27 +336,46 @@ async function buildUploadVerification(args, local) {
233
336
  const mtimeDelta = local.exists && remote.exists ? Math.abs((local.mtimeMs ?? 0) - (remote.mtimeMs ?? 0)) : undefined;
234
337
  checks.mtime = mtimeDelta !== undefined ? mtimeDelta < 2000 : false;
235
338
  }
236
- if (args.verifyMode && remote.exists) {
339
+ if (args.verifyMode) {
237
340
  const expectedMode = normalizeExpectedMode(args.verifyMode);
238
- checks.mode = expectedMode !== undefined && remote.mode === expectedMode;
341
+ checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
239
342
  }
240
- if (args.verifyOwner !== undefined && remote.exists) {
241
- const expectedOwner = String(args.verifyOwner);
242
- checks.owner = String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner;
343
+ if (args.verifyOwner !== undefined) {
344
+ const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
345
+ checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
243
346
  }
244
347
  if (args.verifyMd5 && local.exists) {
245
348
  const [localMd5, remoteMd5] = await Promise.all([
246
349
  hashLocalFileMd5(local.resolvedPath),
247
- hashRemoteFileMd5(args.alias, args.remotePath),
350
+ hashRemoteFileMd5(args.alias, verificationRemotePath),
248
351
  ]);
249
352
  checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
250
353
  return {
354
+ expected: {
355
+ owner: args.verifyOwner,
356
+ mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
357
+ size: args.verifySize && local.exists ? local.size : undefined,
358
+ mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
359
+ md5: localMd5,
360
+ },
361
+ actual: { ...remote, md5: remoteMd5 },
251
362
  local: { ...summarizeLocalPathProbe(local), md5: localMd5 },
252
363
  remote: { ...remote, md5: remoteMd5 },
253
364
  checks,
254
365
  };
255
366
  }
256
- return { local: summarizeLocalPathProbe(local), remote, checks };
367
+ return {
368
+ expected: {
369
+ owner: args.verifyOwner,
370
+ mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
371
+ size: args.verifySize && local.exists ? local.size : undefined,
372
+ mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
373
+ },
374
+ actual: remote,
375
+ local: summarizeLocalPathProbe(local),
376
+ remote,
377
+ checks,
378
+ };
257
379
  }
258
380
  function normalizeExpectedMode(mode) {
259
381
  const trimmed = mode.trim();
@@ -262,11 +384,11 @@ function normalizeExpectedMode(mode) {
262
384
  }
263
385
  return permissionStringToOctal(trimmed);
264
386
  }
265
- function buildSyncVerificationChecks(args, remote) {
387
+ async function buildSyncVerificationChecks(args, remote) {
266
388
  const checks = {};
267
389
  if (args.verifyOwner !== undefined) {
268
- const expectedOwner = String(args.verifyOwner);
269
- checks.owner = remote.exists && (String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner);
390
+ const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
391
+ checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
270
392
  }
271
393
  if (args.verifyMode !== undefined) {
272
394
  const expectedMode = normalizeExpectedMode(args.verifyMode);
@@ -274,8 +396,8 @@ function buildSyncVerificationChecks(args, remote) {
274
396
  }
275
397
  return checks;
276
398
  }
277
- async function resolveSyncUploadVerificationPath(args, local) {
278
- const requestedRemote = await probeRemoteFile(args.alias, args.remotePath);
399
+ async function resolveSyncUploadVerificationPath(args, local, timeout) {
400
+ const requestedRemote = await probeRemoteFile(args.alias, args.remotePath, timeout);
279
401
  if (requestedRemote.exists && requestedRemote.isDirectory) {
280
402
  return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
281
403
  }
@@ -284,7 +406,7 @@ async function resolveSyncUploadVerificationPath(args, local) {
284
406
  }
285
407
  return args.remotePath;
286
408
  }
287
- async function buildSyncUploadVerification(args, local) {
409
+ async function buildSyncUploadVerification(args, local, timeout) {
288
410
  if (args.verifyOwner === undefined && args.verifyMode === undefined) {
289
411
  return undefined;
290
412
  }
@@ -300,12 +422,15 @@ async function buildSyncUploadVerification(args, local) {
300
422
  kind: 'owner_mode',
301
423
  skipped: true,
302
424
  reason: 'verifyOwner/verifyMode 只对单文件 upload 做后置校验,目录同步不会递归扫描远端权限',
303
- suggestion: '如需目录权限校验,请同步完成后对目标文件调用 ssh_file_info 或用 ssh_exec 执行显式检查',
425
+ suggestion: '目录权限校验请使用 verify.owner 或 verify.mode',
304
426
  };
305
427
  }
306
- const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local);
307
- const remote = await probeRemoteFile(args.alias, verificationRemotePath);
308
- const checks = buildSyncVerificationChecks(args, remote);
428
+ if (timeout <= 0) {
429
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before owner/mode verification started', true);
430
+ }
431
+ const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, timeout);
432
+ const remote = await probeRemoteFile(args.alias, verificationRemotePath, timeout);
433
+ const checks = await buildSyncVerificationChecks(args, remote);
309
434
  const matched = Object.values(checks).every(Boolean);
310
435
  return {
311
436
  kind: 'owner_mode',
@@ -323,41 +448,178 @@ async function buildSyncUploadVerification(args, local) {
323
448
  : '同步已完成,但远端 owner/mode 与期望不一致;工具不会自动 chown/chmod,请按需用 ssh_exec 显式处理权限',
324
449
  };
325
450
  }
326
- function mergeSyncVerification(existing, ownerMode) {
327
- if (!ownerMode) {
328
- return existing;
451
+ async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, timeout) {
452
+ const remoteCommand = buildRemoteDirectoryManifestCommand(remotePath, request, exclude, followSymlinks);
453
+ let remoteResult;
454
+ try {
455
+ remoteResult = await sessionManager.exec(alias, remoteCommand, {
456
+ timeout,
457
+ useLoginUser: true,
458
+ maxOutputSize: 16 * 1024 * 1024,
459
+ });
329
460
  }
330
- if (!existing) {
331
- return ownerMode;
461
+ catch (error) {
462
+ const details = error && typeof error === 'object' && 'details' in error
463
+ ? error.details
464
+ : undefined;
465
+ throw new VerificationStageError('remote_manifest_command', boundedDiagnostic(error instanceof Error ? error.message : String(error)).text, true, { timeout, ...details });
332
466
  }
467
+ if (!remoteResult.success) {
468
+ const detail = boundedDiagnostic(remoteResult.stderr || remoteResult.stdout || 'remote directory manifest failed');
469
+ throw new VerificationStageError('remote_manifest_command', detail.text, remoteResult.failureKind !== 'remote_command', {
470
+ ...commandFailureDetails(remoteResult),
471
+ diagnosticBytes: detail.bytes,
472
+ diagnosticTruncated: detail.truncated || undefined,
473
+ });
474
+ }
475
+ if (remoteResult.stdoutTruncated) {
476
+ throw new VerificationStageError('remote_manifest_output', 'remote directory manifest output exceeded the 16MB response limit', false, { maxOutputSize: 16 * 1024 * 1024 });
477
+ }
478
+ try {
479
+ return parseRemoteDirectoryManifest(remoteResult.stdout);
480
+ }
481
+ catch (error) {
482
+ throw new VerificationStageError('remote_manifest_parse', error instanceof Error ? error.message : String(error), false);
483
+ }
484
+ }
485
+ function directoryVerificationFollowsSymlinks(args) {
486
+ return args.direction === 'upload' && args.followSymlinks === true;
487
+ }
488
+ function deletionManifestRequest(request) {
333
489
  return {
334
- ...existing,
490
+ ...request,
491
+ count: false,
492
+ sha256: false,
493
+ owner: false,
494
+ mode: false,
495
+ deletions: false,
496
+ staleFiles: false,
497
+ };
498
+ }
499
+ async function captureDeletionBaseline(args, remainingTimeout) {
500
+ if (!args.verify?.deletions || args.dryRun) {
501
+ return undefined;
502
+ }
503
+ const request = deletionManifestRequest(args.verify);
504
+ if (args.direction === 'upload') {
505
+ const probeTimeout = remainingTimeout();
506
+ if (probeTimeout <= 0) {
507
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline capture started', true);
508
+ }
509
+ const remote = await probeRemoteFile(args.alias, args.remotePath, probeTimeout);
510
+ if (!remote.exists) {
511
+ return createEmptyDirectoryManifest();
512
+ }
513
+ if (!remote.isDirectory) {
514
+ throw new VerificationStageError('remote_probe', 'deletion verification requires the remote destination to be a directory', false, { remotePath: args.remotePath, fileType: remote.fileType });
515
+ }
516
+ const manifestTimeout = remainingTimeout();
517
+ if (manifestTimeout <= 0) {
518
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline manifest started', true);
519
+ }
520
+ return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), manifestTimeout);
521
+ }
522
+ const local = fileOps.probeLocalPath(args.localPath);
523
+ if (!local.exists) {
524
+ return createEmptyDirectoryManifest();
525
+ }
526
+ if (!local.isDirectory) {
527
+ throw new VerificationStageError('local_manifest', 'deletion verification requires the local destination to be a directory', false, { localPath: args.localPath });
528
+ }
529
+ try {
530
+ return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
531
+ }
532
+ catch (error) {
533
+ throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
534
+ }
535
+ }
536
+ async function buildDirectorySyncVerification(args, local, timeout, deletionBaseline) {
537
+ if (!args.verify) {
538
+ return undefined;
539
+ }
540
+ if (args.dryRun) {
541
+ return { kind: 'directory', skipped: true, reason: 'directory verification is not executed during dryRun' };
542
+ }
543
+ if (!local.exists || !local.isDirectory) {
544
+ return { kind: 'directory', skipped: true, reason: 'bounded directory verification requires a local directory' };
545
+ }
546
+ if (timeout <= 0) {
547
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before directory verification started', true);
548
+ }
549
+ const request = args.verify;
550
+ const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), timeout);
551
+ let localManifest;
552
+ try {
553
+ localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
554
+ }
555
+ catch (error) {
556
+ throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
557
+ }
558
+ return args.direction === 'upload'
559
+ ? compareDirectoryManifests(localManifest, remoteManifest, request, deletionBaseline)
560
+ : compareDirectoryManifests(remoteManifest, localManifest, request, deletionBaseline);
561
+ }
562
+ function mergeSyncVerification(existing, ownerMode, directory) {
563
+ const parts = [existing, ownerMode, directory].filter((part) => Boolean(part));
564
+ if (parts.length === 0) {
565
+ return undefined;
566
+ }
567
+ if (parts.length === 1) {
568
+ return parts[0];
569
+ }
570
+ return {
571
+ transport: existing,
335
572
  ownerMode,
573
+ directory,
336
574
  };
337
575
  }
338
576
  async function cleanupRemotePath(alias, remotePath) {
339
- await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
340
- timeout: 10000,
341
- useLoginUser: true,
342
- maxOutputSize: 4096,
343
- });
577
+ try {
578
+ await fileOps.removeRemoteFile(alias, remotePath);
579
+ }
580
+ catch (error) {
581
+ throw new Error(`Temporary remote file cleanup failed: ${error instanceof Error ? error.message : String(error)}`, {
582
+ cause: error,
583
+ });
584
+ }
344
585
  }
345
- async function applyRemoteMode(alias, remotePath, mode) {
346
- const result = await sessionManager.exec(alias, `chmod ${escapeShellArg(mode)} ${escapeShellArg(remotePath)}`, {
347
- timeout: 10000,
348
- useLoginUser: true,
349
- maxOutputSize: 4096,
350
- });
351
- if (!result.success) {
352
- throw new Error(result.stderr || result.stdout || `chmod failed with exit code ${result.exitCode}`);
586
+ export function createAtomicUploadPath(remotePath) {
587
+ return `${remotePath}.mcp-tmp-${process.pid}-${randomBytes(12).toString('hex')}`;
588
+ }
589
+ function uploadPathDetails(args, verificationRemotePath, verification) {
590
+ return {
591
+ finalRemotePath: args.remotePath,
592
+ verifiedRemotePath: verification ? verificationRemotePath : undefined,
593
+ verifiedTempRemotePath: verification && args.atomic ? verificationRemotePath : undefined,
594
+ };
595
+ }
596
+ function addUploadVerificationPaths(verification, args, verificationRemotePath) {
597
+ if (!verification) {
598
+ return undefined;
353
599
  }
600
+ return {
601
+ ...verification,
602
+ ...uploadPathDetails(args, verificationRemotePath, verification),
603
+ };
354
604
  }
355
605
  async function handleUpload(args) {
356
- const local = fileOps.probeLocalPath(args.localPath);
357
- if (local.exists && local.isDirectory) {
358
- return uploadPathError('UPLOAD_PATH_IS_DIRECTORY', 'localPath is a directory', {
359
- local: summarizeLocalPathProbe(local),
360
- suggestion: '使用 ssh_sync 上传目录,或把 localPath 指向具体文件',
606
+ let local;
607
+ try {
608
+ fileOps.validateUploadFileSource(args.localPath);
609
+ local = fileOps.probeLocalPath(args.localPath);
610
+ }
611
+ catch (error) {
612
+ local = fileOps.probeLocalPath(args.localPath);
613
+ if (local.exists && local.isDirectory) {
614
+ return uploadPathError('UPLOAD_PATH_IS_DIRECTORY', 'localPath is a directory', {
615
+ local: summarizeLocalPathProbe(local),
616
+ suggestion: '使用 ssh_sync 上传目录,或把 localPath 指向具体文件',
617
+ });
618
+ }
619
+ return formatResult({
620
+ success: false,
621
+ error: error instanceof Error ? error.message : String(error),
622
+ diagnostics: { local: summarizeLocalPathProbe(local) },
361
623
  });
362
624
  }
363
625
  const largeFileSuggestion = local.exists && typeof local.size === 'number' && local.size >= LARGE_UPLOAD_THRESHOLD
@@ -372,55 +634,165 @@ async function handleUpload(args) {
372
634
  ].join(', ')
373
635
  : undefined;
374
636
  const remoteParent = await probeRemoteParent(args.alias, args.remotePath);
375
- const tempRemotePath = args.atomic
376
- ? `${args.remotePath}.mcp-tmp-${process.pid}-${Date.now().toString(36)}`
377
- : args.remotePath;
637
+ let remoteBefore;
378
638
  try {
379
- const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath);
380
- if (local.exists && 'mode' in local && typeof local.mode === 'string') {
381
- await applyRemoteMode(args.alias, tempRemotePath, local.mode);
639
+ remoteBefore = await probeRemoteFile(args.alias, args.remotePath);
640
+ }
641
+ catch (error) {
642
+ return formatResult({
643
+ success: false,
644
+ error: error instanceof Error ? error.message : String(error),
645
+ diagnostics: {
646
+ local: summarizeLocalPathProbe(local),
647
+ remoteParent,
648
+ remoteProbe: verificationErrorDetails(error),
649
+ atomic: args.atomic === true,
650
+ },
651
+ });
652
+ }
653
+ const sourceMode = local.exists && 'mode' in local && typeof local.mode === 'string'
654
+ ? Number.parseInt(local.mode, 8) & 0o777
655
+ : undefined;
656
+ const existingMode = remoteBefore.exists && remoteBefore.mode ? Number.parseInt(remoteBefore.mode, 8) & 0o777 : undefined;
657
+ const createMode = args.atomic && existingMode !== undefined ? existingMode : sourceMode;
658
+ const tempRemotePath = args.atomic ? createAtomicUploadPath(args.remotePath) : args.remotePath;
659
+ const verificationRequested = Boolean(args.verifyOwner !== undefined ||
660
+ args.verifyMode !== undefined ||
661
+ args.verifyMd5 ||
662
+ args.verifySize ||
663
+ args.verifyMtime);
664
+ try {
665
+ const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true);
666
+ let verification;
667
+ let verificationError;
668
+ if (verificationRequested) {
669
+ try {
670
+ verification = await buildUploadVerification(args, local, tempRemotePath);
671
+ }
672
+ catch (error) {
673
+ verificationError = error;
674
+ verification = verificationErrorDetails(error);
675
+ }
676
+ }
677
+ verification = addUploadVerificationPaths(verification, args, tempRemotePath);
678
+ const outcome = buildTransferOutcome(uploadResult.success, verificationRequested, verification, verificationError);
679
+ const pathDetails = uploadPathDetails(args, tempRemotePath, verification);
680
+ if (args.atomic && !outcome.success) {
681
+ let cleanupWarning;
682
+ try {
683
+ await cleanupRemotePath(args.alias, tempRemotePath);
684
+ }
685
+ catch (cleanupError) {
686
+ cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
687
+ }
688
+ return formatResult({
689
+ ...uploadResult,
690
+ ...outcome,
691
+ message: `Atomic upload verification failed; existing target preserved: ${args.remotePath}`,
692
+ error: verificationError === undefined
693
+ ? `Atomic upload verification failed: ${args.remotePath}`
694
+ : `Atomic upload verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
695
+ cleanupWarning,
696
+ atomic: true,
697
+ targetReplaced: false,
698
+ ...pathDetails,
699
+ createMode: uploadResult.createMode,
700
+ existingTargetModePreserved: remoteBefore.exists,
701
+ suggestion: largeFileSuggestion,
702
+ recommendedSync,
703
+ diagnostics: {
704
+ local: summarizeLocalPathProbe(local),
705
+ remoteParent,
706
+ atomic: true,
707
+ tempRemotePath,
708
+ },
709
+ verification,
710
+ });
382
711
  }
383
712
  if (args.atomic) {
384
- const rename = await sessionManager.exec(args.alias, `mv -f -- ${escapeShellArg(tempRemotePath)} ${escapeShellArg(args.remotePath)}`, { timeout: 30000, useLoginUser: true, maxOutputSize: 4096 });
385
- if (!rename.success) {
386
- const renameError = rename.stderr || rename.stdout || `atomic rename failed with exit code ${rename.exitCode}`;
387
- await cleanupRemotePath(args.alias, tempRemotePath).catch(() => undefined);
713
+ try {
714
+ await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists);
715
+ }
716
+ catch (error) {
717
+ const renameNotStarted = error instanceof fileOps.RemoteRenameNotStartedError;
718
+ const renameError = error instanceof Error ? error.message : String(error);
719
+ let cleanupWarning;
720
+ try {
721
+ await cleanupRemotePath(args.alias, tempRemotePath);
722
+ }
723
+ catch (cleanupError) {
724
+ cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
725
+ }
388
726
  return formatResult({
389
727
  success: false,
390
- error: renameError,
728
+ transferSuccess: true,
729
+ operationStatus: renameNotStarted ? 'failed' : 'unknown',
730
+ retryable: true,
731
+ error: renameNotStarted
732
+ ? `Atomic SFTP rename request was not sent; target was not replaced: ${renameError}`
733
+ : `Atomic SFTP rename response failed; target replacement state is unknown: ${renameError}`,
734
+ cleanupWarning,
735
+ atomic: true,
736
+ targetReplaced: renameNotStarted ? false : null,
737
+ targetReplacementStatus: renameNotStarted ? 'not_replaced' : 'unknown',
738
+ ...pathDetails,
391
739
  diagnostics: {
392
740
  local: summarizeLocalPathProbe(local),
393
741
  remoteParent,
394
742
  atomic: true,
743
+ tempRemotePath,
395
744
  },
745
+ verification,
396
746
  });
397
747
  }
398
748
  }
399
749
  return formatResult({
400
750
  ...uploadResult,
401
- message: `Uploaded to ${args.remotePath}`,
751
+ ...outcome,
752
+ message: outcome.success
753
+ ? `Uploaded to ${args.remotePath}`
754
+ : `Uploaded but verification failed: ${args.remotePath}`,
755
+ error: verificationError === undefined
756
+ ? undefined
757
+ : `Upload completed, but verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
402
758
  atomic: args.atomic === true,
759
+ targetReplaced: args.atomic ? true : undefined,
760
+ ...pathDetails,
761
+ createMode: uploadResult.createMode,
762
+ existingTargetModePreserved: remoteBefore.exists,
403
763
  suggestion: largeFileSuggestion,
404
764
  recommendedSync,
405
765
  diagnostics: {
406
766
  local: summarizeLocalPathProbe(local),
407
767
  remoteParent,
408
768
  atomic: args.atomic === true,
769
+ tempRemotePath: args.atomic ? tempRemotePath : undefined,
409
770
  },
410
- verification: await buildUploadVerification(args, local),
771
+ verification,
411
772
  });
412
773
  }
413
774
  catch (error) {
414
- if (args.atomic) {
415
- await cleanupRemotePath(args.alias, tempRemotePath).catch(() => undefined);
775
+ let cleanupWarning;
776
+ const shouldCleanupTemporaryUpload = args.atomic && (!(error instanceof fileOps.UploadFileError) || error.remoteCreated);
777
+ if (shouldCleanupTemporaryUpload) {
778
+ try {
779
+ await cleanupRemotePath(args.alias, tempRemotePath);
780
+ }
781
+ catch (cleanupError) {
782
+ cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
783
+ }
416
784
  }
417
785
  return formatResult({
418
786
  success: false,
419
787
  error: error instanceof Error ? error.message : String(error),
788
+ cleanupWarning,
789
+ finalRemotePath: args.remotePath,
420
790
  diagnostics: {
421
791
  local: summarizeLocalPathProbe(local),
422
792
  remoteParent,
793
+ remoteBefore,
423
794
  atomic: args.atomic === true,
795
+ tempRemotePath: args.atomic ? tempRemotePath : undefined,
424
796
  },
425
797
  });
426
798
  }
@@ -498,23 +870,106 @@ async function handleMkdir(args) {
498
870
  }
499
871
  }
500
872
  async function handleSync(args) {
501
- const local = fileOps.probeLocalPath(args.localPath);
873
+ const startedAt = Date.now();
874
+ if (args.verify?.deletions && args.delete !== true) {
875
+ return formatResult({
876
+ success: false,
877
+ code: 'DELETION_VERIFICATION_REQUIRES_DELETE',
878
+ error: 'verify.deletions=true requires delete=true',
879
+ });
880
+ }
881
+ const operationTimeout = args.operationTimeout ?? 600_000;
882
+ const remainingTimeout = () => operationTimeout - (Date.now() - startedAt);
883
+ try {
884
+ if (args.direction === 'upload') {
885
+ fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true, args.exclude);
886
+ }
887
+ else {
888
+ fileOps.validateLocalPathPolicy(args.localPath);
889
+ }
890
+ }
891
+ catch (error) {
892
+ return formatResult({
893
+ success: false,
894
+ error: error instanceof Error ? error.message : String(error),
895
+ diagnostics: {
896
+ localBefore: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true)),
897
+ },
898
+ });
899
+ }
900
+ const localBefore = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
502
901
  const diagnostics = {
503
- local: summarizeLocalPathProbe(local),
902
+ localBefore: summarizeLocalPathProbe(localBefore),
504
903
  remoteParent: await probeRemoteParent(args.alias, args.remotePath),
505
904
  };
506
905
  try {
906
+ let deletionBaseline;
907
+ try {
908
+ deletionBaseline = await captureDeletionBaseline(args, remainingTimeout);
909
+ if (deletionBaseline) {
910
+ diagnostics.deletionBaseline = {
911
+ count: deletionBaseline.count,
912
+ limited: deletionBaseline.limited,
913
+ limitReason: deletionBaseline.limitReason,
914
+ skippedSymlinks: deletionBaseline.skippedSymlinks,
915
+ skippedUnsupported: deletionBaseline.skippedUnsupported,
916
+ unsupportedSamples: deletionBaseline.unsupportedSamples,
917
+ };
918
+ }
919
+ }
920
+ catch (error) {
921
+ const verification = verificationErrorDetails(error);
922
+ return formatResult({
923
+ success: false,
924
+ transferSuccess: false,
925
+ verificationRequested: true,
926
+ verificationSuccess: false,
927
+ verificationStatus: 'error',
928
+ failedChecks: ['deletions'],
929
+ error: `Deletion baseline capture failed: ${error instanceof Error ? error.message : String(error)}`,
930
+ verification,
931
+ diagnostics,
932
+ });
933
+ }
934
+ const transferTimeout = remainingTimeout();
935
+ if (transferTimeout <= 0) {
936
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before transfer started', true);
937
+ }
507
938
  const syncResult = await fileOps.syncFiles(args.alias, args.localPath, args.remotePath, args.direction, {
508
939
  delete: args.delete,
509
940
  dryRun: args.dryRun,
510
941
  exclude: args.exclude,
511
942
  recursive: args.recursive,
512
943
  followSymlinks: args.followSymlinks,
944
+ preflightTimeout: args.preflightTimeout,
945
+ connectTimeout: args.connectTimeout,
946
+ operationTimeout: transferTimeout,
513
947
  });
514
- const ownerModeVerification = syncResult.success ? await buildSyncUploadVerification(args, local) : undefined;
948
+ const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
949
+ diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
950
+ const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
951
+ let verification;
952
+ let verificationError;
953
+ if (verificationRequested && syncResult.success) {
954
+ try {
955
+ const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout());
956
+ const directoryVerification = await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline);
957
+ verification = mergeSyncVerification(undefined, ownerModeVerification, directoryVerification);
958
+ }
959
+ catch (error) {
960
+ verificationError = error;
961
+ verification = mergeSyncVerification(undefined, verificationErrorDetails(error), undefined);
962
+ }
963
+ }
964
+ const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
515
965
  return formatResult({
516
966
  ...syncResult,
517
- verification: mergeSyncVerification(syncResult.verification, ownerModeVerification),
967
+ ...outcome,
968
+ error: verificationError === undefined
969
+ ? undefined
970
+ : `Sync completed, but verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
971
+ transportVerification: syncResult.verification,
972
+ verification,
518
973
  direction: args.direction,
519
974
  localPath: args.localPath,
520
975
  remotePath: args.remotePath,
@@ -562,7 +1017,8 @@ export function registerFileTools(server) {
562
1017
  server.registerTool('ssh_sync', {
563
1018
  description: `智能文件同步(支持目录递归)
564
1019
 
565
- 优先使用 rsync(如果本地和远程都安装了),否则回退到 SFTP
1020
+ 只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline key 和 jump host session 使用 SFTP
1021
+ 满足 rsync 条件且本地、远端均可用 rsync 时使用 rsync,否则使用 SFTP
566
1022
  rsync 可实现增量传输,对大目录同步效率更高
567
1023
 
568
1024
  用途: