GCoordinator/src/server/ssh/sftp-service.ts

592 lines
19 KiB
TypeScript

import crypto from 'node:crypto';
import path from 'node:path';
import type { Readable } from 'node:stream';
import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2';
import type { SSHPool } from './ssh-pool.js';
import { posixSingleQuote } from './sudo.js';
export type SftpEntryType = 'dir' | 'file' | 'symlink' | 'other';
export interface SftpListEntry {
name: string;
path: string;
type: SftpEntryType;
size: number;
mode: number;
permissionsOctal: string;
mtimeMs: number;
uid: number;
gid: number;
}
export interface SftpTextFile {
path: string;
content: string;
sha256: string;
size: number;
mode: number;
}
export class SftpServiceError extends Error {
constructor(
public readonly code:
| 'NOT_FOUND'
| 'NOT_A_DIRECTORY'
| 'IS_A_DIRECTORY'
| 'FILE_TOO_LARGE'
| 'BINARY_FILE_NOT_EDITABLE'
| 'CONFLICT'
| 'INVALID_PATH'
| 'INVALID_MODE',
message: string,
) {
super(message);
}
}
const DEFAULT_MAX_TEXT_BYTES = 512 * 1024;
const DEFAULT_MAX_UPLOAD_BYTES = 512 * 1024 * 1024;
function modeToType(mode: number): SftpEntryType {
const kind = mode & 0o170000;
if (kind === 0o040000) return 'dir';
if (kind === 0o100000) return 'file';
if (kind === 0o120000) return 'symlink';
return 'other';
}
function sha256Buffer(buf: Buffer): string {
return crypto.createHash('sha256').update(buf).digest('hex');
}
function promisifySftp<T>(
fn: (cb: (err: Error | undefined | null, result: T) => void) => void,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
fn((err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
function promisifySftpVoid(
fn: (cb: (err?: Error | null) => void) => void,
): Promise<void> {
return new Promise<void>((resolve, reject) => {
fn((err) => {
if (err) reject(err);
else resolve();
});
});
}
export class SftpService {
constructor(private readonly sshPool: SSHPool) {}
async listDirectory(
serverId: string,
requestedPath?: string,
): Promise<{ path: string; parentPath: string | null; entries: SftpListEntry[] }> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, requestedPath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
if (modeToType(stats.mode) !== 'dir') {
throw new SftpServiceError('NOT_A_DIRECTORY', `Not a directory: ${resolved}`);
}
const rawEntries = await promisifySftp<FileEntryWithStats[]>((cb) =>
sftp.readdir(resolved, cb),
);
const entries: SftpListEntry[] = [];
for (const item of rawEntries) {
if (item.filename === '.' || item.filename === '..') continue;
const mode = item.attrs.mode ?? 0;
const type = modeToType(mode);
entries.push({
name: item.filename,
path: path.posix.join(resolved, item.filename),
type,
size: item.attrs.size ?? 0,
mode,
permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'),
mtimeMs: (item.attrs.mtime ?? 0) * 1000,
uid: item.attrs.uid ?? 0,
gid: item.attrs.gid ?? 0,
});
}
entries.sort((a, b) => {
if (a.type === 'dir' && b.type !== 'dir') return -1;
if (a.type !== 'dir' && b.type === 'dir') return 1;
return a.name.localeCompare(b.name);
});
const parentPath = resolved === '/' ? null : path.posix.dirname(resolved);
return { path: resolved, parentPath, entries };
});
}
async statPath(serverId: string, remotePath: string): Promise<SftpListEntry> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
const mode = stats.mode ?? 0;
return {
name: path.posix.basename(resolved) || '/',
path: resolved,
type: modeToType(mode),
size: stats.size ?? 0,
mode,
permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'),
mtimeMs: (stats.mtime ?? 0) * 1000,
uid: stats.uid ?? 0,
gid: stats.gid ?? 0,
};
});
}
async openDownloadStream(
serverId: string,
remotePath: string,
): Promise<{
path: string;
fileName: string;
size: number;
stream: Readable;
cleanup: () => void;
}> {
const sftp = await this.sshPool.openSftp(serverId);
const cleanup = () => {
try {
sftp.end();
} catch {
// Ignore close error
}
};
try {
const resolved = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
if (modeToType(stats.mode) === 'dir') {
throw new SftpServiceError(
'IS_A_DIRECTORY',
'Cannot download a directory as a single file; use /archive instead.',
);
}
const stream = sftp.createReadStream(resolved);
stream.once('close', cleanup);
stream.once('error', cleanup);
return {
path: resolved,
fileName: path.posix.basename(resolved),
size: stats.size ?? 0,
stream,
cleanup,
};
} catch (err) {
cleanup();
throw err;
}
}
async uploadStream(
serverId: string,
remotePath: string,
source: Readable,
maxBytes = DEFAULT_MAX_UPLOAD_BYTES,
): Promise<{ path: string; bytesWritten: number }> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
const dest = sftp.createWriteStream(resolved);
let bytesWritten = 0;
return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => {
let settled = false;
const fail = (err: Error) => {
if (settled) return;
settled = true;
try {
source.destroy();
} catch {
// Ignore
}
try {
dest.destroy();
} catch {
// Ignore
}
reject(err);
};
source.on('data', (chunk: Buffer) => {
bytesWritten += chunk.length;
if (bytesWritten > maxBytes) {
fail(
new SftpServiceError(
'FILE_TOO_LARGE',
`Upload exceeded limit of ${maxBytes} bytes`,
),
);
}
});
source.on('error', fail);
dest.on('error', fail);
dest.on('close', () => {
if (settled) return;
settled = true;
resolve({ path: resolved, bytesWritten });
});
source.pipe(dest);
});
});
}
async mkdir(serverId: string, remotePath: string): Promise<string> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
await promisifySftpVoid((cb) => sftp.mkdir(resolved, cb));
return resolved;
});
}
async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> {
return this.withSftp(serverId, async (sftp) => {
const resolvedFrom = await this.resolveRemotePath(sftp, fromPath);
const resolvedTo = await this.resolveRemotePath(sftp, toPath);
await this.renameSftpPath(sftp, resolvedFrom, resolvedTo);
return { from: resolvedFrom, to: resolvedTo };
});
}
async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> {
const parsedMode =
typeof modeInput === 'number'
? modeInput
: /^[0-7]{3,4}$/.test(modeInput.trim())
? Number.parseInt(modeInput.trim(), 8)
: Number.NaN;
if (!Number.isInteger(parsedMode) || parsedMode < 0 || parsedMode > 0o7777) {
throw new SftpServiceError('INVALID_MODE', `Invalid POSIX mode: ${String(modeInput)}`);
}
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
await promisifySftpVoid((cb) => sftp.chmod(resolved, parsedMode, cb));
return {
path: resolved,
permissionsOctal: parsedMode.toString(8).padStart(4, '0'),
};
});
}
async deletePath(
serverId: string,
remotePath: string,
recursive = false,
): Promise<string> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
if (resolved === '/' || resolved === '.') {
throw new SftpServiceError('INVALID_PATH', 'Refusing to delete root directory');
}
await this.deleteResolved(sftp, resolved, recursive);
return resolved;
});
}
async readTextFile(
serverId: string,
remotePath: string,
opts: { sudo?: boolean; maxBytes?: number } = {},
): Promise<SftpTextFile> {
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_TEXT_BYTES;
if (opts.sudo) {
const resolved = await this.resolvePathNoStat(serverId, remotePath);
const quoted = posixSingleQuote(resolved);
const statRes = await this.sshPool.exec(
serverId,
`test -f ${quoted} && wc -c < ${quoted} && (stat -c '%a' ${quoted} 2>/dev/null || stat -f '%Lp' ${quoted} 2>/dev/null || echo 644)`,
{ sudo: true },
);
if (statRes.exitCode !== 0) {
throw new SftpServiceError(
'NOT_FOUND',
statRes.stderr.trim() || `Unable to read file ${resolved}`,
);
}
const [sizeLine, modeLine] = statRes.stdout.trim().split(/\r?\n/);
const size = Number.parseInt(sizeLine ?? '0', 10) || 0;
if (size > maxBytes) {
throw new SftpServiceError(
'FILE_TOO_LARGE',
`File "${resolved}" (${size}B) exceeds inline editor limit (${maxBytes}B)`,
);
}
const mode = Number.parseInt(modeLine ?? '644', 8) || 0o644;
const catRes = await this.sshPool.exec(serverId, `cat -- ${quoted}`, {
sudo: true,
maxBytes: maxBytes + 16,
});
if (catRes.exitCode !== 0) {
throw new SftpServiceError(
'NOT_FOUND',
catRes.stderr.trim() || `Unable to read ${resolved}`,
);
}
const buf = Buffer.from(catRes.stdout, 'utf8');
if (buf.includes(0)) {
throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor');
}
return {
path: resolved,
content: catRes.stdout,
sha256: sha256Buffer(buf),
size: buf.length,
mode,
};
}
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
if (modeToType(stats.mode) === 'dir') {
throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`);
}
if ((stats.size ?? 0) > maxBytes) {
throw new SftpServiceError(
'FILE_TOO_LARGE',
`File "${resolved}" (${stats.size}B) exceeds inline editor limit (${maxBytes}B)`,
);
}
const buf = await promisifySftp<Buffer>((cb) => sftp.readFile(resolved, cb));
if (buf.length > maxBytes) {
throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit');
}
if (buf.includes(0)) {
throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor');
}
return {
path: resolved,
content: buf.toString('utf8'),
sha256: sha256Buffer(buf),
size: buf.length,
mode: stats.mode & 0o7777,
};
});
}
async writeTextFileAtomic(
serverId: string,
remotePath: string,
content: string,
opts: { expectedSha256?: string; force?: boolean; sudo?: boolean } = {},
): Promise<{ path: string; sha256: string; size: number }> {
const newBuf = Buffer.from(content, 'utf8');
const newSha = sha256Buffer(newBuf);
if (opts.sudo) {
const resolved = await this.resolvePathNoStat(serverId, remotePath);
if (opts.expectedSha256 && !opts.force) {
try {
const existing = await this.readTextFile(serverId, resolved, { sudo: true });
if (existing.sha256 !== opts.expectedSha256) {
throw new SftpServiceError(
'CONFLICT',
`Remote file "${resolved}" changed on disk since you loaded it.`,
);
}
} catch (err) {
if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err;
}
}
const dir = path.posix.dirname(resolved);
const tmp = path.posix.join(dir, `.gcoord-tmp-${crypto.randomBytes(6).toString('hex')}`);
const qDst = posixSingleQuote(resolved);
const qTmp = posixSingleQuote(tmp);
const res = await this.sshPool.exec(
serverId,
`umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || chmod --reference=${qDst} ${qTmp} 2>/dev/null || true; } && mv -f ${qTmp} ${qDst}`,
{ sudo: true, stdin: newBuf },
);
if (res.exitCode !== 0) {
throw new Error(res.stderr.trim() || `Atomic sudo write failed for ${resolved}`);
}
return { path: resolved, sha256: newSha, size: newBuf.length };
}
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
let existingMode: number | undefined;
try {
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
existingMode = stats.mode & 0o7777;
if (opts.expectedSha256 && !opts.force) {
const prevBuf = await promisifySftp<Buffer>((cb) => sftp.readFile(resolved, cb));
if (sha256Buffer(prevBuf) !== opts.expectedSha256) {
throw new SftpServiceError(
'CONFLICT',
`Remote file "${resolved}" changed on disk since you loaded it.`,
);
}
}
} catch (err) {
if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err;
// File does not yet exist or could not be pre-read
}
const dir = path.posix.dirname(resolved);
const tmp = path.posix.join(dir, `.gcoord-tmp-${crypto.randomBytes(6).toString('hex')}`);
try {
await promisifySftpVoid((cb) => sftp.writeFile(tmp, newBuf, cb));
if (existingMode !== undefined) {
await promisifySftpVoid((cb) => sftp.chmod(tmp, existingMode!, cb)).catch(
() => undefined,
);
}
await this.renameSftpPath(sftp, tmp, resolved);
} catch (err) {
await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined);
throw err;
}
return { path: resolved, sha256: newSha, size: newBuf.length };
});
}
async streamDirectoryArchive(
serverId: string,
remotePath: string,
requestedFormat: 'auto' | 'tar.zst' | 'tar.gz' = 'auto',
): Promise<{
path: string;
resolvedFormat: 'tar.zst' | 'tar.gz';
archiveFileName: string;
stream: Readable;
done: Promise<{ exitCode: number | null; signal?: string }>;
abort: () => void;
}> {
const resolved = await this.withSftp(serverId, async (sftp) => {
const p = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(p, cb));
if (modeToType(stats.mode) !== 'dir') {
throw new SftpServiceError('NOT_A_DIRECTORY', `Not a directory: ${p}`);
}
return p;
});
let resolvedFormat: 'tar.zst' | 'tar.gz' =
requestedFormat === 'auto' ? 'tar.gz' : requestedFormat;
if (requestedFormat === 'auto') {
const probe = await this.sshPool
.exec(serverId, 'command -v zstd >/dev/null 2>&1', { timeoutMs: 8_000 })
.catch(() => ({ exitCode: 1 }));
if (probe.exitCode === 0) {
resolvedFormat = 'tar.zst';
}
}
const parentDir = resolved === '/' ? '/' : path.posix.dirname(resolved);
const baseName = resolved === '/' ? '.' : path.posix.basename(resolved);
const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_');
const archiveFileName = `${safeName}.${resolvedFormat}`;
const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T0 -c' : 'gzip -c';
const cmd = `set -o pipefail 2>/dev/null || true; tar -C ${posixSingleQuote(parentDir)} -cf - ${posixSingleQuote(baseName)} | ${compressCmd}`;
const handle = await this.sshPool.execStream(serverId, cmd);
return {
path: resolved,
resolvedFormat,
archiveFileName,
stream: handle.channel,
done: handle.done,
abort: handle.abort,
};
}
private async withSftp<T>(
serverId: string,
fn: (sftp: SFTPWrapper) => Promise<T>,
): Promise<T> {
const sftp = await this.sshPool.openSftp(serverId);
try {
return await fn(sftp);
} finally {
try {
sftp.end();
} catch {
// Ignore close errors
}
}
}
private async resolvePathNoStat(serverId: string, requestedPath?: string): Promise<string> {
const trimmed = requestedPath?.trim() ?? '';
if (trimmed.startsWith('/')) {
return path.posix.normalize(trimmed);
}
return this.withSftp(serverId, (sftp) => this.resolveRemotePath(sftp, requestedPath));
}
private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise<string> {
const trimmed = requestedPath?.trim() ?? '';
if (!trimmed || trimmed === '.' || trimmed === '~') {
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
return path.posix.normalize(home || '/');
}
if (trimmed.startsWith('~/')) {
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
return path.posix.normalize(path.posix.join(home || '/', trimmed.slice(2)));
}
if (!trimmed.startsWith('/')) {
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
return path.posix.normalize(path.posix.join(home || '/', trimmed));
}
return path.posix.normalize(trimmed);
}
private async renameSftpPath(
sftp: SFTPWrapper,
fromPath: string,
toPath: string,
): Promise<void> {
try {
await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb));
} catch {
await promisifySftpVoid((cb) => sftp.unlink(toPath, cb)).catch(() => undefined);
await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb));
}
}
private async deleteResolved(
sftp: SFTPWrapper,
resolved: string,
recursive: boolean,
): Promise<void> {
const stats = await promisifySftp<Stats>((cb) => sftp.lstat(resolved, cb));
if (modeToType(stats.mode) !== 'dir') {
await promisifySftpVoid((cb) => sftp.unlink(resolved, cb));
return;
}
if (recursive) {
const entries = await promisifySftp<FileEntryWithStats[]>((cb) =>
sftp.readdir(resolved, cb),
);
for (const entry of entries) {
if (entry.filename === '.' || entry.filename === '..') continue;
await this.deleteResolved(sftp, path.posix.join(resolved, entry.filename), true);
}
}
await promisifySftpVoid((cb) => sftp.rmdir(resolved, cb));
}
}