security(pty,sftp): fix PTY cwd injection/recording/crashes & harden + upgrade SFTP manager

This commit is contained in:
tyuXX 2026-11-27 22:42:33 +00:00
parent 716627afdd
commit 838e69ba4e
6 changed files with 605 additions and 94 deletions

View file

@ -1,4 +1,4 @@
import { Router, type Response } from 'express';
import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express';
import { z } from 'zod';
import type { ConfigManager } from '../../config/config-manager.js';
import type { AuditService } from '../../security/audit.js';
@ -7,6 +7,7 @@ import {
enforceSafeMode,
requireAuth,
requireCsrf,
requireStepUp,
} from '../../security/guards.js';
import { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js';
@ -15,6 +16,16 @@ export interface SftpRouterDeps {
configManager: ConfigManager;
auditService: AuditService;
sftpService: SftpService;
stepUpGuard?: RequestHandler;
}
function buildContentDisposition(fileName: string): string {
const asciiFallback = fileName.replace(/[^\x20-\x7e]|["\\;]/g, '_');
const rfc5987 = encodeURIComponent(fileName).replace(
/['()*!]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${rfc5987}`;
}
function sendSftpError(res: Response, err: unknown): void {
@ -22,7 +33,7 @@ function sendSftpError(res: Response, err: unknown): void {
const status =
err.code === 'NOT_FOUND'
? 404
: err.code === 'CONFLICT'
: err.code === 'CONFLICT' || err.code === 'ALREADY_EXISTS'
? 409
: err.code === 'FILE_TOO_LARGE'
? 413
@ -37,7 +48,13 @@ function sendSftpError(res: Response, err: unknown): void {
export function createSftpRouter(deps: SftpRouterDeps): Router {
const router = Router({ mergeParams: true });
const { authService, configManager, auditService, sftpService } = deps;
const {
authService,
configManager,
auditService,
sftpService,
stepUpGuard = requireStepUp,
} = deps;
const ensureServer = (serverId: string, res: Response): boolean => {
if (!configManager.getServer(serverId)) {
@ -47,6 +64,18 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
return true;
};
const conditionalSudoStepUp = (req: Request, res: Response, next: NextFunction) => {
const wantsSudo =
req.query.sudo === '1' ||
req.query.sudo === 'true' ||
Boolean((req.body as { sudo?: unknown } | undefined)?.sudo);
if (!wantsSudo) {
next();
return;
}
stepUpGuard(req, res, next);
};
router.get('/list', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
@ -75,6 +104,24 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
}
});
router.get('/search', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const basePath = typeof req.query.path === 'string' ? req.query.path : '/';
const q = typeof req.query.q === 'string' ? req.query.q : '';
const max = req.query.max ? Number(req.query.max) : 100;
if (!q.trim()) {
res.status(400).json({ error: 'MISSING_QUERY' });
return;
}
try {
const result = await sftpService.searchFiles(serverId, basePath, q, Number.isFinite(max) ? max : 100);
res.json(result);
} catch (err) {
sendSftpError(res, err);
}
});
router.get('/download', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
@ -86,9 +133,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
try {
const dl = await sftpService.openDownloadStream(serverId, targetPath);
const safeName = dl.fileName.replace(/["\r\n\\]/g, '_');
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${safeName}"`);
res.setHeader('Content-Disposition', buildContentDisposition(dl.fileName));
res.setHeader('Cache-Control', 'no-store');
if (Number.isFinite(dl.size)) {
res.setHeader('Content-Length', String(dl.size));
}
@ -127,11 +174,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
try {
const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format);
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader(
'Content-Disposition',
`attachment; filename="${arch.archiveFileName}"`,
);
res.setHeader('Content-Disposition', buildContentDisposition(arch.archiveFileName));
res.setHeader('X-Archive-Format', arch.resolvedFormat);
res.setHeader('Cache-Control', 'no-store');
res.once('close', () => {
if (!res.writableEnded) {
@ -183,6 +228,35 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
},
);
router.post(
'/touch',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z.object({ path: z.string().min(1) }).safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const created = await sftpService.touchFile(serverId, parsed.data.path);
auditService.log({
action: 'sftp.touch',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${created}`,
status: 'ok',
});
res.status(201).json({ ok: true, path: created });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.post(
'/mkdir',
requireAuth(authService),
@ -221,7 +295,11 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z
.object({ fromPath: z.string().min(1), toPath: z.string().min(1) })
.object({
fromPath: z.string().min(1),
toPath: z.string().min(1),
overwrite: z.boolean().optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
@ -232,6 +310,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
serverId,
parsed.data.fromPath,
parsed.data.toPath,
Boolean(parsed.data.overwrite),
);
auditService.log({
action: 'sftp.rename',
@ -283,6 +362,50 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
},
);
router.post(
'/chown',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
stepUpGuard,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z
.object({
path: z.string().min(1),
uid: z.number().int().min(0),
gid: z.number().int().min(0),
sudo: z.boolean().optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const result = await sftpService.chown(
serverId,
parsed.data.path,
parsed.data.uid,
parsed.data.gid,
Boolean(parsed.data.sudo),
);
auditService.log({
action: 'sftp.chown',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${result.path}`,
status: 'ok',
details: { uid: result.uid, gid: result.gid, sudo: Boolean(parsed.data.sudo) },
});
res.json({ ok: true, ...result });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.delete(
'/entry',
requireAuth(authService),
@ -314,7 +437,42 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
},
);
router.get('/text', requireAuth(authService), async (req, res) => {
router.post(
'/bulk-delete',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z
.object({
paths: z.array(z.string().min(1)).min(1).max(100),
recursive: z.boolean().optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
const result = await sftpService.bulkDelete(
serverId,
parsed.data.paths,
Boolean(parsed.data.recursive),
);
auditService.log({
action: 'sftp.bulk_delete',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: serverId,
status: result.failed.length === 0 ? 'ok' : 'error',
details: { count: result.deleted.length, failedCount: result.failed.length },
});
res.json(result);
},
);
router.get('/text', requireAuth(authService), conditionalSudoStepUp, async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
@ -325,6 +483,15 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
}
try {
const file = await sftpService.readTextFile(serverId, targetPath, { sudo });
if (sudo) {
auditService.log({
action: 'sftp.sudo_read',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${file.path}`,
status: 'ok',
});
}
res.json({ file });
} catch (err) {
sendSftpError(res, err);
@ -336,6 +503,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
requireAuth(authService),
requireCsrf,
enforceSafeMode,
conditionalSudoStepUp,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;

View file

@ -37,7 +37,11 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
serverId: EntityIdSchema,
cols: z.number().int().min(10).max(500).optional(),
rows: z.number().int().min(4).max(200).optional(),
cwd: z.string().max(1024).optional(),
cwd: z
.string()
.max(1024)
.refine((v) => !/[\x00-\x1f\x7f]/.test(v), 'Control characters not permitted in cwd')
.optional(),
title: z.string().max(120).optional(),
})
.safeParse(req.body ?? {});
@ -70,6 +74,36 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
},
);
router.post(
'/sessions/:sessionId/reconnect',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const sessionId = String(req.params.sessionId ?? '');
try {
const session = await ptyManager.reconnectSession(sessionId);
if (!session) {
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' });
return;
}
auditService.log({
action: 'pty.reconnect',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${session.serverId}:${sessionId}`,
status: 'ok',
});
res.json({ ok: true, session });
} catch (err) {
res.status(502).json({
error: 'PTY_RECONNECT_FAILED',
message: err instanceof Error ? err.message : 'Unable to reconnect PTY session',
});
}
},
);
router.post(
'/sessions/:sessionId/resize',
requireAuth(authService),
@ -98,7 +132,12 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => {
const sessionId = String(req.params.sessionId ?? '');
const format = req.query.format === 'ansi' ? 'ansi' : 'plain';
const format =
req.query.format === 'ansi'
? 'ansi'
: req.query.format === 'cast'
? 'cast'
: 'plain';
const exported = ptyManager.exportScrollback(sessionId, format);
if (!exported) {
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' });
@ -106,8 +145,9 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
}
const safeFile = exported.filename.replace(/[^A-Za-z0-9._-]/g, '_');
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Content-Type', exported.contentType);
res.setHeader('Content-Disposition', `attachment; filename="${safeFile}"`);
res.setHeader('Cache-Control', 'no-store');
res.send(exported.content);
});

View file

@ -177,7 +177,7 @@ export async function createGCoordinatorServer(
const knownHosts = new KnownHostsService(db, auditService);
const sshPool = new SSHPool(configManager, vaultService, knownHosts);
const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService);
const ptyManager = new PTYManager(sshPool, configManager, wsHub);
const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits);
const sftpService = new SftpService(sshPool);
const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService);
const customSystemsEngine = new CustomSystemsEngine(
@ -564,7 +564,7 @@ export async function createGCoordinatorServer(
app.use('/api/ai', createAiRouter({ authService, aiService }));
app.use(
'/api/servers/:id/sftp',
createSftpRouter({ authService, configManager, auditService, sftpService }),
createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }),
);
app.use(
'/api/servers',

View file

@ -4,6 +4,7 @@ import type { ClientChannel } from 'ssh2';
import { WS_CHANNELS } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.js';
import type { RuntimeLimits } from '../config/runtime-limits.js';
import type { SSHPool } from './ssh-pool.js';
import { posixSingleQuote } from './sudo.js';
@ -34,22 +35,34 @@ export interface OpenPtyParams {
}
interface ScrollChunk {
offsetMs: number;
text: string;
bytes: number;
}
interface InternalPtySession {
info: PtySessionInfo;
env?: Record<string, string>;
sudo?: boolean;
channel: ClientChannel;
chunks: ScrollChunk[];
stdoutDecoder: StringDecoder;
stderrDecoder: StringDecoder;
}
const MAX_RETAINED_EXITED_SESSIONS = 20;
export function assertSafeCwd(cwd: string): string {
if (/[\x00-\x1f\x7f]/.test(cwd)) {
throw new Error('Invalid cwd: control characters are not permitted');
}
const trimmed = cwd.trim();
if (trimmed.length > 1024) {
throw new Error('Invalid cwd: exceeds 1024 character limit');
}
return trimmed;
}
export function formatRemoteCd(cwd: string): string {
const trimmed = cwd.trim();
const trimmed = assertSafeCwd(cwd);
if (trimmed === '~' || trimmed === '~/') {
return 'cd -- "$HOME"';
}
@ -71,7 +84,6 @@ function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; byte
return { text, bytes: buf.length };
}
let start = buf.length - maxBytes;
// Skip UTF-8 continuation bytes (10xxxxxx) so we never cut inside a codepoint
while (start < buf.length && (buf[start]! & 0b1100_0000) === 0b1000_0000) {
start++;
}
@ -87,6 +99,7 @@ export class PTYManager {
private readonly sshPool: SSHPool,
private readonly configManager: ConfigManager,
private readonly wsHub: WsHub,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) {
this.reaperTimer = setInterval(() => {
this.reapIdleSessions();
@ -94,14 +107,12 @@ export class PTYManager {
this.reaperTimer.unref();
}
async openSession(params: OpenPtyParams): Promise<PtySessionInfo> {
const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80)));
const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24)));
const now = Date.now();
const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`;
const trimmedCwd = params.cwd?.trim();
let channel: ClientChannel;
private async createChannel(
params: OpenPtyParams,
cols: number,
rows: number,
trimmedCwd?: string,
): Promise<ClientChannel> {
if (params.command) {
const cmd = trimmedCwd
? `${formatRemoteCd(trimmedCwd)} && (${params.command})`
@ -111,45 +122,30 @@ export class PTYManager {
sudo: params.sudo,
pty: { cols, rows, term: 'xterm-256color' },
});
channel = stream.channel;
} else {
channel = await this.sshPool.openShell(params.serverId, {
stream.done.catch(() => undefined);
return stream.channel;
}
if (trimmedCwd && trimmedCwd !== '~') {
const channel = await this.sshPool.openShell(params.serverId, {
cols,
rows,
term: 'xterm-256color',
});
if (trimmedCwd && trimmedCwd !== '~') {
channel.write(`${formatRemoteCd(trimmedCwd)}\n`);
}
return channel;
}
const title =
params.title?.trim() ||
(params.command
? `${params.serverId}: ${params.command.slice(0, 32)}`
: `${params.serverId} shell`);
const internal: InternalPtySession = {
info: {
sessionId,
serverId: params.serverId,
title,
cwd: trimmedCwd || undefined,
command: params.command,
return this.sshPool.openShell(params.serverId, {
cols,
rows,
createdAt: now,
lastActivityAt: now,
exited: false,
exitCode: null,
scrollbackBytes: 0,
},
channel,
chunks: [],
stdoutDecoder: new StringDecoder('utf8'),
stderrDecoder: new StringDecoder('utf8'),
};
this.sessions.set(sessionId, internal);
term: 'xterm-256color',
});
}
private bindChannelHandlers(internal: InternalPtySession): void {
const { channel } = internal;
const { sessionId } = internal.info;
channel.on('data', (chunk: Buffer) => {
const text = internal.stdoutDecoder.write(chunk);
@ -162,7 +158,7 @@ export class PTYManager {
});
const finalizeExit = (code: number | null) => {
if (internal.info.exited) return;
if (internal.channel !== channel || internal.info.exited) return;
const tailOut = internal.stdoutDecoder.end();
if (tailOut) this.appendOutput(internal, tailOut);
const tailErr = internal.stderrDecoder.end();
@ -185,7 +181,99 @@ export class PTYManager {
channel.on('close', () => {
finalizeExit(internal.info.exitCode);
});
channel.on('error', () => {
finalizeExit(internal.info.exitCode);
});
}
async openSession(params: OpenPtyParams): Promise<PtySessionInfo> {
const limits = this.getRuntimeLimits?.();
const maxActive = limits?.maxActivePtys ?? 32;
const activeCount = [...this.sessions.values()].filter((s) => !s.info.exited).length;
if (activeCount >= maxActive) {
throw new Error(`Active PTY limit (${maxActive}) reached`);
}
const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80)));
const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24)));
const now = Date.now();
const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`;
const trimmedCwd = params.cwd !== undefined ? assertSafeCwd(params.cwd) : undefined;
const channel = await this.createChannel(
params,
cols,
rows,
trimmedCwd || undefined,
);
const title =
params.title?.trim() ||
(params.command
? `${params.serverId}: ${params.command.slice(0, 32)}`
: `${params.serverId} shell`);
const internal: InternalPtySession = {
info: {
sessionId,
serverId: params.serverId,
title,
cwd: trimmedCwd || undefined,
command: params.command,
cols,
rows,
createdAt: now,
lastActivityAt: now,
exited: false,
exitCode: null,
scrollbackBytes: 0,
},
env: params.env,
sudo: params.sudo,
channel,
chunks: [],
stdoutDecoder: new StringDecoder('utf8'),
stderrDecoder: new StringDecoder('utf8'),
};
this.sessions.set(sessionId, internal);
this.bindChannelHandlers(internal);
return { ...internal.info };
}
async reconnectSession(sessionId: string): Promise<PtySessionInfo | null> {
const internal = this.sessions.get(sessionId);
if (!internal) return null;
const oldChannel = internal.channel;
const channel = await this.createChannel(
{
serverId: internal.info.serverId,
command: internal.info.command,
env: internal.env,
sudo: internal.sudo,
},
internal.info.cols,
internal.info.rows,
internal.info.cwd,
);
internal.channel = channel;
internal.stdoutDecoder = new StringDecoder('utf8');
internal.stderrDecoder = new StringDecoder('utf8');
internal.info.exited = false;
internal.info.exitCode = null;
internal.info.lastActivityAt = Date.now();
this.bindChannelHandlers(internal);
try {
oldChannel.close();
oldChannel.destroy();
} catch {
// Ignore cleanup errors on prior channel
}
this.appendOutput(internal, '\r\n[gcoord: reconnected PTY session]\r\n');
return { ...internal.info };
}
@ -215,7 +303,6 @@ export class PTYManager {
entry.info.cols = clampedCols;
entry.info.rows = clampedRows;
entry.info.lastActivityAt = Date.now();
// @types/ssh2: Channel.setWindow(rows, cols, height, width)
entry.channel.setWindow(clampedRows, clampedCols, 0, 0);
return true;
}
@ -228,16 +315,34 @@ export class PTYManager {
exportScrollback(
sessionId: string,
format: 'plain' | 'ansi' = 'plain',
): { filename: string; content: string } | null {
format: 'plain' | 'ansi' | 'cast' = 'plain',
): { filename: string; content: string; contentType: string } | null {
const entry = this.sessions.get(sessionId);
if (!entry) return null;
if (format === 'cast') {
const header = JSON.stringify({
version: 2,
width: entry.info.cols,
height: entry.info.rows,
timestamp: Math.floor(entry.info.createdAt / 1000),
title: entry.info.title,
});
const events = entry.chunks.map((c) =>
JSON.stringify([Number((c.offsetMs / 1000).toFixed(3)), 'o', c.text]),
);
return {
filename: `${entry.info.serverId}-${sessionId}.cast`,
content: `${[header, ...events].join('\n')}\n`,
contentType: 'application/x-asciicast; charset=utf-8',
};
}
const raw = entry.chunks.map((c) => c.text).join('');
const content = format === 'ansi' ? raw : stripAnsiSequences(raw);
const ext = format === 'ansi' ? 'ansi.log' : 'txt';
return {
filename: `${entry.info.serverId}-${sessionId}.${ext}`,
content,
contentType: 'text/plain; charset=utf-8',
};
}
@ -275,15 +380,22 @@ export class PTYManager {
}
private appendOutput(entry: InternalPtySession, text: string): void {
const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes);
const configuredMax = this.configManager.getSettings().ptyScrollbackBytes;
const runtimeCap = this.getRuntimeLimits?.()?.defaultPtyScrollbackBytes;
const maxBytes = Math.max(
16_384,
runtimeCap ? Math.min(configuredMax, runtimeCap) : configuredMax,
);
const rawBytes = Buffer.byteLength(text, 'utf8');
const now = Date.now();
const offsetMs = Math.max(0, now - entry.info.createdAt);
if (rawBytes >= maxBytes) {
const trimmed = sliceTrailingUtf8(text, maxBytes);
entry.chunks = [{ text: trimmed.text, bytes: trimmed.bytes }];
entry.chunks = [{ offsetMs, text: trimmed.text, bytes: trimmed.bytes }];
entry.info.scrollbackBytes = trimmed.bytes;
} else {
entry.chunks.push({ text, bytes: rawBytes });
entry.chunks.push({ offsetMs, text, bytes: rawBytes });
entry.info.scrollbackBytes += rawBytes;
while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) {
const dropped = entry.chunks.shift()!;
@ -291,7 +403,7 @@ export class PTYManager {
}
}
entry.info.lastActivityAt = Date.now();
entry.info.lastActivityAt = now;
this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), {
type: 'pty:output',
sessionId: entry.info.sessionId,
@ -320,10 +432,11 @@ export class PTYManager {
}
private pruneExcessExited(): void {
const maxRetained = this.getRuntimeLimits?.()?.maxRetainedExitedPtys ?? 12;
const exited = [...this.sessions.values()]
.filter((s) => s.info.exited)
.sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt);
while (exited.length > MAX_RETAINED_EXITED_SESSIONS) {
while (exited.length > maxRetained) {
const oldest = exited.shift()!;
this.sessions.delete(oldest.info.sessionId);
}

View file

@ -17,6 +17,7 @@ export interface SftpListEntry {
mtimeMs: number;
uid: number;
gid: number;
symlinkTarget?: string;
}
export interface SftpTextFile {
@ -33,6 +34,8 @@ export class SftpServiceError extends Error {
| 'NOT_FOUND'
| 'NOT_A_DIRECTORY'
| 'IS_A_DIRECTORY'
| 'UNSUPPORTED_FILE_TYPE'
| 'ALREADY_EXISTS'
| 'FILE_TOO_LARGE'
| 'BINARY_FILE_NOT_EDITABLE'
| 'CONFLICT'
@ -104,9 +107,18 @@ export class SftpService {
if (item.filename === '.' || item.filename === '..') continue;
const mode = item.attrs.mode ?? 0;
const type = modeToType(mode);
const itemPath = path.posix.join(resolved, item.filename);
let symlinkTarget: string | undefined;
if (type === 'symlink') {
try {
symlinkTarget = await promisifySftp<string>((cb) => sftp.readlink(itemPath, cb));
} catch {
symlinkTarget = undefined;
}
}
entries.push({
name: item.filename,
path: path.posix.join(resolved, item.filename),
path: itemPath,
type,
size: item.attrs.size ?? 0,
mode,
@ -114,6 +126,7 @@ export class SftpService {
mtimeMs: (item.attrs.mtime ?? 0) * 1000,
uid: item.attrs.uid ?? 0,
gid: item.attrs.gid ?? 0,
...(symlinkTarget !== undefined ? { symlinkTarget } : {}),
});
}
@ -131,18 +144,28 @@ export class SftpService {
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;
const lstats = await promisifySftp<Stats>((cb) => sftp.lstat(resolved, cb));
const mode = lstats.mode ?? 0;
const type = modeToType(mode);
let symlinkTarget: string | undefined;
if (type === 'symlink') {
try {
symlinkTarget = await promisifySftp<string>((cb) => sftp.readlink(resolved, cb));
} catch {
symlinkTarget = undefined;
}
}
return {
name: path.posix.basename(resolved) || '/',
path: resolved,
type: modeToType(mode),
size: stats.size ?? 0,
type,
size: lstats.size ?? 0,
mode,
permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'),
mtimeMs: (stats.mtime ?? 0) * 1000,
uid: stats.uid ?? 0,
gid: stats.gid ?? 0,
mtimeMs: (lstats.mtime ?? 0) * 1000,
uid: lstats.uid ?? 0,
gid: lstats.gid ?? 0,
...(symlinkTarget !== undefined ? { symlinkTarget } : {}),
};
});
}
@ -169,12 +192,19 @@ export class SftpService {
try {
const resolved = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
if (modeToType(stats.mode) === 'dir') {
const kind = modeToType(stats.mode);
if (kind === 'dir') {
throw new SftpServiceError(
'IS_A_DIRECTORY',
'Cannot download a directory as a single file; use /archive instead.',
);
}
if (kind !== 'file') {
throw new SftpServiceError(
'UNSUPPORTED_FILE_TYPE',
`Refusing to download special/non-regular file: ${resolved}`,
);
}
const stream = sftp.createReadStream(resolved);
stream.once('close', cleanup);
stream.once('error', cleanup);
@ -199,10 +229,14 @@ export class SftpService {
): Promise<{ path: string; bytesWritten: number }> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
const dest = sftp.createWriteStream(resolved);
const tmpPath = path.posix.join(
path.posix.dirname(resolved),
`.gcoord-up-${crypto.randomBytes(6).toString('hex')}`,
);
const dest = sftp.createWriteStream(tmpPath);
let bytesWritten = 0;
return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => {
await new Promise<void>((resolve, reject) => {
let settled = false;
const fail = (err: Error) => {
if (settled) return;
@ -237,11 +271,41 @@ export class SftpService {
dest.on('close', () => {
if (settled) return;
settled = true;
resolve({ path: resolved, bytesWritten });
resolve();
});
source.pipe(dest);
}).catch(async (err) => {
await promisifySftpVoid((cb) => sftp.unlink(tmpPath, cb)).catch(() => undefined);
throw err;
});
try {
await this.renameSftpPath(sftp, tmpPath, resolved, true);
} catch (err) {
await promisifySftpVoid((cb) => sftp.unlink(tmpPath, cb)).catch(() => undefined);
throw err;
}
return { path: resolved, bytesWritten };
});
}
async touchFile(serverId: string, remotePath: string): Promise<string> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
let exists = false;
try {
await promisifySftp<Stats>((cb) => sftp.lstat(resolved, cb));
exists = true;
} catch {
exists = false;
}
if (exists) {
throw new SftpServiceError('ALREADY_EXISTS', `Path already exists: ${resolved}`);
}
await promisifySftpVoid((cb) => sftp.writeFile(resolved, Buffer.alloc(0), cb));
return resolved;
});
}
@ -253,16 +317,43 @@ export class SftpService {
});
}
async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> {
async rename(
serverId: string,
fromPath: string,
toPath: string,
overwrite = false,
): 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);
if (resolvedFrom === resolvedTo) {
return { from: resolvedFrom, to: resolvedTo };
}
if (!overwrite) {
let destExists = false;
try {
await promisifySftp<Stats>((cb) => sftp.lstat(resolvedTo, cb));
destExists = true;
} catch {
destExists = false;
}
if (destExists) {
throw new SftpServiceError(
'ALREADY_EXISTS',
`Destination "${resolvedTo}" already exists`,
);
}
}
await this.renameSftpPath(sftp, resolvedFrom, resolvedTo, overwrite);
return { from: resolvedFrom, to: resolvedTo };
});
}
async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> {
async chmod(
serverId: string,
remotePath: string,
modeInput: string | number,
): Promise<{ path: string; permissionsOctal: string }> {
const parsedMode =
typeof modeInput === 'number'
? modeInput
@ -283,6 +374,37 @@ export class SftpService {
});
}
async chown(
serverId: string,
remotePath: string,
uid: number,
gid: number,
sudo = false,
): Promise<{ path: string; uid: number; gid: number }> {
if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) {
throw new SftpServiceError('INVALID_MODE', 'uid and gid must be non-negative integers');
}
if (sudo) {
const resolved = await this.resolvePathNoStat(serverId, remotePath);
const res = await this.sshPool.exec(
serverId,
`chown ${uid}:${gid} -- ${posixSingleQuote(resolved)}`,
{ sudo: true },
);
if (res.exitCode !== 0) {
throw new Error(res.stderr.trim() || `chown failed for ${resolved}`);
}
return { path: resolved, uid, gid };
}
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
await promisifySftpVoid((cb) => sftp.chown(resolved, uid, gid, cb));
return { path: resolved, uid, gid };
});
}
async deletePath(
serverId: string,
remotePath: string,
@ -298,6 +420,51 @@ export class SftpService {
});
}
async bulkDelete(
serverId: string,
paths: string[],
recursive = false,
): Promise<{ deleted: string[]; failed: Array<{ path: string; error: string }> }> {
const deleted: string[] = [];
const failed: Array<{ path: string; error: string }> = [];
for (const p of paths) {
try {
const res = await this.deletePath(serverId, p, recursive);
deleted.push(res);
} catch (err) {
failed.push({
path: p,
error: err instanceof Error ? err.message : String(err),
});
}
}
return { deleted, failed };
}
async searchFiles(
serverId: string,
basePath: string,
query: string,
maxResults = 100,
): Promise<{ basePath: string; matches: string[] }> {
const cleanQuery = query.trim();
if (!cleanQuery || /[\x00\r\n]/.test(cleanQuery)) {
throw new SftpServiceError('INVALID_PATH', 'Invalid search query');
}
const resolvedBase = await this.resolvePathNoStat(serverId, basePath || '/');
const escapedPattern = cleanQuery.includes('*') || cleanQuery.includes('?')
? cleanQuery
: `*${cleanQuery}*`;
const cap = Math.max(1, Math.min(200, maxResults));
const cmd = `find ${posixSingleQuote(resolvedBase)} -maxdepth 5 -iname ${posixSingleQuote(escapedPattern)} 2>/dev/null | head -n ${cap}`;
const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000, maxBytes: 256 * 1024 });
const matches = res.stdout
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l.length > 0 && l !== resolvedBase);
return { basePath: resolvedBase, matches };
}
async readTextFile(
serverId: string,
remotePath: string,
@ -341,7 +508,10 @@ export class SftpService {
}
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');
throw new SftpServiceError(
'BINARY_FILE_NOT_EDITABLE',
'Binary file cannot be opened in inline editor',
);
}
return {
path: resolved,
@ -355,9 +525,16 @@ export class SftpService {
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') {
const kind = modeToType(stats.mode);
if (kind === 'dir') {
throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`);
}
if (kind !== 'file') {
throw new SftpServiceError(
'UNSUPPORTED_FILE_TYPE',
`Refusing to open special/non-regular file: ${resolved}`,
);
}
if ((stats.size ?? 0) > maxBytes) {
throw new SftpServiceError(
'FILE_TOO_LARGE',
@ -369,7 +546,10 @@ export class SftpService {
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');
throw new SftpServiceError(
'BINARY_FILE_NOT_EDITABLE',
'Binary file cannot be opened in inline editor',
);
}
return {
path: resolved,
@ -412,7 +592,7 @@ export class SftpService {
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}`,
`umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || { chmod --reference=${qDst} ${qTmp} 2>/dev/null; chown --reference=${qDst} ${qTmp} 2>/dev/null; true; }; } && mv -f -- ${qTmp} ${qDst}`,
{ sudo: true, stdin: newBuf },
);
if (res.exitCode !== 0) {
@ -438,7 +618,6 @@ export class SftpService {
}
} 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);
@ -450,7 +629,7 @@ export class SftpService {
() => undefined,
);
}
await this.renameSftpPath(sftp, tmp, resolved);
await this.renameSftpPath(sftp, tmp, resolved, true);
} catch (err) {
await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined);
throw err;
@ -498,8 +677,10 @@ export class SftpService {
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 osDetected = this.sshPool.getState(serverId)?.osDetected;
const oneFsFlag = osDetected !== 'bsd' && osDetected !== 'macos' ? '--one-file-system ' : '';
const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T2 -c' : 'gzip -c';
const cmd = `set -o pipefail 2>/dev/null || true; tar ${oneFsFlag}-C ${posixSingleQuote(parentDir)} -cf - -- ${posixSingleQuote(baseName)} | ${compressCmd}`;
const handle = await this.sshPool.execStream(serverId, cmd);
return {
@ -538,6 +719,9 @@ export class SftpService {
private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise<string> {
const trimmed = requestedPath?.trim() ?? '';
if (/[\x00\r\n]/.test(trimmed)) {
throw new SftpServiceError('INVALID_PATH', 'Control characters not permitted in path');
}
if (!trimmed || trimmed === '.' || trimmed === '~') {
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
return path.posix.normalize(home || '/');
@ -557,7 +741,12 @@ export class SftpService {
sftp: SFTPWrapper,
fromPath: string,
toPath: string,
overwrite = false,
): Promise<void> {
if (!overwrite) {
await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb));
return;
}
try {
await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb));
} catch {

View file

@ -567,7 +567,8 @@ export class MockSshServer {
rawCommand: string,
): { stdout: Buffer; stderr?: string; exitCode: number } | null {
// Support streamed SFTP folder archive command in integration tests
const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec(
const tarMatch =
/tar (?:--one-file-system )?-C ('(?:[^']|'\\'')*'|\S+) -cf - (?:-- )?('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec(
rawCommand,
);
if (tarMatch) {