feat(workflows,transfers,broadcast): harden templates/rsync/SFTP-transfer, add http/notify steps, retries, secret inputs & broadcast history
This commit is contained in:
parent
d5822c9eca
commit
2b878c1d99
8 changed files with 1217 additions and 168 deletions
|
|
@ -2,6 +2,7 @@ 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';
|
||||
|
|
@ -15,8 +16,42 @@ export interface TransferResult {
|
|||
durationMs: number;
|
||||
}
|
||||
|
||||
const FILE_TYPE_MASK = 0o170000;
|
||||
const MODE_DIR = 0o040000;
|
||||
const MODE_REG = 0o100000;
|
||||
|
||||
function isDirMode(mode: number): boolean {
|
||||
return (mode & 0o170000) === 0o040000;
|
||||
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<T>(
|
||||
|
|
@ -46,6 +81,7 @@ export class TransferEngine {
|
|||
private readonly sshPool: SSHPool,
|
||||
private readonly _sftpService: SftpService,
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly knownHosts?: KnownHostsService,
|
||||
) {
|
||||
void this._sftpService;
|
||||
}
|
||||
|
|
@ -54,6 +90,8 @@ export class TransferEngine {
|
|||
mode: 'hub-relayed' | 'direct';
|
||||
source: { serverId: string; path: string };
|
||||
destination: { serverId: string; path: string };
|
||||
delete?: boolean;
|
||||
exclude?: string[];
|
||||
sudo?: boolean;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
|
|
@ -72,12 +110,29 @@ export class TransferEngine {
|
|||
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 sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`;
|
||||
const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`;
|
||||
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, {
|
||||
|
|
@ -157,8 +212,8 @@ export class TransferEngine {
|
|||
|
||||
return {
|
||||
mode: 'direct',
|
||||
sourcePath: opts.source.path,
|
||||
destinationPath: opts.destination.path,
|
||||
sourcePath: safeSrcPath,
|
||||
destinationPath: safeDstPath,
|
||||
filesTransferred: 1,
|
||||
bytesTransferred: 0,
|
||||
durationMs: Date.now() - started,
|
||||
|
|
@ -201,16 +256,21 @@ export class TransferEngine {
|
|||
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
try {
|
||||
const trimmedDest = opts.destination.path.trim();
|
||||
const trimmedDest = safeDstPath;
|
||||
const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/');
|
||||
const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path);
|
||||
const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path);
|
||||
const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath);
|
||||
const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath);
|
||||
|
||||
const srcStat = await promisifySftp<Stats>((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}"`);
|
||||
}
|
||||
|
||||
const srcStat = await promisifySftp<Stats>((cb) => srcSftp.stat(resolvedSrc, cb));
|
||||
let filesTransferred = 0;
|
||||
let bytesTransferred = 0;
|
||||
|
||||
if (isDirMode(srcStat.mode ?? 0)) {
|
||||
if (isDirMode(srcMode)) {
|
||||
const dstStat = await promisifySftp<Stats>((cb) => dstSftp!.stat(resolvedDest, cb)).catch(
|
||||
() => null,
|
||||
);
|
||||
|
|
@ -254,7 +314,7 @@ export class TransferEngine {
|
|||
dstSftp,
|
||||
resolvedSrc,
|
||||
targetFile,
|
||||
srcStat.mode ?? 0o644,
|
||||
srcMode || 0o644,
|
||||
activeStreams,
|
||||
() => timedOutOrAborted,
|
||||
opts.onProgress,
|
||||
|
|
@ -341,10 +401,21 @@ export class TransferEngine {
|
|||
let files = 0;
|
||||
let bytes = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.filename === '.' || entry.filename === '..') continue;
|
||||
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);
|
||||
const mode = entry.attrs.mode ?? 0;
|
||||
let mode = entry.attrs.mode ?? 0;
|
||||
if (mode === 0) {
|
||||
const ls = await promisifySftp<Stats>((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null);
|
||||
mode = ls?.mode ?? 0;
|
||||
}
|
||||
|
||||
if (isDirMode(mode)) {
|
||||
const sub = await this.copyDirectoryRecursive(
|
||||
|
|
@ -358,7 +429,7 @@ export class TransferEngine {
|
|||
);
|
||||
files += sub.files;
|
||||
bytes += sub.bytes;
|
||||
} else {
|
||||
} else if (isRegularMode(mode)) {
|
||||
const copied = await this.copySingleFile(
|
||||
srcSftp,
|
||||
dstSftp,
|
||||
|
|
@ -371,6 +442,8 @@ export class TransferEngine {
|
|||
);
|
||||
files += 1;
|
||||
bytes += copied;
|
||||
} else {
|
||||
onProgress?.(`Skipping non-regular entry ${srcChild}`);
|
||||
}
|
||||
}
|
||||
return { files, bytes };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue