feat(ssh): add PTYManager with circular scrollback, SSHPool stream/sftp helpers, and WS hooks

This commit is contained in:
tyuXX 2026-11-26 21:40:17 +00:00
parent 21176265aa
commit eec1bfe66d
7 changed files with 662 additions and 115 deletions

View file

@ -1,5 +1,10 @@
import type { Duplex } from 'node:stream';
import ssh2, { type Client, type ConnectConfig } from 'ssh2';
import ssh2, {
type Client,
type ClientChannel,
type ConnectConfig,
type SFTPWrapper,
} from 'ssh2';
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
import type {
ServerConnectionStatus,
@ -26,6 +31,19 @@ export interface ExecOptions {
maxBytes?: number;
}
export interface ExecStreamOptions {
sudo?: boolean;
env?: Record<string, string>;
pty?: { cols: number; rows: number; term?: string };
stdin?: Buffer | string;
}
export interface ExecStreamHandle {
channel: ClientChannel;
done: Promise<{ exitCode: number | null; signal?: string }>;
abort: () => void;
}
interface PooledConnection {
serverId: string;
client: Client;
@ -135,17 +153,11 @@ export class SSHPool {
return connectPromise;
}
async exec(
serverId: string,
private prepareCommand(
server: ServerConfig,
command: string,
opts: ExecOptions = {},
): Promise<ExecResult> {
const client = await this.acquireClient(serverId);
const server = this.configManager.getServer(serverId);
if (!server) {
throw new Error(`Unknown server "${serverId}"`);
}
opts: { sudo?: boolean; env?: Record<string, string>; stdin?: Buffer | string },
): { finalCommand: string; stdinBuf?: Buffer } {
const envPrefix = buildEnvPrefix(opts.env);
let finalCommand = `${envPrefix}${command}`;
let stdinBuf: Buffer | undefined =
@ -172,6 +184,127 @@ export class SSHPool {
stdinBuf = prepared.stdin;
}
return { finalCommand, stdinBuf };
}
async openShell(
serverId: string,
opts: { cols: number; rows: number; term?: string } = { cols: 80, rows: 24 },
): Promise<ClientChannel> {
const client = await this.acquireClient(serverId);
return new Promise<ClientChannel>((resolve, reject) => {
client.shell(
{
term: opts.term ?? 'xterm-256color',
cols: opts.cols,
rows: opts.rows,
},
(err, channel) => {
if (err) reject(err);
else resolve(channel);
},
);
});
}
async openSftp(serverId: string): Promise<SFTPWrapper> {
const client = await this.acquireClient(serverId);
return new Promise<SFTPWrapper>((resolve, reject) => {
client.sftp((err, sftp) => {
if (err) reject(err);
else resolve(sftp);
});
});
}
async execStream(
serverId: string,
command: string,
opts: ExecStreamOptions = {},
): Promise<ExecStreamHandle> {
const client = await this.acquireClient(serverId);
const server = this.configManager.getServer(serverId);
if (!server) {
throw new Error(`Unknown server "${serverId}"`);
}
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
return new Promise<ExecStreamHandle>((resolve, reject) => {
const execOpts = opts.pty
? {
pty: {
term: opts.pty.term ?? 'xterm-256color',
cols: opts.pty.cols,
rows: opts.pty.rows,
},
}
: {};
client.exec(finalCommand, execOpts, (err, channel) => {
if (err) {
if (stdinBuf) stdinBuf.fill(0);
reject(err);
return;
}
let exitCode: number | null = null;
let signal: string | undefined;
const done = new Promise<{ exitCode: number | null; signal?: string }>(
(resolveDone, rejectDone) => {
channel.on('exit', (code: number | null, sig?: string) => {
exitCode = typeof code === 'number' ? code : null;
signal = sig;
});
channel.on('close', () => {
resolveDone({ exitCode, signal });
});
channel.on('error', (streamErr: Error) => {
rejectDone(streamErr);
});
},
);
if (stdinBuf && stdinBuf.length > 0) {
channel.stdin.write(stdinBuf);
stdinBuf.fill(0);
}
if (!opts.pty) {
channel.stdin.end();
}
const abort = () => {
try {
channel.signal?.('TERM');
} catch {
// Ignore signal errors on unsupported servers
}
try {
channel.close();
channel.destroy();
} catch {
// Ignore close errors
}
};
resolve({ channel, done, abort });
});
});
}
async exec(
serverId: string,
command: string,
opts: ExecOptions = {},
): Promise<ExecResult> {
const client = await this.acquireClient(serverId);
const server = this.configManager.getServer(serverId);
if (!server) {
throw new Error(`Unknown server "${serverId}"`);
}
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
const started = Date.now();