import crypto from 'node:crypto'; import path from 'node:path'; import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; import type { ConfigManager } from '../config/config-manager.js'; import type { KnownHostsService } from '../ssh/known-hosts.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { posixSingleQuote } from '../ssh/sudo.js'; export interface TransferResult { mode: 'hub-relayed' | 'direct'; sourcePath: string; destinationPath: string; filesTransferred: number; bytesTransferred: number; durationMs: number; } const FILE_TYPE_MASK = 0o170000; const MODE_DIR = 0o040000; const MODE_REG = 0o100000; function isDirMode(mode: number): boolean { return (mode & FILE_TYPE_MASK) === MODE_DIR; } function isRegularMode(mode: number): boolean { return (mode & FILE_TYPE_MASK) === MODE_REG; } function assertSafeRemotePath(rawPath: string, label: string): string { const trimmed = rawPath.trim(); if (!trimmed || /[\x00-\x1f\x7f]/.test(trimmed)) { throw new Error(`Invalid ${label} path`); } const parts = trimmed.split('/'); if (parts.some((seg) => seg === '..')) { throw new Error(`${label} path cannot contain ".." traversal segments`); } return trimmed; } function sanitizeRsyncExcludes(excludes?: string[]): string[] { if (!excludes || excludes.length === 0) return []; const out: string[] = []; for (const raw of excludes) { const clean = raw.trim(); if (!clean) continue; if (/[\x00-\x1f\x7f]/.test(clean) || clean.startsWith('-')) { throw new Error(`Invalid rsync exclude pattern: "${clean}"`); } out.push(clean); } return out; } function promisifySftp( fn: (cb: (err: Error | undefined | null, result: T) => void) => void, ): Promise { return new Promise((resolve, reject) => { fn((err, result) => { if (err) reject(err); else resolve(result); }); }); } function promisifySftpVoid( fn: (cb: (err?: Error | null) => void) => void, ): Promise { return new Promise((resolve, reject) => { fn((err) => { if (err) reject(err); else resolve(); }); }); } export class TransferEngine { constructor( private readonly sshPool: SSHPool, private readonly _sftpService: SftpService, private readonly configManager: ConfigManager, private readonly knownHosts?: KnownHostsService, ) { void this._sftpService; } async transfer(opts: { mode: 'hub-relayed' | 'direct'; source: { serverId: string; path: string }; destination: { serverId: string; path: string }; delete?: boolean; exclude?: string[]; sudo?: boolean; timeoutMs?: number; signal?: AbortSignal; onProgress?: (msg: string) => void; }): Promise { if (opts.signal?.aborted) { throw new Error('Transfer cancelled before start'); } const srcServer = this.configManager.getServer(opts.source.serverId); const dstServer = this.configManager.getServer(opts.destination.serverId); if (!srcServer || !srcServer.enabled) { throw new Error(`Source server "${opts.source.serverId}" not found or disabled`); } if (!dstServer || !dstServer.enabled) { throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`); } const safeSrcPath = assertSafeRemotePath(opts.source.path, 'source'); const safeDstPath = assertSafeRemotePath(opts.destination.path, 'destination'); const started = Date.now(); const timeoutMs = opts.timeoutMs ?? 600_000; if (opts.mode === 'direct') { const safeExcludes = sanitizeRsyncExcludes(opts.exclude); const excludeFlags = safeExcludes .map((ex) => `--exclude=${posixSingleQuote(ex)} `) .join(''); const deleteFlag = opts.delete ? '--delete ' : ''; const dstTarget = `${dstServer.username}@${dstServer.host}:${safeDstPath}`; const khLine = this.knownHosts?.getOpenSshKnownHostLine(dstServer); let cmd: string; if (khLine) { const sshCmd = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$_kh`; cmd = `_kh=$(mktemp /tmp/.gcoord_kh.XXXXXX) && chmod 600 "$_kh" && trap 'rm -f -- "$_kh"' EXIT && printf '%s\\n' ${posixSingleQuote(khLine)} > "$_kh" && rsync -az -s --stats -e "${sshCmd}" ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; } else { const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; cmd = `rsync -az -s --stats -e ${posixSingleQuote(sshOpt)} ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; } opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`); const handle = await this.sshPool.execStream(srcServer.id, cmd, { sudo: opts.sudo, }); const errBuf: Buffer[] = []; let errLen = 0; handle.channel.on('data', (chunk: Buffer) => { opts.onProgress?.(chunk.toString('utf8')); }); handle.channel.stderr?.on('data', (chunk: Buffer) => { if (errLen < 16_384) { errBuf.push(chunk); errLen += chunk.length; } opts.onProgress?.(chunk.toString('utf8')); }); const result = await new Promise<{ exitCode: number | null }>((resolve, reject) => { let settled = false; const cleanup = () => { if (timer) clearTimeout(timer); if (opts.signal && onAbort) { opts.signal.removeEventListener('abort', onAbort); } }; const timer = setTimeout(() => { handle.abort(); if (!settled) { settled = true; cleanup(); reject(new Error(`Direct transfer timed out after ${timeoutMs}ms`)); } }, timeoutMs); timer.unref(); const onAbort = () => { handle.abort(); if (!settled) { settled = true; cleanup(); reject(new Error('Direct transfer cancelled')); } }; if (opts.signal) { if (opts.signal.aborted) { onAbort(); return; } opts.signal.addEventListener('abort', onAbort, { once: true }); } handle.done .then((res) => { if (!settled) { settled = true; cleanup(); resolve(res); } }) .catch((err) => { if (!settled) { settled = true; cleanup(); reject(err); } }); }); if (result.exitCode !== 0) { const stderr = Buffer.concat(errBuf).toString('utf8').trim(); throw new Error( `Direct rsync failed (exit=${result.exitCode})${stderr ? `: ${stderr}` : ''}`, ); } return { mode: 'direct', sourcePath: safeSrcPath, destinationPath: safeDstPath, filesTransferred: 1, bytesTransferred: 0, durationMs: Date.now() - started, }; } // hub-relayed SFTP stream const srcSftp = await this.sshPool.openSftp(srcServer.id); let dstSftp: SFTPWrapper | null = null; try { dstSftp = await this.sshPool.openSftp(dstServer.id); } catch (err) { try { srcSftp.end(); } catch { // Ignore } throw err; } const activeStreams = new Set<{ destroy: () => void }>(); let timedOutOrAborted: Error | null = null; const cancelAll = (err: Error) => { if (!timedOutOrAborted) timedOutOrAborted = err; for (const s of activeStreams) { try { s.destroy(); } catch { // Ignore destroy errors } } }; const timer = setTimeout(() => { cancelAll(new Error(`Hub-relayed SFTP transfer timed out after ${timeoutMs}ms`)); }, timeoutMs); timer.unref(); const onAbort = () => cancelAll(new Error('Hub-relayed SFTP transfer cancelled')); opts.signal?.addEventListener('abort', onAbort, { once: true }); try { const trimmedDest = safeDstPath; const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/'); const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath); const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath); const srcStat = await promisifySftp((cb) => srcSftp.lstat(resolvedSrc, cb)); const srcMode = srcStat.mode ?? 0; if (!isDirMode(srcMode) && !isRegularMode(srcMode)) { throw new Error(`Refusing SFTP transfer of non-regular/symlink source "${resolvedSrc}"`); } let filesTransferred = 0; let bytesTransferred = 0; if (isDirMode(srcMode)) { const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( () => null, ); const targetDir = destEndsWithSlash && dstStat && isDirMode(dstStat.mode ?? 0) ? path.posix.join(resolvedDest, path.posix.basename(resolvedSrc)) : resolvedDest; const counts = await this.copyDirectoryRecursive( srcSftp, dstSftp, resolvedSrc, targetDir, activeStreams, () => timedOutOrAborted, opts.onProgress, ); filesTransferred = counts.files; bytesTransferred = counts.bytes; return { mode: 'hub-relayed', sourcePath: resolvedSrc, destinationPath: targetDir, filesTransferred, bytesTransferred, durationMs: Date.now() - started, }; } const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( () => null, ); const targetFile = destEndsWithSlash || (dstStat !== null && isDirMode(dstStat.mode ?? 0)) ? path.posix.join(resolvedDest, path.posix.basename(resolvedSrc)) : resolvedDest; bytesTransferred = await this.copySingleFile( srcSftp, dstSftp, resolvedSrc, targetFile, srcMode || 0o644, activeStreams, () => timedOutOrAborted, opts.onProgress, ); filesTransferred = 1; return { mode: 'hub-relayed', sourcePath: resolvedSrc, destinationPath: targetFile, filesTransferred, bytesTransferred, durationMs: Date.now() - started, }; } finally { clearTimeout(timer); opts.signal?.removeEventListener('abort', onAbort); for (const s of activeStreams) { try { s.destroy(); } catch { // Ignore } } try { srcSftp.end(); } catch { // Ignore } try { dstSftp.end(); } catch { // Ignore } } } private async resolveRemotePath(sftp: SFTPWrapper, requestedPath: string): Promise { const trimmed = requestedPath.trim(); if (!trimmed || trimmed === '.' || trimmed === '~') { const home = await promisifySftp((cb) => sftp.realpath('.', cb)); return path.posix.normalize(home || '/'); } if (trimmed.startsWith('~/')) { const home = await promisifySftp((cb) => sftp.realpath('.', cb)); return path.posix.normalize(path.posix.join(home || '/', trimmed.slice(2))); } if (!trimmed.startsWith('/')) { const home = await promisifySftp((cb) => sftp.realpath('.', cb)); return path.posix.normalize(path.posix.join(home || '/', trimmed)); } return path.posix.normalize(trimmed); } private async ensureRemoteDir(sftp: SFTPWrapper, dirPath: string): Promise { const normalized = path.posix.normalize(dirPath); if (!normalized || normalized === '/' || normalized === '.') return; const stat = await promisifySftp((cb) => sftp.stat(normalized, cb)).catch(() => null); if (stat) return; await this.ensureRemoteDir(sftp, path.posix.dirname(normalized)); await promisifySftpVoid((cb) => sftp.mkdir(normalized, cb)).catch(async (err) => { const again = await promisifySftp((cb) => sftp.stat(normalized, cb)).catch(() => null); if (!again) throw err; }); } private async copyDirectoryRecursive( srcSftp: SFTPWrapper, dstSftp: SFTPWrapper, srcDir: string, dstDir: string, activeStreams: Set<{ destroy: () => void }>, getCancelError: () => Error | null, onProgress?: (msg: string) => void, ): Promise<{ files: number; bytes: number }> { const cancelErr = getCancelError(); if (cancelErr) throw cancelErr; await this.ensureRemoteDir(dstSftp, dstDir); const entries = await promisifySftp((cb) => srcSftp.readdir(srcDir, cb)); let files = 0; let bytes = 0; for (const entry of entries) { if ( entry.filename === '.' || entry.filename === '..' || entry.filename.includes('/') || entry.filename.includes('\0') ) { continue; } const srcChild = path.posix.join(srcDir, entry.filename); const dstChild = path.posix.join(dstDir, entry.filename); let mode = entry.attrs.mode ?? 0; if (mode === 0) { const ls = await promisifySftp((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null); mode = ls?.mode ?? 0; } if (isDirMode(mode)) { const sub = await this.copyDirectoryRecursive( srcSftp, dstSftp, srcChild, dstChild, activeStreams, getCancelError, onProgress, ); files += sub.files; bytes += sub.bytes; } else if (isRegularMode(mode)) { const copied = await this.copySingleFile( srcSftp, dstSftp, srcChild, dstChild, mode || 0o644, activeStreams, getCancelError, onProgress, ); files += 1; bytes += copied; } else { onProgress?.(`Skipping non-regular entry ${srcChild}`); } } return { files, bytes }; } private async copySingleFile( srcSftp: SFTPWrapper, dstSftp: SFTPWrapper, srcFile: string, dstFile: string, srcMode: number, activeStreams: Set<{ destroy: () => void }>, getCancelError: () => Error | null, onProgress?: (msg: string) => void, ): Promise { const cancelErr = getCancelError(); if (cancelErr) throw cancelErr; const dstDir = path.posix.dirname(dstFile); await this.ensureRemoteDir(dstSftp, dstDir); const tmpFile = path.posix.join( dstDir, `.gcoord-xfer-${crypto.randomBytes(6).toString('hex')}`, ); onProgress?.(`Relaying ${srcFile} -> ${dstFile}`); const readStream = srcSftp.createReadStream(srcFile); const writeStream = dstSftp.createWriteStream(tmpFile); activeStreams.add(readStream); activeStreams.add(writeStream); let bytes = 0; try { await new Promise((resolve, reject) => { let settled = false; const fail = (err: Error) => { if (settled) return; settled = true; readStream.destroy(); writeStream.destroy(); reject(getCancelError() ?? err); }; readStream.on('data', (chunk: Buffer) => { bytes += chunk.length; }); readStream.on('error', fail); writeStream.on('error', fail); writeStream.on('close', () => { if (settled) return; settled = true; const ce = getCancelError(); if (ce) reject(ce); else resolve(); }); readStream.pipe(writeStream); }); const perm = srcMode & 0o7777; if (perm > 0) { await promisifySftpVoid((cb) => dstSftp.chmod(tmpFile, perm, cb)).catch(() => undefined); } try { await promisifySftpVoid((cb) => dstSftp.ext_openssh_rename(tmpFile, dstFile, cb)); } catch { await promisifySftpVoid((cb) => dstSftp.unlink(dstFile, cb)).catch(() => undefined); await promisifySftpVoid((cb) => dstSftp.rename(tmpFile, dstFile, cb)); } return bytes; } catch (err) { await promisifySftpVoid((cb) => dstSftp.unlink(tmpFile, cb)).catch(() => undefined); throw err; } finally { activeStreams.delete(readStream); activeStreams.delete(writeStream); } } }