feat: v0.3.0 版本 - SSH终端、SFTP、端口转发功能实现
核心功能: - SSH终端: 密码/密钥认证、XTerm.js终端、多主题配色、IP高亮 - SFTP管理: 双栏文件管理、上传下载、传输队列 - 端口转发: 本地/远程转发、SOCKS5动态代理、规则管理 架构改进: - 拆分大型组件 (SFTPView/TabBar/Sidebar) - 添加统一日志和错误处理 - 修复React严格模式下的终端黑屏问题 UI更新: - 新增端口转发视图 - 更新UI预览文档 - 左侧栏右键菜单支持SFTP快捷打开
This commit is contained in:
1 parent
cf1c054381
commit
484d850abd
105 files changed
+25330
-64
No files matched your search
@@ -0,0 +1,95 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm'
|
||||
const KEY_LENGTH = 32
|
||||
const IV_LENGTH = 16
|
||||
const TAG_LENGTH = 16
|
||||
const SALT_LENGTH = 32
|
||||
const ITERATIONS = 100000
|
||||
|
||||
// 从密码派生密钥
|
||||
function deriveKey(password: string, salt: Buffer): Buffer {
|
||||
return crypto.pbkdf2Sync(password, salt, ITERATIONS, KEY_LENGTH, 'sha256')
|
||||
}
|
||||
|
||||
// 生成随机密钥(用于主密钥)
|
||||
export function generateMasterKey(): string {
|
||||
return crypto.randomBytes(KEY_LENGTH).toString('hex')
|
||||
}
|
||||
|
||||
// 加密数据
|
||||
export function encrypt(plaintext: string, password: string): string {
|
||||
const salt = crypto.randomBytes(SALT_LENGTH)
|
||||
const key = deriveKey(password, salt)
|
||||
const iv = crypto.randomBytes(IV_LENGTH)
|
||||
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
|
||||
// 格式: salt:iv:tag:encrypted (全部 hex)
|
||||
return [
|
||||
salt.toString('hex'),
|
||||
iv.toString('hex'),
|
||||
tag.toString('hex'),
|
||||
encrypted.toString('hex'),
|
||||
].join(':')
|
||||
}
|
||||
|
||||
// 解密数据
|
||||
export function decrypt(ciphertext: string, password: string): string {
|
||||
try {
|
||||
const [saltHex, ivHex, tagHex, encryptedHex] = ciphertext.split(':')
|
||||
|
||||
if (!saltHex || !ivHex || !tagHex || !encryptedHex) {
|
||||
throw new Error('Invalid ciphertext format')
|
||||
}
|
||||
|
||||
const salt = Buffer.from(saltHex, 'hex')
|
||||
const iv = Buffer.from(ivHex, 'hex')
|
||||
const tag = Buffer.from(tagHex, 'hex')
|
||||
const encrypted = Buffer.from(encryptedHex, 'hex')
|
||||
|
||||
const key = deriveKey(password, salt)
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
|
||||
decipher.setAuthTag(tag)
|
||||
|
||||
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
|
||||
return decrypted.toString('utf8')
|
||||
} catch (error) {
|
||||
throw new Error('Decryption failed: ' + (error as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
// 简单加密(不带 salt,用于可逆加密)
|
||||
export function simpleEncrypt(plaintext: string, key: string): string {
|
||||
const iv = crypto.randomBytes(IV_LENGTH)
|
||||
const keyBuffer = Buffer.from(key, 'hex').slice(0, KEY_LENGTH)
|
||||
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, keyBuffer, iv)
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
|
||||
return iv.toString('hex') + ':' + tag.toString('hex') + ':' + encrypted.toString('hex')
|
||||
}
|
||||
|
||||
// 简单解密
|
||||
export function simpleDecrypt(ciphertext: string, key: string): string {
|
||||
try {
|
||||
const [ivHex, tagHex, encryptedHex] = ciphertext.split(':')
|
||||
|
||||
const iv = Buffer.from(ivHex, 'hex')
|
||||
const tag = Buffer.from(tagHex, 'hex')
|
||||
const encrypted = Buffer.from(encryptedHex, 'hex')
|
||||
const keyBuffer = Buffer.from(key, 'hex').slice(0, KEY_LENGTH)
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, keyBuffer, iv)
|
||||
decipher.setAuthTag(tag)
|
||||
|
||||
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
|
||||
return decrypted.toString('utf8')
|
||||
} catch (error) {
|
||||
throw new Error('Decryption failed: ' + (error as Error).message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import Database from 'better-sqlite3'
|
||||
import path from 'path'
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs'
|
||||
import { simpleEncrypt, simpleDecrypt } from './crypto'
|
||||
import { keyService } from './key-service'
|
||||
import { createLogger } from '../utils/logger'
|
||||
|
||||
const logger = createLogger('DatabaseService')
|
||||
|
||||
export class DatabaseService {
|
||||
private db: Database.Database | null = null
|
||||
private dbPath: string
|
||||
private masterKey: string | null = null
|
||||
|
||||
constructor() {
|
||||
// 使用应用数据目录存储数据库
|
||||
const userDataPath = app.getPath('userData')
|
||||
this.dbPath = path.join(userDataPath, 'opsxshell.db')
|
||||
}
|
||||
|
||||
initialize(): void {
|
||||
try {
|
||||
// 确保目录存在
|
||||
const dbDir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true })
|
||||
}
|
||||
|
||||
// 获取主密钥
|
||||
this.masterKey = keyService.getMasterKey()
|
||||
|
||||
this.db = new Database(this.dbPath)
|
||||
this.createTables()
|
||||
logger.info('Database initialized at:', this.dbPath)
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize database:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private createTables(): void {
|
||||
if (!this.db) return
|
||||
|
||||
// 会话表
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER DEFAULT 22,
|
||||
username TEXT NOT NULL,
|
||||
auth_type TEXT CHECK(auth_type IN ('password', 'key', 'agent')),
|
||||
password TEXT,
|
||||
private_key_path TEXT,
|
||||
passphrase_encrypted TEXT,
|
||||
group_name TEXT DEFAULT 'default',
|
||||
tags TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
|
||||
// 迁移:如果 password 列不存在,添加它
|
||||
try {
|
||||
this.db.exec(`ALTER TABLE sessions ADD COLUMN password TEXT`)
|
||||
} catch (e) {
|
||||
// 列可能已存在,忽略错误
|
||||
}
|
||||
|
||||
// 连接历史表
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS connection_history (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT REFERENCES sessions(id),
|
||||
connected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
disconnected_at DATETIME,
|
||||
duration INTEGER,
|
||||
status TEXT
|
||||
)
|
||||
`)
|
||||
|
||||
// 设置表
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
|
||||
// 密钥表
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT CHECK(type IN ('rsa', 'ed25519', 'ecdsa')),
|
||||
private_key_encrypted TEXT NOT NULL,
|
||||
public_key TEXT,
|
||||
passphrase_encrypted TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
|
||||
// 端口转发规则表
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS port_forwards (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT REFERENCES sessions(id),
|
||||
type TEXT CHECK(type IN ('local', 'remote', 'dynamic')),
|
||||
local_host TEXT,
|
||||
local_port INTEGER,
|
||||
remote_host TEXT,
|
||||
remote_port INTEGER,
|
||||
is_active BOOLEAN DEFAULT FALSE
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
// 加密字段
|
||||
private encryptField(value: string | null | undefined): string | null {
|
||||
if (!value) return null
|
||||
if (!this.masterKey) throw new Error('Master key not initialized')
|
||||
return simpleEncrypt(value, this.masterKey)
|
||||
}
|
||||
|
||||
// 解密字段
|
||||
private decryptField(value: string | null | undefined): string | null {
|
||||
if (!value) return null
|
||||
if (!this.masterKey) {
|
||||
logger.error('Decrypt failed: Master key not initialized')
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const decrypted = simpleDecrypt(value, this.masterKey)
|
||||
logger.info('Decrypted field length:', decrypted?.length || 0)
|
||||
return decrypted
|
||||
} catch (error) {
|
||||
logger.error('Decrypt failed:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 会话 CRUD 操作
|
||||
createSession(session: any): any {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
logger.info('Creating session with password:', session.password ? `len=${session.password.length}` : 'null/undefined')
|
||||
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO sessions (id, name, host, port, username, auth_type, password, private_key_path, passphrase_encrypted, group_name, tags)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const id = `session-${Date.now()}`
|
||||
const encryptedPassword = this.encryptField(session.password)
|
||||
logger.info('Encrypted password:', encryptedPassword ? `len=${encryptedPassword.length}` : 'null')
|
||||
|
||||
stmt.run(
|
||||
id,
|
||||
session.name,
|
||||
session.host,
|
||||
session.port || 22,
|
||||
session.username,
|
||||
session.authType,
|
||||
encryptedPassword,
|
||||
session.privateKey || null, // 私钥路径不加密
|
||||
this.encryptField(session.passphrase),
|
||||
session.group || 'default',
|
||||
session.tags ? JSON.stringify(session.tags) : null
|
||||
)
|
||||
|
||||
return this.getSessionById(id)
|
||||
}
|
||||
|
||||
getAllSessions(): any[] {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const stmt = this.db.prepare('SELECT * FROM sessions ORDER BY created_at DESC')
|
||||
const sessions = stmt.all()
|
||||
|
||||
return sessions.map((s: any) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
host: s.host,
|
||||
port: s.port,
|
||||
username: s.username,
|
||||
authType: s.auth_type,
|
||||
password: this.decryptField(s.password),
|
||||
privateKey: s.private_key_path,
|
||||
passphrase: this.decryptField(s.passphrase_encrypted),
|
||||
group: s.group_name,
|
||||
tags: s.tags ? JSON.parse(s.tags) : [],
|
||||
}))
|
||||
}
|
||||
|
||||
getSessionById(id: string): any {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const stmt = this.db.prepare('SELECT * FROM sessions WHERE id = ?')
|
||||
const session = stmt.get(id) as any
|
||||
|
||||
if (session) {
|
||||
return {
|
||||
id: session.id,
|
||||
name: session.name,
|
||||
host: session.host,
|
||||
port: session.port,
|
||||
username: session.username,
|
||||
authType: session.auth_type,
|
||||
password: this.decryptField(session.password),
|
||||
privateKey: session.private_key_path,
|
||||
passphrase: this.decryptField(session.passphrase_encrypted),
|
||||
group: session.group_name,
|
||||
tags: session.tags ? JSON.parse(session.tags) : [],
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
updateSession(id: string, updates: any): any {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const fields: string[] = []
|
||||
const values: any[] = []
|
||||
|
||||
if (updates.name !== undefined) {
|
||||
fields.push('name = ?')
|
||||
values.push(updates.name)
|
||||
}
|
||||
if (updates.host !== undefined) {
|
||||
fields.push('host = ?')
|
||||
values.push(updates.host)
|
||||
}
|
||||
if (updates.port !== undefined) {
|
||||
fields.push('port = ?')
|
||||
values.push(updates.port)
|
||||
}
|
||||
if (updates.username !== undefined) {
|
||||
fields.push('username = ?')
|
||||
values.push(updates.username)
|
||||
}
|
||||
if (updates.authType !== undefined) {
|
||||
fields.push('auth_type = ?')
|
||||
values.push(updates.authType)
|
||||
}
|
||||
if (updates.password !== undefined) {
|
||||
fields.push('password = ?')
|
||||
values.push(this.encryptField(updates.password))
|
||||
}
|
||||
if (updates.passphrase !== undefined) {
|
||||
fields.push('passphrase_encrypted = ?')
|
||||
values.push(this.encryptField(updates.passphrase))
|
||||
}
|
||||
if (updates.group !== undefined) {
|
||||
fields.push('group_name = ?')
|
||||
values.push(updates.group)
|
||||
}
|
||||
if (updates.tags !== undefined) {
|
||||
fields.push('tags = ?')
|
||||
values.push(JSON.stringify(updates.tags))
|
||||
}
|
||||
|
||||
fields.push('updated_at = CURRENT_TIMESTAMP')
|
||||
values.push(id)
|
||||
|
||||
const stmt = this.db.prepare(`
|
||||
UPDATE sessions SET ${fields.join(', ')} WHERE id = ?
|
||||
`)
|
||||
stmt.run(...values)
|
||||
|
||||
return this.getSessionById(id)
|
||||
}
|
||||
|
||||
deleteSession(id: string): void {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const stmt = this.db.prepare('DELETE FROM sessions WHERE id = ?')
|
||||
stmt.run(id)
|
||||
}
|
||||
|
||||
// 设置操作
|
||||
getSetting(key: string): any {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const stmt = this.db.prepare('SELECT value FROM settings WHERE key = ?')
|
||||
const row: any = stmt.get(key)
|
||||
return row ? JSON.parse(row.value) : null
|
||||
}
|
||||
|
||||
setSetting(key: string, value: any): void {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO settings (key, value, updated_at)
|
||||
VALUES (?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
`)
|
||||
stmt.run(key, JSON.stringify(value))
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.db) {
|
||||
this.db.close()
|
||||
this.db = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { app } from 'electron'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import crypto from 'crypto'
|
||||
import { createLogger } from '../utils/logger'
|
||||
|
||||
const logger = createLogger('KeyService')
|
||||
|
||||
const KEY_FILE = 'encryption.key'
|
||||
|
||||
export class KeyService {
|
||||
private key: string | null = null
|
||||
|
||||
// 获取或创建主密钥
|
||||
getMasterKey(): string {
|
||||
if (this.key) return this.key
|
||||
|
||||
const keyPath = path.join(app.getPath('userData'), KEY_FILE)
|
||||
|
||||
// 尝试读取现有密钥
|
||||
if (fs.existsSync(keyPath)) {
|
||||
try {
|
||||
this.key = fs.readFileSync(keyPath, 'utf8').trim()
|
||||
return this.key
|
||||
} catch (error) {
|
||||
logger.error('Failed to read master key:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 生成新密钥
|
||||
this.key = crypto.randomBytes(32).toString('hex')
|
||||
fs.writeFileSync(keyPath, this.key, { mode: 0o600 })
|
||||
return this.key
|
||||
}
|
||||
|
||||
// 清除密钥(登出时)
|
||||
clearKey(): void {
|
||||
this.key = null
|
||||
}
|
||||
}
|
||||
|
||||
// 全局单例
|
||||
export const keyService = new KeyService()
|
||||
@@ -0,0 +1,685 @@
|
||||
import { Client, ClientChannel } from 'ssh2'
|
||||
import { SFTPWrapper } from 'ssh2'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { createLogger } from '../utils/logger'
|
||||
import * as net from 'net'
|
||||
|
||||
const logger = createLogger('SSHService')
|
||||
|
||||
// ===== 彩色调试日志 =====
|
||||
const DEBUG = true
|
||||
function debug(...args: any[]) {
|
||||
if (DEBUG) console.log('[SSHService]', ...args)
|
||||
}
|
||||
function logHeader(msg: string) {
|
||||
console.log(`%c${msg}`, 'background: #e74c3c; color: #fff; padding: 4px 8px; border-radius: 4px; font-weight: bold;')
|
||||
}
|
||||
function logInfo(label: string, value: any) {
|
||||
console.log(`%c${label}:%c ${value}`, 'background: #2c3e50; color: #fff; padding: 2px 6px; border-radius: 3px;', 'color: #3498db; font-weight: bold;')
|
||||
}
|
||||
function logSuccess(msg: string) {
|
||||
console.log(`%c✓ ${msg}`, 'color: #27ae60; font-weight: bold;')
|
||||
}
|
||||
function logError(msg: string) {
|
||||
console.log(`%c✗ ${msg}`, 'color: #e74c3c; font-weight: bold;')
|
||||
}
|
||||
function logWarning(msg: string) {
|
||||
console.log(`%c⚠ ${msg}`, 'color: #f39c12; font-weight: bold;')
|
||||
}
|
||||
|
||||
export interface SSHConfig {
|
||||
host: string
|
||||
port?: number
|
||||
username: string
|
||||
password?: string
|
||||
privateKey?: string
|
||||
passphrase?: string
|
||||
agent?: string
|
||||
readyTimeout?: number
|
||||
keepaliveInterval?: number
|
||||
}
|
||||
|
||||
export interface Connection {
|
||||
id: string
|
||||
client: Client
|
||||
config: SSHConfig
|
||||
status: 'connecting' | 'connected' | 'disconnected' | 'error'
|
||||
}
|
||||
|
||||
export interface ShellSession {
|
||||
id: string
|
||||
connectionId: string
|
||||
channel: ClientChannel
|
||||
}
|
||||
|
||||
export interface SFTPSession {
|
||||
id: string
|
||||
connectionId: string
|
||||
sftp: SFTPWrapper
|
||||
}
|
||||
|
||||
export class SSHService {
|
||||
private connections: Map<string, Connection> = new Map()
|
||||
private shells: Map<string, ShellSession> = new Map()
|
||||
private sftps: Map<string, SFTPSession> = new Map()
|
||||
|
||||
async connect(config: SSHConfig): Promise<Connection> {
|
||||
console.log('=== SSHService connect ===')
|
||||
console.log(' host:', config.host)
|
||||
console.log(' port:', config.port || 22)
|
||||
console.log(' username:', config.username)
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = new Client()
|
||||
const connectionId = uuidv4()
|
||||
debug('>>> Generated connectionId:', connectionId)
|
||||
|
||||
const connection: Connection = {
|
||||
id: connectionId,
|
||||
client,
|
||||
config,
|
||||
status: 'connecting'
|
||||
}
|
||||
|
||||
this.connections.set(connectionId, connection)
|
||||
debug('>>> Connection stored, total connections:', this.connections.size)
|
||||
|
||||
client.on('ready', () => {
|
||||
connection.status = 'connected'
|
||||
logger.info(`SSH connection ${connectionId} established`)
|
||||
debug('>>> SSH client ready, connectionId:', connectionId)
|
||||
resolve(connection)
|
||||
})
|
||||
|
||||
client.on('error', (err) => {
|
||||
connection.status = 'error'
|
||||
logger.error(`SSH connection ${connectionId} error:`, err)
|
||||
debug('>>> SSH client ERROR:', err.message)
|
||||
reject(err)
|
||||
})
|
||||
|
||||
client.on('close', () => {
|
||||
connection.status = 'disconnected'
|
||||
logger.info(`SSH connection ${connectionId} closed`)
|
||||
debug('>>> SSH client closed, connectionId:', connectionId)
|
||||
this.connections.delete(connectionId)
|
||||
})
|
||||
|
||||
debug('>>> Starting SSH client.connect...')
|
||||
client.connect({
|
||||
host: config.host,
|
||||
port: config.port || 22,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
privateKey: config.privateKey,
|
||||
passphrase: config.passphrase,
|
||||
agent: config.agent,
|
||||
readyTimeout: config.readyTimeout || 20000,
|
||||
keepaliveInterval: config.keepaliveInterval || 60000,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async disconnect(connectionId: string): Promise<void> {
|
||||
const connection = this.connections.get(connectionId)
|
||||
if (connection) {
|
||||
connection.client.end()
|
||||
this.connections.delete(connectionId)
|
||||
|
||||
// Clean up associated shells
|
||||
for (const [shellId, shell] of this.shells.entries()) {
|
||||
if (shell.connectionId === connectionId) {
|
||||
shell.channel.close()
|
||||
this.shells.delete(shellId)
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up associated SFTP sessions
|
||||
for (const [sftpId, sftp] of this.sftps.entries()) {
|
||||
if (sftp.connectionId === connectionId) {
|
||||
this.sftps.delete(sftpId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
disconnectAll(): void {
|
||||
for (const connectionId of this.connections.keys()) {
|
||||
this.disconnect(connectionId)
|
||||
}
|
||||
}
|
||||
|
||||
async exec(connectionId: string, command: string): Promise<string> {
|
||||
const connection = this.connections.get(connectionId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
throw new Error('Connection not established')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
|
||||
connection.client.exec(command, (err, stream) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
|
||||
stream.on('close', (code: number) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Command failed with code ${code}: ${stderr}`))
|
||||
} else {
|
||||
resolve(stdout)
|
||||
}
|
||||
})
|
||||
|
||||
stream.on('data', (data: Buffer) => {
|
||||
stdout += data.toString()
|
||||
})
|
||||
|
||||
stream.stderr.on('data', (data: Buffer) => {
|
||||
stderr += data.toString()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async createShell(
|
||||
connectionId: string,
|
||||
options: { cols?: number; rows?: number; term?: string } = {},
|
||||
onData?: (shellId: string, data: Buffer) => void,
|
||||
preferredShellId?: string
|
||||
): Promise<ShellSession> {
|
||||
console.log('=== SSHService createShell ===')
|
||||
console.log(' connectionId:', connectionId)
|
||||
console.log(' options:', options)
|
||||
console.log(' preferredShellId:', preferredShellId)
|
||||
|
||||
const connection = this.connections.get(connectionId)
|
||||
console.log(' connection found:', !!connection)
|
||||
console.log(' connection status:', connection?.status)
|
||||
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
throw new Error('Connection not established')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
debug('>>> Calling client.shell...')
|
||||
connection.client.shell({
|
||||
cols: options.cols || 80,
|
||||
rows: options.rows || 24,
|
||||
term: options.term || 'xterm-256color'
|
||||
}, (err, channel) => {
|
||||
if (err) {
|
||||
debug('>>> client.shell ERROR:', err.message)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
|
||||
debug('>>> client.shell success, channel created')
|
||||
|
||||
// 使用前端提供的 shellId 或生成新的
|
||||
const shellId = preferredShellId || uuidv4()
|
||||
debug('>>> Using shellId:', shellId)
|
||||
|
||||
const shell: ShellSession = {
|
||||
id: shellId,
|
||||
connectionId,
|
||||
channel
|
||||
}
|
||||
|
||||
// Store shell BEFORE setting up callbacks
|
||||
this.shells.set(shellId, shell)
|
||||
debug('>>> Shell stored, total shells:', this.shells.size)
|
||||
|
||||
// Set up data callback AFTER shell is stored
|
||||
if (onData) {
|
||||
debug('>>> Setting up channel.on(data) handler')
|
||||
channel.on('data', (data: Buffer) => {
|
||||
// Log first few chunks for debugging
|
||||
const text = data.toString('utf-8')
|
||||
console.log('=== SSHService channel.on(data) ===')
|
||||
console.log(' shellId:', shellId)
|
||||
console.log(' data length:', data.length)
|
||||
console.log(' data preview:', text.substring(0, 100).replace(/\n/g, '\\n'))
|
||||
|
||||
if (text.includes('Last login') || text.includes('Welcome')) {
|
||||
logger.info('[SSHService] Shell data (first 200 chars):', text.substring(0, 200))
|
||||
}
|
||||
debug('>>> Calling onData callback...')
|
||||
onData(shellId, data)
|
||||
debug('>>> onData callback returned')
|
||||
})
|
||||
} else {
|
||||
debug('>>> WARNING: onData callback is undefined!')
|
||||
}
|
||||
|
||||
channel.on('close', () => {
|
||||
debug('>>> Channel closed, shellId:', shellId)
|
||||
this.shells.delete(shellId)
|
||||
})
|
||||
|
||||
debug('>>> Resolving shell:', shellId)
|
||||
resolve(shell)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
shellWrite(shellId: string, data: string | Uint8Array): void {
|
||||
const shell = this.shells.get(shellId)
|
||||
if (shell) {
|
||||
shell.channel.write(data)
|
||||
}
|
||||
}
|
||||
|
||||
shellResize(shellId: string, cols: number, rows: number): void {
|
||||
const shell = this.shells.get(shellId)
|
||||
if (shell) {
|
||||
shell.channel.setWindow(rows, cols, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
getShell(shellId: string): ShellSession | undefined {
|
||||
return this.shells.get(shellId)
|
||||
}
|
||||
|
||||
getConnection(connectionId: string): Connection | undefined {
|
||||
return this.connections.get(connectionId)
|
||||
}
|
||||
|
||||
// ===== SFTP 操作 =====
|
||||
async createSFTP(connectionId: string): Promise<SFTPSession> {
|
||||
logHeader('📁 SFTP CREATE')
|
||||
logInfo('connectionId', connectionId)
|
||||
|
||||
const connection = this.connections.get(connectionId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
logError('Connection not established')
|
||||
throw new Error('Connection not established')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
debug('>>> Calling client.sftp()...')
|
||||
connection.client.sftp((err, sftp) => {
|
||||
if (err) {
|
||||
logError(`SFTP creation failed: ${err.message}`)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
|
||||
const sftpId = uuidv4()
|
||||
const session: SFTPSession = {
|
||||
id: sftpId,
|
||||
connectionId,
|
||||
sftp
|
||||
}
|
||||
|
||||
this.sftps.set(sftpId, session)
|
||||
logSuccess(`SFTP session created: ${sftpId}`)
|
||||
resolve(session)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async sftpListDirectory(sftpId: string, path: string): Promise<any[]> {
|
||||
logHeader('📁 SFTP LIST DIRECTORY')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('path', path)
|
||||
|
||||
const session = this.sftps.get(sftpId)
|
||||
if (!session) {
|
||||
logError('SFTP session not found')
|
||||
throw new Error('SFTP session not found')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
session.sftp.readdir(path, (err, list) => {
|
||||
if (err) {
|
||||
logError(`List directory failed: ${err.message}`)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
logSuccess(`Listed ${list.length} items in ${path}`)
|
||||
resolve(list)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async sftpUpload(
|
||||
sftpId: string,
|
||||
localPath: string,
|
||||
remotePath: string,
|
||||
onProgress?: (transferred: number, total: number) => void
|
||||
): Promise<void> {
|
||||
logHeader('📤 SFTP UPLOAD')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('localPath', localPath)
|
||||
logInfo('remotePath', remotePath)
|
||||
|
||||
const session = this.sftps.get(sftpId)
|
||||
if (!session) {
|
||||
logError('SFTP session not found')
|
||||
throw new Error('SFTP session not found')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
session.sftp.fastPut(localPath, remotePath, {
|
||||
step: (transferred: number, _chunk: number, total: number) => {
|
||||
debug(`Upload progress: ${transferred}/${total}`)
|
||||
if (onProgress) {
|
||||
onProgress(transferred, total)
|
||||
}
|
||||
}
|
||||
}, (err) => {
|
||||
if (err) {
|
||||
logError(`Upload failed: ${err.message}`)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
logSuccess(`Upload complete: ${remotePath}`)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async sftpDownload(
|
||||
sftpId: string,
|
||||
remotePath: string,
|
||||
localPath: string,
|
||||
onProgress?: (transferred: number, total: number) => void
|
||||
): Promise<void> {
|
||||
logHeader('📥 SFTP DOWNLOAD')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('remotePath', remotePath)
|
||||
logInfo('localPath', localPath)
|
||||
|
||||
const session = this.sftps.get(sftpId)
|
||||
if (!session) {
|
||||
logError('SFTP session not found')
|
||||
throw new Error('SFTP session not found')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
session.sftp.fastGet(remotePath, localPath, {
|
||||
step: (transferred: number, _chunk: number, total: number) => {
|
||||
debug(`Download progress: ${transferred}/${total}`)
|
||||
if (onProgress) {
|
||||
onProgress(transferred, total)
|
||||
}
|
||||
}
|
||||
}, (err) => {
|
||||
if (err) {
|
||||
logError(`Download failed: ${err.message}`)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
logSuccess(`Download complete: ${remotePath}`)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async sftpRename(sftpId: string, oldPath: string, newPath: string): Promise<void> {
|
||||
const session = this.sftps.get(sftpId)
|
||||
if (!session) {
|
||||
throw new Error('SFTP session not found')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
session.sftp.rename(oldPath, newPath, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async sftpDelete(sftpId: string, path: string, isDirectory: boolean): Promise<void> {
|
||||
const session = this.sftps.get(sftpId)
|
||||
if (!session) {
|
||||
throw new Error('SFTP session not found')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
if (isDirectory) {
|
||||
session.sftp.rmdir(path, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
} else {
|
||||
session.sftp.unlink(path, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async sftpMkdir(sftpId: string, path: string): Promise<void> {
|
||||
const session = this.sftps.get(sftpId)
|
||||
if (!session) {
|
||||
throw new Error('SFTP session not found')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
session.sftp.mkdir(path, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 端口转发
|
||||
// ===== 本地端口转发 =====
|
||||
async forwardLocal(
|
||||
connectionId: string,
|
||||
localPort: number,
|
||||
remoteHost: string,
|
||||
remotePort: number
|
||||
): Promise<{ success: boolean; boundPort: number }> {
|
||||
logHeader('🔀 LOCAL PORT FORWARD')
|
||||
logInfo('connectionId', connectionId)
|
||||
logInfo('localPort', localPort)
|
||||
logInfo('remoteHost', remoteHost)
|
||||
logInfo('remotePort', remotePort)
|
||||
|
||||
const connection = this.connections.get(connectionId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
logError('Connection not established')
|
||||
throw new Error('Connection not established')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
debug('>>> Creating local server on port', localPort)
|
||||
const server = net.createServer((socket) => {
|
||||
debug('>>> Local connection received, forwarding to', remoteHost, remotePort)
|
||||
connection.client.forwardOut('127.0.0.1', 0, remoteHost, remotePort, (err, stream) => {
|
||||
if (err) {
|
||||
logError(`ForwardOut failed: ${err.message}`)
|
||||
socket.end()
|
||||
return
|
||||
}
|
||||
socket.pipe(stream).pipe(socket)
|
||||
debug('>>> Pipeline established')
|
||||
})
|
||||
})
|
||||
|
||||
server.listen(localPort, '127.0.0.1', () => {
|
||||
const actualPort = (server.address() as net.AddressInfo).port
|
||||
logSuccess(`Local forward established: 127.0.0.1:${actualPort} -> ${remoteHost}:${remotePort}`)
|
||||
resolve({ success: true, boundPort: actualPort })
|
||||
})
|
||||
|
||||
server.on('error', (err) => {
|
||||
logError(`Server error: ${err.message}`)
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 远程端口转发 =====
|
||||
async forwardRemote(
|
||||
connectionId: string,
|
||||
remotePort: number,
|
||||
localHost: string,
|
||||
localPort: number
|
||||
): Promise<{ success: boolean }> {
|
||||
logHeader('🔀 REMOTE PORT FORWARD')
|
||||
logInfo('connectionId', connectionId)
|
||||
logInfo('remotePort', remotePort)
|
||||
logInfo('localHost', localHost)
|
||||
logInfo('localPort', localPort)
|
||||
|
||||
const connection = this.connections.get(connectionId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
logError('Connection not established')
|
||||
throw new Error('Connection not established')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
connection.client.forwardIn('127.0.0.1', remotePort, (err) => {
|
||||
if (err) {
|
||||
logError(`forwardIn failed: ${err.message}`)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
logSuccess(`Remote forward established: remote:${remotePort} -> ${localHost}:${localPort}`)
|
||||
resolve({ success: true })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 动态端口转发 (SOCKS5) =====
|
||||
private socksServers: Map<string, net.Server> = new Map()
|
||||
|
||||
async forwardDynamic(
|
||||
connectionId: string,
|
||||
localPort: number
|
||||
): Promise<{ success: boolean; boundPort: number }> {
|
||||
logHeader('🧦 SOCKS5 DYNAMIC FORWARD')
|
||||
logInfo('connectionId', connectionId)
|
||||
logInfo('localPort', localPort)
|
||||
|
||||
const connection = this.connections.get(connectionId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
logError('Connection not established')
|
||||
throw new Error('Connection not established')
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer((socket) => {
|
||||
debug('>>> SOCKS5 client connected')
|
||||
|
||||
socket.once('data', (data) => {
|
||||
// 解析 SOCKS5 握手
|
||||
if (data.length < 3 || data[0] !== 0x05) {
|
||||
logError('Invalid SOCKS5 handshake')
|
||||
socket.end()
|
||||
return
|
||||
}
|
||||
|
||||
// 发送握手响应 (无认证)
|
||||
socket.write(Buffer.from([0x05, 0x00]))
|
||||
|
||||
socket.once('data', (data) => {
|
||||
// 解析 SOCKS5 请求
|
||||
const req = Buffer.from(data)
|
||||
if (req.length < 10 || req[0] !== 0x05) {
|
||||
logError('Invalid SOCKS5 request')
|
||||
socket.end()
|
||||
return
|
||||
}
|
||||
|
||||
const cmd = req[1]
|
||||
const atyp = req[3]
|
||||
|
||||
if (cmd !== 0x01) { // CONNECT only
|
||||
socket.write(Buffer.from([0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
||||
socket.end()
|
||||
return
|
||||
}
|
||||
|
||||
let targetHost: string
|
||||
let targetPort: number
|
||||
let headerLen: number
|
||||
|
||||
if (atyp === 0x01) { // IPv4
|
||||
targetHost = `${req[4]}.${req[5]}.${req[6]}.${req[7]}`
|
||||
targetPort = req.readUInt16BE(8)
|
||||
headerLen = 10
|
||||
} else if (atyp === 0x03) { // Domain
|
||||
const domainLen = req[4]
|
||||
targetHost = req.slice(5, 5 + domainLen).toString('ascii')
|
||||
targetPort = req.readUInt16BE(5 + domainLen)
|
||||
headerLen = 5 + domainLen + 2
|
||||
} else {
|
||||
socket.write(Buffer.from([0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
||||
socket.end()
|
||||
return
|
||||
}
|
||||
|
||||
logInfo('SOCKS5 target', `${targetHost}:${targetPort}`)
|
||||
|
||||
// 通过 SSH 连接目标
|
||||
connection.client.forwardOut('127.0.0.1', 0, targetHost, targetPort, (err, stream) => {
|
||||
if (err) {
|
||||
logError(`SOCKS5 forwardOut failed: ${err.message}`)
|
||||
socket.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
||||
socket.end()
|
||||
return
|
||||
}
|
||||
|
||||
// 发送成功响应
|
||||
socket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
||||
|
||||
// 建立双向管道
|
||||
stream.pipe(socket)
|
||||
socket.pipe(stream)
|
||||
|
||||
// 如果有残留数据,发送给 stream
|
||||
if (req.length > headerLen) {
|
||||
stream.write(req.slice(headerLen))
|
||||
}
|
||||
|
||||
logSuccess(`SOCKS5 tunnel established to ${targetHost}:${targetPort}`)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
server.listen(localPort, '127.0.0.1', () => {
|
||||
const actualPort = (server.address() as net.AddressInfo).port
|
||||
this.socksServers.set(`${connectionId}:${actualPort}`, server)
|
||||
logSuccess(`SOCKS5 proxy started on 127.0.0.1:${actualPort}`)
|
||||
resolve({ success: true, boundPort: actualPort })
|
||||
})
|
||||
|
||||
server.on('error', (err) => {
|
||||
logError(`SOCKS5 server error: ${err.message}`)
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 停止 SOCKS5 代理
|
||||
stopDynamicForward(connectionId: string, localPort: number): void {
|
||||
const key = `${connectionId}:${localPort}`
|
||||
const server = this.socksServers.get(key)
|
||||
if (server) {
|
||||
server.close()
|
||||
this.socksServers.delete(key)
|
||||
logSuccess(`SOCKS5 proxy stopped on port ${localPort}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import Zmodem from 'zmodem-ts'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { app } from 'electron'
|
||||
import { createLogger } from '../utils/logger'
|
||||
|
||||
const logger = createLogger('ZmodemService')
|
||||
|
||||
// Type definitions for Zmodem sessions (since zmodem-ts doesn't export them properly)
|
||||
interface ZmodemSendSession {
|
||||
type: 'send'
|
||||
set_sender(func: (octets: number[]) => void): void
|
||||
send_offer(params: { name: string; size: number; mtime?: number }): Promise<any>
|
||||
on(event: string, handler: (data: any) => void): void
|
||||
abort(): void
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
interface ZmodemReceiveSession {
|
||||
type: 'receive'
|
||||
set_sender(func: (octets: number[]) => void): void
|
||||
start(): Promise<any>
|
||||
on(event: string, handler: (data: any) => void): void
|
||||
abort(): void
|
||||
}
|
||||
|
||||
interface ZmodemSentry {
|
||||
consume(octets: number[]): void
|
||||
}
|
||||
|
||||
export interface ZmodemProgress {
|
||||
percentage: number
|
||||
transferred: number
|
||||
total: number
|
||||
fileName?: string
|
||||
}
|
||||
|
||||
interface ZmodemSessionInfo {
|
||||
id: string
|
||||
shellId: string
|
||||
type: 'send' | 'receive'
|
||||
session: ZmodemSendSession | ZmodemReceiveSession
|
||||
fileName?: string
|
||||
filePath?: string
|
||||
totalSize?: number
|
||||
transferred?: number
|
||||
sentry?: ZmodemSentry
|
||||
onComplete?: (success: boolean, error?: string) => void
|
||||
}
|
||||
|
||||
export class ZmodemService {
|
||||
private sessions: Map<string, ZmodemSessionInfo> = new Map()
|
||||
private shellDataCallbacks: Map<string, (data: Buffer) => void> = new Map()
|
||||
|
||||
constructor() {
|
||||
app.on('before-quit', () => {
|
||||
this.closeAll()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Send file to server via Zmodem (rz)
|
||||
*
|
||||
* Flow: Server types "rz" -> sends ZRQINIT/ZRINIT -> we send file
|
||||
* We use Sentry to detect when server is ready (ZRINIT received)
|
||||
*/
|
||||
sendFile(
|
||||
shellId: string,
|
||||
fileName: string,
|
||||
fileData: Buffer,
|
||||
writeFunc: (data: Uint8Array) => void,
|
||||
onProgress?: (progress: ZmodemProgress) => void,
|
||||
onComplete?: (success: boolean, error?: string) => void
|
||||
): string {
|
||||
const sessionId = `zmodem-send-${Date.now()}`
|
||||
const totalSize = fileData.length
|
||||
|
||||
// Create session info
|
||||
const sessionInfo: ZmodemSessionInfo = {
|
||||
id: sessionId,
|
||||
shellId,
|
||||
type: 'send',
|
||||
session: null as any,
|
||||
fileName,
|
||||
totalSize,
|
||||
transferred: 0
|
||||
}
|
||||
|
||||
this.sessions.set(sessionId, sessionInfo)
|
||||
|
||||
// Store completion callback
|
||||
if (onComplete) {
|
||||
sessionInfo.onComplete = onComplete
|
||||
}
|
||||
|
||||
// Create Sentry to detect ZRINIT from server
|
||||
// @ts-ignore - zmodem-ts types are incomplete
|
||||
const sentry = new Zmodem.Sentry({
|
||||
to_terminal: (octets: number[]) => {
|
||||
// Echo to terminal
|
||||
writeFunc(new Uint8Array(octets))
|
||||
},
|
||||
on_detect: (detection: any) => {
|
||||
const detectedSession = detection.get_session()
|
||||
if (detectedSession && detectedSession.type === 'send') {
|
||||
// Server is ready for file transfer (received ZRINIT)
|
||||
const sendSession = detectedSession as ZmodemSendSession
|
||||
|
||||
// Update session reference
|
||||
sessionInfo.session = sendSession
|
||||
|
||||
// Set up sender to write to shell
|
||||
sendSession.set_sender((octets: number[]) => {
|
||||
writeFunc(new Uint8Array(octets))
|
||||
})
|
||||
|
||||
// Handle session end
|
||||
sendSession.on('session_end', () => {
|
||||
this.sessions.delete(sessionId)
|
||||
})
|
||||
|
||||
sendSession.on('error', (err: Error) => {
|
||||
logger.error('Zmodem send error:', err)
|
||||
onComplete?.(false, err.message)
|
||||
})
|
||||
|
||||
// Send the file
|
||||
this.doSendFile(sessionId, sendSession, fileName, fileData, onProgress, onComplete)
|
||||
}
|
||||
},
|
||||
on_retract: () => {
|
||||
// Session was retracted
|
||||
logger.info('Zmodem send session retracted')
|
||||
this.sessions.delete(sessionId)
|
||||
onComplete?.(false, 'Session retracted')
|
||||
},
|
||||
sender: (octets: number[]) => {
|
||||
writeFunc(new Uint8Array(octets))
|
||||
}
|
||||
})
|
||||
|
||||
sessionInfo.sentry = sentry
|
||||
|
||||
// Store shell data callback to feed to Sentry
|
||||
this.shellDataCallbacks.set(shellId, (data: Buffer) => {
|
||||
sentry.consume(Array.from(data))
|
||||
})
|
||||
|
||||
return sessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to send file after ZRINIT is received
|
||||
*/
|
||||
private async doSendFile(
|
||||
sessionId: string,
|
||||
session: ZmodemSendSession,
|
||||
fileName: string,
|
||||
fileData: Buffer,
|
||||
onProgress?: (progress: ZmodemProgress) => void,
|
||||
onComplete?: (success: boolean, error?: string) => void
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Send file offer
|
||||
const result = await session.send_offer({
|
||||
name: fileName,
|
||||
size: fileData.length,
|
||||
mtime: Date.now()
|
||||
})
|
||||
|
||||
if (result) {
|
||||
// Transfer completed successfully
|
||||
onProgress?.({
|
||||
percentage: 100,
|
||||
transferred: fileData.length,
|
||||
total: fileData.length,
|
||||
fileName
|
||||
})
|
||||
onComplete?.(true)
|
||||
} else {
|
||||
// Transfer was skipped or rejected
|
||||
onComplete?.(false, 'Transfer skipped or rejected')
|
||||
}
|
||||
} catch (err: any) {
|
||||
logger.error('Zmodem send error:', err)
|
||||
onComplete?.(false, err.message)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Feed shell data to Zmodem service for protocol detection
|
||||
* This should be called when shell receives data
|
||||
*/
|
||||
feedShellData(shellId: string, data: Buffer): void {
|
||||
const callback = this.shellDataCallbacks.get(shellId)
|
||||
if (callback) {
|
||||
callback(data)
|
||||
}
|
||||
|
||||
// Also check all sessions for matching shellId
|
||||
for (const [sessionId, session] of this.sessions) {
|
||||
if (session.shellId === shellId && session.sentry) {
|
||||
// Feed to sentry for detection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive file from server via Zmodem (sz)
|
||||
*
|
||||
* Flow: User clicks "sz" in UI -> we open receive session
|
||||
* Server sends ZRQINIT -> we accept -> server sends file
|
||||
*/
|
||||
receiveFile(
|
||||
shellId: string,
|
||||
filePath: string,
|
||||
writeFunc: (data: Uint8Array) => void,
|
||||
onProgress?: (progress: ZmodemProgress) => void,
|
||||
onComplete?: (success: boolean, error?: string) => void
|
||||
): string {
|
||||
const sessionId = `zmodem-receive-${Date.now()}`
|
||||
const fileName = path.basename(filePath)
|
||||
|
||||
// Create receive session
|
||||
// @ts-ignore - zmodem-ts types are incomplete
|
||||
const session: ZmodemReceiveSession = new Zmodem.ReceiveSession()
|
||||
|
||||
const sessionInfo: ZmodemSessionInfo = {
|
||||
id: sessionId,
|
||||
shellId,
|
||||
type: 'receive',
|
||||
session,
|
||||
filePath,
|
||||
fileName,
|
||||
totalSize: 0,
|
||||
transferred: 0
|
||||
}
|
||||
|
||||
this.sessions.set(sessionId, sessionInfo)
|
||||
|
||||
if (onComplete) {
|
||||
sessionInfo.onComplete = onComplete
|
||||
}
|
||||
|
||||
// Set up sender to write responses to shell
|
||||
session.set_sender((octets: number[]) => {
|
||||
writeFunc(new Uint8Array(octets))
|
||||
})
|
||||
|
||||
// Handle file offer
|
||||
session.on('offer', (offer: any) => {
|
||||
const details = offer.getDetails()
|
||||
logger.info('Zmodem offer received:', details)
|
||||
|
||||
sessionInfo.fileName = details.name || fileName
|
||||
sessionInfo.totalSize = details.size || 0
|
||||
|
||||
// Accept the offer
|
||||
offer.accept({
|
||||
on_input: 'spool_array'
|
||||
}).then((transfer: any) => {
|
||||
// Handle incoming data
|
||||
transfer.on('input', (data: Uint8Array) => {
|
||||
sessionInfo.transferred = (sessionInfo.transferred || 0) + data.length
|
||||
|
||||
// Write to file
|
||||
try {
|
||||
fs.writeFileSync(filePath, data, { flag: 'a' })
|
||||
} catch (err: any) {
|
||||
logger.error('Error writing Zmodem file:', err)
|
||||
}
|
||||
|
||||
const total = sessionInfo.totalSize || sessionInfo.transferred || 0
|
||||
onProgress?.({
|
||||
percentage: total > 0
|
||||
? Math.round((sessionInfo.transferred! / total) * 100)
|
||||
: 0,
|
||||
transferred: sessionInfo.transferred!,
|
||||
total: total,
|
||||
fileName: sessionInfo.fileName
|
||||
})
|
||||
})
|
||||
|
||||
transfer.on('complete', () => {
|
||||
logger.info('Zmodem receive complete')
|
||||
onProgress?.({
|
||||
percentage: 100,
|
||||
transferred: sessionInfo.totalSize || sessionInfo.transferred || 0,
|
||||
total: sessionInfo.totalSize || sessionInfo.transferred || 0,
|
||||
fileName: sessionInfo.fileName
|
||||
})
|
||||
onComplete?.(true)
|
||||
})
|
||||
}).catch((err: Error) => {
|
||||
logger.error('Zmodem accept error:', err)
|
||||
onComplete?.(false, err.message)
|
||||
})
|
||||
})
|
||||
|
||||
// Handle session end
|
||||
session.on('session_end', () => {
|
||||
this.sessions.delete(sessionId)
|
||||
})
|
||||
|
||||
session.on('error', (err: Error) => {
|
||||
logger.error('Zmodem receive error:', err)
|
||||
onComplete?.(false, err.message)
|
||||
})
|
||||
|
||||
// Start receiving - this sends ZRINIT to signal we're ready
|
||||
session.start().catch((err: Error) => {
|
||||
logger.error('Zmodem start error:', err)
|
||||
this.sessions.delete(sessionId)
|
||||
onComplete?.(false, err.message)
|
||||
})
|
||||
|
||||
return sessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a Zmodem session
|
||||
*/
|
||||
cancelSession(sessionId: string): void {
|
||||
const session = this.sessions.get(sessionId)
|
||||
if (session) {
|
||||
try {
|
||||
const s = session.session as any
|
||||
s.abort?.()
|
||||
s.close?.()
|
||||
} catch (err: any) {
|
||||
logger.error('Error canceling Zmodem session:', err)
|
||||
}
|
||||
|
||||
// Clean up shell data callback
|
||||
this.shellDataCallbacks.delete(session.shellId)
|
||||
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all active sessions
|
||||
*/
|
||||
closeAll(): void {
|
||||
for (const sessionId of this.sessions.keys()) {
|
||||
this.cancelSession(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active session IDs
|
||||
*/
|
||||
getActiveSessions(): string[] {
|
||||
return Array.from(this.sessions.keys())
|
||||
}
|
||||
|
||||
/**
|
||||
* Get session by ID
|
||||
*/
|
||||
getSession(sessionId: string): ZmodemSessionInfo | undefined {
|
||||
return this.sessions.get(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
export const zmodemService = new ZmodemService()
|
||||
Reference in new issue
Block a user