feat(ssh): add PTYManager with circular scrollback, SSHPool stream/sftp helpers, and WS hooks
This commit is contained in:
parent
21176265aa
commit
eec1bfe66d
7 changed files with 662 additions and 115 deletions
331
src/server/ssh/pty-manager.ts
Normal file
331
src/server/ssh/pty-manager.ts
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
import crypto from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
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 { SSHPool } from './ssh-pool.js';
|
||||
import { posixSingleQuote } from './sudo.js';
|
||||
|
||||
export interface PtySessionInfo {
|
||||
sessionId: string;
|
||||
serverId: string;
|
||||
title: string;
|
||||
cwd?: string;
|
||||
command?: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
createdAt: number;
|
||||
lastActivityAt: number;
|
||||
exited: boolean;
|
||||
exitCode: number | null;
|
||||
scrollbackBytes: number;
|
||||
}
|
||||
|
||||
export interface OpenPtyParams {
|
||||
serverId: string;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
cwd?: string;
|
||||
command?: string;
|
||||
env?: Record<string, string>;
|
||||
sudo?: boolean;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
interface ScrollChunk {
|
||||
text: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
interface InternalPtySession {
|
||||
info: PtySessionInfo;
|
||||
channel: ClientChannel;
|
||||
chunks: ScrollChunk[];
|
||||
stdoutDecoder: StringDecoder;
|
||||
stderrDecoder: StringDecoder;
|
||||
}
|
||||
|
||||
const MAX_RETAINED_EXITED_SESSIONS = 20;
|
||||
|
||||
export function formatRemoteCd(cwd: string): string {
|
||||
const trimmed = cwd.trim();
|
||||
if (trimmed === '~' || trimmed === '~/') {
|
||||
return 'cd -- "$HOME"';
|
||||
}
|
||||
if (trimmed.startsWith('~/')) {
|
||||
return `cd -- "$HOME/"${posixSingleQuote(trimmed.slice(2))}`;
|
||||
}
|
||||
return `cd -- ${posixSingleQuote(trimmed)}`;
|
||||
}
|
||||
|
||||
export function stripAnsiSequences(input: string): string {
|
||||
return input
|
||||
.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '')
|
||||
.replace(/\r\n/g, '\n');
|
||||
}
|
||||
|
||||
function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; bytes: number } {
|
||||
const buf = Buffer.from(text, 'utf8');
|
||||
if (buf.length <= maxBytes) {
|
||||
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++;
|
||||
}
|
||||
const sliced = buf.subarray(start);
|
||||
return { text: sliced.toString('utf8'), bytes: sliced.length };
|
||||
}
|
||||
|
||||
export class PTYManager {
|
||||
private readonly sessions = new Map<string, InternalPtySession>();
|
||||
private readonly reaperTimer: NodeJS.Timeout;
|
||||
|
||||
constructor(
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly wsHub: WsHub,
|
||||
) {
|
||||
this.reaperTimer = setInterval(() => {
|
||||
this.reapIdleSessions();
|
||||
}, 30_000);
|
||||
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;
|
||||
if (params.command) {
|
||||
const cmd = trimmedCwd
|
||||
? `${formatRemoteCd(trimmedCwd)} && (${params.command})`
|
||||
: params.command;
|
||||
const stream = await this.sshPool.execStream(params.serverId, cmd, {
|
||||
env: params.env,
|
||||
sudo: params.sudo,
|
||||
pty: { cols, rows, term: 'xterm-256color' },
|
||||
});
|
||||
channel = stream.channel;
|
||||
} else {
|
||||
channel = await this.sshPool.openShell(params.serverId, {
|
||||
cols,
|
||||
rows,
|
||||
term: 'xterm-256color',
|
||||
});
|
||||
if (trimmedCwd && trimmedCwd !== '~') {
|
||||
channel.write(`${formatRemoteCd(trimmedCwd)}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
channel,
|
||||
chunks: [],
|
||||
stdoutDecoder: new StringDecoder('utf8'),
|
||||
stderrDecoder: new StringDecoder('utf8'),
|
||||
};
|
||||
this.sessions.set(sessionId, internal);
|
||||
|
||||
channel.on('data', (chunk: Buffer) => {
|
||||
const text = internal.stdoutDecoder.write(chunk);
|
||||
if (text) this.appendOutput(internal, text);
|
||||
});
|
||||
|
||||
channel.stderr?.on('data', (chunk: Buffer) => {
|
||||
const text = internal.stderrDecoder.write(chunk);
|
||||
if (text) this.appendOutput(internal, text);
|
||||
});
|
||||
|
||||
const finalizeExit = (code: number | null) => {
|
||||
if (internal.info.exited) return;
|
||||
const tailOut = internal.stdoutDecoder.end();
|
||||
if (tailOut) this.appendOutput(internal, tailOut);
|
||||
const tailErr = internal.stderrDecoder.end();
|
||||
if (tailErr) this.appendOutput(internal, tailErr);
|
||||
|
||||
internal.info.exited = true;
|
||||
internal.info.exitCode = code;
|
||||
internal.info.lastActivityAt = Date.now();
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.pty(sessionId), {
|
||||
type: 'pty:exit',
|
||||
sessionId,
|
||||
exitCode: code,
|
||||
});
|
||||
this.pruneExcessExited();
|
||||
};
|
||||
|
||||
channel.on('exit', (code: number | null) => {
|
||||
finalizeExit(typeof code === 'number' ? code : null);
|
||||
});
|
||||
channel.on('close', () => {
|
||||
finalizeExit(internal.info.exitCode);
|
||||
});
|
||||
|
||||
return { ...internal.info };
|
||||
}
|
||||
|
||||
listSessions(): PtySessionInfo[] {
|
||||
return [...this.sessions.values()]
|
||||
.map((s) => ({ ...s.info }))
|
||||
.sort((a, b) => b.createdAt - a.createdAt);
|
||||
}
|
||||
|
||||
getSession(sessionId: string): PtySessionInfo | undefined {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
return entry ? { ...entry.info } : undefined;
|
||||
}
|
||||
|
||||
writeInput(sessionId: string, data: string): boolean {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
if (!entry || entry.info.exited) return false;
|
||||
entry.info.lastActivityAt = Date.now();
|
||||
return entry.channel.write(data);
|
||||
}
|
||||
|
||||
resize(sessionId: string, cols: number, rows: number): boolean {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
if (!entry || entry.info.exited) return false;
|
||||
const clampedCols = Math.max(10, Math.min(500, Math.floor(cols)));
|
||||
const clampedRows = Math.max(4, Math.min(200, Math.floor(rows)));
|
||||
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;
|
||||
}
|
||||
|
||||
getScrollback(sessionId: string): string | null {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
if (!entry) return null;
|
||||
return entry.chunks.map((c) => c.text).join('');
|
||||
}
|
||||
|
||||
exportScrollback(
|
||||
sessionId: string,
|
||||
format: 'plain' | 'ansi' = 'plain',
|
||||
): { filename: string; content: string } | null {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
if (!entry) return null;
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
closeSession(sessionId: string): boolean {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
if (!entry) return false;
|
||||
this.sessions.delete(sessionId);
|
||||
this.destroyChannel(entry);
|
||||
return true;
|
||||
}
|
||||
|
||||
closeServerSessions(serverId: string): void {
|
||||
for (const [id, entry] of this.sessions.entries()) {
|
||||
if (entry.info.serverId === serverId) {
|
||||
this.sessions.delete(id);
|
||||
this.destroyChannel(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
closeAll(wipeScrollback = true): void {
|
||||
for (const [id, entry] of this.sessions.entries()) {
|
||||
this.sessions.delete(id);
|
||||
if (wipeScrollback) {
|
||||
entry.chunks = [];
|
||||
entry.info.scrollbackBytes = 0;
|
||||
}
|
||||
this.destroyChannel(entry);
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.reaperTimer);
|
||||
this.closeAll(true);
|
||||
}
|
||||
|
||||
private appendOutput(entry: InternalPtySession, text: string): void {
|
||||
const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes);
|
||||
const rawBytes = Buffer.byteLength(text, 'utf8');
|
||||
|
||||
if (rawBytes >= maxBytes) {
|
||||
const trimmed = sliceTrailingUtf8(text, maxBytes);
|
||||
entry.chunks = [{ text: trimmed.text, bytes: trimmed.bytes }];
|
||||
entry.info.scrollbackBytes = trimmed.bytes;
|
||||
} else {
|
||||
entry.chunks.push({ text, bytes: rawBytes });
|
||||
entry.info.scrollbackBytes += rawBytes;
|
||||
while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) {
|
||||
const dropped = entry.chunks.shift()!;
|
||||
entry.info.scrollbackBytes -= dropped.bytes;
|
||||
}
|
||||
}
|
||||
|
||||
entry.info.lastActivityAt = Date.now();
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), {
|
||||
type: 'pty:output',
|
||||
sessionId: entry.info.sessionId,
|
||||
data: text,
|
||||
});
|
||||
}
|
||||
|
||||
private destroyChannel(entry: InternalPtySession): void {
|
||||
try {
|
||||
entry.channel.close();
|
||||
entry.channel.destroy();
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
}
|
||||
|
||||
private reapIdleSessions(): void {
|
||||
const ttlMs = Math.max(60, this.configManager.getSettings().ptyIdleTtlSec) * 1000;
|
||||
const cutoff = Date.now() - ttlMs;
|
||||
for (const [id, entry] of this.sessions.entries()) {
|
||||
if (entry.info.lastActivityAt < cutoff) {
|
||||
this.sessions.delete(id);
|
||||
this.destroyChannel(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private pruneExcessExited(): void {
|
||||
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) {
|
||||
const oldest = exited.shift()!;
|
||||
this.sessions.delete(oldest.info.sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue