@pyrokine/mcp-ssh 3.0.0 → 3.2.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 +423 -102
- package/README_zh.md +300 -74
- package/dist/command-risk.js +5 -2
- package/dist/directory-verification.d.ts +10 -3
- package/dist/directory-verification.js +271 -55
- package/dist/file-mode.js +25 -13
- package/dist/file-ops.d.ts +20 -6
- package/dist/file-ops.js +669 -282
- package/dist/forward-manager.js +6 -1
- package/dist/known-hosts.d.ts +22 -0
- package/dist/known-hosts.js +553 -0
- package/dist/openssh.d.ts +51 -0
- package/dist/openssh.js +553 -0
- package/dist/operation-manager.d.ts +2 -3
- package/dist/operation-manager.js +33 -5
- package/dist/pty-manager.d.ts +2 -1
- package/dist/pty-manager.js +81 -19
- package/dist/remote-platform.d.ts +1 -1
- package/dist/remote-platform.js +82 -50
- package/dist/security.d.ts +2 -0
- package/dist/security.js +39 -3
- package/dist/session-manager.d.ts +40 -4
- package/dist/session-manager.js +377 -61
- package/dist/sftp-timeout.d.ts +16 -1
- package/dist/sftp-timeout.js +104 -12
- package/dist/ssh-config.js +1 -1
- package/dist/tools/connection.js +89 -5
- package/dist/tools/exec.js +90 -37
- package/dist/tools/file.js +457 -146
- package/dist/tools/operation.js +7 -5
- package/dist/tools/pty.js +16 -13
- package/dist/tools/utils.d.ts +1 -1
- package/dist/tools/utils.js +2 -2
- package/dist/types.d.ts +46 -5
- package/dist/types.js +1 -0
- package/dist/utf8.d.ts +1 -1
- package/dist/utf8.js +2 -2
- package/dist/windows-acl.d.ts +1 -0
- package/dist/windows-acl.js +167 -80
- package/package.json +6 -5
package/dist/tools/file.js
CHANGED
|
@@ -4,16 +4,16 @@
|
|
|
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 {
|
|
7
|
+
import { 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 { compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, createRemoteDirectoryManifest, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, } from '../directory-verification.js';
|
|
11
|
+
import { compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, createOpenSshDirectoryManifest, createRemoteDirectoryManifest, DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, matchesDirectoryExclude, remainingVerificationTimeout, } from '../directory-verification.js';
|
|
12
12
|
import { FILE_CREATE_MODE_MASK, formatFileMode, parseExpectedFileMode } from '../file-mode.js';
|
|
13
13
|
import * as fileOps from '../file-ops.js';
|
|
14
|
+
import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remotePathModule, remoteShellPath, sftpPath, } from '../remote-platform.js';
|
|
14
15
|
import { sessionManager } from '../session-manager.js';
|
|
15
|
-
import { withSftpOperationTimeout } from '../sftp-timeout.js';
|
|
16
|
-
import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remoteShellPath, sftpPath, } from '../remote-platform.js';
|
|
16
|
+
import { SftpOperationTimeoutError, sftpOperationOutcome, withSftpOperationTimeout } from '../sftp-timeout.js';
|
|
17
17
|
import { buildTransferOutcome } from '../transfer-outcome.js';
|
|
18
18
|
import { operationTimeoutSchema } from './schema.js';
|
|
19
19
|
import { escapeShellArg, formatError, formatResult } from './utils.js';
|
|
@@ -71,12 +71,42 @@ const writeFileSchema = z.object({
|
|
|
71
71
|
append: z.boolean().optional().describe('是否追加模式,默认覆盖'),
|
|
72
72
|
timeout: operationTimeoutSchema.optional(),
|
|
73
73
|
});
|
|
74
|
-
|
|
74
|
+
function compareDirectoryTimes(left, right) {
|
|
75
|
+
const milliseconds = Date.parse(left) - Date.parse(right);
|
|
76
|
+
if (milliseconds !== 0) {
|
|
77
|
+
return milliseconds;
|
|
78
|
+
}
|
|
79
|
+
// 保留 ISO 8601 的亚毫秒部分,避免 Date.parse 截断时间边界
|
|
80
|
+
const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(?<fraction>\d+)/)?.[1].slice(3) ?? '').replace(/0+$/, ''));
|
|
81
|
+
return leftFraction < rightFraction ? -1 : leftFraction > rightFraction ? 1 : 0;
|
|
82
|
+
}
|
|
83
|
+
const listDirSchema = z
|
|
84
|
+
.object({
|
|
75
85
|
alias: z.string().describe('连接别名'),
|
|
76
86
|
remotePath: z.string().describe('远程目录路径'),
|
|
77
87
|
showHidden: z.boolean().optional().describe('是否显示隐藏文件'),
|
|
88
|
+
namePattern: z.string().optional().describe('名称通配模式,复用同步 exclude 的 * 和 ? 规则,区分大小写'),
|
|
89
|
+
modifiedAfter: z.iso
|
|
90
|
+
.datetime({ offset: true })
|
|
91
|
+
.optional()
|
|
92
|
+
.describe('修改时间下界,包含;使用带时区的 ISO 8601 时间'),
|
|
93
|
+
modifiedBefore: z.iso
|
|
94
|
+
.datetime({ offset: true })
|
|
95
|
+
.optional()
|
|
96
|
+
.describe('修改时间上界,不包含;使用带时区的 ISO 8601 时间'),
|
|
97
|
+
offset: z.number().int().nonnegative().optional().describe('筛选并排序后的条目偏移,默认 0'),
|
|
98
|
+
limit: z.number().int().positive().optional().describe('单页最多条数,使用任一新参数时默认 100'),
|
|
99
|
+
maxBytes: z
|
|
100
|
+
.number()
|
|
101
|
+
.int()
|
|
102
|
+
.positive()
|
|
103
|
+
.optional()
|
|
104
|
+
.describe('响应 JSON 文本的 UTF-8 字节预算,包含分页元数据;使用任一新参数时默认 65536'),
|
|
78
105
|
timeout: operationTimeoutSchema.optional(),
|
|
79
|
-
})
|
|
106
|
+
})
|
|
107
|
+
.refine((args) => args.modifiedAfter === undefined ||
|
|
108
|
+
args.modifiedBefore === undefined ||
|
|
109
|
+
compareDirectoryTimes(args.modifiedAfter, args.modifiedBefore) <= 0, { message: 'modifiedAfter must be at or before modifiedBefore', path: ['modifiedAfter'] });
|
|
80
110
|
const fileInfoSchema = z.object({
|
|
81
111
|
alias: z.string().describe('连接别名'),
|
|
82
112
|
remotePath: z.string().describe('远程路径'),
|
|
@@ -104,12 +134,21 @@ const syncSchema = z.object({
|
|
|
104
134
|
preflightTimeout: z.number().int().positive().max(60000).optional().describe('传输能力预检超时,默认 10000ms'),
|
|
105
135
|
connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
|
|
106
136
|
operationTimeout: z.number().int().positive().max(3600000).optional().describe('同步操作超时,默认 600000ms'),
|
|
107
|
-
verifyOwner: z
|
|
108
|
-
|
|
137
|
+
verifyOwner: z
|
|
138
|
+
.union([z.string(), z.number()])
|
|
139
|
+
.optional()
|
|
140
|
+
.describe('仅非 dryRun 单文件 upload 校验远端 owner(用户名或 uid),目录用 verify.owner'),
|
|
141
|
+
verifyMode: z
|
|
142
|
+
.string()
|
|
143
|
+
.optional()
|
|
144
|
+
.describe('仅非 dryRun 单文件 upload 校验远端权限,例如 0644、4755 或 -rwsr-xr-x,目录用 verify.mode'),
|
|
109
145
|
verify: z
|
|
110
146
|
.object({
|
|
111
147
|
count: z.boolean().optional().describe('校验目录条目数'),
|
|
112
|
-
sha256: z
|
|
148
|
+
sha256: z
|
|
149
|
+
.boolean()
|
|
150
|
+
.optional()
|
|
151
|
+
.describe('显式启用文件 SHA-256 或目录 SHA-256 root manifest 校验,默认 false'),
|
|
113
152
|
owner: z.boolean().optional().describe('逐项校验 owner'),
|
|
114
153
|
mode: z.boolean().optional().describe('逐项校验 POSIX mode;Windows 不支持'),
|
|
115
154
|
aclSddl: z
|
|
@@ -117,7 +156,7 @@ const syncSchema = z.object({
|
|
|
117
156
|
.min(1)
|
|
118
157
|
.max(8192)
|
|
119
158
|
.optional()
|
|
120
|
-
.describe('Windows
|
|
159
|
+
.describe('Windows 远端文件或目录根路径的预期 DACL SDDL,独立于 POSIX mode/owner'),
|
|
121
160
|
deletions: z.boolean().optional().describe('校验请求删除后没有额外条目'),
|
|
122
161
|
staleFiles: z.boolean().optional().describe('校验没有旧文件残留'),
|
|
123
162
|
maxEntries: z
|
|
@@ -143,7 +182,7 @@ const syncSchema = z.object({
|
|
|
143
182
|
.describe('SHA-256 校验的总字节上限,默认 1GB,最大 16GB'),
|
|
144
183
|
})
|
|
145
184
|
.optional()
|
|
146
|
-
.describe('
|
|
185
|
+
.describe('有界文件或目录校验;count/deletions/staleFiles 仅适用于目录,未传时不执行额外远端扫描'),
|
|
147
186
|
});
|
|
148
187
|
// ========== Handlers ==========
|
|
149
188
|
const LARGE_UPLOAD_THRESHOLD = 100 * 1024 * 1024;
|
|
@@ -159,17 +198,6 @@ class VerificationStageError extends Error {
|
|
|
159
198
|
this.name = 'VerificationStageError';
|
|
160
199
|
}
|
|
161
200
|
}
|
|
162
|
-
function sftpOperationOutcome(error) {
|
|
163
|
-
if (!error || typeof error !== 'object') {
|
|
164
|
-
return {};
|
|
165
|
-
}
|
|
166
|
-
const details = 'details' in error ? error.details : undefined;
|
|
167
|
-
if (details && typeof details === 'object' && 'operationStatus' in details) {
|
|
168
|
-
return details;
|
|
169
|
-
}
|
|
170
|
-
const cause = 'cause' in error ? error.cause : undefined;
|
|
171
|
-
return sftpOperationOutcome(cause);
|
|
172
|
-
}
|
|
173
201
|
function formatFileOperationError(error) {
|
|
174
202
|
const operationOutcome = sftpOperationOutcome(error);
|
|
175
203
|
if (Object.keys(operationOutcome).length === 0) {
|
|
@@ -201,6 +229,12 @@ function verificationErrorDetails(error) {
|
|
|
201
229
|
retryable: false,
|
|
202
230
|
};
|
|
203
231
|
}
|
|
232
|
+
function syncVerificationError(error, control) {
|
|
233
|
+
if (!control.signal.aborted && Date.now() < control.deadline) {
|
|
234
|
+
return error;
|
|
235
|
+
}
|
|
236
|
+
return new VerificationStageError('verification_timeout', 'Sync verification exceeded the operation timeout', true, { status: 'unknown', timedOut: true, cause: error instanceof Error ? error.message : String(error) });
|
|
237
|
+
}
|
|
204
238
|
function summarizeLocalPathProbe(probe) {
|
|
205
239
|
const summary = {
|
|
206
240
|
exists: probe.exists,
|
|
@@ -240,29 +274,21 @@ function uploadPathError(code, message, diagnostics) {
|
|
|
240
274
|
function normalizeRemotePath(alias, remotePath) {
|
|
241
275
|
return sftpPath(remotePath, sessionManager.getRemotePathStyle(alias));
|
|
242
276
|
}
|
|
243
|
-
async function probeRemoteParent(alias, remotePath) {
|
|
277
|
+
async function probeRemoteParent(alias, remotePath, timeout, signal) {
|
|
244
278
|
const parent = remoteDirname(sessionManager.getRemotePathStyle(alias), remotePath);
|
|
279
|
+
const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
|
|
245
280
|
try {
|
|
246
|
-
const result = await probeRemoteFile(alias, parent);
|
|
281
|
+
const result = await probeRemoteFile(alias, parent, timeout, signal);
|
|
247
282
|
return {
|
|
248
283
|
exists: result.exists,
|
|
249
284
|
isDirectory: result.exists ? result.isDirectory : false,
|
|
250
|
-
probeMethod
|
|
285
|
+
probeMethod,
|
|
251
286
|
};
|
|
252
287
|
}
|
|
253
288
|
catch (error) {
|
|
254
|
-
return { error: error instanceof Error ? error.message : String(error), probeMethod
|
|
289
|
+
return { error: error instanceof Error ? error.message : String(error), probeMethod };
|
|
255
290
|
}
|
|
256
291
|
}
|
|
257
|
-
function hashLocalFileMd5(filePath) {
|
|
258
|
-
return new Promise((resolve, reject) => {
|
|
259
|
-
const hash = createHash('md5');
|
|
260
|
-
const stream = fs.createReadStream(filePath);
|
|
261
|
-
stream.on('data', (chunk) => hash.update(chunk));
|
|
262
|
-
stream.on('error', reject);
|
|
263
|
-
stream.on('end', () => resolve(hash.digest('hex')));
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
292
|
function boundedDiagnostic(value, maxBytes = 2048) {
|
|
267
293
|
const buffer = Buffer.from(value, 'utf8');
|
|
268
294
|
if (buffer.length <= maxBytes) {
|
|
@@ -289,21 +315,21 @@ function commandFailureDetails(result) {
|
|
|
289
315
|
stderrTruncated: result.stderrTruncated || stderr.truncated || undefined,
|
|
290
316
|
};
|
|
291
317
|
}
|
|
292
|
-
async function hashRemoteFileMd5(alias, remotePath) {
|
|
318
|
+
async function hashRemoteFileMd5(alias, remotePath, timeout) {
|
|
293
319
|
try {
|
|
294
|
-
return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5');
|
|
320
|
+
return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5', timeout);
|
|
295
321
|
}
|
|
296
322
|
catch (error) {
|
|
297
323
|
throw new VerificationStageError('remote_probe', `Remote SFTP MD5 read failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'md5', probeMethod: 'sftp' });
|
|
298
324
|
}
|
|
299
325
|
}
|
|
300
|
-
async function resolveExpectedOwnerId(alias, owner) {
|
|
326
|
+
async function resolveExpectedOwnerId(alias, owner, timeout = 10000) {
|
|
301
327
|
const ownerText = String(owner);
|
|
302
328
|
if (/^\d+$/.test(ownerText)) {
|
|
303
329
|
return ownerText;
|
|
304
330
|
}
|
|
305
331
|
const result = await sessionManager.exec(alias, `id -u ${escapeShellArg(ownerText)}`, {
|
|
306
|
-
timeout
|
|
332
|
+
timeout,
|
|
307
333
|
useLoginUser: true,
|
|
308
334
|
maxOutputSize: 4096,
|
|
309
335
|
});
|
|
@@ -323,23 +349,24 @@ function isRemoteMissingError(error) {
|
|
|
323
349
|
}
|
|
324
350
|
const code = 'code' in error ? error.code : undefined;
|
|
325
351
|
const message = error instanceof Error ? error.message : String(error);
|
|
326
|
-
return code === 2 || code === 'ENOENT' || /no such file|not found
|
|
352
|
+
return code === 2 || code === 'ENOENT' || /no such file|^(?:file |remote path )?not found$/i.test(message);
|
|
327
353
|
}
|
|
328
|
-
async function probeRemoteFile(alias, remotePath, timeout = 10000) {
|
|
354
|
+
async function probeRemoteFile(alias, remotePath, timeout = 10000, signal) {
|
|
355
|
+
const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
|
|
329
356
|
let info;
|
|
330
357
|
try {
|
|
331
|
-
info = await fileOps.getFileInfo(alias, remotePath, timeout);
|
|
358
|
+
info = await fileOps.getFileInfo(alias, remotePath, timeout, undefined, signal);
|
|
332
359
|
}
|
|
333
360
|
catch (error) {
|
|
334
361
|
if (isRemoteMissingError(error)) {
|
|
335
|
-
return { exists: false, remotePath, probeMethod
|
|
362
|
+
return { exists: false, remotePath, probeMethod };
|
|
336
363
|
}
|
|
337
|
-
throw new VerificationStageError('remote_probe', `Remote
|
|
364
|
+
throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod, ...sftpOperationOutcome(error) });
|
|
338
365
|
}
|
|
339
366
|
return {
|
|
340
367
|
exists: true,
|
|
341
368
|
remotePath,
|
|
342
|
-
probeMethod
|
|
369
|
+
probeMethod,
|
|
343
370
|
ownerName: undefined,
|
|
344
371
|
ownerId: info.owner,
|
|
345
372
|
groupName: undefined,
|
|
@@ -361,7 +388,7 @@ async function probeRemoteFile(alias, remotePath, timeout = 10000) {
|
|
|
361
388
|
};
|
|
362
389
|
}
|
|
363
390
|
async function buildUploadVerification(args, local, verificationRemotePath = args.remotePath) {
|
|
364
|
-
const remote = await probeRemoteFile(args.alias, verificationRemotePath);
|
|
391
|
+
const remote = await probeRemoteFile(args.alias, verificationRemotePath, args.timeout);
|
|
365
392
|
const checks = {};
|
|
366
393
|
if (args.verifySize) {
|
|
367
394
|
checks.size = local.exists && remote.exists ? local.size === remote.size : false;
|
|
@@ -375,13 +402,13 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
|
|
|
375
402
|
checks.mode = remote.exists && expectedMode !== undefined && remote.modeValue === expectedMode;
|
|
376
403
|
}
|
|
377
404
|
if (args.verifyOwner !== undefined) {
|
|
378
|
-
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
|
|
405
|
+
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner, args.timeout);
|
|
379
406
|
checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
|
|
380
407
|
}
|
|
381
408
|
if (args.verifyMd5 && local.exists) {
|
|
382
409
|
const [localMd5, remoteMd5] = await Promise.all([
|
|
383
|
-
|
|
384
|
-
hashRemoteFileMd5(args.alias, verificationRemotePath),
|
|
410
|
+
fileOps.hashLocalFile(local.resolvedPath, 'md5', args.timeout),
|
|
411
|
+
hashRemoteFileMd5(args.alias, verificationRemotePath, args.timeout),
|
|
385
412
|
]);
|
|
386
413
|
checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
|
|
387
414
|
return {
|
|
@@ -418,10 +445,10 @@ function displayExpectedMode(mode) {
|
|
|
418
445
|
const parsed = normalizeExpectedMode(mode);
|
|
419
446
|
return parsed === undefined ? undefined : formatFileMode(parsed);
|
|
420
447
|
}
|
|
421
|
-
async function buildSyncVerificationChecks(args, remote) {
|
|
448
|
+
async function buildSyncVerificationChecks(args, remote, timeout) {
|
|
422
449
|
const checks = {};
|
|
423
450
|
if (args.verifyOwner !== undefined) {
|
|
424
|
-
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
|
|
451
|
+
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner, timeout);
|
|
425
452
|
checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
|
|
426
453
|
}
|
|
427
454
|
if (args.verifyMode !== undefined) {
|
|
@@ -433,14 +460,14 @@ async function buildSyncVerificationChecks(args, remote) {
|
|
|
433
460
|
async function resolveSyncUploadVerificationPath(args, local, timeout) {
|
|
434
461
|
const requestedRemote = await probeRemoteFile(args.alias, args.remotePath, timeout);
|
|
435
462
|
if (requestedRemote.exists && requestedRemote.isDirectory) {
|
|
436
|
-
return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.
|
|
463
|
+
return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.expandedPath));
|
|
437
464
|
}
|
|
438
465
|
if (!requestedRemote.exists && args.remotePath.endsWith('/')) {
|
|
439
|
-
return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.
|
|
466
|
+
return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.expandedPath));
|
|
440
467
|
}
|
|
441
468
|
return args.remotePath;
|
|
442
469
|
}
|
|
443
|
-
async function buildSyncUploadVerification(args, local,
|
|
470
|
+
async function buildSyncUploadVerification(args, local, control) {
|
|
444
471
|
if (args.verifyOwner === undefined && args.verifyMode === undefined) {
|
|
445
472
|
return undefined;
|
|
446
473
|
}
|
|
@@ -459,12 +486,10 @@ async function buildSyncUploadVerification(args, local, timeout) {
|
|
|
459
486
|
suggestion: '目录权限校验请使用 verify.owner 或 verify.mode',
|
|
460
487
|
};
|
|
461
488
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
const remote = await probeRemoteFile(args.alias, verificationRemotePath, timeout);
|
|
467
|
-
const checks = await buildSyncVerificationChecks(args, remote);
|
|
489
|
+
const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, remainingVerificationTimeout(control));
|
|
490
|
+
const remote = await probeRemoteFile(args.alias, verificationRemotePath, remainingVerificationTimeout(control));
|
|
491
|
+
const checks = await buildSyncVerificationChecks(args, remote, remainingVerificationTimeout(control));
|
|
492
|
+
remainingVerificationTimeout(control);
|
|
468
493
|
const matched = Object.values(checks).every(Boolean);
|
|
469
494
|
return {
|
|
470
495
|
kind: 'owner_mode',
|
|
@@ -482,13 +507,19 @@ async function buildSyncUploadVerification(args, local, timeout) {
|
|
|
482
507
|
: '同步已完成,但远端 owner/mode 与期望不一致;工具不会自动 chown/chmod,请按需用 ssh_exec 显式处理权限',
|
|
483
508
|
};
|
|
484
509
|
}
|
|
485
|
-
async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks,
|
|
510
|
+
async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, control) {
|
|
511
|
+
const connection = sessionManager.getOpenSshConnection(alias);
|
|
512
|
+
if (connection) {
|
|
513
|
+
return createOpenSshDirectoryManifest(connection, remotePath, request, remainingVerificationTimeout(control), exclude, followSymlinks, control);
|
|
514
|
+
}
|
|
515
|
+
const timeout = remainingVerificationTimeout(control);
|
|
486
516
|
const requestSftp = sessionManager.getSftp(alias);
|
|
487
517
|
const sftp = await withSftpOperationTimeout(requestSftp, timeout, () => {
|
|
488
518
|
void requestSftp.then((late) => late.end(), () => undefined);
|
|
489
|
-
});
|
|
519
|
+
}, control.signal);
|
|
490
520
|
try {
|
|
491
|
-
|
|
521
|
+
const remaining = remainingVerificationTimeout(control);
|
|
522
|
+
return await withSftpOperationTimeout(createRemoteDirectoryManifest(sftp, remotePath, request, exclude, followSymlinks, sessionManager.getRemotePathStyle(alias), control), remaining, () => sftp.end(), control.signal);
|
|
492
523
|
}
|
|
493
524
|
catch (error) {
|
|
494
525
|
throw new VerificationStageError('remote_manifest_output', error instanceof Error ? error.message : String(error), true);
|
|
@@ -511,28 +542,21 @@ function deletionManifestRequest(request) {
|
|
|
511
542
|
staleFiles: false,
|
|
512
543
|
};
|
|
513
544
|
}
|
|
514
|
-
async function captureDeletionBaseline(args,
|
|
545
|
+
async function captureDeletionBaseline(args, control) {
|
|
515
546
|
if (!args.verify?.deletions || args.dryRun) {
|
|
516
547
|
return undefined;
|
|
517
548
|
}
|
|
549
|
+
remainingVerificationTimeout(control);
|
|
518
550
|
const request = deletionManifestRequest(args.verify);
|
|
519
551
|
if (args.direction === 'upload') {
|
|
520
|
-
const
|
|
521
|
-
if (probeTimeout <= 0) {
|
|
522
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline capture started', true);
|
|
523
|
-
}
|
|
524
|
-
const remote = await probeRemoteFile(args.alias, args.remotePath, probeTimeout);
|
|
552
|
+
const remote = await probeRemoteFile(args.alias, args.remotePath, remainingVerificationTimeout(control));
|
|
525
553
|
if (!remote.exists) {
|
|
526
554
|
return createEmptyDirectoryManifest();
|
|
527
555
|
}
|
|
528
556
|
if (!remote.isDirectory) {
|
|
529
557
|
throw new VerificationStageError('remote_probe', 'deletion verification requires the remote destination to be a directory', false, { remotePath: args.remotePath, fileType: remote.fileType });
|
|
530
558
|
}
|
|
531
|
-
|
|
532
|
-
if (manifestTimeout <= 0) {
|
|
533
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline manifest started', true);
|
|
534
|
-
}
|
|
535
|
-
return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), manifestTimeout);
|
|
559
|
+
return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
536
560
|
}
|
|
537
561
|
const local = fileOps.probeLocalPath(args.localPath);
|
|
538
562
|
if (!local.exists) {
|
|
@@ -542,13 +566,93 @@ async function captureDeletionBaseline(args, remainingTimeout) {
|
|
|
542
566
|
throw new VerificationStageError('local_manifest', 'deletion verification requires the local destination to be a directory', false, { localPath: args.localPath });
|
|
543
567
|
}
|
|
544
568
|
try {
|
|
545
|
-
return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
|
|
569
|
+
return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
546
570
|
}
|
|
547
571
|
catch (error) {
|
|
548
572
|
throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
|
|
549
573
|
}
|
|
550
574
|
}
|
|
551
|
-
async function
|
|
575
|
+
async function buildSingleFileSyncVerification(args, local, control) {
|
|
576
|
+
if (!args.verify) {
|
|
577
|
+
return undefined;
|
|
578
|
+
}
|
|
579
|
+
if (args.dryRun) {
|
|
580
|
+
return { kind: 'single_file', skipped: true, reason: 'file verification is not executed during dryRun' };
|
|
581
|
+
}
|
|
582
|
+
if (!local.exists || !local.isFile) {
|
|
583
|
+
throw new VerificationStageError('local_manifest', 'File verification requires the transferred local file', false);
|
|
584
|
+
}
|
|
585
|
+
const remaining = () => remainingVerificationTimeout(control);
|
|
586
|
+
const remotePath = args.direction === 'upload'
|
|
587
|
+
? await resolveSyncUploadVerificationPath(args, local, remaining())
|
|
588
|
+
: args.remotePath;
|
|
589
|
+
const remote = await probeRemoteFile(args.alias, remotePath, remaining());
|
|
590
|
+
const checks = {
|
|
591
|
+
file: remote.exists && remote.isFile,
|
|
592
|
+
size: remote.exists && remote.size === local.size,
|
|
593
|
+
};
|
|
594
|
+
if (args.verify.owner) {
|
|
595
|
+
checks.owner = remote.exists && String(remote.ownerId) === String(fs.statSync(local.resolvedPath).uid);
|
|
596
|
+
}
|
|
597
|
+
if (args.verify.mode) {
|
|
598
|
+
checks.mode = remote.exists && remote.modeValue === local.modeValue;
|
|
599
|
+
}
|
|
600
|
+
let localSha256;
|
|
601
|
+
let remoteSha256;
|
|
602
|
+
if (args.verify.sha256 && remote.exists && remote.isFile) {
|
|
603
|
+
const maxBytes = Math.min(args.verify.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
|
|
604
|
+
if (local.size > maxBytes || remote.size > maxBytes) {
|
|
605
|
+
return { kind: 'single_file', skipped: true, reason: 'file verification byte budget exceeded', maxBytes };
|
|
606
|
+
}
|
|
607
|
+
;
|
|
608
|
+
[localSha256, remoteSha256] = await Promise.all([
|
|
609
|
+
Promise.resolve().then(() => fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size })),
|
|
610
|
+
Promise.resolve().then(() => fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
|
|
611
|
+
maxBytes,
|
|
612
|
+
expectedSize: remote.size,
|
|
613
|
+
}, control.signal)),
|
|
614
|
+
]);
|
|
615
|
+
checks.sha256 = localSha256 === remoteSha256;
|
|
616
|
+
const after = await probeRemoteFile(args.alias, remotePath, remaining());
|
|
617
|
+
if (!after.exists ||
|
|
618
|
+
after.size !== remote.size ||
|
|
619
|
+
after.mtimeMs !== remote.mtimeMs ||
|
|
620
|
+
after.modeValue !== remote.modeValue ||
|
|
621
|
+
after.ownerId !== remote.ownerId) {
|
|
622
|
+
throw new VerificationStageError('remote_probe', 'Remote file changed during sync verification', true);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
else if (args.verify.sha256) {
|
|
626
|
+
checks.sha256 = false;
|
|
627
|
+
}
|
|
628
|
+
if (args.verify.aclSddl) {
|
|
629
|
+
const command = encodedPowershell('$acl = Get-Acl -LiteralPath ' +
|
|
630
|
+
`${quotePowershell(remoteShellPath(remotePath, sessionManager.getRemotePathStyle(args.alias)))}` +
|
|
631
|
+
'; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.Acce' +
|
|
632
|
+
'ssControlSections]::Access)');
|
|
633
|
+
const result = await sessionManager.exec(args.alias, command, {
|
|
634
|
+
timeout: remaining(),
|
|
635
|
+
useLoginUser: true,
|
|
636
|
+
maxOutputSize: 8192,
|
|
637
|
+
});
|
|
638
|
+
if (!result.success || result.stdoutTruncated) {
|
|
639
|
+
throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
|
|
640
|
+
}
|
|
641
|
+
checks.acl = result.stdout.trim() === args.verify.aclSddl;
|
|
642
|
+
}
|
|
643
|
+
remaining();
|
|
644
|
+
return {
|
|
645
|
+
kind: 'single_file',
|
|
646
|
+
matched: Object.values(checks).every(Boolean),
|
|
647
|
+
checks,
|
|
648
|
+
direction: args.direction,
|
|
649
|
+
remotePath,
|
|
650
|
+
localPath: local.expandedPath,
|
|
651
|
+
local: { ...summarizeLocalPathProbe(local), sha256: localSha256 },
|
|
652
|
+
remote: { ...remote, sha256: remoteSha256 },
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
async function buildDirectorySyncVerification(args, local, control, deletionBaseline) {
|
|
552
656
|
if (!args.verify) {
|
|
553
657
|
return undefined;
|
|
554
658
|
}
|
|
@@ -558,14 +662,12 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
|
|
|
558
662
|
if (!local.exists || !local.isDirectory) {
|
|
559
663
|
return { kind: 'directory', skipped: true, reason: 'bounded directory verification requires a local directory' };
|
|
560
664
|
}
|
|
561
|
-
|
|
562
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before directory verification started', true);
|
|
563
|
-
}
|
|
665
|
+
remainingVerificationTimeout(control);
|
|
564
666
|
const request = args.verify;
|
|
565
|
-
const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args),
|
|
667
|
+
const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
566
668
|
let localManifest;
|
|
567
669
|
try {
|
|
568
|
-
localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
|
|
670
|
+
localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
569
671
|
}
|
|
570
672
|
catch (error) {
|
|
571
673
|
throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
|
|
@@ -573,10 +675,21 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
|
|
|
573
675
|
const comparison = args.direction === 'upload'
|
|
574
676
|
? compareDirectoryManifests(localManifest, remoteManifest, request, deletionBaseline)
|
|
575
677
|
: compareDirectoryManifests(remoteManifest, localManifest, request, deletionBaseline);
|
|
678
|
+
if (remoteManifest.skippedSymlinks > 0 ||
|
|
679
|
+
localManifest.skippedSymlinks > 0 ||
|
|
680
|
+
(deletionBaseline?.skippedSymlinks ?? 0) > 0) {
|
|
681
|
+
comparison.suggestion =
|
|
682
|
+
args.direction === 'upload' && !args.followSymlinks
|
|
683
|
+
? '排除符号链接后重新同步和校验,或显式设置 followSymlinks=true 上传并校验链接目标'
|
|
684
|
+
: '排除符号链接后重新同步和校验;download 保持跳过链接目标,followSymlinks 仅适用于 upload';
|
|
685
|
+
}
|
|
576
686
|
if (request.aclSddl && !('skipped' in comparison)) {
|
|
577
|
-
const command = encodedPowershell(
|
|
687
|
+
const command = encodedPowershell('$acl = Get-Acl -LiteralPath ' +
|
|
688
|
+
`${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}` +
|
|
689
|
+
'; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.Acce' +
|
|
690
|
+
'ssControlSections]::Access)');
|
|
578
691
|
const result = await sessionManager.exec(args.alias, command, {
|
|
579
|
-
timeout,
|
|
692
|
+
timeout: remainingVerificationTimeout(control),
|
|
580
693
|
useLoginUser: true,
|
|
581
694
|
maxOutputSize: 8192,
|
|
582
695
|
});
|
|
@@ -589,10 +702,11 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
|
|
|
589
702
|
comparison.matched = comparison.matched === true && aclMatch;
|
|
590
703
|
comparison.acl = { matched: aclMatch, expected: request.aclSddl, actual: result.stdout.trim() };
|
|
591
704
|
}
|
|
705
|
+
remainingVerificationTimeout(control);
|
|
592
706
|
return comparison;
|
|
593
707
|
}
|
|
594
|
-
function mergeSyncVerification(existing, ownerMode,
|
|
595
|
-
const parts = [existing, ownerMode,
|
|
708
|
+
function mergeSyncVerification(existing, ownerMode, content) {
|
|
709
|
+
const parts = [existing, ownerMode, content].filter((part) => Boolean(part));
|
|
596
710
|
if (parts.length === 0) {
|
|
597
711
|
return undefined;
|
|
598
712
|
}
|
|
@@ -602,12 +716,13 @@ function mergeSyncVerification(existing, ownerMode, directory) {
|
|
|
602
716
|
return {
|
|
603
717
|
transport: existing,
|
|
604
718
|
ownerMode,
|
|
605
|
-
directory,
|
|
719
|
+
directory: content?.kind === 'directory' ? content : undefined,
|
|
720
|
+
singleFile: content?.kind === 'single_file' ? content : undefined,
|
|
606
721
|
};
|
|
607
722
|
}
|
|
608
|
-
async function cleanupRemotePath(alias, remotePath) {
|
|
723
|
+
async function cleanupRemotePath(alias, remotePath, timeout) {
|
|
609
724
|
try {
|
|
610
|
-
await fileOps.removeRemoteFile(alias, remotePath);
|
|
725
|
+
await fileOps.removeRemoteFile(alias, remotePath, timeout);
|
|
611
726
|
}
|
|
612
727
|
catch (error) {
|
|
613
728
|
throw new Error(`Temporary remote file cleanup failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
@@ -642,7 +757,8 @@ async function handleUpload(args) {
|
|
|
642
757
|
return formatResult({
|
|
643
758
|
success: false,
|
|
644
759
|
code: 'unsupported_remote_platform',
|
|
645
|
-
error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use
|
|
760
|
+
error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use ' +
|
|
761
|
+
'Windows ACL verification',
|
|
646
762
|
});
|
|
647
763
|
}
|
|
648
764
|
}
|
|
@@ -679,15 +795,17 @@ async function handleUpload(args) {
|
|
|
679
795
|
'direction="upload")',
|
|
680
796
|
].join(', ')
|
|
681
797
|
: undefined;
|
|
682
|
-
const remoteParent = await probeRemoteParent(args.alias, args.remotePath);
|
|
798
|
+
const remoteParent = await probeRemoteParent(args.alias, args.remotePath, args.timeout);
|
|
683
799
|
let remoteBefore;
|
|
684
800
|
try {
|
|
685
|
-
remoteBefore = await probeRemoteFile(args.alias, args.remotePath);
|
|
801
|
+
remoteBefore = await probeRemoteFile(args.alias, args.remotePath, args.timeout);
|
|
686
802
|
}
|
|
687
803
|
catch (error) {
|
|
688
|
-
return
|
|
689
|
-
|
|
690
|
-
|
|
804
|
+
return formatError(error, {
|
|
805
|
+
...sftpOperationOutcome(error),
|
|
806
|
+
operationStatus: 'failed',
|
|
807
|
+
failureStage: 'preflight',
|
|
808
|
+
acknowledgedBytes: 0,
|
|
691
809
|
diagnostics: {
|
|
692
810
|
local: summarizeLocalPathProbe(local),
|
|
693
811
|
remoteParent,
|
|
@@ -712,12 +830,14 @@ async function handleUpload(args) {
|
|
|
712
830
|
}
|
|
713
831
|
}
|
|
714
832
|
catch (error) {
|
|
715
|
-
return
|
|
716
|
-
|
|
833
|
+
return formatError(error, {
|
|
834
|
+
...sftpOperationOutcome(error),
|
|
835
|
+
operationStatus: 'failed',
|
|
836
|
+
failureStage: 'preflight',
|
|
837
|
+
acknowledgedBytes: 0,
|
|
717
838
|
code: 'atomic_replace_unverified',
|
|
718
839
|
atomicReplaceSupported: null,
|
|
719
840
|
targetReplaced: false,
|
|
720
|
-
error: error instanceof Error ? error.message : String(error),
|
|
721
841
|
});
|
|
722
842
|
}
|
|
723
843
|
}
|
|
@@ -759,7 +879,7 @@ async function handleUpload(args) {
|
|
|
759
879
|
if (args.atomic && !outcome.success) {
|
|
760
880
|
let cleanupWarning;
|
|
761
881
|
try {
|
|
762
|
-
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
882
|
+
await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
|
|
763
883
|
}
|
|
764
884
|
catch (cleanupError) {
|
|
765
885
|
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
@@ -795,11 +915,12 @@ async function handleUpload(args) {
|
|
|
795
915
|
await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists, args.timeout);
|
|
796
916
|
}
|
|
797
917
|
catch (error) {
|
|
798
|
-
const
|
|
918
|
+
const renameOutcome = sftpOperationOutcome(error);
|
|
919
|
+
const renameNotStarted = renameOutcome.operationStatus === 'failed' || error instanceof fileOps.RemoteRenameNotStartedError;
|
|
799
920
|
const renameError = error instanceof Error ? error.message : String(error);
|
|
800
921
|
let cleanupWarning;
|
|
801
922
|
try {
|
|
802
|
-
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
923
|
+
await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
|
|
803
924
|
}
|
|
804
925
|
catch (cleanupError) {
|
|
805
926
|
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
@@ -807,11 +928,14 @@ async function handleUpload(args) {
|
|
|
807
928
|
return formatResult({
|
|
808
929
|
success: false,
|
|
809
930
|
transferSuccess: true,
|
|
931
|
+
...renameOutcome,
|
|
932
|
+
acknowledgedBytes: uploadResult.size,
|
|
810
933
|
operationStatus: renameNotStarted ? 'failed' : 'unknown',
|
|
811
|
-
retryable:
|
|
934
|
+
retryable: false,
|
|
812
935
|
error: renameNotStarted
|
|
813
936
|
? `Atomic SFTP rename request was not sent; target was not replaced: ${renameError}`
|
|
814
|
-
:
|
|
937
|
+
: 'Atomic SFTP rename response failed; target replacement state is unknown: ' +
|
|
938
|
+
`${renameError}`,
|
|
815
939
|
cleanupWarning,
|
|
816
940
|
atomic: true,
|
|
817
941
|
atomicReplaceSupported,
|
|
@@ -863,17 +987,16 @@ async function handleUpload(args) {
|
|
|
863
987
|
(error instanceof fileOps.UploadFileError && error.remoteCreated));
|
|
864
988
|
if (shouldCleanupTemporaryUpload) {
|
|
865
989
|
try {
|
|
866
|
-
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
990
|
+
await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
|
|
867
991
|
}
|
|
868
992
|
catch (cleanupError) {
|
|
869
993
|
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
870
994
|
}
|
|
871
995
|
}
|
|
872
|
-
return
|
|
873
|
-
success: false,
|
|
996
|
+
return formatError(error, {
|
|
874
997
|
...sftpOperationOutcome(error),
|
|
875
|
-
error: error instanceof Error ? error.message : String(error),
|
|
876
998
|
cleanupWarning,
|
|
999
|
+
targetReplaced: args.atomic ? false : undefined,
|
|
877
1000
|
atomicReplaceSupported,
|
|
878
1001
|
finalRemotePath: args.remotePath,
|
|
879
1002
|
diagnostics: {
|
|
@@ -893,10 +1016,10 @@ async function handleDownload(args) {
|
|
|
893
1016
|
return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
|
|
894
1017
|
}
|
|
895
1018
|
catch (error) {
|
|
896
|
-
return
|
|
897
|
-
success: false,
|
|
1019
|
+
return formatError(error, {
|
|
898
1020
|
...sftpOperationOutcome(error),
|
|
899
|
-
|
|
1021
|
+
operationStatus: 'failed',
|
|
1022
|
+
targetReplaced: false,
|
|
900
1023
|
diagnostics: {
|
|
901
1024
|
local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
|
|
902
1025
|
localParent: summarizeLocalPathProbe(fileOps.probeLocalPath(path.dirname(args.localPath))),
|
|
@@ -937,12 +1060,67 @@ async function handleListDir(args) {
|
|
|
937
1060
|
try {
|
|
938
1061
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
939
1062
|
const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
|
|
940
|
-
|
|
1063
|
+
const bounded = [
|
|
1064
|
+
args.namePattern,
|
|
1065
|
+
args.modifiedAfter,
|
|
1066
|
+
args.modifiedBefore,
|
|
1067
|
+
args.offset,
|
|
1068
|
+
args.limit,
|
|
1069
|
+
args.maxBytes,
|
|
1070
|
+
].some((value) => value !== undefined);
|
|
1071
|
+
if (!bounded) {
|
|
1072
|
+
return formatResult({ success: true, path: args.remotePath, count: files.length, files });
|
|
1073
|
+
}
|
|
1074
|
+
const patterns = args.namePattern === undefined ? undefined : [args.namePattern];
|
|
1075
|
+
const matching = files.filter((file) => (patterns === undefined || matchesDirectoryExclude(file.name, patterns)) &&
|
|
1076
|
+
(args.modifiedAfter === undefined ||
|
|
1077
|
+
compareDirectoryTimes(file.mtime.toISOString(), args.modifiedAfter) >= 0) &&
|
|
1078
|
+
(args.modifiedBefore === undefined ||
|
|
1079
|
+
compareDirectoryTimes(file.mtime.toISOString(), args.modifiedBefore) < 0));
|
|
1080
|
+
const offset = args.offset ?? 0;
|
|
1081
|
+
const limit = args.limit ?? 100;
|
|
1082
|
+
const maxBytes = args.maxBytes ?? 65536;
|
|
1083
|
+
const page = (count) => formatResult({
|
|
941
1084
|
success: true,
|
|
942
1085
|
path: args.remotePath,
|
|
943
|
-
count
|
|
944
|
-
files,
|
|
1086
|
+
count,
|
|
1087
|
+
files: matching.slice(offset, offset + count),
|
|
1088
|
+
total_count: matching.length,
|
|
1089
|
+
offset,
|
|
1090
|
+
has_more: offset + count < matching.length,
|
|
1091
|
+
next_offset: offset + count,
|
|
945
1092
|
});
|
|
1093
|
+
let lower = 0;
|
|
1094
|
+
let upper = Math.min(limit, Math.max(0, matching.length - offset));
|
|
1095
|
+
let response = page(0);
|
|
1096
|
+
while (lower < upper) {
|
|
1097
|
+
const count = Math.ceil((lower + upper) / 2);
|
|
1098
|
+
const candidate = page(count);
|
|
1099
|
+
if (Buffer.byteLength(candidate.content[0].text, 'utf8') <= maxBytes) {
|
|
1100
|
+
lower = count;
|
|
1101
|
+
response = candidate;
|
|
1102
|
+
}
|
|
1103
|
+
else {
|
|
1104
|
+
upper = count - 1;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
if (Buffer.byteLength(response.content[0].text, 'utf8') > maxBytes ||
|
|
1108
|
+
(lower === 0 && offset < matching.length)) {
|
|
1109
|
+
const minimum = page(offset < matching.length ? 1 : 0);
|
|
1110
|
+
return {
|
|
1111
|
+
...formatResult({
|
|
1112
|
+
success: false,
|
|
1113
|
+
code: 'LIST_DIR_MAX_BYTES_TOO_SMALL',
|
|
1114
|
+
error: 'maxBytes is too small for directory page metadata and the next complete ' + 'entry, if any',
|
|
1115
|
+
offset,
|
|
1116
|
+
next_offset: offset,
|
|
1117
|
+
maxBytes,
|
|
1118
|
+
requiredBytes: Buffer.byteLength(minimum.content[0].text, 'utf8'),
|
|
1119
|
+
}),
|
|
1120
|
+
isError: true,
|
|
1121
|
+
};
|
|
1122
|
+
}
|
|
1123
|
+
return response;
|
|
946
1124
|
}
|
|
947
1125
|
catch (error) {
|
|
948
1126
|
return formatFileOperationError(error);
|
|
@@ -968,7 +1146,7 @@ async function handleMkdir(args) {
|
|
|
968
1146
|
return formatFileOperationError(error);
|
|
969
1147
|
}
|
|
970
1148
|
}
|
|
971
|
-
async function handleSync(args) {
|
|
1149
|
+
async function handleSync(args, extra) {
|
|
972
1150
|
const startedAt = Date.now();
|
|
973
1151
|
try {
|
|
974
1152
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
@@ -992,6 +1170,15 @@ async function handleSync(args) {
|
|
|
992
1170
|
catch (error) {
|
|
993
1171
|
return formatError(error);
|
|
994
1172
|
}
|
|
1173
|
+
const ownerModeRequested = args.verifyOwner !== undefined || args.verifyMode !== undefined;
|
|
1174
|
+
if (ownerModeRequested && (args.direction !== 'upload' || args.dryRun)) {
|
|
1175
|
+
return formatResult({
|
|
1176
|
+
success: false,
|
|
1177
|
+
transferSuccess: false,
|
|
1178
|
+
code: 'UNSUPPORTED_SYNC_VERIFICATION',
|
|
1179
|
+
error: 'verifyOwner/verifyMode require a non-dryRun single-file upload; use verify.owner/verify.mode for directory or download verification',
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
995
1182
|
if (args.verify?.deletions && args.delete !== true) {
|
|
996
1183
|
return formatResult({
|
|
997
1184
|
success: false,
|
|
@@ -1000,7 +1187,8 @@ async function handleSync(args) {
|
|
|
1000
1187
|
});
|
|
1001
1188
|
}
|
|
1002
1189
|
const operationTimeout = args.operationTimeout ?? 600_000;
|
|
1003
|
-
const
|
|
1190
|
+
const deadline = startedAt + operationTimeout;
|
|
1191
|
+
const remainingTimeout = () => deadline - Date.now();
|
|
1004
1192
|
try {
|
|
1005
1193
|
if (args.direction === 'upload') {
|
|
1006
1194
|
fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true);
|
|
@@ -1019,14 +1207,116 @@ async function handleSync(args) {
|
|
|
1019
1207
|
});
|
|
1020
1208
|
}
|
|
1021
1209
|
const localBefore = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
1022
|
-
const diagnostics = {
|
|
1023
|
-
|
|
1024
|
-
|
|
1210
|
+
const diagnostics = { localBefore: summarizeLocalPathProbe(localBefore) };
|
|
1211
|
+
if (ownerModeRequested && localBefore.exists && localBefore.isDirectory) {
|
|
1212
|
+
return formatResult({
|
|
1213
|
+
success: false,
|
|
1214
|
+
transferSuccess: false,
|
|
1215
|
+
code: 'UNSUPPORTED_SYNC_VERIFICATION',
|
|
1216
|
+
error: 'verifyOwner/verifyMode require a single-file upload; use verify.owner/verify.mode for directory verification',
|
|
1217
|
+
diagnostics,
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
const controller = new AbortController();
|
|
1221
|
+
const control = {
|
|
1222
|
+
deadline,
|
|
1223
|
+
signal: extra?.signal ? AbortSignal.any([controller.signal, extra.signal]) : controller.signal,
|
|
1025
1224
|
};
|
|
1225
|
+
let progressWarning;
|
|
1226
|
+
let lastProgressAt = -Infinity;
|
|
1227
|
+
let progress = 0;
|
|
1228
|
+
let progressPending = false;
|
|
1229
|
+
const progressToken = extra?._meta?.progressToken;
|
|
1230
|
+
const onProgress = progressToken === undefined
|
|
1231
|
+
? undefined
|
|
1232
|
+
: (update) => {
|
|
1233
|
+
if (control.signal?.aborted ||
|
|
1234
|
+
progressPending ||
|
|
1235
|
+
progressWarning ||
|
|
1236
|
+
Date.now() - lastProgressAt < 1000) {
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
lastProgressAt = Date.now();
|
|
1240
|
+
progressPending = true;
|
|
1241
|
+
const current = ++progress;
|
|
1242
|
+
void Promise.resolve()
|
|
1243
|
+
.then(() => control.signal?.aborted
|
|
1244
|
+
? undefined
|
|
1245
|
+
: extra.sendNotification({
|
|
1246
|
+
method: 'notifications/progress',
|
|
1247
|
+
params: {
|
|
1248
|
+
progressToken,
|
|
1249
|
+
progress: current,
|
|
1250
|
+
message: `${args.direction === 'upload' ? '上传' : '下载'}:${update.transferred} bytes,${update.percent}%` +
|
|
1251
|
+
(update.total > 0 ? `,当前文件共 ${update.total} bytes` : ''),
|
|
1252
|
+
},
|
|
1253
|
+
}))
|
|
1254
|
+
.catch((error) => {
|
|
1255
|
+
progressWarning = `MCP progress notification failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1256
|
+
console.warn(`[ssh_sync] ${progressWarning}`);
|
|
1257
|
+
})
|
|
1258
|
+
.finally(() => {
|
|
1259
|
+
progressPending = false;
|
|
1260
|
+
});
|
|
1261
|
+
};
|
|
1262
|
+
const timer = setTimeout(() => controller.abort(new SftpOperationTimeoutError(operationTimeout)), Math.max(0, remainingTimeout()));
|
|
1026
1263
|
try {
|
|
1264
|
+
control.signal?.throwIfAborted();
|
|
1265
|
+
const probeTimeout = remainingTimeout();
|
|
1266
|
+
if (probeTimeout <= 0) {
|
|
1267
|
+
throw new Error('sync operation timeout was exhausted before remote probing');
|
|
1268
|
+
}
|
|
1269
|
+
diagnostics.remoteParent = await probeRemoteParent(args.alias, args.remotePath, probeTimeout, control.signal);
|
|
1270
|
+
if (remainingTimeout() <= 0) {
|
|
1271
|
+
throw new Error('sync operation timeout was exhausted before transfer started');
|
|
1272
|
+
}
|
|
1273
|
+
const remoteSource = args.direction === 'download'
|
|
1274
|
+
? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout(), undefined, control.signal)
|
|
1275
|
+
: undefined;
|
|
1276
|
+
const sourceIsDirectory = args.direction === 'upload' ? localBefore.exists && localBefore.isDirectory : remoteSource.isDirectory;
|
|
1277
|
+
const remoteParent = diagnostics.remoteParent;
|
|
1278
|
+
if (args.direction === 'upload' &&
|
|
1279
|
+
!sourceIsDirectory &&
|
|
1280
|
+
!args.dryRun &&
|
|
1281
|
+
(remoteParent.exists === false || (remoteParent.exists === true && remoteParent.isDirectory === false))) {
|
|
1282
|
+
return formatResult({
|
|
1283
|
+
success: false,
|
|
1284
|
+
transferSuccess: false,
|
|
1285
|
+
operationStatus: 'failed',
|
|
1286
|
+
failureStage: 'remote_prepare',
|
|
1287
|
+
code: remoteParent.exists === false ? 'REMOTE_PARENT_NOT_FOUND' : 'REMOTE_PARENT_NOT_DIRECTORY',
|
|
1288
|
+
error: remoteParent.exists === false
|
|
1289
|
+
? '远端父目录不存在,请先用 ssh_mkdir 创建后重新上传'
|
|
1290
|
+
: '远端父路径是文件,请改用目录作为父路径',
|
|
1291
|
+
diagnostics,
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
if (!sourceIsDirectory && (args.verify?.count || args.verify?.deletions || args.verify?.staleFiles)) {
|
|
1295
|
+
return formatResult({
|
|
1296
|
+
success: false,
|
|
1297
|
+
transferSuccess: false,
|
|
1298
|
+
code: 'DIRECTORY_VERIFICATION_REQUIRES_DIRECTORY',
|
|
1299
|
+
error: 'verify.count, verify.deletions and verify.staleFiles require a directory source',
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
const sourceSize = args.direction === 'upload' && localBefore.exists ? localBefore.size : remoteSource?.size;
|
|
1303
|
+
const maxFileBytes = Math.min(args.verify?.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify?.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
|
|
1304
|
+
if (!sourceIsDirectory && args.verify?.sha256 && sourceSize !== undefined && sourceSize > maxFileBytes) {
|
|
1305
|
+
return formatResult({
|
|
1306
|
+
success: false,
|
|
1307
|
+
transferSuccess: false,
|
|
1308
|
+
verificationRequested: true,
|
|
1309
|
+
verificationSuccess: false,
|
|
1310
|
+
verificationStatus: 'skipped',
|
|
1311
|
+
code: 'VERIFICATION_BYTE_LIMIT',
|
|
1312
|
+
error: 'file verification byte budget exceeded before transfer',
|
|
1313
|
+
sourceSize,
|
|
1314
|
+
maxBytes: maxFileBytes,
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1027
1317
|
let deletionBaseline;
|
|
1028
1318
|
try {
|
|
1029
|
-
deletionBaseline = await captureDeletionBaseline(args,
|
|
1319
|
+
deletionBaseline = await captureDeletionBaseline(args, control);
|
|
1030
1320
|
if (deletionBaseline) {
|
|
1031
1321
|
diagnostics.deletionBaseline = {
|
|
1032
1322
|
count: deletionBaseline.count,
|
|
@@ -1039,7 +1329,8 @@ async function handleSync(args) {
|
|
|
1039
1329
|
}
|
|
1040
1330
|
}
|
|
1041
1331
|
catch (error) {
|
|
1042
|
-
const
|
|
1332
|
+
const failure = syncVerificationError(error, control);
|
|
1333
|
+
const verification = verificationErrorDetails(failure);
|
|
1043
1334
|
return formatResult({
|
|
1044
1335
|
success: false,
|
|
1045
1336
|
transferSuccess: false,
|
|
@@ -1047,7 +1338,8 @@ async function handleSync(args) {
|
|
|
1047
1338
|
verificationSuccess: false,
|
|
1048
1339
|
verificationStatus: 'error',
|
|
1049
1340
|
failedChecks: ['deletions'],
|
|
1050
|
-
error:
|
|
1341
|
+
error: 'Deletion baseline capture failed: ' +
|
|
1342
|
+
`${failure instanceof Error ? failure.message : String(failure)}`,
|
|
1051
1343
|
verification,
|
|
1052
1344
|
diagnostics,
|
|
1053
1345
|
});
|
|
@@ -1066,25 +1358,35 @@ async function handleSync(args) {
|
|
|
1066
1358
|
exclude: args.exclude,
|
|
1067
1359
|
recursive: args.recursive,
|
|
1068
1360
|
followSymlinks: args.followSymlinks,
|
|
1361
|
+
verifySha256: args.verify?.sha256 === true,
|
|
1069
1362
|
preflightTimeout: args.preflightTimeout,
|
|
1070
1363
|
connectTimeout: args.connectTimeout,
|
|
1071
1364
|
operationTimeout: transferTimeout,
|
|
1365
|
+
deadline,
|
|
1366
|
+
signal: control.signal,
|
|
1072
1367
|
remotePathStyle: sessionManager.getRemotePathStyle(args.alias),
|
|
1368
|
+
onProgress,
|
|
1073
1369
|
});
|
|
1074
1370
|
const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
1075
1371
|
diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
|
|
1372
|
+
const transferredLocal = args.direction === 'download' && !sourceIsDirectory && localAfter.exists && localAfter.isDirectory
|
|
1373
|
+
? fileOps.probeLocalPath(path.join(localAfter.expandedPath, remotePathModule(sessionManager.getRemotePathStyle(args.alias)).basename(args.remotePath)))
|
|
1374
|
+
: localAfter;
|
|
1076
1375
|
const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
|
|
1077
1376
|
let verification;
|
|
1078
1377
|
let verificationError;
|
|
1079
1378
|
if (verificationRequested && syncResult.success) {
|
|
1080
1379
|
try {
|
|
1081
|
-
const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter,
|
|
1082
|
-
const
|
|
1083
|
-
|
|
1380
|
+
const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, control);
|
|
1381
|
+
const contentVerification = sourceIsDirectory
|
|
1382
|
+
? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, control, deletionBaseline)
|
|
1383
|
+
: await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, control);
|
|
1384
|
+
remainingVerificationTimeout(control);
|
|
1385
|
+
verification = mergeSyncVerification(undefined, ownerModeVerification, contentVerification);
|
|
1084
1386
|
}
|
|
1085
1387
|
catch (error) {
|
|
1086
|
-
verificationError = error;
|
|
1087
|
-
verification = mergeSyncVerification(undefined, verificationErrorDetails(
|
|
1388
|
+
verificationError = syncVerificationError(error, control);
|
|
1389
|
+
verification = mergeSyncVerification(undefined, verificationErrorDetails(verificationError), undefined);
|
|
1088
1390
|
}
|
|
1089
1391
|
}
|
|
1090
1392
|
const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
|
|
@@ -1101,15 +1403,19 @@ async function handleSync(args) {
|
|
|
1101
1403
|
localPath: args.localPath,
|
|
1102
1404
|
remotePath: args.remotePath,
|
|
1103
1405
|
diagnostics,
|
|
1406
|
+
...(progressWarning ? { progressWarning } : {}),
|
|
1104
1407
|
});
|
|
1105
1408
|
}
|
|
1106
1409
|
catch (error) {
|
|
1107
|
-
return
|
|
1108
|
-
|
|
1109
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1410
|
+
return formatError(error, {
|
|
1411
|
+
...sftpOperationOutcome(error),
|
|
1110
1412
|
diagnostics,
|
|
1413
|
+
...(progressWarning ? { progressWarning } : {}),
|
|
1111
1414
|
});
|
|
1112
1415
|
}
|
|
1416
|
+
finally {
|
|
1417
|
+
clearTimeout(timer);
|
|
1418
|
+
}
|
|
1113
1419
|
}
|
|
1114
1420
|
// ========== Register ==========
|
|
1115
1421
|
export function registerFileTools(server) {
|
|
@@ -1118,7 +1424,8 @@ export function registerFileTools(server) {
|
|
|
1118
1424
|
inputSchema: uploadSchema,
|
|
1119
1425
|
}, (args) => handleUpload(args));
|
|
1120
1426
|
server.registerTool('ssh_download', {
|
|
1121
|
-
description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout
|
|
1427
|
+
description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout ' +
|
|
1428
|
+
'限制单个 SFTP 操作,超时后远端传输状态可能未知。',
|
|
1122
1429
|
inputSchema: downloadSchema,
|
|
1123
1430
|
}, (args) => handleDownload(args));
|
|
1124
1431
|
server.registerTool('ssh_read_file', {
|
|
@@ -1130,7 +1437,8 @@ export function registerFileTools(server) {
|
|
|
1130
1437
|
inputSchema: writeFileSchema,
|
|
1131
1438
|
}, (args) => handleWriteFile(args));
|
|
1132
1439
|
server.registerTool('ssh_list_dir', {
|
|
1133
|
-
description: '
|
|
1440
|
+
description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 ' +
|
|
1441
|
+
'条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
|
|
1134
1442
|
inputSchema: listDirSchema,
|
|
1135
1443
|
}, (args) => handleListDir(args));
|
|
1136
1444
|
server.registerTool('ssh_file_info', {
|
|
@@ -1142,21 +1450,24 @@ export function registerFileTools(server) {
|
|
|
1142
1450
|
inputSchema: mkdirSchema,
|
|
1143
1451
|
}, (args) => handleMkdir(args));
|
|
1144
1452
|
server.registerTool('ssh_sync', {
|
|
1145
|
-
description:
|
|
1146
|
-
|
|
1147
|
-
只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline
|
|
1148
|
-
|
|
1149
|
-
rsync
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
-
|
|
1154
|
-
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
-
|
|
1159
|
-
|
|
1453
|
+
description: '智能文件同步(支持目录递归)\n' +
|
|
1454
|
+
'\n' +
|
|
1455
|
+
'只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline ' +
|
|
1456
|
+
'key 和 jump host session 使用 SFTP\n' +
|
|
1457
|
+
'满足 rsync 条件且本地、远端均可用 rsync 时使用 rsync,否则使用 SFTP\n' +
|
|
1458
|
+
'rsync 可实现增量传输,对大目录同步效率更高\n' +
|
|
1459
|
+
'\n' +
|
|
1460
|
+
'用途:\n' +
|
|
1461
|
+
'- 同步本地目录到远程\n' +
|
|
1462
|
+
'- 从远程同步目录到本地\n' +
|
|
1463
|
+
'- 支持排除特定文件/目录\n' +
|
|
1464
|
+
'\n' +
|
|
1465
|
+
'示例:\n' +
|
|
1466
|
+
'- 上传目录: ssh_sync(alias="server", localPath="/local/dir", ' +
|
|
1467
|
+
'remotePath="/remote/dir", direction="upload")\n' +
|
|
1468
|
+
'- 下载目录: ssh_sync(alias="server", localPath="/local/dir", ' +
|
|
1469
|
+
'remotePath="/remote/dir", direction="download")\n' +
|
|
1470
|
+
'- 排除文件: ssh_sync(..., exclude=["*.log", "node_modules"])',
|
|
1160
1471
|
inputSchema: syncSchema,
|
|
1161
|
-
}, (args) => handleSync(args));
|
|
1472
|
+
}, (args, extra) => handleSync(args, extra));
|
|
1162
1473
|
}
|