@pyrokine/mcp-ssh 2.3.2 → 2.4.0
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/README.md +94 -20
- package/README_zh.md +64 -19
- package/dist/command-risk.d.ts +7 -0
- package/dist/command-risk.js +106 -0
- package/dist/directory-verification.d.ts +43 -0
- package/dist/directory-verification.js +485 -0
- package/dist/file-ops.d.ts +56 -13
- package/dist/file-ops.js +531 -145
- package/dist/forward-manager.d.ts +5 -2
- package/dist/forward-manager.js +133 -19
- package/dist/index.js +2 -1
- package/dist/operation-manager.d.ts +52 -0
- package/dist/operation-manager.js +402 -0
- package/dist/pty-manager.d.ts +1 -0
- package/dist/pty-manager.js +11 -7
- package/dist/session-manager.d.ts +21 -10
- package/dist/session-manager.js +328 -75
- package/dist/tools/connection.js +48 -8
- package/dist/tools/exec.js +7 -66
- package/dist/tools/file.js +455 -81
- package/dist/tools/forward.js +12 -4
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +1 -0
- package/dist/tools/operation.d.ts +2 -0
- package/dist/tools/operation.js +126 -0
- package/dist/tools/utils.d.ts +2 -2
- package/dist/transfer-outcome.d.ts +12 -0
- package/dist/transfer-outcome.js +72 -0
- package/dist/types.d.ts +94 -6
- package/package.json +10 -8
package/dist/tools/file.js
CHANGED
|
@@ -8,8 +8,10 @@ import { createHash } 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,
|
|
@@ -143,14 +209,53 @@ function hashLocalFileMd5(filePath) {
|
|
|
143
209
|
stream.on('end', () => resolve(hash.digest('hex')));
|
|
144
210
|
});
|
|
145
211
|
}
|
|
212
|
+
function boundedDiagnostic(value, maxBytes = 2048) {
|
|
213
|
+
const buffer = Buffer.from(value, 'utf8');
|
|
214
|
+
if (buffer.length <= maxBytes) {
|
|
215
|
+
return { text: value, bytes: buffer.length, truncated: false };
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
text: buffer.subarray(0, maxBytes).toString('utf8'),
|
|
219
|
+
bytes: buffer.length,
|
|
220
|
+
truncated: true,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function commandFailureDetails(result) {
|
|
224
|
+
const stderr = boundedDiagnostic(result.stderr);
|
|
225
|
+
const stdout = boundedDiagnostic(result.stdout);
|
|
226
|
+
return {
|
|
227
|
+
exitCode: result.exitCode,
|
|
228
|
+
failureKind: result.failureKind,
|
|
229
|
+
timedOut: result.timedOut,
|
|
230
|
+
stdout: stdout.text || undefined,
|
|
231
|
+
stdoutBytes: result.stdoutBytes ?? stdout.bytes,
|
|
232
|
+
stdoutTruncated: result.stdoutTruncated || stdout.truncated || undefined,
|
|
233
|
+
stderr: stderr.text || undefined,
|
|
234
|
+
stderrBytes: result.stderrBytes ?? stderr.bytes,
|
|
235
|
+
stderrTruncated: result.stderrTruncated || stderr.truncated || undefined,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
146
238
|
async function hashRemoteFileMd5(alias, remotePath) {
|
|
147
239
|
const result = await sessionManager.exec(alias, `md5sum ${escapeShellArg(remotePath)} | awk '{print $1}'`, {
|
|
148
240
|
timeout: 30000,
|
|
149
241
|
useLoginUser: true,
|
|
150
242
|
maxOutputSize: 4096,
|
|
151
243
|
});
|
|
244
|
+
if (!result.success) {
|
|
245
|
+
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.exitCode}`;
|
|
246
|
+
throw new VerificationStageError('remote_probe', `Remote MD5 command failed: ${detail}`, true, {
|
|
247
|
+
operation: 'md5',
|
|
248
|
+
...commandFailureDetails(result),
|
|
249
|
+
});
|
|
250
|
+
}
|
|
152
251
|
const digest = result.stdout.trim().split(/\s+/)[0];
|
|
153
|
-
|
|
252
|
+
if (!/^[a-fA-F0-9]{32}$/.test(digest)) {
|
|
253
|
+
throw new VerificationStageError('remote_probe', 'Remote MD5 command returned an invalid digest', false, {
|
|
254
|
+
operation: 'md5',
|
|
255
|
+
...commandFailureDetails(result),
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
return digest;
|
|
154
259
|
}
|
|
155
260
|
function permissionStringToOctal(permissions) {
|
|
156
261
|
const bits = permissions.slice(-9);
|
|
@@ -172,56 +277,68 @@ function permissionStringToOctal(permissions) {
|
|
|
172
277
|
});
|
|
173
278
|
return `0${values.join('')}`;
|
|
174
279
|
}
|
|
175
|
-
async function probeRemoteFile(alias, remotePath) {
|
|
280
|
+
async function probeRemoteFile(alias, remotePath, timeout = 10000) {
|
|
176
281
|
const escapedRemotePath = escapeShellArg(remotePath);
|
|
177
282
|
const command = [
|
|
178
283
|
`if [ -e ${escapedRemotePath} ]; then`,
|
|
179
284
|
`stat -c '%U\t%u\t%G\t%g\t%a\t%s\t%Y\t%F' ${escapedRemotePath};`,
|
|
180
285
|
'else printf missing; fi',
|
|
181
286
|
].join(' ');
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
287
|
+
const result = await sessionManager.exec(alias, command, {
|
|
288
|
+
timeout,
|
|
289
|
+
useLoginUser: true,
|
|
290
|
+
maxOutputSize: 4096,
|
|
291
|
+
});
|
|
292
|
+
if (!result.success) {
|
|
293
|
+
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.exitCode}`;
|
|
294
|
+
throw new VerificationStageError('remote_probe', `Remote stat command failed: ${detail}`, true, {
|
|
295
|
+
operation: 'stat',
|
|
296
|
+
...commandFailureDetails(result),
|
|
187
297
|
});
|
|
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
|
-
};
|
|
208
298
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
299
|
+
if (result.stdout.trim() === 'missing') {
|
|
300
|
+
return { exists: false, remotePath, probeMethod: 'stat' };
|
|
301
|
+
}
|
|
302
|
+
const fields = result.stdout.trim().split('\t');
|
|
303
|
+
if (fields.length !== 8) {
|
|
304
|
+
throw new VerificationStageError('remote_probe', 'Remote stat command returned malformed output', false, {
|
|
305
|
+
operation: 'stat',
|
|
306
|
+
...commandFailureDetails(result),
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
const [ownerName, ownerId, groupName, groupId, mode, size, mtimeSeconds, fileType] = fields;
|
|
310
|
+
const ownerIdValue = Number(ownerId);
|
|
311
|
+
const groupIdValue = Number(groupId);
|
|
312
|
+
const sizeValue = Number(size);
|
|
313
|
+
const mtimeValue = Number(mtimeSeconds);
|
|
314
|
+
if (!Number.isSafeInteger(ownerIdValue) ||
|
|
315
|
+
ownerIdValue < 0 ||
|
|
316
|
+
!Number.isSafeInteger(groupIdValue) ||
|
|
317
|
+
groupIdValue < 0 ||
|
|
318
|
+
!Number.isSafeInteger(sizeValue) ||
|
|
319
|
+
sizeValue < 0 ||
|
|
320
|
+
!Number.isFinite(mtimeValue) ||
|
|
321
|
+
!/^[0-7]{3,4}$/.test(mode)) {
|
|
322
|
+
throw new VerificationStageError('remote_probe', 'Remote stat command returned invalid metadata', false, {
|
|
323
|
+
operation: 'stat',
|
|
324
|
+
...commandFailureDetails(result),
|
|
325
|
+
});
|
|
224
326
|
}
|
|
327
|
+
return {
|
|
328
|
+
exists: true,
|
|
329
|
+
remotePath,
|
|
330
|
+
probeMethod: 'stat',
|
|
331
|
+
ownerName,
|
|
332
|
+
ownerId: ownerIdValue,
|
|
333
|
+
groupName,
|
|
334
|
+
groupId: groupIdValue,
|
|
335
|
+
mode: mode.length === 3 ? `0${mode}` : mode,
|
|
336
|
+
size: sizeValue,
|
|
337
|
+
mtimeMs: mtimeValue * 1000,
|
|
338
|
+
fileType,
|
|
339
|
+
isDirectory: fileType === 'directory',
|
|
340
|
+
isFile: fileType.startsWith('regular '),
|
|
341
|
+
};
|
|
225
342
|
}
|
|
226
343
|
async function buildUploadVerification(args, local) {
|
|
227
344
|
const remote = await probeRemoteFile(args.alias, args.remotePath);
|
|
@@ -233,13 +350,13 @@ async function buildUploadVerification(args, local) {
|
|
|
233
350
|
const mtimeDelta = local.exists && remote.exists ? Math.abs((local.mtimeMs ?? 0) - (remote.mtimeMs ?? 0)) : undefined;
|
|
234
351
|
checks.mtime = mtimeDelta !== undefined ? mtimeDelta < 2000 : false;
|
|
235
352
|
}
|
|
236
|
-
if (args.verifyMode
|
|
353
|
+
if (args.verifyMode) {
|
|
237
354
|
const expectedMode = normalizeExpectedMode(args.verifyMode);
|
|
238
|
-
checks.mode = expectedMode !== undefined && remote.mode === expectedMode;
|
|
355
|
+
checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
|
|
239
356
|
}
|
|
240
|
-
if (args.verifyOwner !== undefined
|
|
357
|
+
if (args.verifyOwner !== undefined) {
|
|
241
358
|
const expectedOwner = String(args.verifyOwner);
|
|
242
|
-
checks.owner = String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner;
|
|
359
|
+
checks.owner = remote.exists && (String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner);
|
|
243
360
|
}
|
|
244
361
|
if (args.verifyMd5 && local.exists) {
|
|
245
362
|
const [localMd5, remoteMd5] = await Promise.all([
|
|
@@ -248,12 +365,31 @@ async function buildUploadVerification(args, local) {
|
|
|
248
365
|
]);
|
|
249
366
|
checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
|
|
250
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
|
+
md5: localMd5,
|
|
374
|
+
},
|
|
375
|
+
actual: { ...remote, md5: remoteMd5 },
|
|
251
376
|
local: { ...summarizeLocalPathProbe(local), md5: localMd5 },
|
|
252
377
|
remote: { ...remote, md5: remoteMd5 },
|
|
253
378
|
checks,
|
|
254
379
|
};
|
|
255
380
|
}
|
|
256
|
-
return {
|
|
381
|
+
return {
|
|
382
|
+
expected: {
|
|
383
|
+
owner: args.verifyOwner,
|
|
384
|
+
mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
|
|
385
|
+
size: args.verifySize && local.exists ? local.size : undefined,
|
|
386
|
+
mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
|
|
387
|
+
},
|
|
388
|
+
actual: remote,
|
|
389
|
+
local: summarizeLocalPathProbe(local),
|
|
390
|
+
remote,
|
|
391
|
+
checks,
|
|
392
|
+
};
|
|
257
393
|
}
|
|
258
394
|
function normalizeExpectedMode(mode) {
|
|
259
395
|
const trimmed = mode.trim();
|
|
@@ -274,8 +410,8 @@ function buildSyncVerificationChecks(args, remote) {
|
|
|
274
410
|
}
|
|
275
411
|
return checks;
|
|
276
412
|
}
|
|
277
|
-
async function resolveSyncUploadVerificationPath(args, local) {
|
|
278
|
-
const requestedRemote = await probeRemoteFile(args.alias, args.remotePath);
|
|
413
|
+
async function resolveSyncUploadVerificationPath(args, local, timeout) {
|
|
414
|
+
const requestedRemote = await probeRemoteFile(args.alias, args.remotePath, timeout);
|
|
279
415
|
if (requestedRemote.exists && requestedRemote.isDirectory) {
|
|
280
416
|
return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
|
|
281
417
|
}
|
|
@@ -284,7 +420,7 @@ async function resolveSyncUploadVerificationPath(args, local) {
|
|
|
284
420
|
}
|
|
285
421
|
return args.remotePath;
|
|
286
422
|
}
|
|
287
|
-
async function buildSyncUploadVerification(args, local) {
|
|
423
|
+
async function buildSyncUploadVerification(args, local, timeout) {
|
|
288
424
|
if (args.verifyOwner === undefined && args.verifyMode === undefined) {
|
|
289
425
|
return undefined;
|
|
290
426
|
}
|
|
@@ -300,11 +436,14 @@ async function buildSyncUploadVerification(args, local) {
|
|
|
300
436
|
kind: 'owner_mode',
|
|
301
437
|
skipped: true,
|
|
302
438
|
reason: 'verifyOwner/verifyMode 只对单文件 upload 做后置校验,目录同步不会递归扫描远端权限',
|
|
303
|
-
suggestion: '
|
|
439
|
+
suggestion: '目录权限校验请使用 verify.owner 或 verify.mode',
|
|
304
440
|
};
|
|
305
441
|
}
|
|
306
|
-
|
|
307
|
-
|
|
442
|
+
if (timeout <= 0) {
|
|
443
|
+
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before owner/mode verification started', true);
|
|
444
|
+
}
|
|
445
|
+
const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, timeout);
|
|
446
|
+
const remote = await probeRemoteFile(args.alias, verificationRemotePath, timeout);
|
|
308
447
|
const checks = buildSyncVerificationChecks(args, remote);
|
|
309
448
|
const matched = Object.values(checks).every(Boolean);
|
|
310
449
|
return {
|
|
@@ -323,33 +462,140 @@ async function buildSyncUploadVerification(args, local) {
|
|
|
323
462
|
: '同步已完成,但远端 owner/mode 与期望不一致;工具不会自动 chown/chmod,请按需用 ssh_exec 显式处理权限',
|
|
324
463
|
};
|
|
325
464
|
}
|
|
326
|
-
function
|
|
327
|
-
|
|
328
|
-
|
|
465
|
+
async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, timeout) {
|
|
466
|
+
const remoteCommand = buildRemoteDirectoryManifestCommand(remotePath, request, exclude, followSymlinks);
|
|
467
|
+
let remoteResult;
|
|
468
|
+
try {
|
|
469
|
+
remoteResult = await sessionManager.exec(alias, remoteCommand, {
|
|
470
|
+
timeout,
|
|
471
|
+
useLoginUser: true,
|
|
472
|
+
maxOutputSize: 16 * 1024 * 1024,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
catch (error) {
|
|
476
|
+
const details = error && typeof error === 'object' && 'details' in error
|
|
477
|
+
? error.details
|
|
478
|
+
: undefined;
|
|
479
|
+
throw new VerificationStageError('remote_manifest_command', boundedDiagnostic(error instanceof Error ? error.message : String(error)).text, true, { timeout, ...details });
|
|
480
|
+
}
|
|
481
|
+
if (!remoteResult.success) {
|
|
482
|
+
const detail = boundedDiagnostic(remoteResult.stderr || remoteResult.stdout || 'remote directory manifest failed');
|
|
483
|
+
throw new VerificationStageError('remote_manifest_command', detail.text, remoteResult.failureKind !== 'remote_command', {
|
|
484
|
+
...commandFailureDetails(remoteResult),
|
|
485
|
+
diagnosticBytes: detail.bytes,
|
|
486
|
+
diagnosticTruncated: detail.truncated || undefined,
|
|
487
|
+
});
|
|
329
488
|
}
|
|
330
|
-
if (
|
|
331
|
-
|
|
489
|
+
if (remoteResult.stdoutTruncated) {
|
|
490
|
+
throw new VerificationStageError('remote_manifest_output', 'remote directory manifest output exceeded the 16MB response limit', false, { maxOutputSize: 16 * 1024 * 1024 });
|
|
332
491
|
}
|
|
492
|
+
try {
|
|
493
|
+
return parseRemoteDirectoryManifest(remoteResult.stdout);
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
throw new VerificationStageError('remote_manifest_parse', error instanceof Error ? error.message : String(error), false);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
function directoryVerificationFollowsSymlinks(args) {
|
|
500
|
+
return args.direction === 'upload' && args.followSymlinks === true;
|
|
501
|
+
}
|
|
502
|
+
function deletionManifestRequest(request) {
|
|
333
503
|
return {
|
|
334
|
-
...
|
|
504
|
+
...request,
|
|
505
|
+
count: false,
|
|
506
|
+
sha256: false,
|
|
507
|
+
owner: false,
|
|
508
|
+
mode: false,
|
|
509
|
+
deletions: false,
|
|
510
|
+
staleFiles: false,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
async function captureDeletionBaseline(args, remainingTimeout) {
|
|
514
|
+
if (!args.verify?.deletions || args.dryRun) {
|
|
515
|
+
return undefined;
|
|
516
|
+
}
|
|
517
|
+
const request = deletionManifestRequest(args.verify);
|
|
518
|
+
if (args.direction === 'upload') {
|
|
519
|
+
const probeTimeout = remainingTimeout();
|
|
520
|
+
if (probeTimeout <= 0) {
|
|
521
|
+
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline capture started', true);
|
|
522
|
+
}
|
|
523
|
+
const remote = await probeRemoteFile(args.alias, args.remotePath, probeTimeout);
|
|
524
|
+
if (!remote.exists) {
|
|
525
|
+
return createEmptyDirectoryManifest();
|
|
526
|
+
}
|
|
527
|
+
if (!remote.isDirectory) {
|
|
528
|
+
throw new VerificationStageError('remote_probe', 'deletion verification requires the remote destination to be a directory', false, { remotePath: args.remotePath, fileType: remote.fileType });
|
|
529
|
+
}
|
|
530
|
+
const manifestTimeout = remainingTimeout();
|
|
531
|
+
if (manifestTimeout <= 0) {
|
|
532
|
+
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline manifest started', true);
|
|
533
|
+
}
|
|
534
|
+
return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), manifestTimeout);
|
|
535
|
+
}
|
|
536
|
+
const local = fileOps.probeLocalPath(args.localPath);
|
|
537
|
+
if (!local.exists) {
|
|
538
|
+
return createEmptyDirectoryManifest();
|
|
539
|
+
}
|
|
540
|
+
if (!local.isDirectory) {
|
|
541
|
+
throw new VerificationStageError('local_manifest', 'deletion verification requires the local destination to be a directory', false, { localPath: args.localPath });
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
async function buildDirectorySyncVerification(args, local, timeout, deletionBaseline) {
|
|
551
|
+
if (!args.verify) {
|
|
552
|
+
return undefined;
|
|
553
|
+
}
|
|
554
|
+
if (args.dryRun) {
|
|
555
|
+
return { kind: 'directory', skipped: true, reason: 'directory verification is not executed during dryRun' };
|
|
556
|
+
}
|
|
557
|
+
if (!local.exists || !local.isDirectory) {
|
|
558
|
+
return { kind: 'directory', skipped: true, reason: 'bounded directory verification requires a local directory' };
|
|
559
|
+
}
|
|
560
|
+
if (timeout <= 0) {
|
|
561
|
+
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before directory verification started', true);
|
|
562
|
+
}
|
|
563
|
+
const request = args.verify;
|
|
564
|
+
const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), timeout);
|
|
565
|
+
let localManifest;
|
|
566
|
+
try {
|
|
567
|
+
localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
|
|
568
|
+
}
|
|
569
|
+
catch (error) {
|
|
570
|
+
throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
|
|
571
|
+
}
|
|
572
|
+
return args.direction === 'upload'
|
|
573
|
+
? compareDirectoryManifests(localManifest, remoteManifest, request, deletionBaseline)
|
|
574
|
+
: compareDirectoryManifests(remoteManifest, localManifest, request, deletionBaseline);
|
|
575
|
+
}
|
|
576
|
+
function mergeSyncVerification(existing, ownerMode, directory) {
|
|
577
|
+
const parts = [existing, ownerMode, directory].filter((part) => Boolean(part));
|
|
578
|
+
if (parts.length === 0) {
|
|
579
|
+
return undefined;
|
|
580
|
+
}
|
|
581
|
+
if (parts.length === 1) {
|
|
582
|
+
return parts[0];
|
|
583
|
+
}
|
|
584
|
+
return {
|
|
585
|
+
transport: existing,
|
|
335
586
|
ownerMode,
|
|
587
|
+
directory,
|
|
336
588
|
};
|
|
337
589
|
}
|
|
338
590
|
async function cleanupRemotePath(alias, remotePath) {
|
|
339
|
-
await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
|
|
340
|
-
timeout: 10000,
|
|
341
|
-
useLoginUser: true,
|
|
342
|
-
maxOutputSize: 4096,
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
async function applyRemoteMode(alias, remotePath, mode) {
|
|
346
|
-
const result = await sessionManager.exec(alias, `chmod ${escapeShellArg(mode)} ${escapeShellArg(remotePath)}`, {
|
|
591
|
+
const result = await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
|
|
347
592
|
timeout: 10000,
|
|
348
593
|
useLoginUser: true,
|
|
349
594
|
maxOutputSize: 4096,
|
|
350
595
|
});
|
|
351
596
|
if (!result.success) {
|
|
352
|
-
|
|
597
|
+
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.exitCode}`;
|
|
598
|
+
throw new Error(`Temporary remote file cleanup failed: ${detail}`);
|
|
353
599
|
}
|
|
354
600
|
}
|
|
355
601
|
async function handleUpload(args) {
|
|
@@ -372,55 +618,116 @@ async function handleUpload(args) {
|
|
|
372
618
|
].join(', ')
|
|
373
619
|
: undefined;
|
|
374
620
|
const remoteParent = await probeRemoteParent(args.alias, args.remotePath);
|
|
621
|
+
let remoteBefore;
|
|
622
|
+
try {
|
|
623
|
+
remoteBefore = await probeRemoteFile(args.alias, args.remotePath);
|
|
624
|
+
}
|
|
625
|
+
catch (error) {
|
|
626
|
+
return formatResult({
|
|
627
|
+
success: false,
|
|
628
|
+
error: error instanceof Error ? error.message : String(error),
|
|
629
|
+
diagnostics: {
|
|
630
|
+
local: summarizeLocalPathProbe(local),
|
|
631
|
+
remoteParent,
|
|
632
|
+
remoteProbe: verificationErrorDetails(error),
|
|
633
|
+
atomic: args.atomic === true,
|
|
634
|
+
},
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
const sourceMode = local.exists && 'mode' in local && typeof local.mode === 'string'
|
|
638
|
+
? Number.parseInt(local.mode, 8) & 0o777
|
|
639
|
+
: undefined;
|
|
640
|
+
const existingMode = remoteBefore.exists && remoteBefore.mode ? Number.parseInt(remoteBefore.mode, 8) & 0o777 : undefined;
|
|
641
|
+
const createMode = args.atomic && existingMode !== undefined ? existingMode : sourceMode;
|
|
375
642
|
const tempRemotePath = args.atomic
|
|
376
643
|
? `${args.remotePath}.mcp-tmp-${process.pid}-${Date.now().toString(36)}`
|
|
377
644
|
: args.remotePath;
|
|
378
645
|
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);
|
|
382
|
-
}
|
|
646
|
+
const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode);
|
|
383
647
|
if (args.atomic) {
|
|
384
648
|
const rename = await sessionManager.exec(args.alias, `mv -f -- ${escapeShellArg(tempRemotePath)} ${escapeShellArg(args.remotePath)}`, { timeout: 30000, useLoginUser: true, maxOutputSize: 4096 });
|
|
385
649
|
if (!rename.success) {
|
|
386
650
|
const renameError = rename.stderr || rename.stdout || `atomic rename failed with exit code ${rename.exitCode}`;
|
|
387
|
-
|
|
651
|
+
let cleanupWarning;
|
|
652
|
+
try {
|
|
653
|
+
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
654
|
+
}
|
|
655
|
+
catch (error) {
|
|
656
|
+
cleanupWarning = error instanceof Error ? error.message : String(error);
|
|
657
|
+
}
|
|
388
658
|
return formatResult({
|
|
389
659
|
success: false,
|
|
390
660
|
error: renameError,
|
|
661
|
+
cleanupWarning,
|
|
391
662
|
diagnostics: {
|
|
392
663
|
local: summarizeLocalPathProbe(local),
|
|
393
664
|
remoteParent,
|
|
394
665
|
atomic: true,
|
|
666
|
+
tempRemotePath,
|
|
395
667
|
},
|
|
396
668
|
});
|
|
397
669
|
}
|
|
398
670
|
}
|
|
671
|
+
const verificationRequested = Boolean(args.verifyOwner !== undefined ||
|
|
672
|
+
args.verifyMode !== undefined ||
|
|
673
|
+
args.verifyMd5 ||
|
|
674
|
+
args.verifySize ||
|
|
675
|
+
args.verifyMtime);
|
|
676
|
+
let verification;
|
|
677
|
+
let verificationError;
|
|
678
|
+
if (verificationRequested) {
|
|
679
|
+
try {
|
|
680
|
+
verification = await buildUploadVerification(args, local);
|
|
681
|
+
}
|
|
682
|
+
catch (error) {
|
|
683
|
+
verificationError = error;
|
|
684
|
+
verification = verificationErrorDetails(error);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const outcome = buildTransferOutcome(uploadResult.success, verificationRequested, verification, verificationError);
|
|
399
688
|
return formatResult({
|
|
400
689
|
...uploadResult,
|
|
401
|
-
|
|
690
|
+
...outcome,
|
|
691
|
+
message: outcome.success
|
|
692
|
+
? `Uploaded to ${args.remotePath}`
|
|
693
|
+
: `Uploaded but verification failed: ${args.remotePath}`,
|
|
694
|
+
error: verificationError === undefined
|
|
695
|
+
? undefined
|
|
696
|
+
: `Upload completed, but verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
|
|
402
697
|
atomic: args.atomic === true,
|
|
698
|
+
createMode: uploadResult.createMode,
|
|
699
|
+
existingTargetModePreserved: remoteBefore.exists,
|
|
403
700
|
suggestion: largeFileSuggestion,
|
|
404
701
|
recommendedSync,
|
|
405
702
|
diagnostics: {
|
|
406
703
|
local: summarizeLocalPathProbe(local),
|
|
407
704
|
remoteParent,
|
|
408
705
|
atomic: args.atomic === true,
|
|
706
|
+
tempRemotePath: args.atomic ? tempRemotePath : undefined,
|
|
409
707
|
},
|
|
410
|
-
verification
|
|
708
|
+
verification,
|
|
411
709
|
});
|
|
412
710
|
}
|
|
413
711
|
catch (error) {
|
|
712
|
+
let cleanupWarning;
|
|
414
713
|
if (args.atomic) {
|
|
415
|
-
|
|
714
|
+
try {
|
|
715
|
+
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
716
|
+
}
|
|
717
|
+
catch (cleanupError) {
|
|
718
|
+
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
719
|
+
}
|
|
416
720
|
}
|
|
417
721
|
return formatResult({
|
|
418
722
|
success: false,
|
|
419
723
|
error: error instanceof Error ? error.message : String(error),
|
|
724
|
+
cleanupWarning,
|
|
420
725
|
diagnostics: {
|
|
421
726
|
local: summarizeLocalPathProbe(local),
|
|
422
727
|
remoteParent,
|
|
728
|
+
remoteBefore,
|
|
423
729
|
atomic: args.atomic === true,
|
|
730
|
+
tempRemotePath: args.atomic ? tempRemotePath : undefined,
|
|
424
731
|
},
|
|
425
732
|
});
|
|
426
733
|
}
|
|
@@ -498,23 +805,89 @@ async function handleMkdir(args) {
|
|
|
498
805
|
}
|
|
499
806
|
}
|
|
500
807
|
async function handleSync(args) {
|
|
501
|
-
const
|
|
808
|
+
const startedAt = Date.now();
|
|
809
|
+
if (args.verify?.deletions && args.delete !== true) {
|
|
810
|
+
return formatResult({
|
|
811
|
+
success: false,
|
|
812
|
+
code: 'DELETION_VERIFICATION_REQUIRES_DELETE',
|
|
813
|
+
error: 'verify.deletions=true requires delete=true',
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
const operationTimeout = args.operationTimeout ?? 600_000;
|
|
817
|
+
const remainingTimeout = () => operationTimeout - (Date.now() - startedAt);
|
|
818
|
+
const localBefore = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
502
819
|
const diagnostics = {
|
|
503
|
-
|
|
820
|
+
localBefore: summarizeLocalPathProbe(localBefore),
|
|
504
821
|
remoteParent: await probeRemoteParent(args.alias, args.remotePath),
|
|
505
822
|
};
|
|
506
823
|
try {
|
|
824
|
+
let deletionBaseline;
|
|
825
|
+
try {
|
|
826
|
+
deletionBaseline = await captureDeletionBaseline(args, remainingTimeout);
|
|
827
|
+
if (deletionBaseline) {
|
|
828
|
+
diagnostics.deletionBaseline = {
|
|
829
|
+
count: deletionBaseline.count,
|
|
830
|
+
limited: deletionBaseline.limited,
|
|
831
|
+
limitReason: deletionBaseline.limitReason,
|
|
832
|
+
skippedSymlinks: deletionBaseline.skippedSymlinks,
|
|
833
|
+
skippedUnsupported: deletionBaseline.skippedUnsupported,
|
|
834
|
+
unsupportedSamples: deletionBaseline.unsupportedSamples,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
catch (error) {
|
|
839
|
+
const verification = verificationErrorDetails(error);
|
|
840
|
+
return formatResult({
|
|
841
|
+
success: false,
|
|
842
|
+
transferSuccess: false,
|
|
843
|
+
verificationRequested: true,
|
|
844
|
+
verificationSuccess: false,
|
|
845
|
+
verificationStatus: 'error',
|
|
846
|
+
failedChecks: ['deletions'],
|
|
847
|
+
error: `Deletion baseline capture failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
848
|
+
verification,
|
|
849
|
+
diagnostics,
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
const transferTimeout = remainingTimeout();
|
|
853
|
+
if (transferTimeout <= 0) {
|
|
854
|
+
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before transfer started', true);
|
|
855
|
+
}
|
|
507
856
|
const syncResult = await fileOps.syncFiles(args.alias, args.localPath, args.remotePath, args.direction, {
|
|
508
857
|
delete: args.delete,
|
|
509
858
|
dryRun: args.dryRun,
|
|
510
859
|
exclude: args.exclude,
|
|
511
860
|
recursive: args.recursive,
|
|
512
861
|
followSymlinks: args.followSymlinks,
|
|
862
|
+
preflightTimeout: args.preflightTimeout,
|
|
863
|
+
connectTimeout: args.connectTimeout,
|
|
864
|
+
operationTimeout: transferTimeout,
|
|
513
865
|
});
|
|
514
|
-
const
|
|
866
|
+
const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
867
|
+
diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
|
|
868
|
+
const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
|
|
869
|
+
let verification;
|
|
870
|
+
let verificationError;
|
|
871
|
+
if (verificationRequested && syncResult.success) {
|
|
872
|
+
try {
|
|
873
|
+
const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout());
|
|
874
|
+
const directoryVerification = await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline);
|
|
875
|
+
verification = mergeSyncVerification(undefined, ownerModeVerification, directoryVerification);
|
|
876
|
+
}
|
|
877
|
+
catch (error) {
|
|
878
|
+
verificationError = error;
|
|
879
|
+
verification = mergeSyncVerification(undefined, verificationErrorDetails(error), undefined);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
|
|
515
883
|
return formatResult({
|
|
516
884
|
...syncResult,
|
|
517
|
-
|
|
885
|
+
...outcome,
|
|
886
|
+
error: verificationError === undefined
|
|
887
|
+
? undefined
|
|
888
|
+
: `Sync completed, but verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
|
|
889
|
+
transportVerification: syncResult.verification,
|
|
890
|
+
verification,
|
|
518
891
|
direction: args.direction,
|
|
519
892
|
localPath: args.localPath,
|
|
520
893
|
remotePath: args.remotePath,
|
|
@@ -562,7 +935,8 @@ export function registerFileTools(server) {
|
|
|
562
935
|
server.registerTool('ssh_sync', {
|
|
563
936
|
description: `智能文件同步(支持目录递归)
|
|
564
937
|
|
|
565
|
-
|
|
938
|
+
只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline key 和 jump host session 使用 SFTP
|
|
939
|
+
满足 rsync 条件且本地、远端均可用 rsync 时使用 rsync,否则使用 SFTP
|
|
566
940
|
rsync 可实现增量传输,对大目录同步效率更高
|
|
567
941
|
|
|
568
942
|
用途:
|