@pyrokine/mcp-ssh 3.1.0 → 3.3.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 +395 -112
- package/README_zh.md +211 -45
- package/dist/command-risk.js +5 -2
- package/dist/directory-verification.d.ts +10 -5
- package/dist/directory-verification.js +161 -74
- package/dist/file-mode.js +25 -13
- package/dist/file-ops.d.ts +22 -11
- package/dist/file-ops.js +605 -230
- package/dist/forward-manager.js +6 -1
- package/dist/known-hosts.d.ts +22 -0
- package/dist/known-hosts.js +563 -0
- package/dist/openssh.d.ts +5 -5
- package/dist/openssh.js +138 -59
- package/dist/operation-manager.js +13 -4
- 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 +29 -3
- package/dist/session-manager.js +367 -67
- package/dist/sftp-timeout.d.ts +16 -1
- package/dist/sftp-timeout.js +114 -12
- package/dist/ssh-config.js +1 -1
- package/dist/tools/connection.js +31 -13
- package/dist/tools/exec.js +147 -71
- package/dist/tools/file.js +333 -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/transfer-outcome.js +1 -1
- package/dist/types.d.ts +24 -4
- 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 -6
package/dist/tools/file.js
CHANGED
|
@@ -8,12 +8,12 @@ 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,
|
|
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 { sessionManager } from '../session-manager.js';
|
|
15
|
-
import { withSftpOperationTimeout } from '../sftp-timeout.js';
|
|
16
14
|
import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remotePathModule, remoteShellPath, sftpPath, } from '../remote-platform.js';
|
|
15
|
+
import { sessionManager } from '../session-manager.js';
|
|
16
|
+
import { normalizeSftpOperationTimeout, sftpOperationOutcome, SftpOperationTimeoutError, 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';
|
|
@@ -73,10 +73,11 @@ const writeFileSchema = z.object({
|
|
|
73
73
|
});
|
|
74
74
|
function compareDirectoryTimes(left, right) {
|
|
75
75
|
const milliseconds = Date.parse(left) - Date.parse(right);
|
|
76
|
-
if (milliseconds !== 0)
|
|
76
|
+
if (milliseconds !== 0) {
|
|
77
77
|
return milliseconds;
|
|
78
|
+
}
|
|
78
79
|
// 保留 ISO 8601 的亚毫秒部分,避免 Date.parse 截断时间边界
|
|
79
|
-
const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(
|
|
80
|
+
const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(?<fraction>\d+)/)?.groups?.fraction.slice(3) ?? '').replace(/0+$/, ''));
|
|
80
81
|
return leftFraction < rightFraction ? -1 : leftFraction > rightFraction ? 1 : 0;
|
|
81
82
|
}
|
|
82
83
|
const listDirSchema = z
|
|
@@ -85,13 +86,11 @@ const listDirSchema = z
|
|
|
85
86
|
remotePath: z.string().describe('远程目录路径'),
|
|
86
87
|
showHidden: z.boolean().optional().describe('是否显示隐藏文件'),
|
|
87
88
|
namePattern: z.string().optional().describe('名称通配模式,复用同步 exclude 的 * 和 ? 规则,区分大小写'),
|
|
88
|
-
modifiedAfter: z
|
|
89
|
-
.string()
|
|
89
|
+
modifiedAfter: z.iso
|
|
90
90
|
.datetime({ offset: true })
|
|
91
91
|
.optional()
|
|
92
92
|
.describe('修改时间下界,包含;使用带时区的 ISO 8601 时间'),
|
|
93
|
-
modifiedBefore: z
|
|
94
|
-
.string()
|
|
93
|
+
modifiedBefore: z.iso
|
|
95
94
|
.datetime({ offset: true })
|
|
96
95
|
.optional()
|
|
97
96
|
.describe('修改时间上界,不包含;使用带时区的 ISO 8601 时间'),
|
|
@@ -134,13 +133,34 @@ const syncSchema = z.object({
|
|
|
134
133
|
.describe('upload 时是否跟随本地 symlink,默认 false(跳过 symlink 并 warn,避免上传链接目标内容)'),
|
|
135
134
|
preflightTimeout: z.number().int().positive().max(60000).optional().describe('传输能力预检超时,默认 10000ms'),
|
|
136
135
|
connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
|
|
137
|
-
operationTimeout: z
|
|
138
|
-
|
|
139
|
-
|
|
136
|
+
operationTimeout: z
|
|
137
|
+
.number()
|
|
138
|
+
.int()
|
|
139
|
+
.positive()
|
|
140
|
+
.max(3600000)
|
|
141
|
+
.optional()
|
|
142
|
+
.describe('同步总期限(含预检、传输、校验),默认 600000 ms;宿主请求期限独立生效'),
|
|
143
|
+
bandwidthLimitKiBps: z
|
|
144
|
+
.number()
|
|
145
|
+
.int()
|
|
146
|
+
.positive()
|
|
147
|
+
.optional()
|
|
148
|
+
.describe('本次同步的总传输速率上限,单位 KiB/s(1 KiB = 1024 bytes),适用于 rsync/SFTP,默认不限速'),
|
|
149
|
+
verifyOwner: z
|
|
150
|
+
.union([z.string(), z.number()])
|
|
151
|
+
.optional()
|
|
152
|
+
.describe('仅非 dryRun 单文件 upload 校验远端 owner(用户名或 uid),目录用 verify.owner'),
|
|
153
|
+
verifyMode: z
|
|
154
|
+
.string()
|
|
155
|
+
.optional()
|
|
156
|
+
.describe('仅非 dryRun 单文件 upload 校验远端权限,例如 0644、4755 或 -rwsr-xr-x,目录用 verify.mode'),
|
|
140
157
|
verify: z
|
|
141
158
|
.object({
|
|
142
159
|
count: z.boolean().optional().describe('校验目录条目数'),
|
|
143
|
-
sha256: z
|
|
160
|
+
sha256: z
|
|
161
|
+
.boolean()
|
|
162
|
+
.optional()
|
|
163
|
+
.describe('显式启用文件 SHA-256 或目录 SHA-256 root manifest 校验,默认 false'),
|
|
144
164
|
owner: z.boolean().optional().describe('逐项校验 owner'),
|
|
145
165
|
mode: z.boolean().optional().describe('逐项校验 POSIX mode;Windows 不支持'),
|
|
146
166
|
aclSddl: z
|
|
@@ -190,17 +210,6 @@ class VerificationStageError extends Error {
|
|
|
190
210
|
this.name = 'VerificationStageError';
|
|
191
211
|
}
|
|
192
212
|
}
|
|
193
|
-
function sftpOperationOutcome(error) {
|
|
194
|
-
if (!error || typeof error !== 'object') {
|
|
195
|
-
return {};
|
|
196
|
-
}
|
|
197
|
-
const details = 'details' in error ? error.details : undefined;
|
|
198
|
-
if (details && typeof details === 'object' && 'operationStatus' in details) {
|
|
199
|
-
return details;
|
|
200
|
-
}
|
|
201
|
-
const cause = 'cause' in error ? error.cause : undefined;
|
|
202
|
-
return sftpOperationOutcome(cause);
|
|
203
|
-
}
|
|
204
213
|
function formatFileOperationError(error) {
|
|
205
214
|
const operationOutcome = sftpOperationOutcome(error);
|
|
206
215
|
if (Object.keys(operationOutcome).length === 0) {
|
|
@@ -232,6 +241,12 @@ function verificationErrorDetails(error) {
|
|
|
232
241
|
retryable: false,
|
|
233
242
|
};
|
|
234
243
|
}
|
|
244
|
+
function syncVerificationError(error, control) {
|
|
245
|
+
if (!control.signal.aborted && Date.now() < control.deadline) {
|
|
246
|
+
return error;
|
|
247
|
+
}
|
|
248
|
+
return new VerificationStageError('verification_timeout', 'Sync verification exceeded the operation timeout', true, { status: 'unknown', timedOut: true, cause: error instanceof Error ? error.message : String(error) });
|
|
249
|
+
}
|
|
235
250
|
function summarizeLocalPathProbe(probe) {
|
|
236
251
|
const summary = {
|
|
237
252
|
exists: probe.exists,
|
|
@@ -271,11 +286,11 @@ function uploadPathError(code, message, diagnostics) {
|
|
|
271
286
|
function normalizeRemotePath(alias, remotePath) {
|
|
272
287
|
return sftpPath(remotePath, sessionManager.getRemotePathStyle(alias));
|
|
273
288
|
}
|
|
274
|
-
async function probeRemoteParent(alias, remotePath, timeout) {
|
|
289
|
+
async function probeRemoteParent(alias, remotePath, timeout, signal) {
|
|
275
290
|
const parent = remoteDirname(sessionManager.getRemotePathStyle(alias), remotePath);
|
|
276
291
|
const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
|
|
277
292
|
try {
|
|
278
|
-
const result = await probeRemoteFile(alias, parent, timeout);
|
|
293
|
+
const result = await probeRemoteFile(alias, parent, timeout, signal);
|
|
279
294
|
return {
|
|
280
295
|
exists: result.exists,
|
|
281
296
|
isDirectory: result.exists ? result.isDirectory : false,
|
|
@@ -346,19 +361,19 @@ function isRemoteMissingError(error) {
|
|
|
346
361
|
}
|
|
347
362
|
const code = 'code' in error ? error.code : undefined;
|
|
348
363
|
const message = error instanceof Error ? error.message : String(error);
|
|
349
|
-
return code === 2 || code === 'ENOENT' || /no such file|not found
|
|
364
|
+
return code === 2 || code === 'ENOENT' || /no such file|^(?:file |remote path )?not found$/i.test(message);
|
|
350
365
|
}
|
|
351
|
-
async function probeRemoteFile(alias, remotePath, timeout = 10000) {
|
|
366
|
+
async function probeRemoteFile(alias, remotePath, timeout = 10000, signal) {
|
|
352
367
|
const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
|
|
353
368
|
let info;
|
|
354
369
|
try {
|
|
355
|
-
info = await fileOps.getFileInfo(alias, remotePath, timeout);
|
|
370
|
+
info = await fileOps.getFileInfo(alias, remotePath, timeout, undefined, signal);
|
|
356
371
|
}
|
|
357
372
|
catch (error) {
|
|
358
373
|
if (isRemoteMissingError(error)) {
|
|
359
374
|
return { exists: false, remotePath, probeMethod };
|
|
360
375
|
}
|
|
361
|
-
throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod });
|
|
376
|
+
throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod, ...sftpOperationOutcome(error) });
|
|
362
377
|
}
|
|
363
378
|
return {
|
|
364
379
|
exists: true,
|
|
@@ -442,10 +457,10 @@ function displayExpectedMode(mode) {
|
|
|
442
457
|
const parsed = normalizeExpectedMode(mode);
|
|
443
458
|
return parsed === undefined ? undefined : formatFileMode(parsed);
|
|
444
459
|
}
|
|
445
|
-
async function buildSyncVerificationChecks(args, remote) {
|
|
460
|
+
async function buildSyncVerificationChecks(args, remote, timeout) {
|
|
446
461
|
const checks = {};
|
|
447
462
|
if (args.verifyOwner !== undefined) {
|
|
448
|
-
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
|
|
463
|
+
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner, timeout);
|
|
449
464
|
checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
|
|
450
465
|
}
|
|
451
466
|
if (args.verifyMode !== undefined) {
|
|
@@ -464,7 +479,7 @@ async function resolveSyncUploadVerificationPath(args, local, timeout) {
|
|
|
464
479
|
}
|
|
465
480
|
return args.remotePath;
|
|
466
481
|
}
|
|
467
|
-
async function buildSyncUploadVerification(args, local,
|
|
482
|
+
async function buildSyncUploadVerification(args, local, control) {
|
|
468
483
|
if (args.verifyOwner === undefined && args.verifyMode === undefined) {
|
|
469
484
|
return undefined;
|
|
470
485
|
}
|
|
@@ -483,12 +498,10 @@ async function buildSyncUploadVerification(args, local, timeout) {
|
|
|
483
498
|
suggestion: '目录权限校验请使用 verify.owner 或 verify.mode',
|
|
484
499
|
};
|
|
485
500
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
const remote = await probeRemoteFile(args.alias, verificationRemotePath, timeout);
|
|
491
|
-
const checks = await buildSyncVerificationChecks(args, remote);
|
|
501
|
+
const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, remainingVerificationTimeout(control));
|
|
502
|
+
const remote = await probeRemoteFile(args.alias, verificationRemotePath, remainingVerificationTimeout(control));
|
|
503
|
+
const checks = await buildSyncVerificationChecks(args, remote, remainingVerificationTimeout(control));
|
|
504
|
+
remainingVerificationTimeout(control);
|
|
492
505
|
const matched = Object.values(checks).every(Boolean);
|
|
493
506
|
return {
|
|
494
507
|
kind: 'owner_mode',
|
|
@@ -506,16 +519,19 @@ async function buildSyncUploadVerification(args, local, timeout) {
|
|
|
506
519
|
: '同步已完成,但远端 owner/mode 与期望不一致;工具不会自动 chown/chmod,请按需用 ssh_exec 显式处理权限',
|
|
507
520
|
};
|
|
508
521
|
}
|
|
509
|
-
async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks,
|
|
522
|
+
async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, control) {
|
|
510
523
|
const connection = sessionManager.getOpenSshConnection(alias);
|
|
511
|
-
if (connection)
|
|
512
|
-
return createOpenSshDirectoryManifest(connection, remotePath, request,
|
|
524
|
+
if (connection) {
|
|
525
|
+
return createOpenSshDirectoryManifest(connection, remotePath, request, remainingVerificationTimeout(control), exclude, followSymlinks, control);
|
|
526
|
+
}
|
|
527
|
+
const timeout = remainingVerificationTimeout(control);
|
|
513
528
|
const requestSftp = sessionManager.getSftp(alias);
|
|
514
529
|
const sftp = await withSftpOperationTimeout(requestSftp, timeout, () => {
|
|
515
530
|
void requestSftp.then((late) => late.end(), () => undefined);
|
|
516
|
-
});
|
|
531
|
+
}, control.signal);
|
|
517
532
|
try {
|
|
518
|
-
|
|
533
|
+
const remaining = remainingVerificationTimeout(control);
|
|
534
|
+
return await withSftpOperationTimeout(createRemoteDirectoryManifest(sftp, remotePath, request, exclude, followSymlinks, sessionManager.getRemotePathStyle(alias), control), remaining, () => sftp.end(), control.signal);
|
|
519
535
|
}
|
|
520
536
|
catch (error) {
|
|
521
537
|
throw new VerificationStageError('remote_manifest_output', error instanceof Error ? error.message : String(error), true);
|
|
@@ -538,28 +554,21 @@ function deletionManifestRequest(request) {
|
|
|
538
554
|
staleFiles: false,
|
|
539
555
|
};
|
|
540
556
|
}
|
|
541
|
-
async function captureDeletionBaseline(args,
|
|
557
|
+
async function captureDeletionBaseline(args, control) {
|
|
542
558
|
if (!args.verify?.deletions || args.dryRun) {
|
|
543
559
|
return undefined;
|
|
544
560
|
}
|
|
561
|
+
remainingVerificationTimeout(control);
|
|
545
562
|
const request = deletionManifestRequest(args.verify);
|
|
546
563
|
if (args.direction === 'upload') {
|
|
547
|
-
const
|
|
548
|
-
if (probeTimeout <= 0) {
|
|
549
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline capture started', true);
|
|
550
|
-
}
|
|
551
|
-
const remote = await probeRemoteFile(args.alias, args.remotePath, probeTimeout);
|
|
564
|
+
const remote = await probeRemoteFile(args.alias, args.remotePath, remainingVerificationTimeout(control));
|
|
552
565
|
if (!remote.exists) {
|
|
553
566
|
return createEmptyDirectoryManifest();
|
|
554
567
|
}
|
|
555
568
|
if (!remote.isDirectory) {
|
|
556
569
|
throw new VerificationStageError('remote_probe', 'deletion verification requires the remote destination to be a directory', false, { remotePath: args.remotePath, fileType: remote.fileType });
|
|
557
570
|
}
|
|
558
|
-
|
|
559
|
-
if (manifestTimeout <= 0) {
|
|
560
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline manifest started', true);
|
|
561
|
-
}
|
|
562
|
-
return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), manifestTimeout);
|
|
571
|
+
return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
563
572
|
}
|
|
564
573
|
const local = fileOps.probeLocalPath(args.localPath);
|
|
565
574
|
if (!local.exists) {
|
|
@@ -569,26 +578,23 @@ async function captureDeletionBaseline(args, remainingTimeout) {
|
|
|
569
578
|
throw new VerificationStageError('local_manifest', 'deletion verification requires the local destination to be a directory', false, { localPath: args.localPath });
|
|
570
579
|
}
|
|
571
580
|
try {
|
|
572
|
-
return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
|
|
581
|
+
return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
573
582
|
}
|
|
574
583
|
catch (error) {
|
|
575
584
|
throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
|
|
576
585
|
}
|
|
577
586
|
}
|
|
578
|
-
async function buildSingleFileSyncVerification(args, local,
|
|
579
|
-
if (!args.verify)
|
|
587
|
+
async function buildSingleFileSyncVerification(args, local, control) {
|
|
588
|
+
if (!args.verify) {
|
|
580
589
|
return undefined;
|
|
581
|
-
|
|
590
|
+
}
|
|
591
|
+
if (args.dryRun) {
|
|
582
592
|
return { kind: 'single_file', skipped: true, reason: 'file verification is not executed during dryRun' };
|
|
583
|
-
|
|
593
|
+
}
|
|
594
|
+
if (!local.exists || !local.isFile) {
|
|
584
595
|
throw new VerificationStageError('local_manifest', 'File verification requires the transferred local file', false);
|
|
585
|
-
|
|
586
|
-
const remaining = () =>
|
|
587
|
-
const value = deadline - Date.now();
|
|
588
|
-
if (value <= 0)
|
|
589
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted during file verification', true);
|
|
590
|
-
return value;
|
|
591
|
-
};
|
|
596
|
+
}
|
|
597
|
+
const remaining = () => remainingVerificationTimeout(control);
|
|
592
598
|
const remotePath = args.direction === 'upload'
|
|
593
599
|
? await resolveSyncUploadVerificationPath(args, local, remaining())
|
|
594
600
|
: args.remotePath;
|
|
@@ -597,22 +603,26 @@ async function buildSingleFileSyncVerification(args, local, timeout) {
|
|
|
597
603
|
file: remote.exists && remote.isFile,
|
|
598
604
|
size: remote.exists && remote.size === local.size,
|
|
599
605
|
};
|
|
600
|
-
if (args.verify.owner)
|
|
606
|
+
if (args.verify.owner) {
|
|
601
607
|
checks.owner = remote.exists && String(remote.ownerId) === String(fs.statSync(local.resolvedPath).uid);
|
|
602
|
-
|
|
608
|
+
}
|
|
609
|
+
if (args.verify.mode) {
|
|
603
610
|
checks.mode = remote.exists && remote.modeValue === local.modeValue;
|
|
611
|
+
}
|
|
604
612
|
let localSha256;
|
|
605
613
|
let remoteSha256;
|
|
606
614
|
if (args.verify.sha256 && remote.exists && remote.isFile) {
|
|
607
615
|
const maxBytes = Math.min(args.verify.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
|
|
608
|
-
if (local.size > maxBytes || remote.size > maxBytes)
|
|
616
|
+
if (local.size > maxBytes || remote.size > maxBytes) {
|
|
609
617
|
return { kind: 'single_file', skipped: true, reason: 'file verification byte budget exceeded', maxBytes };
|
|
618
|
+
}
|
|
619
|
+
;
|
|
610
620
|
[localSha256, remoteSha256] = await Promise.all([
|
|
611
|
-
fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size }),
|
|
612
|
-
fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
|
|
621
|
+
Promise.resolve().then(() => fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size })),
|
|
622
|
+
Promise.resolve().then(() => fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
|
|
613
623
|
maxBytes,
|
|
614
624
|
expectedSize: remote.size,
|
|
615
|
-
}),
|
|
625
|
+
}, control.signal)),
|
|
616
626
|
]);
|
|
617
627
|
checks.sha256 = localSha256 === remoteSha256;
|
|
618
628
|
const after = await probeRemoteFile(args.alias, remotePath, remaining());
|
|
@@ -624,19 +634,25 @@ async function buildSingleFileSyncVerification(args, local, timeout) {
|
|
|
624
634
|
throw new VerificationStageError('remote_probe', 'Remote file changed during sync verification', true);
|
|
625
635
|
}
|
|
626
636
|
}
|
|
627
|
-
else if (args.verify.sha256)
|
|
637
|
+
else if (args.verify.sha256) {
|
|
628
638
|
checks.sha256 = false;
|
|
639
|
+
}
|
|
629
640
|
if (args.verify.aclSddl) {
|
|
630
|
-
const command = encodedPowershell(
|
|
641
|
+
const command = encodedPowershell('$acl = Get-Acl -LiteralPath ' +
|
|
642
|
+
`${quotePowershell(remoteShellPath(remotePath, sessionManager.getRemotePathStyle(args.alias)))}` +
|
|
643
|
+
'; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.Acce' +
|
|
644
|
+
'ssControlSections]::Access)');
|
|
631
645
|
const result = await sessionManager.exec(args.alias, command, {
|
|
632
646
|
timeout: remaining(),
|
|
633
647
|
useLoginUser: true,
|
|
634
648
|
maxOutputSize: 8192,
|
|
635
649
|
});
|
|
636
|
-
if (!result.success || result.stdoutTruncated)
|
|
650
|
+
if (!result.success || result.stdoutTruncated) {
|
|
637
651
|
throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
|
|
652
|
+
}
|
|
638
653
|
checks.acl = result.stdout.trim() === args.verify.aclSddl;
|
|
639
654
|
}
|
|
655
|
+
remaining();
|
|
640
656
|
return {
|
|
641
657
|
kind: 'single_file',
|
|
642
658
|
matched: Object.values(checks).every(Boolean),
|
|
@@ -648,7 +664,7 @@ async function buildSingleFileSyncVerification(args, local, timeout) {
|
|
|
648
664
|
remote: { ...remote, sha256: remoteSha256 },
|
|
649
665
|
};
|
|
650
666
|
}
|
|
651
|
-
async function buildDirectorySyncVerification(args, local,
|
|
667
|
+
async function buildDirectorySyncVerification(args, local, control, deletionBaseline) {
|
|
652
668
|
if (!args.verify) {
|
|
653
669
|
return undefined;
|
|
654
670
|
}
|
|
@@ -658,14 +674,12 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
|
|
|
658
674
|
if (!local.exists || !local.isDirectory) {
|
|
659
675
|
return { kind: 'directory', skipped: true, reason: 'bounded directory verification requires a local directory' };
|
|
660
676
|
}
|
|
661
|
-
|
|
662
|
-
throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before directory verification started', true);
|
|
663
|
-
}
|
|
677
|
+
remainingVerificationTimeout(control);
|
|
664
678
|
const request = args.verify;
|
|
665
|
-
const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args),
|
|
679
|
+
const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
666
680
|
let localManifest;
|
|
667
681
|
try {
|
|
668
|
-
localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
|
|
682
|
+
localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
|
|
669
683
|
}
|
|
670
684
|
catch (error) {
|
|
671
685
|
throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
|
|
@@ -682,9 +696,12 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
|
|
|
682
696
|
: '排除符号链接后重新同步和校验;download 保持跳过链接目标,followSymlinks 仅适用于 upload';
|
|
683
697
|
}
|
|
684
698
|
if (request.aclSddl && !('skipped' in comparison)) {
|
|
685
|
-
const command = encodedPowershell(
|
|
699
|
+
const command = encodedPowershell('$acl = Get-Acl -LiteralPath ' +
|
|
700
|
+
`${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}` +
|
|
701
|
+
'; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.Acce' +
|
|
702
|
+
'ssControlSections]::Access)');
|
|
686
703
|
const result = await sessionManager.exec(args.alias, command, {
|
|
687
|
-
timeout,
|
|
704
|
+
timeout: remainingVerificationTimeout(control),
|
|
688
705
|
useLoginUser: true,
|
|
689
706
|
maxOutputSize: 8192,
|
|
690
707
|
});
|
|
@@ -697,6 +714,7 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
|
|
|
697
714
|
comparison.matched = comparison.matched === true && aclMatch;
|
|
698
715
|
comparison.acl = { matched: aclMatch, expected: request.aclSddl, actual: result.stdout.trim() };
|
|
699
716
|
}
|
|
717
|
+
remainingVerificationTimeout(control);
|
|
700
718
|
return comparison;
|
|
701
719
|
}
|
|
702
720
|
function mergeSyncVerification(existing, ownerMode, content) {
|
|
@@ -751,7 +769,8 @@ async function handleUpload(args) {
|
|
|
751
769
|
return formatResult({
|
|
752
770
|
success: false,
|
|
753
771
|
code: 'unsupported_remote_platform',
|
|
754
|
-
error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use
|
|
772
|
+
error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use ' +
|
|
773
|
+
'Windows ACL verification',
|
|
755
774
|
});
|
|
756
775
|
}
|
|
757
776
|
}
|
|
@@ -794,9 +813,11 @@ async function handleUpload(args) {
|
|
|
794
813
|
remoteBefore = await probeRemoteFile(args.alias, args.remotePath, args.timeout);
|
|
795
814
|
}
|
|
796
815
|
catch (error) {
|
|
797
|
-
return
|
|
798
|
-
|
|
799
|
-
|
|
816
|
+
return formatError(error, {
|
|
817
|
+
...sftpOperationOutcome(error),
|
|
818
|
+
operationStatus: 'failed',
|
|
819
|
+
failureStage: 'preflight',
|
|
820
|
+
acknowledgedBytes: 0,
|
|
800
821
|
diagnostics: {
|
|
801
822
|
local: summarizeLocalPathProbe(local),
|
|
802
823
|
remoteParent,
|
|
@@ -821,12 +842,14 @@ async function handleUpload(args) {
|
|
|
821
842
|
}
|
|
822
843
|
}
|
|
823
844
|
catch (error) {
|
|
824
|
-
return
|
|
825
|
-
|
|
845
|
+
return formatError(error, {
|
|
846
|
+
...sftpOperationOutcome(error),
|
|
847
|
+
operationStatus: 'failed',
|
|
848
|
+
failureStage: 'preflight',
|
|
849
|
+
acknowledgedBytes: 0,
|
|
826
850
|
code: 'atomic_replace_unverified',
|
|
827
851
|
atomicReplaceSupported: null,
|
|
828
852
|
targetReplaced: false,
|
|
829
|
-
error: error instanceof Error ? error.message : String(error),
|
|
830
853
|
});
|
|
831
854
|
}
|
|
832
855
|
}
|
|
@@ -850,6 +873,7 @@ async function handleUpload(args) {
|
|
|
850
873
|
privateTempCreated = true;
|
|
851
874
|
}
|
|
852
875
|
const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true && !privateTempCreated, args.timeout);
|
|
876
|
+
// noinspection JSUnusedAssignment -- read by the failure cleanup path
|
|
853
877
|
uploadedTempCreated = args.atomic === true;
|
|
854
878
|
let verification;
|
|
855
879
|
let verificationError;
|
|
@@ -904,7 +928,8 @@ async function handleUpload(args) {
|
|
|
904
928
|
await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists, args.timeout);
|
|
905
929
|
}
|
|
906
930
|
catch (error) {
|
|
907
|
-
const
|
|
931
|
+
const renameOutcome = sftpOperationOutcome(error);
|
|
932
|
+
const renameNotStarted = renameOutcome.operationStatus === 'failed' || error instanceof fileOps.RemoteRenameNotStartedError;
|
|
908
933
|
const renameError = error instanceof Error ? error.message : String(error);
|
|
909
934
|
let cleanupWarning;
|
|
910
935
|
try {
|
|
@@ -916,11 +941,14 @@ async function handleUpload(args) {
|
|
|
916
941
|
return formatResult({
|
|
917
942
|
success: false,
|
|
918
943
|
transferSuccess: true,
|
|
944
|
+
...renameOutcome,
|
|
945
|
+
acknowledgedBytes: uploadResult.size,
|
|
919
946
|
operationStatus: renameNotStarted ? 'failed' : 'unknown',
|
|
920
|
-
retryable:
|
|
947
|
+
retryable: false,
|
|
921
948
|
error: renameNotStarted
|
|
922
949
|
? `Atomic SFTP rename request was not sent; target was not replaced: ${renameError}`
|
|
923
|
-
:
|
|
950
|
+
: 'Atomic SFTP rename response failed; target replacement state is unknown: ' +
|
|
951
|
+
`${renameError}`,
|
|
924
952
|
cleanupWarning,
|
|
925
953
|
atomic: true,
|
|
926
954
|
atomicReplaceSupported,
|
|
@@ -978,11 +1006,10 @@ async function handleUpload(args) {
|
|
|
978
1006
|
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
979
1007
|
}
|
|
980
1008
|
}
|
|
981
|
-
return
|
|
982
|
-
success: false,
|
|
1009
|
+
return formatError(error, {
|
|
983
1010
|
...sftpOperationOutcome(error),
|
|
984
|
-
error: error instanceof Error ? error.message : String(error),
|
|
985
1011
|
cleanupWarning,
|
|
1012
|
+
targetReplaced: args.atomic ? false : undefined,
|
|
986
1013
|
atomicReplaceSupported,
|
|
987
1014
|
finalRemotePath: args.remotePath,
|
|
988
1015
|
diagnostics: {
|
|
@@ -995,21 +1022,30 @@ async function handleUpload(args) {
|
|
|
995
1022
|
});
|
|
996
1023
|
}
|
|
997
1024
|
}
|
|
998
|
-
async function handleDownload(args) {
|
|
1025
|
+
async function handleDownload(args, extra) {
|
|
1026
|
+
const deadline = Date.now() + normalizeSftpOperationTimeout(args.timeout);
|
|
999
1027
|
try {
|
|
1028
|
+
extra?.signal.throwIfAborted();
|
|
1000
1029
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
1001
|
-
const
|
|
1030
|
+
const remaining = deadline - Date.now();
|
|
1031
|
+
if (remaining <= 0) {
|
|
1032
|
+
// noinspection ExceptionCaughtLocallyJS — 超时经统一错误响应返回并共享剩余诊断期限
|
|
1033
|
+
throw new SftpOperationTimeoutError(args.timeout ?? 600_000);
|
|
1034
|
+
}
|
|
1035
|
+
const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath, undefined, undefined, extra?.signal, remaining);
|
|
1002
1036
|
return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
|
|
1003
1037
|
}
|
|
1004
1038
|
catch (error) {
|
|
1005
|
-
return
|
|
1006
|
-
success: false,
|
|
1039
|
+
return formatError(error, {
|
|
1007
1040
|
...sftpOperationOutcome(error),
|
|
1008
|
-
|
|
1041
|
+
operationStatus: 'failed',
|
|
1042
|
+
targetReplaced: false,
|
|
1009
1043
|
diagnostics: {
|
|
1010
1044
|
local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
|
|
1011
1045
|
localParent: summarizeLocalPathProbe(fileOps.probeLocalPath(path.dirname(args.localPath))),
|
|
1012
|
-
remoteParent:
|
|
1046
|
+
remoteParent: !extra?.signal.aborted && Date.now() < deadline
|
|
1047
|
+
? await probeRemoteParent(args.alias, args.remotePath, deadline - Date.now(), extra?.signal)
|
|
1048
|
+
: undefined,
|
|
1013
1049
|
},
|
|
1014
1050
|
});
|
|
1015
1051
|
}
|
|
@@ -1032,10 +1068,10 @@ async function handleReadFile(args) {
|
|
|
1032
1068
|
return formatFileOperationError(error);
|
|
1033
1069
|
}
|
|
1034
1070
|
}
|
|
1035
|
-
async function handleWriteFile(args) {
|
|
1071
|
+
async function handleWriteFile(args, extra) {
|
|
1036
1072
|
try {
|
|
1037
1073
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
1038
|
-
const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout);
|
|
1074
|
+
const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout, extra?.signal);
|
|
1039
1075
|
return formatResult(result);
|
|
1040
1076
|
}
|
|
1041
1077
|
catch (error) {
|
|
@@ -1097,7 +1133,7 @@ async function handleListDir(args) {
|
|
|
1097
1133
|
...formatResult({
|
|
1098
1134
|
success: false,
|
|
1099
1135
|
code: 'LIST_DIR_MAX_BYTES_TOO_SMALL',
|
|
1100
|
-
error: 'maxBytes is too small for directory page metadata and the next complete entry, if any',
|
|
1136
|
+
error: 'maxBytes is too small for directory page metadata and the next complete ' + 'entry, if any',
|
|
1101
1137
|
offset,
|
|
1102
1138
|
next_offset: offset,
|
|
1103
1139
|
maxBytes,
|
|
@@ -1126,13 +1162,39 @@ async function handleMkdir(args) {
|
|
|
1126
1162
|
try {
|
|
1127
1163
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
1128
1164
|
const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
|
|
1129
|
-
|
|
1165
|
+
const session = sessionManager.listSessionDetails().find((item) => item.alias === args.alias);
|
|
1166
|
+
const result = {
|
|
1167
|
+
success,
|
|
1168
|
+
path: args.remotePath,
|
|
1169
|
+
loginUser: session?.username,
|
|
1170
|
+
runAs: session?.runAs,
|
|
1171
|
+
creationIdentity: 'sftp_login',
|
|
1172
|
+
};
|
|
1173
|
+
try {
|
|
1174
|
+
const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout);
|
|
1175
|
+
return formatResult({
|
|
1176
|
+
...result,
|
|
1177
|
+
owner: info.owner,
|
|
1178
|
+
group: info.group,
|
|
1179
|
+
mode: info.mode,
|
|
1180
|
+
permissions: info.permissions,
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
catch (error) {
|
|
1184
|
+
return formatResult({
|
|
1185
|
+
...result,
|
|
1186
|
+
operationStatus: 'completed',
|
|
1187
|
+
retryable: false,
|
|
1188
|
+
metadataStatus: 'unavailable',
|
|
1189
|
+
metadataError: JSON.parse(formatFileOperationError(error).content[0].text),
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1130
1192
|
}
|
|
1131
1193
|
catch (error) {
|
|
1132
1194
|
return formatFileOperationError(error);
|
|
1133
1195
|
}
|
|
1134
1196
|
}
|
|
1135
|
-
async function handleSync(args) {
|
|
1197
|
+
async function handleSync(args, extra) {
|
|
1136
1198
|
const startedAt = Date.now();
|
|
1137
1199
|
try {
|
|
1138
1200
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
@@ -1156,6 +1218,16 @@ async function handleSync(args) {
|
|
|
1156
1218
|
catch (error) {
|
|
1157
1219
|
return formatError(error);
|
|
1158
1220
|
}
|
|
1221
|
+
const ownerModeRequested = args.verifyOwner !== undefined || args.verifyMode !== undefined;
|
|
1222
|
+
if (ownerModeRequested && (args.direction !== 'upload' || args.dryRun)) {
|
|
1223
|
+
return formatResult({
|
|
1224
|
+
success: false,
|
|
1225
|
+
transferSuccess: false,
|
|
1226
|
+
code: 'UNSUPPORTED_SYNC_VERIFICATION',
|
|
1227
|
+
error: 'verifyOwner/verifyMode require a non-dryRun single-file upload; ' +
|
|
1228
|
+
'use verify.owner/verify.mode for directory or download verification',
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1159
1231
|
if (args.verify?.deletions && args.delete !== true) {
|
|
1160
1232
|
return formatResult({
|
|
1161
1233
|
success: false,
|
|
@@ -1164,7 +1236,8 @@ async function handleSync(args) {
|
|
|
1164
1236
|
});
|
|
1165
1237
|
}
|
|
1166
1238
|
const operationTimeout = args.operationTimeout ?? 600_000;
|
|
1167
|
-
const
|
|
1239
|
+
const deadline = startedAt + operationTimeout;
|
|
1240
|
+
const remainingTimeout = () => deadline - Date.now();
|
|
1168
1241
|
try {
|
|
1169
1242
|
if (args.direction === 'upload') {
|
|
1170
1243
|
fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true);
|
|
@@ -1183,15 +1256,97 @@ async function handleSync(args) {
|
|
|
1183
1256
|
});
|
|
1184
1257
|
}
|
|
1185
1258
|
const localBefore = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
1186
|
-
const diagnostics = {
|
|
1187
|
-
|
|
1188
|
-
|
|
1259
|
+
const diagnostics = { localBefore: summarizeLocalPathProbe(localBefore) };
|
|
1260
|
+
if (ownerModeRequested && localBefore.exists && localBefore.isDirectory) {
|
|
1261
|
+
return formatResult({
|
|
1262
|
+
success: false,
|
|
1263
|
+
transferSuccess: false,
|
|
1264
|
+
code: 'UNSUPPORTED_SYNC_VERIFICATION',
|
|
1265
|
+
error: 'verifyOwner/verifyMode require a single-file upload; ' +
|
|
1266
|
+
'use verify.owner/verify.mode for directory verification',
|
|
1267
|
+
diagnostics,
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
const controller = new AbortController();
|
|
1271
|
+
const control = {
|
|
1272
|
+
deadline,
|
|
1273
|
+
signal: extra?.signal ? AbortSignal.any([controller.signal, extra.signal]) : controller.signal,
|
|
1189
1274
|
};
|
|
1275
|
+
let progressWarning;
|
|
1276
|
+
let lastProgressAt = -Infinity;
|
|
1277
|
+
let progress = 0;
|
|
1278
|
+
let progressPending = false;
|
|
1279
|
+
const progressToken = extra?._meta?.progressToken;
|
|
1280
|
+
const onProgress = progressToken === undefined
|
|
1281
|
+
? undefined
|
|
1282
|
+
: (update) => {
|
|
1283
|
+
if (control.signal?.aborted ||
|
|
1284
|
+
progressPending ||
|
|
1285
|
+
progressWarning ||
|
|
1286
|
+
Date.now() - lastProgressAt < 1000) {
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
lastProgressAt = Date.now();
|
|
1290
|
+
progressPending = true;
|
|
1291
|
+
const current = ++progress;
|
|
1292
|
+
void Promise.resolve()
|
|
1293
|
+
.then(() => control.signal?.aborted
|
|
1294
|
+
? undefined
|
|
1295
|
+
: extra.sendNotification({
|
|
1296
|
+
method: 'notifications/progress',
|
|
1297
|
+
params: {
|
|
1298
|
+
progressToken,
|
|
1299
|
+
progress: current,
|
|
1300
|
+
message: `${args.direction === 'upload' ? '上传' : '下载'}:` +
|
|
1301
|
+
`${update.transferred} bytes,` +
|
|
1302
|
+
`${update.percent}%` +
|
|
1303
|
+
(update.total > 0 ? `,当前文件共 ${update.total} bytes` : ''),
|
|
1304
|
+
},
|
|
1305
|
+
}))
|
|
1306
|
+
.catch((error) => {
|
|
1307
|
+
progressWarning =
|
|
1308
|
+
'MCP progress notification failed: ' +
|
|
1309
|
+
(error instanceof Error ? error.message : String(error));
|
|
1310
|
+
console.warn(`[ssh_sync] ${progressWarning}`);
|
|
1311
|
+
})
|
|
1312
|
+
.finally(() => {
|
|
1313
|
+
progressPending = false;
|
|
1314
|
+
});
|
|
1315
|
+
};
|
|
1316
|
+
const timer = setTimeout(() => controller.abort(new SftpOperationTimeoutError(operationTimeout)), Math.max(0, remainingTimeout()));
|
|
1190
1317
|
try {
|
|
1318
|
+
control.signal?.throwIfAborted();
|
|
1319
|
+
const probeTimeout = remainingTimeout();
|
|
1320
|
+
if (probeTimeout <= 0) {
|
|
1321
|
+
// noinspection ExceptionCaughtLocallyJS — 超时仍保留传输诊断
|
|
1322
|
+
throw new Error('sync operation timeout was exhausted before remote probing');
|
|
1323
|
+
}
|
|
1324
|
+
diagnostics.remoteParent = await probeRemoteParent(args.alias, args.remotePath, probeTimeout, control.signal);
|
|
1325
|
+
if (remainingTimeout() <= 0) {
|
|
1326
|
+
// noinspection ExceptionCaughtLocallyJS — 超时仍保留传输诊断
|
|
1327
|
+
throw new Error('sync operation timeout was exhausted before transfer started');
|
|
1328
|
+
}
|
|
1191
1329
|
const remoteSource = args.direction === 'download'
|
|
1192
|
-
? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout())
|
|
1330
|
+
? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout(), undefined, control.signal)
|
|
1193
1331
|
: undefined;
|
|
1194
1332
|
const sourceIsDirectory = args.direction === 'upload' ? localBefore.exists && localBefore.isDirectory : remoteSource.isDirectory;
|
|
1333
|
+
const remoteParent = diagnostics.remoteParent;
|
|
1334
|
+
if (args.direction === 'upload' &&
|
|
1335
|
+
!sourceIsDirectory &&
|
|
1336
|
+
!args.dryRun &&
|
|
1337
|
+
(remoteParent.exists === false || (remoteParent.exists === true && remoteParent.isDirectory === false))) {
|
|
1338
|
+
return formatResult({
|
|
1339
|
+
success: false,
|
|
1340
|
+
transferSuccess: false,
|
|
1341
|
+
operationStatus: 'failed',
|
|
1342
|
+
failureStage: 'remote_prepare',
|
|
1343
|
+
code: !remoteParent.exists ? 'REMOTE_PARENT_NOT_FOUND' : 'REMOTE_PARENT_NOT_DIRECTORY',
|
|
1344
|
+
error: !remoteParent.exists
|
|
1345
|
+
? '远端父目录不存在,请先用 ssh_mkdir 创建后重新上传'
|
|
1346
|
+
: '远端父路径是文件,请改用目录作为父路径',
|
|
1347
|
+
diagnostics,
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1195
1350
|
if (!sourceIsDirectory && (args.verify?.count || args.verify?.deletions || args.verify?.staleFiles)) {
|
|
1196
1351
|
return formatResult({
|
|
1197
1352
|
success: false,
|
|
@@ -1217,7 +1372,7 @@ async function handleSync(args) {
|
|
|
1217
1372
|
}
|
|
1218
1373
|
let deletionBaseline;
|
|
1219
1374
|
try {
|
|
1220
|
-
deletionBaseline = await captureDeletionBaseline(args,
|
|
1375
|
+
deletionBaseline = await captureDeletionBaseline(args, control);
|
|
1221
1376
|
if (deletionBaseline) {
|
|
1222
1377
|
diagnostics.deletionBaseline = {
|
|
1223
1378
|
count: deletionBaseline.count,
|
|
@@ -1230,7 +1385,8 @@ async function handleSync(args) {
|
|
|
1230
1385
|
}
|
|
1231
1386
|
}
|
|
1232
1387
|
catch (error) {
|
|
1233
|
-
const
|
|
1388
|
+
const failure = syncVerificationError(error, control);
|
|
1389
|
+
const verification = verificationErrorDetails(failure);
|
|
1234
1390
|
return formatResult({
|
|
1235
1391
|
success: false,
|
|
1236
1392
|
transferSuccess: false,
|
|
@@ -1238,7 +1394,8 @@ async function handleSync(args) {
|
|
|
1238
1394
|
verificationSuccess: false,
|
|
1239
1395
|
verificationStatus: 'error',
|
|
1240
1396
|
failedChecks: ['deletions'],
|
|
1241
|
-
error:
|
|
1397
|
+
error: 'Deletion baseline capture failed: ' +
|
|
1398
|
+
`${failure instanceof Error ? failure.message : String(failure)}`,
|
|
1242
1399
|
verification,
|
|
1243
1400
|
diagnostics,
|
|
1244
1401
|
});
|
|
@@ -1257,10 +1414,16 @@ async function handleSync(args) {
|
|
|
1257
1414
|
exclude: args.exclude,
|
|
1258
1415
|
recursive: args.recursive,
|
|
1259
1416
|
followSymlinks: args.followSymlinks,
|
|
1417
|
+
// 工具层负责带预算和文件稳定性检查的摘要,传输层只返回元数据
|
|
1418
|
+
verifySha256: false,
|
|
1419
|
+
bandwidthLimitKiBps: args.bandwidthLimitKiBps,
|
|
1260
1420
|
preflightTimeout: args.preflightTimeout,
|
|
1261
1421
|
connectTimeout: args.connectTimeout,
|
|
1262
1422
|
operationTimeout: transferTimeout,
|
|
1423
|
+
deadline,
|
|
1424
|
+
signal: control.signal,
|
|
1263
1425
|
remotePathStyle: sessionManager.getRemotePathStyle(args.alias),
|
|
1426
|
+
onProgress,
|
|
1264
1427
|
});
|
|
1265
1428
|
const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
1266
1429
|
diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
|
|
@@ -1270,20 +1433,35 @@ async function handleSync(args) {
|
|
|
1270
1433
|
const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
|
|
1271
1434
|
let verification;
|
|
1272
1435
|
let verificationError;
|
|
1436
|
+
let contentVerification;
|
|
1273
1437
|
if (verificationRequested && syncResult.success) {
|
|
1274
1438
|
try {
|
|
1275
|
-
const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter,
|
|
1276
|
-
|
|
1277
|
-
? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter,
|
|
1278
|
-
: await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal,
|
|
1439
|
+
const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, control);
|
|
1440
|
+
contentVerification = sourceIsDirectory
|
|
1441
|
+
? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, control, deletionBaseline)
|
|
1442
|
+
: await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, control);
|
|
1443
|
+
remainingVerificationTimeout(control);
|
|
1279
1444
|
verification = mergeSyncVerification(undefined, ownerModeVerification, contentVerification);
|
|
1280
1445
|
}
|
|
1281
1446
|
catch (error) {
|
|
1282
|
-
verificationError = error;
|
|
1283
|
-
verification = mergeSyncVerification(undefined, verificationErrorDetails(
|
|
1447
|
+
verificationError = syncVerificationError(error, control);
|
|
1448
|
+
verification = mergeSyncVerification(undefined, verificationErrorDetails(verificationError), undefined);
|
|
1284
1449
|
}
|
|
1285
1450
|
}
|
|
1286
1451
|
const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
|
|
1452
|
+
if (syncResult.verification && args.verify?.sha256) {
|
|
1453
|
+
const local = contentVerification?.local;
|
|
1454
|
+
const remote = contentVerification?.remote;
|
|
1455
|
+
syncResult.verification = {
|
|
1456
|
+
...syncResult.verification,
|
|
1457
|
+
status: verificationError ? 'error' : contentVerification?.skipped ? 'skipped' : 'completed',
|
|
1458
|
+
hashAlgorithm: 'sha256',
|
|
1459
|
+
hashMatch: contentVerification?.checks?.sha256,
|
|
1460
|
+
local: { ...syncResult.verification.local, sha256: local?.sha256 },
|
|
1461
|
+
remote: { ...syncResult.verification.remote, sha256: remote?.sha256 },
|
|
1462
|
+
...(verificationError ? verificationErrorDetails(verificationError) : {}),
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1287
1465
|
const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
|
|
1288
1466
|
return formatResult({
|
|
1289
1467
|
...syncResult,
|
|
@@ -1297,15 +1475,19 @@ async function handleSync(args) {
|
|
|
1297
1475
|
localPath: args.localPath,
|
|
1298
1476
|
remotePath: args.remotePath,
|
|
1299
1477
|
diagnostics,
|
|
1478
|
+
...(progressWarning ? { progressWarning } : {}),
|
|
1300
1479
|
});
|
|
1301
1480
|
}
|
|
1302
1481
|
catch (error) {
|
|
1303
|
-
return
|
|
1304
|
-
|
|
1305
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1482
|
+
return formatError(error, {
|
|
1483
|
+
...sftpOperationOutcome(error),
|
|
1306
1484
|
diagnostics,
|
|
1485
|
+
...(progressWarning ? { progressWarning } : {}),
|
|
1307
1486
|
});
|
|
1308
1487
|
}
|
|
1488
|
+
finally {
|
|
1489
|
+
clearTimeout(timer);
|
|
1490
|
+
}
|
|
1309
1491
|
}
|
|
1310
1492
|
// ========== Register ==========
|
|
1311
1493
|
export function registerFileTools(server) {
|
|
@@ -1314,9 +1496,10 @@ export function registerFileTools(server) {
|
|
|
1314
1496
|
inputSchema: uploadSchema,
|
|
1315
1497
|
}, (args) => handleUpload(args));
|
|
1316
1498
|
server.registerTool('ssh_download', {
|
|
1317
|
-
description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout
|
|
1499
|
+
description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout ' +
|
|
1500
|
+
'限制下载与失败诊断的总期限,取消或超期后停止远端探测。',
|
|
1318
1501
|
inputSchema: downloadSchema,
|
|
1319
|
-
}, (args) => handleDownload(args));
|
|
1502
|
+
}, (args, extra) => handleDownload(args, extra));
|
|
1320
1503
|
server.registerTool('ssh_read_file', {
|
|
1321
1504
|
description: '读取远程文件内容。文本读取只返回完整 UTF-8 字符;后续读取使用响应中的 next_offset。',
|
|
1322
1505
|
inputSchema: readFileSchema,
|
|
@@ -1324,9 +1507,10 @@ export function registerFileTools(server) {
|
|
|
1324
1507
|
server.registerTool('ssh_write_file', {
|
|
1325
1508
|
description: '写入内容到远程文件。timeout 限制单个 SFTP 操作,超时后远端写入状态可能未知。',
|
|
1326
1509
|
inputSchema: writeFileSchema,
|
|
1327
|
-
}, (args) => handleWriteFile(args));
|
|
1510
|
+
}, (args, extra) => handleWriteFile(args, extra));
|
|
1328
1511
|
server.registerTool('ssh_list_dir', {
|
|
1329
|
-
description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100
|
|
1512
|
+
description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 ' +
|
|
1513
|
+
'条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
|
|
1330
1514
|
inputSchema: listDirSchema,
|
|
1331
1515
|
}, (args) => handleListDir(args));
|
|
1332
1516
|
server.registerTool('ssh_file_info', {
|
|
@@ -1334,25 +1518,28 @@ export function registerFileTools(server) {
|
|
|
1334
1518
|
inputSchema: fileInfoSchema,
|
|
1335
1519
|
}, (args) => handleFileInfo(args));
|
|
1336
1520
|
server.registerTool('ssh_mkdir', {
|
|
1337
|
-
description: '
|
|
1521
|
+
description: '以 SFTP 登录身份创建远程目录,连接 runAs 仅影响命令执行;返回实际 owner、group 和 mode,不自动修改权限;创建已确认后元信息读取失败时保持 success=true,metadataStatus=unavailable,可用 ssh_file_info 重新读取元信息',
|
|
1338
1522
|
inputSchema: mkdirSchema,
|
|
1339
1523
|
}, (args) => handleMkdir(args));
|
|
1340
1524
|
server.registerTool('ssh_sync', {
|
|
1341
|
-
description:
|
|
1342
|
-
|
|
1343
|
-
只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline
|
|
1344
|
-
|
|
1345
|
-
rsync
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
-
|
|
1350
|
-
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
-
|
|
1355
|
-
|
|
1525
|
+
description: '智能文件同步(支持目录递归)\n' +
|
|
1526
|
+
'\n' +
|
|
1527
|
+
'只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline ' +
|
|
1528
|
+
'key 和 jump host session 使用 SFTP\n' +
|
|
1529
|
+
'满足 rsync 条件且本地、远端均可用 rsync 时使用 rsync,否则使用 SFTP\n' +
|
|
1530
|
+
'rsync 可实现增量传输,对大目录同步效率更高\n' +
|
|
1531
|
+
'\n' +
|
|
1532
|
+
'用途:\n' +
|
|
1533
|
+
'- 同步本地目录到远程\n' +
|
|
1534
|
+
'- 从远程同步目录到本地\n' +
|
|
1535
|
+
'- 支持排除特定文件/目录\n' +
|
|
1536
|
+
'\n' +
|
|
1537
|
+
'示例:\n' +
|
|
1538
|
+
'- 上传目录: ssh_sync(alias="server", localPath="/local/dir", ' +
|
|
1539
|
+
'remotePath="/remote/dir", direction="upload")\n' +
|
|
1540
|
+
'- 下载目录: ssh_sync(alias="server", localPath="/local/dir", ' +
|
|
1541
|
+
'remotePath="/remote/dir", direction="download")\n' +
|
|
1542
|
+
'- 排除文件: ssh_sync(..., exclude=["*.log", "node_modules"])',
|
|
1356
1543
|
inputSchema: syncSchema,
|
|
1357
|
-
}, (args) => handleSync(args));
|
|
1544
|
+
}, (args, extra) => handleSync(args, extra));
|
|
1358
1545
|
}
|