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,24 @@
|
||||
/**
|
||||
* App IPC Handlers
|
||||
* 处理应用级别信息
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent, app } from 'electron'
|
||||
|
||||
// IPC channel names
|
||||
export const APP_CHANNELS = {
|
||||
GET_VERSION: 'app:getVersion',
|
||||
GET_DOWNLOADS_PATH: 'app:getDownloadsPath',
|
||||
} as const
|
||||
|
||||
export function registerAppIPCHandlers(): void {
|
||||
// Get app version
|
||||
ipcMain.handle(APP_CHANNELS.GET_VERSION, () => {
|
||||
return app.getVersion()
|
||||
})
|
||||
|
||||
// Get downloads directory path
|
||||
ipcMain.handle(APP_CHANNELS.GET_DOWNLOADS_PATH, () => {
|
||||
return app.getPath('downloads')
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Dialog IPC Handlers
|
||||
* 处理系统对话框
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent, dialog } from 'electron'
|
||||
|
||||
// IPC channel names
|
||||
export const DIALOG_CHANNELS = {
|
||||
SHOW_SAVE: 'dialog:showSaveDialog',
|
||||
SHOW_OPEN: 'dialog:showOpenDialog',
|
||||
} as const
|
||||
|
||||
export interface DialogIPCOptions {
|
||||
mainWindowGetter: () => Electron.BrowserWindow | null
|
||||
}
|
||||
|
||||
export function registerDialogIPCHandlers(options: DialogIPCOptions): void {
|
||||
const { mainWindowGetter } = options
|
||||
|
||||
// Show save dialog
|
||||
ipcMain.handle(DIALOG_CHANNELS.SHOW_SAVE, async (_event: IpcMainInvokeEvent, options: Electron.SaveDialogOptions) => {
|
||||
const mainWindow = mainWindowGetter()
|
||||
if (!mainWindow) {
|
||||
return { canceled: true }
|
||||
}
|
||||
return dialog.showSaveDialog(mainWindow, options)
|
||||
})
|
||||
|
||||
// Show open dialog
|
||||
ipcMain.handle(DIALOG_CHANNELS.SHOW_OPEN, async (_event: IpcMainInvokeEvent, options: Electron.OpenDialogOptions) => {
|
||||
const mainWindow = mainWindowGetter()
|
||||
if (!mainWindow) {
|
||||
return { canceled: true }
|
||||
}
|
||||
return dialog.showOpenDialog(mainWindow, options)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* File IPC Handlers
|
||||
* 处理本地文件操作和远程文件读写
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent, app } from 'electron'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
// IPC channel names
|
||||
export const FILE_CHANNELS = {
|
||||
// Remote file operations (for zmodem)
|
||||
READ: 'file:read',
|
||||
WRITE: 'file:write',
|
||||
// Local file system operations
|
||||
LOCAL_GET_HOME: 'local:getHome',
|
||||
LOCAL_READ_DIR: 'local:readDir',
|
||||
LOCAL_GET_STATS: 'local:getStats',
|
||||
LOCAL_DELETE: 'local:delete',
|
||||
LOCAL_RENAME: 'local:rename',
|
||||
LOCAL_MKDIR: 'local:mkdir',
|
||||
} as const
|
||||
|
||||
export function registerFileIPCHandlers(): void {
|
||||
// Read file (for rz)
|
||||
ipcMain.handle(FILE_CHANNELS.READ, async (_event: IpcMainInvokeEvent, filePath: string) => {
|
||||
try {
|
||||
const data = fs.readFileSync(filePath)
|
||||
return { success: true, data: data.toString('base64') }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Write file (for sz)
|
||||
ipcMain.handle(FILE_CHANNELS.WRITE, async (_event: IpcMainInvokeEvent, filePath: string, data: string) => {
|
||||
try {
|
||||
const buffer = Buffer.from(data, 'base64')
|
||||
fs.writeFileSync(filePath, buffer)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Get user home directory
|
||||
ipcMain.handle(FILE_CHANNELS.LOCAL_GET_HOME, async () => {
|
||||
try {
|
||||
const homePath = app.getPath('home')
|
||||
return { success: true, path: homePath }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Read directory contents
|
||||
ipcMain.handle(FILE_CHANNELS.LOCAL_READ_DIR, async (_event: IpcMainInvokeEvent, dirPath: string) => {
|
||||
try {
|
||||
const entries = fs.readdirSync(dirPath, { withFileTypes: true })
|
||||
const files = entries.map((entry) => {
|
||||
const fullPath = path.join(dirPath, entry.name)
|
||||
let stats: fs.Stats | null = null
|
||||
try {
|
||||
stats = fs.lstatSync(fullPath)
|
||||
} catch {
|
||||
// Skip files we can't stat
|
||||
}
|
||||
|
||||
return {
|
||||
name: entry.name,
|
||||
path: fullPath,
|
||||
type: entry.isDirectory() ? 'directory' : entry.isSymbolicLink() ? 'symlink' : 'file',
|
||||
size: stats?.size || 0,
|
||||
modified: stats?.mtime ? Math.floor(stats.mtime.getTime() / 1000) : 0,
|
||||
permissions: formatPermissions(stats?.mode || 0),
|
||||
}
|
||||
})
|
||||
|
||||
// Sort: directories first, then by name
|
||||
files.sort((a, b) => {
|
||||
if (a.type !== 'file' && b.type === 'file') return -1
|
||||
if (a.type === 'file' && b.type !== 'file') return 1
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
|
||||
return { success: true, files }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Get file stats
|
||||
ipcMain.handle(FILE_CHANNELS.LOCAL_GET_STATS, async (_event: IpcMainInvokeEvent, filePath: string) => {
|
||||
try {
|
||||
const stats = fs.lstatSync(filePath)
|
||||
return {
|
||||
success: true,
|
||||
stats: {
|
||||
name: path.basename(filePath),
|
||||
path: filePath,
|
||||
type: stats.isDirectory() ? 'directory' : stats.isSymbolicLink() ? 'symlink' : 'file',
|
||||
size: stats.size,
|
||||
modified: Math.floor(stats.mtime.getTime() / 1000),
|
||||
permissions: formatPermissions(stats.mode),
|
||||
},
|
||||
}
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Delete file or directory
|
||||
ipcMain.handle(FILE_CHANNELS.LOCAL_DELETE, async (_event: IpcMainInvokeEvent, filePath: string) => {
|
||||
try {
|
||||
const stats = fs.lstatSync(filePath)
|
||||
if (stats.isDirectory()) {
|
||||
fs.rmSync(filePath, { recursive: true, force: true })
|
||||
} else {
|
||||
fs.unlinkSync(filePath)
|
||||
}
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Rename file or directory
|
||||
ipcMain.handle(FILE_CHANNELS.LOCAL_RENAME, async (_event: IpcMainInvokeEvent, oldPath: string, newPath: string) => {
|
||||
try {
|
||||
fs.renameSync(oldPath, newPath)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Create directory
|
||||
ipcMain.handle(FILE_CHANNELS.LOCAL_MKDIR, async (_event: IpcMainInvokeEvent, dirPath: string) => {
|
||||
try {
|
||||
fs.mkdirSync(dirPath, { recursive: true })
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function to format Unix permissions
|
||||
function formatPermissions(mode: number): string {
|
||||
const perms: string[] = []
|
||||
const types = ['---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx']
|
||||
|
||||
// Owner
|
||||
perms.push(types[(mode >> 6) & 7])
|
||||
// Group
|
||||
perms.push(types[(mode >> 3) & 7])
|
||||
// Other
|
||||
perms.push(types[mode & 7])
|
||||
|
||||
return perms.join('')
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* IPC Handler Registration
|
||||
* 统一注册所有 IPC 处理器
|
||||
*/
|
||||
|
||||
import type { SSHService } from '../services/ssh-service'
|
||||
import type { DatabaseService } from '../services/database-service'
|
||||
import type { ZmodemService } from '../services/zmodem-service'
|
||||
import type { BrowserWindow } from 'electron'
|
||||
import { createLogger } from '../utils/logger'
|
||||
|
||||
const logger = createLogger('IPC')
|
||||
|
||||
import { registerSSHIPCHandlers } from './ssh.ipc'
|
||||
import { registerSFTPIPCHandlers } from './sftp.ipc'
|
||||
import { registerSessionIPCHandlers } from './session.ipc'
|
||||
import { registerSettingsIPCHandlers } from './settings.ipc'
|
||||
import { registerDialogIPCHandlers } from './dialog.ipc'
|
||||
import { registerFileIPCHandlers } from './file.ipc'
|
||||
import { registerZmodemIPCHandlers } from './zmodem.ipc'
|
||||
import { registerAppIPCHandlers } from './app.ipc'
|
||||
|
||||
export interface IPCOptions {
|
||||
sshService: SSHService
|
||||
databaseService: DatabaseService
|
||||
zmodemService: ZmodemService
|
||||
mainWindowGetter: () => BrowserWindow | null
|
||||
}
|
||||
|
||||
export function registerAllIPCHandlers(options: IPCOptions): void {
|
||||
const { sshService, databaseService, zmodemService, mainWindowGetter } = options
|
||||
|
||||
// SSH handlers
|
||||
registerSSHIPCHandlers({ sshService, zmodemService, mainWindowGetter })
|
||||
|
||||
// SFTP handlers
|
||||
registerSFTPIPCHandlers({ sshService, mainWindowGetter })
|
||||
|
||||
// Session handlers
|
||||
registerSessionIPCHandlers({ dbService: databaseService })
|
||||
|
||||
// Settings handlers
|
||||
registerSettingsIPCHandlers({ dbService: databaseService })
|
||||
|
||||
// Dialog handlers
|
||||
registerDialogIPCHandlers({ mainWindowGetter })
|
||||
|
||||
// File handlers
|
||||
registerFileIPCHandlers()
|
||||
|
||||
// Zmodem handlers
|
||||
registerZmodemIPCHandlers({ sshService, zmodemService, mainWindowGetter })
|
||||
|
||||
// App handlers
|
||||
registerAppIPCHandlers()
|
||||
|
||||
logger.info('[IPC] All handlers registered')
|
||||
}
|
||||
|
||||
// Re-export channel constants for external use
|
||||
export { SSH_CHANNELS } from './ssh.ipc'
|
||||
export { SFTP_CHANNELS } from './sftp.ipc'
|
||||
export { SESSION_CHANNELS } from './session.ipc'
|
||||
export { SETTINGS_CHANNELS } from './settings.ipc'
|
||||
export { DIALOG_CHANNELS } from './dialog.ipc'
|
||||
export { FILE_CHANNELS } from './file.ipc'
|
||||
export { ZMODEM_CHANNELS } from './zmodem.ipc'
|
||||
export { APP_CHANNELS } from './app.ipc'
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Session IPC Handlers
|
||||
* 处理会话的 CRUD 操作
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent } from 'electron'
|
||||
import type { DatabaseService } from '../services/database-service'
|
||||
|
||||
// IPC channel names
|
||||
export const SESSION_CHANNELS = {
|
||||
CREATE: 'session:create',
|
||||
GET_ALL: 'session:getAll',
|
||||
GET_BY_ID: 'session:getById',
|
||||
UPDATE: 'session:update',
|
||||
DELETE: 'session:delete',
|
||||
} as const
|
||||
|
||||
export interface SessionIPCOptions {
|
||||
dbService: DatabaseService
|
||||
}
|
||||
|
||||
export function registerSessionIPCHandlers(options: SessionIPCOptions): void {
|
||||
const { dbService } = options
|
||||
|
||||
// Create session
|
||||
ipcMain.handle(SESSION_CHANNELS.CREATE, async (_event: IpcMainInvokeEvent, session) => {
|
||||
try {
|
||||
const result = dbService.createSession(session)
|
||||
return { success: true, session: result }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Get all sessions
|
||||
ipcMain.handle(SESSION_CHANNELS.GET_ALL, async () => {
|
||||
try {
|
||||
const sessions = dbService.getAllSessions()
|
||||
return { success: true, sessions }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Get session by ID
|
||||
ipcMain.handle(SESSION_CHANNELS.GET_BY_ID, async (_event: IpcMainInvokeEvent, id: string) => {
|
||||
try {
|
||||
const session = dbService.getSessionById(id)
|
||||
return { success: true, session }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Update session
|
||||
ipcMain.handle(SESSION_CHANNELS.UPDATE, async (_event: IpcMainInvokeEvent, id: string, updates: any) => {
|
||||
try {
|
||||
const result = dbService.updateSession(id, updates)
|
||||
return { success: true, session: result }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Delete session
|
||||
ipcMain.handle(SESSION_CHANNELS.DELETE, async (_event: IpcMainInvokeEvent, id: string) => {
|
||||
try {
|
||||
dbService.deleteSession(id)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Settings IPC Handlers
|
||||
* 处理应用设置读写
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent } from 'electron'
|
||||
import type { DatabaseService } from '../services/database-service'
|
||||
|
||||
// IPC channel names
|
||||
export const SETTINGS_CHANNELS = {
|
||||
GET: 'settings:get',
|
||||
SET: 'settings:set',
|
||||
} as const
|
||||
|
||||
export interface SettingsIPCOptions {
|
||||
dbService: DatabaseService
|
||||
}
|
||||
|
||||
export function registerSettingsIPCHandlers(options: SettingsIPCOptions): void {
|
||||
const { dbService } = options
|
||||
|
||||
// Get setting
|
||||
ipcMain.handle(SETTINGS_CHANNELS.GET, async (_event: IpcMainInvokeEvent, key: string) => {
|
||||
try {
|
||||
const value = dbService.getSetting(key)
|
||||
return { success: true, value }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Set setting
|
||||
ipcMain.handle(SETTINGS_CHANNELS.SET, async (_event: IpcMainInvokeEvent, key: string, value: unknown) => {
|
||||
try {
|
||||
dbService.setSetting(key, value)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* SFTP IPC Handlers
|
||||
* 处理 SFTP 连接和文件操作相关 IPC
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent } from 'electron'
|
||||
import type { SSHService } from '../services/ssh-service'
|
||||
|
||||
// IPC channel names
|
||||
export const SFTP_CHANNELS = {
|
||||
CONNECT: 'sftp:connect',
|
||||
LIST_DIRECTORY: 'sftp:listDirectory',
|
||||
UPLOAD: 'sftp:upload',
|
||||
DOWNLOAD: 'sftp:download',
|
||||
RENAME: 'sftp:rename',
|
||||
DELETE: 'sftp:delete',
|
||||
MKDIR: 'sftp:mkdir',
|
||||
PROGRESS: 'sftp:progress',
|
||||
} as const
|
||||
|
||||
export interface SFTPIPCOptions {
|
||||
sshService: SSHService
|
||||
mainWindowGetter: () => Electron.BrowserWindow | null
|
||||
}
|
||||
|
||||
// ===== 彩色调试日志 =====
|
||||
const DEBUG = true
|
||||
function logHeader(msg: string) {
|
||||
console.log(`%c${msg}`, 'background: #16a085; 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: #1abc9c; 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;')
|
||||
}
|
||||
|
||||
export function registerSFTPIPCHandlers(options: SFTPIPCOptions): void {
|
||||
const { sshService, mainWindowGetter } = options
|
||||
|
||||
// SFTP connect
|
||||
ipcMain.handle(SFTP_CHANNELS.CONNECT, async (_event: IpcMainInvokeEvent, connectionId: string) => {
|
||||
logHeader('📁 SFTP IPC CONNECT')
|
||||
logInfo('connectionId', connectionId)
|
||||
|
||||
try {
|
||||
const sftp = await sshService.createSFTP(connectionId)
|
||||
logSuccess(`SFTP connected: ${sftp.id}`)
|
||||
return { success: true, sftpId: sftp.id }
|
||||
} catch (error: any) {
|
||||
logError(`SFTP connect failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SFTP list directory
|
||||
ipcMain.handle(SFTP_CHANNELS.LIST_DIRECTORY, async (_event: IpcMainInvokeEvent, sftpId: string, dirPath: string) => {
|
||||
logHeader('📁 SFTP IPC LIST')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('dirPath', dirPath)
|
||||
|
||||
try {
|
||||
const files = await sshService.sftpListDirectory(sftpId, dirPath)
|
||||
logSuccess(`Listed ${files.length} items`)
|
||||
return { success: true, files }
|
||||
} catch (error: any) {
|
||||
logError(`List failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SFTP upload file
|
||||
ipcMain.handle(SFTP_CHANNELS.UPLOAD, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
sftpId: string,
|
||||
localPath: string,
|
||||
remotePath: string
|
||||
) => {
|
||||
logHeader('📤 SFTP IPC UPLOAD')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('localPath', localPath)
|
||||
logInfo('remotePath', remotePath)
|
||||
|
||||
try {
|
||||
const mainWindow = mainWindowGetter()
|
||||
await sshService.sftpUpload(sftpId, localPath, remotePath, (transferred, total) => {
|
||||
mainWindow?.webContents.send(SFTP_CHANNELS.PROGRESS, sftpId, {
|
||||
transferred,
|
||||
total,
|
||||
percentage: Math.round((transferred / total) * 100),
|
||||
})
|
||||
})
|
||||
logSuccess('Upload complete')
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
logError(`Upload failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SFTP download file
|
||||
ipcMain.handle(SFTP_CHANNELS.DOWNLOAD, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
sftpId: string,
|
||||
remotePath: string,
|
||||
localPath: string
|
||||
) => {
|
||||
logHeader('📥 SFTP IPC DOWNLOAD')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('remotePath', remotePath)
|
||||
logInfo('localPath', localPath)
|
||||
|
||||
try {
|
||||
const mainWindow = mainWindowGetter()
|
||||
await sshService.sftpDownload(sftpId, remotePath, localPath, (transferred, total) => {
|
||||
mainWindow?.webContents.send(SFTP_CHANNELS.PROGRESS, sftpId, {
|
||||
transferred,
|
||||
total,
|
||||
percentage: Math.round((transferred / total) * 100),
|
||||
})
|
||||
})
|
||||
logSuccess('Download complete')
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
logError(`Download failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SFTP rename
|
||||
ipcMain.handle(SFTP_CHANNELS.RENAME, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
sftpId: string,
|
||||
oldPath: string,
|
||||
newPath: string
|
||||
) => {
|
||||
logHeader('📁 SFTP IPC RENAME')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('oldPath', oldPath)
|
||||
logInfo('newPath', newPath)
|
||||
|
||||
try {
|
||||
await sshService.sftpRename(sftpId, oldPath, newPath)
|
||||
logSuccess('Rename complete')
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
logError(`Rename failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SFTP delete
|
||||
ipcMain.handle(SFTP_CHANNELS.DELETE, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
sftpId: string,
|
||||
filePath: string,
|
||||
isDirectory: boolean
|
||||
) => {
|
||||
logHeader('📁 SFTP IPC DELETE')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('filePath', filePath)
|
||||
logInfo('isDirectory', isDirectory)
|
||||
|
||||
try {
|
||||
await sshService.sftpDelete(sftpId, filePath, isDirectory)
|
||||
logSuccess('Delete complete')
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
logError(`Delete failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SFTP mkdir
|
||||
ipcMain.handle(SFTP_CHANNELS.MKDIR, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
sftpId: string,
|
||||
dirPath: string
|
||||
) => {
|
||||
logHeader('📁 SFTP IPC MKDIR')
|
||||
logInfo('sftpId', sftpId)
|
||||
logInfo('dirPath', dirPath)
|
||||
|
||||
try {
|
||||
await sshService.sftpMkdir(sftpId, dirPath)
|
||||
logSuccess('Mkdir complete')
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
logError(`Mkdir failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* SSH IPC Handlers
|
||||
* 处理 SSH 连接、Shell、会话、端口转发相关 IPC
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent } from 'electron'
|
||||
import type { SSHService } from '../services/ssh-service'
|
||||
import type { ZmodemService } from '../services/zmodem-service'
|
||||
import { createLogger } from '../utils/logger'
|
||||
|
||||
const logger = createLogger('SSH_IPC')
|
||||
|
||||
// ===== 彩色调试日志 =====
|
||||
const DEBUG = true
|
||||
function debug(...args: any[]) {
|
||||
if (DEBUG) console.log('[SSH_IPC]', ...args)
|
||||
}
|
||||
function logHeader(msg: string) {
|
||||
console.log(`%c${msg}`, 'background: #9b59b6; 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;')
|
||||
}
|
||||
|
||||
// IPC channel names
|
||||
export const SSH_CHANNELS = {
|
||||
CONNECT: 'ssh:connect',
|
||||
DISCONNECT: 'ssh:disconnect',
|
||||
EXEC: 'ssh:exec',
|
||||
CREATE_SHELL: 'ssh:createShell',
|
||||
SHELL_WRITE: 'ssh:shellWrite',
|
||||
SHELL_RESIZE: 'ssh:shellResize',
|
||||
FORWARD_LOCAL: 'ssh:forwardLocal',
|
||||
FORWARD_REMOTE: 'ssh:forwardRemote',
|
||||
FORWARD_DYNAMIC: 'ssh:forwardDynamic',
|
||||
SHELL_DATA: 'ssh:shellData',
|
||||
} as const
|
||||
|
||||
export interface SSHIPCOptions {
|
||||
sshService: SSHService
|
||||
zmodemService: ZmodemService
|
||||
mainWindowGetter: () => Electron.BrowserWindow | null
|
||||
}
|
||||
|
||||
export function registerSSHIPCHandlers(options: SSHIPCOptions): void {
|
||||
const { sshService, zmodemService, mainWindowGetter } = options
|
||||
|
||||
// SSH connect
|
||||
ipcMain.handle(SSH_CHANNELS.CONNECT, async (_event: IpcMainInvokeEvent, config) => {
|
||||
try {
|
||||
const connection = await sshService.connect(config)
|
||||
return { success: true, connectionId: connection.id }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH disconnect
|
||||
ipcMain.handle(SSH_CHANNELS.DISCONNECT, async (_event: IpcMainInvokeEvent, connectionId: string) => {
|
||||
try {
|
||||
await sshService.disconnect(connectionId)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH exec command
|
||||
ipcMain.handle(SSH_CHANNELS.EXEC, async (_event: IpcMainInvokeEvent, connectionId: string, command: string) => {
|
||||
try {
|
||||
const result = await sshService.exec(connectionId, command)
|
||||
return { success: true, result }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH create shell
|
||||
ipcMain.handle(SSH_CHANNELS.CREATE_SHELL, async (event: IpcMainInvokeEvent, connectionId: string, options?: { cols?: number; rows?: number }, shellId?: string) => {
|
||||
console.log('=== SSH_IPC CREATE_SHELL ===')
|
||||
console.log(' connectionId:', connectionId)
|
||||
console.log(' options:', options)
|
||||
console.log(' preferredShellId:', shellId)
|
||||
|
||||
try {
|
||||
const preferredShellId = shellId
|
||||
logger.info('[SSH_IPC] Creating shell for connection:', connectionId, 'preferredId:', preferredShellId)
|
||||
debug('>>> Calling sshService.createShell...')
|
||||
|
||||
const shell = await sshService.createShell(connectionId, options || {}, (shellId, data) => {
|
||||
// 检查 sender 是否已被销毁
|
||||
if (event.sender.isDestroyed()) {
|
||||
console.log('=== SHELL DATA CALLBACK - SKIPPED (sender destroyed) ===')
|
||||
return
|
||||
}
|
||||
|
||||
const text = data.toString('utf-8')
|
||||
console.log('=== SHELL DATA CALLBACK ===')
|
||||
console.log(' shellId:', shellId)
|
||||
console.log(' data length:', data.length)
|
||||
console.log(' data preview:', text.substring(0, 100).replace(/\n/g, '\\n'))
|
||||
|
||||
// 打印所有收到的数据前100字符用于调试
|
||||
if (text.length > 0) {
|
||||
logger.info(`[SSH_IPC] Shell data from ${shellId}:`, text.substring(0, 100).replace(/\n/g, '\\n'))
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('>>> Sending SHELL_DATA to renderer...')
|
||||
event.sender.send(SSH_CHANNELS.SHELL_DATA, connectionId, shellId, data)
|
||||
console.log('>>> SHELL_DATA sent successfully')
|
||||
} catch (err) {
|
||||
console.error('>>> FAILED to send SHELL_DATA:', err)
|
||||
}
|
||||
|
||||
zmodemService.feedShellData(shellId, data)
|
||||
}, preferredShellId)
|
||||
|
||||
logger.info('[SSH_IPC] Shell created:', shell.id)
|
||||
debug('>>> Shell created successfully:', shell.id)
|
||||
return { success: true, shellId: shell.id }
|
||||
} catch (error: any) {
|
||||
logger.error('[SSH_IPC] Shell creation failed:', error)
|
||||
debug('>>> Shell creation FAILED:', error.message)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH shell write
|
||||
ipcMain.handle(SSH_CHANNELS.SHELL_WRITE, async (_event: IpcMainInvokeEvent, shellId: string, data: string) => {
|
||||
try {
|
||||
sshService.shellWrite(shellId, data)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH shell resize
|
||||
ipcMain.handle(SSH_CHANNELS.SHELL_RESIZE, async (_event: IpcMainInvokeEvent, shellId: string, cols: number, rows: number) => {
|
||||
try {
|
||||
sshService.shellResize(shellId, cols, rows)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH local port forward
|
||||
ipcMain.handle(SSH_CHANNELS.FORWARD_LOCAL, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
connectionId: string,
|
||||
localPort: number,
|
||||
remoteHost: string,
|
||||
remotePort: number
|
||||
) => {
|
||||
logHeader('🔀 IPC FORWARD_LOCAL')
|
||||
logInfo('connectionId', connectionId)
|
||||
logInfo('localPort', localPort)
|
||||
logInfo('remoteHost', remoteHost)
|
||||
logInfo('remotePort', remotePort)
|
||||
|
||||
try {
|
||||
const result = await sshService.forwardLocal(connectionId, localPort, remoteHost, remotePort)
|
||||
logSuccess(`Local forward bound to port ${result.boundPort}`)
|
||||
return { success: true, boundPort: result.boundPort }
|
||||
} catch (error: any) {
|
||||
logError(`Local forward failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH remote port forward
|
||||
ipcMain.handle(SSH_CHANNELS.FORWARD_REMOTE, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
connectionId: string,
|
||||
remotePort: number,
|
||||
localHost: string,
|
||||
localPort: number
|
||||
) => {
|
||||
logHeader('🔀 IPC FORWARD_REMOTE')
|
||||
logInfo('connectionId', connectionId)
|
||||
logInfo('remotePort', remotePort)
|
||||
logInfo('localHost', localHost)
|
||||
logInfo('localPort', localPort)
|
||||
|
||||
try {
|
||||
const result = await sshService.forwardRemote(connectionId, remotePort, localHost, localPort)
|
||||
logSuccess('Remote forward established')
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
logError(`Remote forward failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// SSH dynamic port forward (SOCKS5)
|
||||
ipcMain.handle(SSH_CHANNELS.FORWARD_DYNAMIC, async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
connectionId: string,
|
||||
localPort: number
|
||||
) => {
|
||||
logHeader('🧦 IPC FORWARD_DYNAMIC (SOCKS5)')
|
||||
logInfo('connectionId', connectionId)
|
||||
logInfo('localPort', localPort)
|
||||
|
||||
try {
|
||||
const result = await sshService.forwardDynamic(connectionId, localPort)
|
||||
logSuccess(`SOCKS5 proxy started on port ${result.boundPort}`)
|
||||
return { success: true, boundPort: result.boundPort }
|
||||
} catch (error: any) {
|
||||
logError(`Dynamic forward failed: ${error.message}`)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Zmodem IPC Handlers
|
||||
* 处理 rz/sz 文件传输
|
||||
*/
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent, app, dialog } from 'electron'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import type { SSHService } from '../services/ssh-service'
|
||||
import type { ZmodemService } from '../services/zmodem-service'
|
||||
import { createLogger } from '../utils/logger'
|
||||
|
||||
const logger = createLogger('Zmodem_IPC')
|
||||
|
||||
// IPC channel names
|
||||
export const ZMODEM_CHANNELS = {
|
||||
SEND: 'zmodem:send',
|
||||
RECEIVE: 'zmodem:receive',
|
||||
CANCEL: 'zmodem:cancel',
|
||||
PROGRESS: 'zmodem:progress',
|
||||
COMPLETE: 'zmodem:complete',
|
||||
} as const
|
||||
|
||||
export interface ZmodemIPCOptions {
|
||||
sshService: SSHService
|
||||
zmodemService: ZmodemService
|
||||
mainWindowGetter: () => Electron.BrowserWindow | null
|
||||
}
|
||||
|
||||
export function registerZmodemIPCHandlers(options: ZmodemIPCOptions): void {
|
||||
const { sshService, zmodemService, mainWindowGetter } = options
|
||||
|
||||
// Zmodem send (rz) - send file to server
|
||||
ipcMain.handle(ZMODEM_CHANNELS.SEND, async (_event: IpcMainInvokeEvent, shellId: string) => {
|
||||
try {
|
||||
const mainWindow = mainWindowGetter()
|
||||
if (!mainWindow) {
|
||||
return { success: false, error: 'Window not available' }
|
||||
}
|
||||
|
||||
// Open file dialog to select file
|
||||
const result = await dialog.showOpenDialog(mainWindow, {
|
||||
title: '选择要发送的文件',
|
||||
properties: ['openFile'],
|
||||
})
|
||||
|
||||
if (result.canceled || !result.filePaths.length) {
|
||||
return { success: false, canceled: true }
|
||||
}
|
||||
|
||||
const filePath = result.filePaths[0]
|
||||
const fileName = path.basename(filePath)
|
||||
|
||||
// Read file
|
||||
const fileData = fs.readFileSync(filePath)
|
||||
|
||||
// Get shell write function
|
||||
const shell = sshService.getShell(shellId)
|
||||
if (!shell) {
|
||||
return { success: false, error: 'Shell not found' }
|
||||
}
|
||||
|
||||
// Send file via Zmodem protocol
|
||||
const sessionId = zmodemService.sendFile(
|
||||
shellId,
|
||||
fileName,
|
||||
fileData,
|
||||
(data) => {
|
||||
shell.channel.write(data)
|
||||
},
|
||||
(progress) => {
|
||||
mainWindow.webContents.send(ZMODEM_CHANNELS.PROGRESS, sessionId, progress)
|
||||
},
|
||||
(success, error) => {
|
||||
mainWindow.webContents.send(ZMODEM_CHANNELS.COMPLETE, sessionId, { success, error })
|
||||
}
|
||||
)
|
||||
|
||||
return { success: true, sessionId, fileName }
|
||||
} catch (error: any) {
|
||||
logger.error('Zmodem send error:', error)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Zmodem receive (sz) - receive file from server
|
||||
ipcMain.handle(ZMODEM_CHANNELS.RECEIVE, async (_event: IpcMainInvokeEvent, shellId: string) => {
|
||||
try {
|
||||
const mainWindow = mainWindowGetter()
|
||||
if (!mainWindow) {
|
||||
return { success: false, error: 'Window not available' }
|
||||
}
|
||||
|
||||
// Get shell to monitor for incoming data
|
||||
const shell = sshService.getShell(shellId)
|
||||
if (!shell) {
|
||||
return { success: false, error: 'Shell not found' }
|
||||
}
|
||||
|
||||
// Open save dialog to select destination
|
||||
const result = await dialog.showSaveDialog(mainWindow, {
|
||||
title: '保存文件',
|
||||
defaultPath: app.getPath('downloads'),
|
||||
})
|
||||
|
||||
if (result.canceled || !result.filePath) {
|
||||
return { success: false, canceled: true }
|
||||
}
|
||||
|
||||
// Start Zmodem receive session
|
||||
const sessionId = zmodemService.receiveFile(
|
||||
shellId,
|
||||
result.filePath,
|
||||
(data) => {
|
||||
shell.channel.write(data)
|
||||
},
|
||||
(progress) => {
|
||||
mainWindow.webContents.send(ZMODEM_CHANNELS.PROGRESS, sessionId, progress)
|
||||
},
|
||||
(success, error) => {
|
||||
mainWindow.webContents.send(ZMODEM_CHANNELS.COMPLETE, sessionId, { success, error })
|
||||
}
|
||||
)
|
||||
|
||||
return { success: true, sessionId }
|
||||
} catch (error: any) {
|
||||
logger.error('Zmodem receive error:', error)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
// Zmodem cancel transfer
|
||||
ipcMain.handle(ZMODEM_CHANNELS.CANCEL, async (_event: IpcMainInvokeEvent, sessionId: string) => {
|
||||
try {
|
||||
zmodemService.cancelSession(sessionId)
|
||||
return { success: true }
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* OpsXShell - Main Process Entry
|
||||
* 跨平台 SSH/SFTP 终端工具 · 简洁高效 · 安全可靠
|
||||
*/
|
||||
|
||||
import { app, BrowserWindow, Menu, shell, dialog } from 'electron'
|
||||
import path from 'path'
|
||||
import { createLogger } from './utils/logger'
|
||||
|
||||
const logger = createLogger('Main')
|
||||
|
||||
// Services
|
||||
import { SSHService } from './services/ssh-service'
|
||||
import { DatabaseService } from './services/database-service'
|
||||
import { keyService } from './services/key-service'
|
||||
import { ZmodemService } from './services/zmodem-service'
|
||||
|
||||
// IPC Handlers
|
||||
import { registerAllIPCHandlers } from './ipc'
|
||||
|
||||
// ============== Global State ==============
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
|
||||
// Services (initialized after app ready)
|
||||
let sshService: SSHService
|
||||
let zmodemService: ZmodemService
|
||||
let dbService: DatabaseService | null = null
|
||||
|
||||
// ============== Window Management ==============
|
||||
|
||||
function createWindow(): void {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1400,
|
||||
height: 900,
|
||||
minWidth: 1000,
|
||||
minHeight: 600,
|
||||
titleBarStyle: 'hiddenInset',
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: false,
|
||||
},
|
||||
show: false,
|
||||
backgroundColor: '#0f172a',
|
||||
})
|
||||
|
||||
// Load the app
|
||||
if (process.env.VITE_DEV_SERVER_URL) {
|
||||
mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
|
||||
// DevTools 通过快捷键 Cmd+Option+I 打开,不自动调用
|
||||
} else {
|
||||
mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
|
||||
}
|
||||
|
||||
// Show window when ready
|
||||
mainWindow.once('ready-to-show', () => {
|
||||
mainWindow?.show()
|
||||
})
|
||||
|
||||
// Handle window closed
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null
|
||||
})
|
||||
|
||||
// Open external links in browser
|
||||
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url)
|
||||
return { action: 'deny' }
|
||||
})
|
||||
|
||||
// Set up application menu
|
||||
createApplicationMenu()
|
||||
}
|
||||
|
||||
// ============== Application Menu ==============
|
||||
|
||||
function createApplicationMenu(): void {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [
|
||||
{
|
||||
label: 'OpsXShell',
|
||||
submenu: [
|
||||
{
|
||||
label: '关于 OpsXShell',
|
||||
click: () => {
|
||||
dialog.showMessageBox(mainWindow!, {
|
||||
type: 'info',
|
||||
title: '关于 OpsXShell',
|
||||
message: 'OpsXShell v1.0.0',
|
||||
detail: '跨平台 SSH/SFTP 终端工具 · 简洁高效 · 安全可靠\n\nMIT License',
|
||||
})
|
||||
},
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '退出',
|
||||
accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
|
||||
click: () => {
|
||||
app.quit()
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '会话',
|
||||
submenu: [
|
||||
{
|
||||
label: '新建会话',
|
||||
accelerator: 'CmdOrCtrl+N',
|
||||
click: () => {
|
||||
mainWindow?.webContents.send('menu-new-session')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '快速连接',
|
||||
accelerator: 'CmdOrCtrl+K',
|
||||
click: () => {
|
||||
mainWindow?.webContents.send('menu-quick-connect')
|
||||
},
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '导入会话',
|
||||
click: () => {
|
||||
mainWindow?.webContents.send('menu-import-sessions')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '导出会话',
|
||||
click: () => {
|
||||
mainWindow?.webContents.send('menu-export-sessions')
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '编辑',
|
||||
submenu: [
|
||||
{ role: 'undo' },
|
||||
{ role: 'redo' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'cut' },
|
||||
{ role: 'copy' },
|
||||
{ role: 'paste' },
|
||||
{ role: 'selectAll' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '视图',
|
||||
submenu: [
|
||||
{
|
||||
label: '重新加载',
|
||||
accelerator: 'CmdOrCtrl+R',
|
||||
click: () => {
|
||||
mainWindow?.webContents.reload()
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '切换开发者工具',
|
||||
accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'F12',
|
||||
click: () => {
|
||||
mainWindow?.webContents.toggleDevTools()
|
||||
},
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ role: 'resetZoom' },
|
||||
{ role: 'zoomIn' },
|
||||
{ role: 'zoomOut' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'togglefullscreen' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '窗口',
|
||||
submenu: [
|
||||
{ role: 'minimize' },
|
||||
{ role: 'close' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '帮助',
|
||||
submenu: [
|
||||
{
|
||||
label: '文档',
|
||||
click: () => {
|
||||
shell.openExternal('https://github.com/opsxshell/docs')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '报告问题',
|
||||
click: () => {
|
||||
shell.openExternal('https://github.com/opsxshell/issues')
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const menu = Menu.buildFromTemplate(template)
|
||||
Menu.setApplicationMenu(menu)
|
||||
}
|
||||
|
||||
// ============== App Lifecycle ==============
|
||||
|
||||
app.whenReady().then(() => {
|
||||
// Initialize encryption key first
|
||||
keyService.getMasterKey()
|
||||
logger.info('[App] Encryption key initialized')
|
||||
|
||||
// Initialize services
|
||||
sshService = new SSHService()
|
||||
zmodemService = new ZmodemService()
|
||||
dbService = new DatabaseService()
|
||||
dbService.initialize()
|
||||
|
||||
// Register IPC handlers
|
||||
registerAllIPCHandlers({
|
||||
sshService,
|
||||
databaseService: dbService,
|
||||
zmodemService,
|
||||
mainWindowGetter: () => mainWindow,
|
||||
})
|
||||
logger.info('[App] IPC handlers registered')
|
||||
|
||||
// Create main window
|
||||
createWindow()
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
// Close all SSH connections
|
||||
sshService?.disconnectAll()
|
||||
|
||||
// Close database
|
||||
dbService?.close()
|
||||
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
}
|
||||
})
|
||||
|
||||
app.on('before-quit', () => {
|
||||
sshService?.disconnectAll()
|
||||
dbService?.close()
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron')
|
||||
|
||||
// 暴露 API 到渲染进程
|
||||
const api = {
|
||||
// SSH 相关
|
||||
sshConnect: (config: any) => ipcRenderer.invoke('ssh:connect', config),
|
||||
sshDisconnect: (connectionId: string) => ipcRenderer.invoke('ssh:disconnect', connectionId),
|
||||
sshExec: (connectionId: string, command: string) => ipcRenderer.invoke('ssh:exec', connectionId, command),
|
||||
sshCreateShell: (connectionId: string, options?: any, shellId?: string) => ipcRenderer.invoke('ssh:createShell', connectionId, options, shellId),
|
||||
sshShellWrite: (shellId: string, data: string | Uint8Array) => ipcRenderer.invoke('ssh:shellWrite', shellId, data),
|
||||
sshShellResize: (shellId: string, cols: number, rows: number) => ipcRenderer.invoke('ssh:shellResize', shellId, cols, rows),
|
||||
|
||||
// 会话管理
|
||||
sessionGetAll: () => ipcRenderer.invoke('session:getAll'),
|
||||
sessionGetById: (id: string) => ipcRenderer.invoke('session:getById', id),
|
||||
sessionCreate: (session: any) => ipcRenderer.invoke('session:create', session),
|
||||
sessionUpdate: (id: string, updates: any) => ipcRenderer.invoke('session:update', id, updates),
|
||||
sessionDelete: (id: string) => ipcRenderer.invoke('session:delete', id),
|
||||
|
||||
// SFTP
|
||||
sftpConnect: (connectionId: string) => ipcRenderer.invoke('sftp:connect', connectionId),
|
||||
sftpListDirectory: (sftpId: string, path: string) => ipcRenderer.invoke('sftp:listDirectory', sftpId, path),
|
||||
sftpUpload: (sftpId: string, localPath: string, remotePath: string) => ipcRenderer.invoke('sftp:upload', sftpId, localPath, remotePath),
|
||||
sftpDownload: (sftpId: string, remotePath: string, localPath: string) => ipcRenderer.invoke('sftp:download', sftpId, remotePath, localPath),
|
||||
sftpRename: (sftpId: string, oldPath: string, newPath: string) => ipcRenderer.invoke('sftp:rename', sftpId, oldPath, newPath),
|
||||
sftpDelete: (sftpId: string, path: string, isDirectory: boolean) => ipcRenderer.invoke('sftp:delete', sftpId, path, isDirectory),
|
||||
sftpMkdir: (sftpId: string, path: string) => ipcRenderer.invoke('sftp:mkdir', sftpId, path),
|
||||
|
||||
// 端口转发
|
||||
sshForwardLocal: (connectionId: string, localPort: number, remoteHost: string, remotePort: number) =>
|
||||
ipcRenderer.invoke('ssh:forwardLocal', connectionId, localPort, remoteHost, remotePort),
|
||||
sshForwardRemote: (connectionId: string, remotePort: number, localHost: string, localPort: number) =>
|
||||
ipcRenderer.invoke('ssh:forwardRemote', connectionId, remotePort, localHost, localPort),
|
||||
sshForwardDynamic: (connectionId: string, localPort: number) =>
|
||||
ipcRenderer.invoke('ssh:forwardDynamic', connectionId, localPort),
|
||||
|
||||
// 设置
|
||||
settingsGet: (key: string) => ipcRenderer.invoke('settings:get', key),
|
||||
settingsSet: (key: string, value: any) => ipcRenderer.invoke('settings:set', key, value),
|
||||
|
||||
// 对话框
|
||||
showSaveDialog: (options: any) => ipcRenderer.invoke('dialog:showSaveDialog', options),
|
||||
showOpenDialog: (options: any) => ipcRenderer.invoke('dialog:showOpenDialog', options),
|
||||
|
||||
// 文件操作
|
||||
readFile: (filePath: string) => ipcRenderer.invoke('file:read', filePath),
|
||||
writeFile: (filePath: string, data: string) => ipcRenderer.invoke('file:write', filePath, data),
|
||||
|
||||
// 本地文件系统
|
||||
getHomePath: () => ipcRenderer.invoke('local:getHome'),
|
||||
getDownloadsPath: () => ipcRenderer.invoke('app:getDownloadsPath'),
|
||||
localReadDir: (dirPath: string) => ipcRenderer.invoke('local:readDir', dirPath),
|
||||
localGetStats: (filePath: string) => ipcRenderer.invoke('local:getStats', filePath),
|
||||
localDelete: (filePath: string) => ipcRenderer.invoke('local:delete', filePath),
|
||||
localRename: (oldPath: string, newPath: string) => ipcRenderer.invoke('local:rename', oldPath, newPath),
|
||||
localMkdir: (dirPath: string) => ipcRenderer.invoke('local:mkdir', dirPath),
|
||||
|
||||
// Zmodem rz/sz
|
||||
zmodemSend: (shellId: string) => ipcRenderer.invoke('zmodem:send', shellId),
|
||||
zmodemReceive: (shellId: string) => ipcRenderer.invoke('zmodem:receive', shellId),
|
||||
zmodemCancel: (sessionId: string) => ipcRenderer.invoke('zmodem:cancel', sessionId),
|
||||
|
||||
// Zmodem events
|
||||
onZmodemProgress: (callback: (event: any, sessionId: string, progress: any) => void) => {
|
||||
ipcRenderer.on('zmodem:progress', callback)
|
||||
},
|
||||
onZmodemComplete: (callback: (event: any, sessionId: string, result: any) => void) => {
|
||||
ipcRenderer.on('zmodem:complete', callback)
|
||||
},
|
||||
|
||||
// 应用信息
|
||||
getVersion: () => ipcRenderer.invoke('app:getVersion'),
|
||||
|
||||
// 事件监听
|
||||
onMenuNewSession: (callback: () => void) => {
|
||||
ipcRenderer.on('menu-new-session', callback)
|
||||
},
|
||||
onMenuQuickConnect: (callback: () => void) => {
|
||||
ipcRenderer.on('menu-quick-connect', callback)
|
||||
},
|
||||
onMenuImportSessions: (callback: () => void) => {
|
||||
ipcRenderer.on('menu-import-sessions', callback)
|
||||
},
|
||||
onMenuExportSessions: (callback: () => void) => {
|
||||
ipcRenderer.on('menu-export-sessions', callback)
|
||||
},
|
||||
onShellData: (callback: (event: any, connectionId: string, shellId: string, data: Buffer) => void) => {
|
||||
ipcRenderer.on('ssh:shellData', callback)
|
||||
},
|
||||
onSFTPProgress: (callback: (event: any, sftpId: string, progress: any) => void) => {
|
||||
ipcRenderer.on('sftp:progress', callback)
|
||||
},
|
||||
removeListener: (channel: string, callback: (...args: any[]) => void) => {
|
||||
ipcRenderer.removeListener(channel, callback)
|
||||
},
|
||||
removeAllListeners: (channel: string) => {
|
||||
ipcRenderer.removeAllListeners(channel)
|
||||
}
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', api)
|
||||
@@ -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()
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"outDir": "../dist-electron",
|
||||
"rootDir": ".",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node"
|
||||
},
|
||||
"include": ["./**/*"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Electron 主进程日志工具
|
||||
*
|
||||
* 简化版,直接输出到控制台
|
||||
*/
|
||||
|
||||
export enum LogLevel {
|
||||
DEBUG = 0,
|
||||
INFO = 1,
|
||||
WARN = 2,
|
||||
ERROR = 3,
|
||||
}
|
||||
|
||||
const LOG_LEVEL = process.env.NODE_ENV === 'production' ? LogLevel.INFO : LogLevel.DEBUG
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return level >= LOG_LEVEL
|
||||
}
|
||||
|
||||
function formatMessage(level: string, module: string, message: string): string {
|
||||
const timestamp = new Date().toISOString()
|
||||
return `[${timestamp}] [${level}] [${module}] ${message}`
|
||||
}
|
||||
|
||||
export function createLogger(module: string) {
|
||||
return {
|
||||
debug: (message: string, ...args: unknown[]) => {
|
||||
if (!shouldLog(LogLevel.DEBUG)) return
|
||||
console.debug(formatMessage('DEBUG', module, message), ...args)
|
||||
},
|
||||
info: (message: string, ...args: unknown[]) => {
|
||||
if (!shouldLog(LogLevel.INFO)) return
|
||||
console.info(formatMessage('INFO', module, message), ...args)
|
||||
},
|
||||
warn: (message: string, ...args: unknown[]) => {
|
||||
if (!shouldLog(LogLevel.WARN)) return
|
||||
console.warn(formatMessage('WARN', module, message), ...args)
|
||||
},
|
||||
error: (message: string, ...args: unknown[]) => {
|
||||
if (!shouldLog(LogLevel.ERROR)) return
|
||||
console.error(formatMessage('ERROR', module, message), ...args)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const logger = createLogger('Main')
|
||||
Reference in new issue
Block a user