diff --git a/packages/backend/src/database/connection.ts b/packages/backend/src/database/connection.ts index 16c80ac..b084560 100644 --- a/packages/backend/src/database/connection.ts +++ b/packages/backend/src/database/connection.ts @@ -3,7 +3,7 @@ import sqlite3, { OPEN_READWRITE, OPEN_CREATE } from 'sqlite3'; import path from 'path'; import fs from 'fs'; import { tableDefinitions } from './schema.registry'; - +import { runMigrations } from './migrations'; // +++ Import runMigrations +++ const dbDir = path.join(__dirname, '..', '..', 'data'); const dbFilename = 'nexus-terminal.db'; @@ -103,7 +103,11 @@ export const getDbInstance = (): Promise => { try { + // 运行初始表创建 await runDatabaseInitializations(db); + // +++ 运行数据库迁移 +++ + await runMigrations(db); + console.log('[数据库] 初始化和迁移完成。'); // 添加日志确认 resolve(db); } catch (initError) { console.error('[数据库] 连接后初始化失败,正在关闭连接...'); diff --git a/packages/backend/src/database/migrations.ts b/packages/backend/src/database/migrations.ts index 55eb0f8..213d5ce 100644 --- a/packages/backend/src/database/migrations.ts +++ b/packages/backend/src/database/migrations.ts @@ -1,17 +1,162 @@ import { Database } from 'sqlite3'; +// 1. 定义 migrations 表 SQL +const createMigrationsTableSQL = ` +CREATE TABLE IF NOT EXISTS migrations ( + id INTEGER PRIMARY KEY, -- 迁移的版本号 + name TEXT NOT NULL, -- 迁移的描述性名称 + applied_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) -- 应用迁移的时间戳 +); +`; + +// 2. 定义迁移列表 +// 注意:这里的迁移应该代表数据库模式从某个已知状态到下一个状态的变化。 +// 初始模式通常在 database.ts 中通过 schema.registry.ts 创建。 +// 这里的迁移应该从版本 1 开始,代表初始模式创建后的第一个变更。 +interface Migration { + id: number; + name: string; + sql: string; // 可以是多条 SQL 语句,用 ; 分隔。db.exec 会处理。 +} + +const definedMigrations: Migration[] = [ + { + id: 1, + name: 'Add ssh_keys table and update connections table for SSH key management', + sql: ` + -- 创建 ssh_keys 表 + CREATE TABLE IF NOT EXISTS ssh_keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + encrypted_private_key TEXT NOT NULL, + encrypted_passphrase TEXT NULL, + created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), + updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) + ); + + -- 修改 connections 表,添加 ssh_key_id 列和外键约束 + -- 注意:如果 connections 表已存在且没有该列,则添加列。 + -- SQLite 的 ALTER TABLE 功能有限,如果表已存在,直接添加带外键的列可能不完全生效或报错。 + -- 但如果表是新创建的(通过 schema.ts),则外键会生效。 + -- 这里我们尝试添加列并定义引用,对于新数据库是安全的。 + -- 对于已存在的旧数据库,可能需要更复杂的迁移(重命名旧表,创建新表,复制数据)。 + -- 为简化起见,我们先执行添加列的操作。 + ALTER TABLE connections ADD COLUMN ssh_key_id INTEGER NULL REFERENCES ssh_keys(id) ON DELETE SET NULL; + + -- 可选:如果旧的 connections 表没有将 private_key/passphrase 设为 NULL,可以在此更新 + -- UPDATE connections SET encrypted_private_key = NULL WHERE encrypted_private_key = ''; -- 示例 + -- UPDATE connections SET encrypted_passphrase = NULL WHERE encrypted_passphrase = ''; -- 示例 + ` + }, + // --- 未来可以添加更多迁移 --- + // { id: 2, name: '...', sql: '...' }, +]; /** * 运行数据库迁移。 - * 注意:此函数目前为空,仅作为未来迁移的占位符。 - * 数据库的初始模式创建在 database.ts 的初始化逻辑中处理。 + * 检查当前数据库版本,并按顺序应用所有新的迁移。 * @param db 数据库实例 */ export const runMigrations = (db: Database): Promise => { - return new Promise((resolve) => { - console.log('[Migrations] 检查数据库迁移(当前无操作)。'); - resolve(); + return new Promise((resolve, reject) => { + console.log('[Migrations] 开始检查和应用数据库迁移...'); + + db.serialize(() => { + // 步骤 1: 确保 migrations 表存在 + db.run(createMigrationsTableSQL, (err) => { + if (err) { + console.error('[Migrations] 创建 migrations 表失败:', err); + return reject(new Error(`创建 migrations 表失败: ${err.message}`)); + } + console.log('[Migrations] migrations 表已确保存在。'); + + // 步骤 2: 获取当前数据库版本 (已应用的最大迁移 ID) + db.get('SELECT MAX(id) as currentVersion FROM migrations', (err, row: { currentVersion: number | null }) => { + if (err) { + console.error('[Migrations] 查询当前数据库版本失败:', err); + return reject(new Error(`查询当前数据库版本失败: ${err.message}`)); + } + + const currentVersion = row?.currentVersion ?? 0; // 如果表为空或没有记录,则认为版本为 0 + console.log(`[Migrations] 当前数据库版本: ${currentVersion}`); + + // 步骤 3: 确定需要应用的迁移 + const migrationsToApply = definedMigrations + .filter(m => m.id > currentVersion) + .sort((a, b) => a.id - b.id); // 确保按 ID 升序应用 + + if (migrationsToApply.length === 0) { + console.log('[Migrations] 数据库已是最新版本,无需迁移。'); + return resolve(); + } + + console.log(`[Migrations] 发现 ${migrationsToApply.length} 个新迁移需要应用:`, migrationsToApply.map(m => ` #${m.id}: ${m.name}`)); + + // 步骤 4: 按顺序应用迁移 (每个迁移在一个事务中) + const applyNextMigration = (index: number) => { + if (index >= migrationsToApply.length) { + // 所有迁移成功应用 + console.log('[Migrations] 所有新迁移已成功应用!'); + return resolve(); + } + + const migration = migrationsToApply[index]; + console.log(`[Migrations] 应用迁移 #${migration.id}: ${migration.name}...`); + + // 开始事务 + db.run('BEGIN TRANSACTION', (beginErr) => { + if (beginErr) { + console.error(`[Migrations] 开始迁移 #${migration.id} 事务失败:`, beginErr); + return reject(new Error(`开始迁移 #${migration.id} 事务失败: ${beginErr.message}`)); + } + + // 执行迁移 SQL (db.exec 可以执行多条语句) + db.exec(migration.sql, (execErr) => { + if (execErr) { + console.error(`[Migrations] 执行迁移 #${migration.id} SQL 失败:`, execErr); + // 回滚事务 + db.run('ROLLBACK', (rollbackErr) => { + if (rollbackErr) console.error(`[Migrations] 回滚迁移 #${migration.id} 事务失败:`, rollbackErr); + reject(new Error(`执行迁移 #${migration.id} SQL 失败: ${execErr.message}`)); + }); + return; // 停止执行后续步骤 + } + + // SQL 执行成功,记录迁移到 migrations 表 + const insertSQL = 'INSERT INTO migrations (id, name, applied_at) VALUES (?, ?, strftime(\'%s\', \'now\'))'; + db.run(insertSQL, [migration.id, migration.name], (insertErr) => { + if (insertErr) { + console.error(`[Migrations] 记录迁移 #${migration.id} 到 migrations 表失败:`, insertErr); + // 回滚事务 + db.run('ROLLBACK', (rollbackErr) => { + if (rollbackErr) console.error(`[Migrations] 回滚迁移 #${migration.id} 事务失败:`, rollbackErr); + reject(new Error(`记录迁移 #${migration.id} 到 migrations 表失败: ${insertErr.message}`)); + }); + return; // 停止执行后续步骤 + } + + // 记录成功,提交事务 + db.run('COMMIT', (commitErr) => { + if (commitErr) { + console.error(`[Migrations] 提交迁移 #${migration.id} 事务失败:`, commitErr); + // 提交失败比较严重,可能需要手动检查数据库状态 + reject(new Error(`提交迁移 #${migration.id} 事务失败: ${commitErr.message}`)); + return; // 停止执行后续步骤 + } + + console.log(`[Migrations] 迁移 #${migration.id}: ${migration.name} 应用成功。`); + // 成功应用当前迁移,继续下一个 + applyNextMigration(index + 1); + }); + }); + }); + }); + }; + + // 开始应用第一个需要应用的迁移 + applyNextMigration(0); + }); + }); + }); }); }; - - diff --git a/packages/backend/src/database/schema.ts b/packages/backend/src/database/schema.ts index d1cc55d..ddd5ab4 100644 --- a/packages/backend/src/database/schema.ts +++ b/packages/backend/src/database/schema.ts @@ -85,10 +85,23 @@ CREATE TABLE IF NOT EXISTS connections ( encrypted_private_key TEXT NULL, encrypted_passphrase TEXT NULL, proxy_id INTEGER NULL, + ssh_key_id INTEGER NULL, -- 新增 ssh_key_id 列 created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), last_connected_at INTEGER NULL, - FOREIGN KEY (proxy_id) REFERENCES proxies(id) ON DELETE SET NULL + FOREIGN KEY (proxy_id) REFERENCES proxies(id) ON DELETE SET NULL, + FOREIGN KEY (ssh_key_id) REFERENCES ssh_keys(id) ON DELETE SET NULL -- 新增外键约束 +); +`; + +export const createSshKeysTableSQL = ` +CREATE TABLE IF NOT EXISTS ssh_keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + encrypted_private_key TEXT NOT NULL, + encrypted_passphrase TEXT NULL, + created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), + updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) ); `; diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index cb1510d..843d18b 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -20,6 +20,7 @@ import commandHistoryRoutes from './command-history/command-history.routes'; import quickCommandsRoutes from './quick-commands/quick-commands.routes'; import terminalThemeRoutes from './terminal-themes/terminal-theme.routes'; import appearanceRoutes from './appearance/appearance.routes'; +import sshKeysRouter from './ssh_keys/ssh_keys.routes'; // +++ Import SSH Key routes +++ import { initializeWebSocket } from './websocket'; import { ipWhitelistMiddleware } from './auth/ipWhitelist.middleware'; @@ -259,6 +260,7 @@ const startServer = () => { app.use('/api/v1/quick-commands', quickCommandsRoutes); app.use('/api/v1/terminal-themes', terminalThemeRoutes); app.use('/api/v1/appearance', appearanceRoutes); + app.use('/api/v1/ssh-keys', sshKeysRouter); // +++ Register SSH Key routes +++ // 状态检查接口 app.get('/api/v1/status', (req: Request, res: Response) => { diff --git a/packages/backend/src/repositories/connection.repository.ts b/packages/backend/src/repositories/connection.repository.ts index d10c6b3..017893a 100644 --- a/packages/backend/src/repositories/connection.repository.ts +++ b/packages/backend/src/repositories/connection.repository.ts @@ -39,7 +39,9 @@ export interface FullConnectionData extends ConnectionBase { // FullConnectionDbRow implicitly includes 'type' via FullConnectionData +// Also add ssh_key_id here as it's part of the connection record itself interface FullConnectionDbRow extends FullConnectionData { + ssh_key_id?: number | null; // +++ Add ssh_key_id +++ proxy_db_id: number | null; proxy_name: string | null; proxy_type: string | null; diff --git a/packages/backend/src/repositories/ssh_key.repository.ts b/packages/backend/src/repositories/ssh_key.repository.ts new file mode 100644 index 0000000..7b1a6f9 --- /dev/null +++ b/packages/backend/src/repositories/ssh_key.repository.ts @@ -0,0 +1,133 @@ +import { getDbInstance, runDb, getDb as getDbRow, allDb } from '../database/connection'; +import { Database, RunResult } from 'sqlite3'; // Import Database type if needed by helpers + +// 定义数据库行的接口 +export interface SshKeyDbRow { + id: number; + name: string; + encrypted_private_key: string; + encrypted_passphrase?: string | null; // 密码短语是可选的 + created_at: number; + updated_at: number; +} + +// 定义创建时需要的数据接口 (不包含 id, created_at, updated_at) +export type CreateSshKeyData = Omit; + +// 定义更新时需要的数据接口 (所有字段可选,除了 id) +export type UpdateSshKeyData = Partial>; + +/** + * 创建新的 SSH 密钥记录 + * @param data - 包含密钥名称和加密后凭证的对象 + * @returns Promise 新创建记录的 ID + */ +export const createSshKey = async (data: CreateSshKeyData): Promise => { + const sql = ` + INSERT INTO ssh_keys (name, encrypted_private_key, encrypted_passphrase, created_at, updated_at) + VALUES (?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')) + `; + const params = [data.name, data.encrypted_private_key, data.encrypted_passphrase ?? null]; + try { + const db = await getDbInstance(); + const result = await runDb(db, sql, params); + if (typeof result.lastID !== 'number' || result.lastID <= 0) { + throw new Error('创建 SSH 密钥后未能获取有效的 lastID'); + } + console.log(`Repository: SSH 密钥创建成功,ID: ${result.lastID}`); + return result.lastID; + } catch (err: any) { // Catch potential errors from helpers + console.error('Repository: 创建 SSH 密钥失败:', err.message); + throw new Error(`创建 SSH 密钥失败: ${err.message}`); + } +}; + +/** + * 根据 ID 查找 SSH 密钥 + * @param id - 密钥 ID + * @returns Promise 找到的密钥记录或 null + */ +export const findSshKeyById = async (id: number): Promise => { + const sql = `SELECT * FROM ssh_keys WHERE id = ?`; + try { + const db = await getDbInstance(); + const row = await getDbRow(db, sql, [id]); + return row || null; + } catch (err: any) { + console.error(`Repository: 查找 SSH 密钥 ${id} 失败:`, err.message); + throw new Error(`查找 SSH 密钥失败: ${err.message}`); + } +}; + +/** + * 查找所有 SSH 密钥 (只包含 id 和 name,用于列表显示) + * @returns Promise<{ id: number; name: string }[]> 密钥列表 + */ +export const findAllSshKeyNames = async (): Promise<{ id: number; name: string }[]> => { + const sql = `SELECT id, name FROM ssh_keys ORDER BY name ASC`; + try { + const db = await getDbInstance(); + const rows = await allDb<{ id: number; name: string }>(db, sql); + return rows; + } catch (err: any) { + console.error('Repository: 查找所有 SSH 密钥名称失败:', err.message); + throw new Error(`查找所有 SSH 密钥名称失败: ${err.message}`); + } +}; + + +/** + * 更新 SSH 密钥记录 + * @param id - 要更新的密钥 ID + * @param data - 包含要更新字段的对象 + * @returns Promise 是否更新成功 + */ +export const updateSshKey = async (id: number, data: UpdateSshKeyData): Promise => { + // 过滤掉 undefined 的值 + const fieldsToUpdate = Object.entries(data) + .filter(([_, value]) => value !== undefined) + .reduce((obj, [key, value]) => { + (obj as any)[key] = value; + return obj; + }, {} as { [key: string]: any }); // Type assertion for index signature + + if (Object.keys(fieldsToUpdate).length === 0) { + console.log(`Repository: 更新 SSH 密钥 ${id} 时没有提供有效字段。`); + return true; // 没有字段需要更新 + } + + // 添加 updated_at 时间戳 + fieldsToUpdate.updated_at = Math.floor(Date.now() / 1000); + + const setClause = Object.keys(fieldsToUpdate).map(field => `${field} = ?`).join(', '); + const values = Object.values(fieldsToUpdate).map(value => value ?? null); // 处理 null 值 + + const sql = `UPDATE ssh_keys SET ${setClause} WHERE id = ?`; + const params = [...values, id]; + + try { + const db = await getDbInstance(); + const result = await runDb(db, sql, params); + return result.changes > 0; // 如果有行被改变则返回 true + } catch (err: any) { + console.error(`Repository: 更新 SSH 密钥 ${id} 失败:`, err.message); + throw new Error(`更新 SSH 密钥失败: ${err.message}`); + } +}; + +/** + * 删除 SSH 密钥记录 + * @param id - 要删除的密钥 ID + * @returns Promise 是否删除成功 + */ +export const deleteSshKey = async (id: number): Promise => { + const sql = `DELETE FROM ssh_keys WHERE id = ?`; + try { + const db = await getDbInstance(); + const result = await runDb(db, sql, [id]); + return result.changes > 0; // 如果有行被删除则返回 true + } catch (err: any) { + console.error(`Repository: 删除 SSH 密钥 ${id} 失败:`, err.message); + throw new Error(`删除 SSH 密钥失败: ${err.message}`); + } +}; \ No newline at end of file diff --git a/packages/backend/src/services/connection.service.ts b/packages/backend/src/services/connection.service.ts index bd11866..bfa430c 100644 --- a/packages/backend/src/services/connection.service.ts +++ b/packages/backend/src/services/connection.service.ts @@ -1,6 +1,7 @@ import * as ConnectionRepository from '../repositories/connection.repository'; import { encrypt, decrypt } from '../utils/crypto'; -import { AuditLogService } from '../services/audit.service'; +import { AuditLogService } from './audit.service'; +import * as SshKeyService from './ssh_key.service'; // +++ Import SshKeyService +++ import { ConnectionBase, ConnectionWithTags, @@ -36,6 +37,9 @@ export const getConnectionById = async (id: number): Promise => { + // +++ Define a local type alias for clarity, including ssh_key_id +++ + type ConnectionDataForRepo = Omit; + console.log('[Service:createConnection] Received input:', JSON.stringify(input, null, 2)); // Log input // 1. 验证输入 (包含 type) // Convert type to uppercase for validation and consistency @@ -54,8 +58,12 @@ export const createConnection = async (input: CreateConnectionInput): Promise = { + // +++ Explicitly type connectionData using the local alias +++ + const connectionData: ConnectionDataForRepo = { name: input.name || '', - type: connectionType, // Use the validated uppercase type + type: connectionType, host: input.host, port: input.port ?? defaultPort, // Use type-specific default port username: input.username, auth_method: authMethodForDb, // Use determined auth method encrypted_password: encryptedPassword, - encrypted_private_key: encryptedPrivateKey, // Will be null for RDP - encrypted_passphrase: encryptedPassphrase, // Will be null for RDP + encrypted_private_key: encryptedPrivateKey, // Null if using ssh_key_id or RDP + encrypted_passphrase: encryptedPassphrase, // Null if using ssh_key_id or RDP + ssh_key_id: sshKeyIdToSave, // +++ Add ssh_key_id +++ proxy_id: input.proxy_id ?? null, }; - console.log('[Service:createConnection] Data to be saved:', JSON.stringify(connectionData, null, 2)); // Log data before saving + // Remove ssh_key_id property if it's null before logging/saving if repository expects exact type match without optional nulls + const finalConnectionData = { ...connectionData }; + if (finalConnectionData.ssh_key_id === null) { + delete (finalConnectionData as any).ssh_key_id; // Adjust based on repository function signature if needed + } + console.log('[Service:createConnection] Data to be saved:', JSON.stringify(finalConnectionData, null, 2)); // Log data before saving // 4. 在仓库中创建连接记录 - const newConnectionId = await ConnectionRepository.createConnection(connectionData); + // Pass the potentially modified finalConnectionData + const newConnectionId = await ConnectionRepository.createConnection(finalConnectionData as Omit); // 5. 处理标签 const tagIds = input.tag_ids?.filter(id => typeof id === 'number' && id > 0) ?? []; @@ -139,8 +173,8 @@ export const updateConnection = async (id: number, input: UpdateConnectionInput) } // 2. 准备更新数据 - // Explicitly type dataToUpdate to match the repository's expected input - const dataToUpdate: Partial> = {}; + // Explicitly type dataToUpdate to match the repository's expected input, including ssh_key_id + const dataToUpdate: Partial> = {}; let needsCredentialUpdate = false; // Determine the final type, converting input type to uppercase if provided const targetType = input.type?.toUpperCase() as 'SSH' | 'RDP' | undefined || currentFullConnection.type; @@ -153,6 +187,8 @@ export const updateConnection = async (id: number, input: UpdateConnectionInput) if (input.port !== undefined) dataToUpdate.port = input.port; if (input.username !== undefined) dataToUpdate.username = input.username; if (input.proxy_id !== undefined) dataToUpdate.proxy_id = input.proxy_id; + // Handle ssh_key_id update (can be set to null or a new ID) + if (input.ssh_key_id !== undefined) dataToUpdate.ssh_key_id = input.ssh_key_id; // 处理认证方法更改或凭证更新 (根据 targetType) // Use the validated targetType for logic @@ -177,31 +213,67 @@ export const updateConnection = async (id: number, input: UpdateConnectionInput) dataToUpdate.encrypted_password = input.password ? encrypt(input.password) : null; needsCredentialUpdate = true; } - // When switching to password, clear key fields + // When switching to password, clear key fields and ssh_key_id if (finalAuthMethod !== currentAuthMethod) { dataToUpdate.encrypted_private_key = null; dataToUpdate.encrypted_passphrase = null; + dataToUpdate.ssh_key_id = null; // Clear ssh_key_id when switching to password } } else { // finalAuthMethod is 'key' - let keyUpdated = false; - // If switching to key or updating key - if (input.private_key !== undefined) { - if (!input.private_key && finalAuthMethod !== currentAuthMethod) { - // Switching to key requires a private key - throw new Error('切换到密钥认证时需要提供 private_key。'); - } - // Encrypt if key is not empty, otherwise set to null (to clear) - dataToUpdate.encrypted_private_key = input.private_key ? encrypt(input.private_key) : null; - needsCredentialUpdate = true; - keyUpdated = true; - } - // Update passphrase only if key was updated OR passphrase itself was provided - if (keyUpdated || input.passphrase !== undefined) { - // Encrypt if passphrase is not empty, otherwise set to null (to clear) + // Handle ssh_key_id selection or direct key input + if (input.ssh_key_id !== undefined) { + // User selected a stored key + if (input.ssh_key_id === null) { + // User explicitly wants to clear the stored key association + dataToUpdate.ssh_key_id = null; + // If clearing ssh_key_id, we might need a direct key, but validation should handle this? + // Or assume clearing means switching back to direct key input (which might be empty) + // Let's assume clearing ssh_key_id means we expect a direct key or nothing + if (input.private_key === undefined) { + // If no direct key provided when clearing ssh_key_id, clear connection's key fields + dataToUpdate.encrypted_private_key = null; + dataToUpdate.encrypted_passphrase = null; + } else { + // Encrypt the direct key provided alongside clearing ssh_key_id + dataToUpdate.encrypted_private_key = input.private_key ? encrypt(input.private_key) : null; + dataToUpdate.encrypted_passphrase = input.passphrase ? encrypt(input.passphrase) : null; + } + } else { + // Validate the provided ssh_key_id + const keyExists = await SshKeyService.getSshKeyDbRowById(input.ssh_key_id); + if (!keyExists) { + throw new Error(`提供的 SSH 密钥 ID ${input.ssh_key_id} 无效或不存在。`); + } + dataToUpdate.ssh_key_id = input.ssh_key_id; + // Clear direct key fields when selecting a stored key + dataToUpdate.encrypted_private_key = null; + dataToUpdate.encrypted_passphrase = null; + } + needsCredentialUpdate = true; // Changing key source is a credential update + } else if (input.private_key !== undefined) { + // User provided a direct key + if (!input.private_key && finalAuthMethod !== currentAuthMethod) { + // Switching to key requires a private key if not using ssh_key_id + throw new Error('切换到密钥认证时需要提供 private_key 或选择一个已保存的密钥。'); + } + // Encrypt if key is not empty, otherwise set to null (to clear) + dataToUpdate.encrypted_private_key = input.private_key ? encrypt(input.private_key) : null; + // Update passphrase only if direct key was provided OR passphrase itself was provided + if (input.passphrase !== undefined) { + dataToUpdate.encrypted_passphrase = input.passphrase ? encrypt(input.passphrase) : null; + } else if (input.private_key) { + // If only private_key is provided, clear passphrase + dataToUpdate.encrypted_passphrase = null; + } + dataToUpdate.ssh_key_id = null; // Clear ssh_key_id when providing direct key + needsCredentialUpdate = true; + } else if (input.passphrase !== undefined && !input.ssh_key_id && currentFullConnection.encrypted_private_key) { + // Only passphrase provided, and not using ssh_key_id, and a direct key already exists dataToUpdate.encrypted_passphrase = input.passphrase ? encrypt(input.passphrase) : null; - needsCredentialUpdate = true; // Consider passphrase change a credential update + needsCredentialUpdate = true; } - // When switching to key, clear password field + + // When switching to key, clear password field if (finalAuthMethod !== currentAuthMethod) { dataToUpdate.encrypted_password = null; } @@ -218,6 +290,7 @@ export const updateConnection = async (id: number, input: UpdateConnectionInput) dataToUpdate.auth_method = 'password'; // RDP uses password auth method in DB dataToUpdate.encrypted_private_key = null; dataToUpdate.encrypted_passphrase = null; + dataToUpdate.ssh_key_id = null; // RDP cannot use ssh_key_id } } @@ -279,8 +352,7 @@ export const deleteConnection = async (id: number): Promise => { export const getConnectionWithDecryptedCredentials = async ( id: number ): Promise<{ connection: ConnectionWithTags; decryptedPassword?: string; decryptedPrivateKey?: string; decryptedPassphrase?: string } | null> => { - // 1. 获取完整的连接数据(包含加密字段) - // Assuming findFullConnectionById exists and returns FullConnectionDbRow or null + // 1. 获取完整的连接数据(包含加密字段和可能的 ssh_key_id) const fullConnectionDbRow = await ConnectionRepository.findFullConnectionById(id); if (!fullConnectionDbRow) { console.log(`[Service:getConnWithDecrypt] Connection not found for ID: ${id}`); @@ -291,11 +363,11 @@ export const getConnectionWithDecryptedCredentials = async ( const fullConnection: FullConnectionData = { ...fullConnectionDbRow, encrypted_password: fullConnectionDbRow.encrypted_password ?? null, - encrypted_private_key: fullConnectionDbRow.encrypted_private_key ?? null, - encrypted_passphrase: fullConnectionDbRow.encrypted_passphrase ?? null, + encrypted_private_key: fullConnectionDbRow.encrypted_private_key ?? null, // May be null if using ssh_key_id + encrypted_passphrase: fullConnectionDbRow.encrypted_passphrase ?? null, // May be null if using ssh_key_id + ssh_key_id: fullConnectionDbRow.ssh_key_id ?? null, // +++ Include ssh_key_id +++ // Ensure other fields match FullConnectionData if necessary - // (Assuming FullConnectionDbRow includes all fields of FullConnectionData) - }; + } as FullConnectionData & { ssh_key_id: number | null }; // Type assertion // 2. 获取带标签的连接数据(用于返回给调用者) const connectionWithTags: ConnectionWithTags | null = await ConnectionRepository.findConnectionByIdWithTags(id); @@ -318,15 +390,31 @@ export const getConnectionWithDecryptedCredentials = async ( } // Decrypt key and passphrase if method is 'key' else if (fullConnection.auth_method === 'key') { - if (fullConnection.encrypted_private_key) { + if (fullConnection.ssh_key_id) { + // +++ If using ssh_key_id, fetch and decrypt the stored key +++ + console.log(`[Service:getConnWithDecrypt] Connection ${id} uses stored SSH key ID: ${fullConnection.ssh_key_id}. Fetching key...`); + const storedKeyDetails = await SshKeyService.getDecryptedSshKeyById(fullConnection.ssh_key_id); + if (!storedKeyDetails) { + // This indicates an inconsistency, as the ssh_key_id should be valid + console.error(`[Service:getConnWithDecrypt] Error: Connection ${id} references non-existent SSH key ID ${fullConnection.ssh_key_id}`); + throw new Error(`关联的 SSH 密钥 (ID: ${fullConnection.ssh_key_id}) 未找到。`); + } + decryptedPrivateKey = storedKeyDetails.privateKey; + decryptedPassphrase = storedKeyDetails.passphrase; + console.log(`[Service:getConnWithDecrypt] Successfully fetched and decrypted stored SSH key ${fullConnection.ssh_key_id} for connection ${id}.`); + } else if (fullConnection.encrypted_private_key) { + // Decrypt the key stored directly in the connection record decryptedPrivateKey = decrypt(fullConnection.encrypted_private_key); - } - // Only decrypt passphrase if it exists - if (fullConnection.encrypted_passphrase) { - decryptedPassphrase = decrypt(fullConnection.encrypted_passphrase); + // Only decrypt passphrase if it exists alongside the direct key + if (fullConnection.encrypted_passphrase) { + decryptedPassphrase = decrypt(fullConnection.encrypted_passphrase); + } + } else { + console.warn(`[Service:getConnWithDecrypt] Connection ${id} uses key auth but has neither ssh_key_id nor encrypted_private_key.`); + // No key available to decrypt } } - } catch (error) { + } catch (error: any) { // Catch decryption or key fetching errors console.error(`[Service:getConnWithDecrypt] Failed to decrypt credentials for connection ID ${id}:`, error); // Decide how to handle decryption errors. Throw? Return null password? // For now, we'll log and continue, returning undefined credentials. diff --git a/packages/backend/src/services/ssh.service.ts b/packages/backend/src/services/ssh.service.ts index 6f0097f..8b068a2 100644 --- a/packages/backend/src/services/ssh.service.ts +++ b/packages/backend/src/services/ssh.service.ts @@ -5,6 +5,7 @@ import net from 'net'; import * as ConnectionRepository from '../repositories/connection.repository'; import * as ProxyRepository from '../repositories/proxy.repository'; import { decrypt } from '../utils/crypto'; +import * as SshKeyService from './ssh_key.service'; // +++ Import SshKeyService +++ const CONNECT_TIMEOUT = 20000; // 连接超时时间 (毫秒) const TEST_TIMEOUT = 15000; // 测试连接超时时间 (毫秒) @@ -56,12 +57,41 @@ export const getConnectionDetails = async (connectionId: number): Promise { throw new Error(`Connection ID ${connectionId} has null port.`); })(), username: rawConnInfo.username ?? (() => { throw new Error(`Connection ID ${connectionId} has null username.`); })(), auth_method: rawConnInfo.auth_method ?? (() => { throw new Error(`Connection ID ${connectionId} has null auth_method.`); })(), - password: (rawConnInfo.auth_method === 'password' && rawConnInfo.encrypted_password) ? decrypt(rawConnInfo.encrypted_password) : undefined, - privateKey: (rawConnInfo.auth_method === 'key' && rawConnInfo.encrypted_private_key) ? decrypt(rawConnInfo.encrypted_private_key) : undefined, - passphrase: (rawConnInfo.auth_method === 'key' && rawConnInfo.encrypted_passphrase) ? decrypt(rawConnInfo.encrypted_passphrase) : undefined, + // Initialize credentials + password: undefined, + privateKey: undefined, + passphrase: undefined, proxy: null, }; + // Decrypt password if method is password + if (fullConnInfo.auth_method === 'password' && rawConnInfo.encrypted_password) { + fullConnInfo.password = decrypt(rawConnInfo.encrypted_password); + } + // Handle key auth: prioritize ssh_key_id, then direct key + else if (fullConnInfo.auth_method === 'key') { + // +++ Use rawConnInfo.ssh_key_id instead of undefined sshKeyId +++ + if (rawConnInfo.ssh_key_id) { + console.log(`SshService: Connection ${connectionId} uses stored SSH key ID: ${rawConnInfo.ssh_key_id}. Fetching key...`); + const storedKeyDetails = await SshKeyService.getDecryptedSshKeyById(rawConnInfo.ssh_key_id); // Use imported SshKeyService + if (!storedKeyDetails) { + console.error(`SshService: Error: Connection ${connectionId} references non-existent SSH key ID ${rawConnInfo.ssh_key_id}`); + throw new Error(`关联的 SSH 密钥 (ID: ${rawConnInfo.ssh_key_id}) 未找到。`); + } + fullConnInfo.privateKey = storedKeyDetails.privateKey; + fullConnInfo.passphrase = storedKeyDetails.passphrase; + console.log(`SshService: Successfully fetched and decrypted stored SSH key ${rawConnInfo.ssh_key_id} for connection ${connectionId}.`); + } else if (rawConnInfo.encrypted_private_key) { + // Decrypt direct key only if ssh_key_id is not present + fullConnInfo.privateKey = decrypt(rawConnInfo.encrypted_private_key); + if (rawConnInfo.encrypted_passphrase) { + fullConnInfo.passphrase = decrypt(rawConnInfo.encrypted_passphrase); + } + } else { + console.warn(`SshService: Connection ${connectionId} uses key auth but has neither ssh_key_id nor encrypted_private_key.`); + } + } + if (rawConnInfo.proxy_db_id) { // Add null checks for required proxy fields inside the if block const proxyName = rawConnInfo.proxy_name ?? (() => { throw new Error(`Proxy for Connection ID ${connectionId} has null name.`); })(); @@ -307,14 +337,16 @@ export const testConnection = async (connectionId: number): Promise<{ latency: n * @returns Promise<{ latency: number }> - 如果连接成功则 resolve 包含延迟的对象,否则 reject * @throws Error 如果连接失败或配置错误 */ +// Ensure ssh_key_id is part of the input type definition export const testUnsavedConnection = async (connectionConfig: { host: string; port: number; username: string; auth_method: 'password' | 'key'; password?: string; - private_key?: string; // 注意这里是 private_key + private_key?: string; // Keep this for direct input passphrase?: string; + ssh_key_id?: number | null; // Ensure this is present proxy_id?: number | null; }): Promise<{ latency: number }> => { console.log(`SshService: 测试未保存的连接到 ${connectionConfig.host}:${connectionConfig.port}...`); @@ -329,13 +361,33 @@ export const testUnsavedConnection = async (connectionConfig: { port: connectionConfig.port, username: connectionConfig.username, auth_method: connectionConfig.auth_method, - // 直接使用传入的凭证,因为它们是未加密的 - password: connectionConfig.password, - privateKey: connectionConfig.private_key, // 映射 private_key - passphrase: connectionConfig.passphrase, + // Initialize credentials, will be populated based on input + password: undefined, + privateKey: undefined, + passphrase: undefined, proxy: null, // 稍后填充 }; + // Populate credentials based on auth method and ssh_key_id presence + if (tempConnDetails.auth_method === 'password') { + tempConnDetails.password = connectionConfig.password; + } else { // auth_method is 'key' + if (connectionConfig.ssh_key_id) { + // Fetch and decrypt stored key if ssh_key_id is provided + console.log(`SshService: Testing unsaved connection using stored SSH key ID: ${connectionConfig.ssh_key_id}...`); + const storedKeyDetails = await SshKeyService.getDecryptedSshKeyById(connectionConfig.ssh_key_id); // Use imported SshKeyService + if (!storedKeyDetails) { + throw new Error(`选择的 SSH 密钥 (ID: ${connectionConfig.ssh_key_id}) 未找到。`); + } + tempConnDetails.privateKey = storedKeyDetails.privateKey; + tempConnDetails.passphrase = storedKeyDetails.passphrase; + } else { + // Use direct key input if ssh_key_id is not provided + tempConnDetails.privateKey = connectionConfig.private_key; // Use private_key from input + tempConnDetails.passphrase = connectionConfig.passphrase; + } + } + // 2. 如果提供了 proxy_id,获取并解密代理信息 if (connectionConfig.proxy_id) { console.log(`SshService: 测试连接需要获取代理 ${connectionConfig.proxy_id} 的信息...`); diff --git a/packages/backend/src/services/ssh_key.service.ts b/packages/backend/src/services/ssh_key.service.ts new file mode 100644 index 0000000..ff54c5a --- /dev/null +++ b/packages/backend/src/services/ssh_key.service.ts @@ -0,0 +1,183 @@ +import * as SshKeyRepository from '../repositories/ssh_key.repository'; +import { encrypt, decrypt } from '../utils/crypto'; +import { SshKeyDbRow, CreateSshKeyData, UpdateSshKeyData } from '../repositories/ssh_key.repository'; + +// 定义 Service 层返回给 Controller 的基本密钥信息 (不含加密内容) +export interface SshKeyBasicInfo { + id: number; + name: string; +} + +// 定义 Service 层创建密钥时的输入类型 +export interface CreateSshKeyInput { + name: string; + private_key: string; // 明文私钥 + passphrase?: string; // 明文密码短语 (可选) +} + +// 定义 Service 层更新密钥时的输入类型 (名称必选,凭证可选) +export interface UpdateSshKeyInput { + name?: string; // 名称可选,但通常会提供 + private_key?: string; // 明文私钥 (可选,表示要更新) + passphrase?: string; // 明文密码短语 (可选,如果提供了私钥,则此项也可能需要更新) +} + +// 定义包含解密后凭证的密钥详情 +export interface DecryptedSshKeyDetails extends SshKeyBasicInfo { + privateKey: string; // 解密后的私钥 + passphrase?: string; // 解密后的密码短语 +} + + +/** + * 创建新的 SSH 密钥 + * @param input 包含名称和明文凭证的对象 + * @returns Promise 新创建密钥的基本信息 + */ +export const createSshKey = async (input: CreateSshKeyInput): Promise => { + // 1. 验证输入 + if (!input.name || !input.private_key) { + throw new Error('必须提供密钥名称和私钥内容。'); + } + // 可选:添加更严格的私钥格式验证 + + // 2. 加密凭证 + const encrypted_private_key = encrypt(input.private_key); + const encrypted_passphrase = input.passphrase ? encrypt(input.passphrase) : null; + + // 3. 准备仓库数据 + const dataToSave: CreateSshKeyData = { + name: input.name, + encrypted_private_key, + encrypted_passphrase, + }; + + // 4. 调用仓库创建记录 + try { + const newId = await SshKeyRepository.createSshKey(dataToSave); + return { id: newId, name: input.name }; + } catch (error: any) { + // 处理可能的 UNIQUE constraint 错误 + if (error.message && error.message.includes('UNIQUE constraint failed: ssh_keys.name')) { + throw new Error(`SSH 密钥名称 "${input.name}" 已存在。`); + } + throw error; // 重新抛出其他错误 + } +}; + +/** + * 获取所有 SSH 密钥的基本信息 (ID 和 Name) + * @returns Promise 密钥列表 + */ +export const getAllSshKeyNames = async (): Promise => { + return SshKeyRepository.findAllSshKeyNames(); +}; + +/** + * 根据 ID 获取 SSH 密钥的完整数据库行 (包含加密凭证) + * 供内部服务使用,例如需要解密的场景 + * @param id 密钥 ID + * @returns Promise 密钥数据库行或 null + */ +export const getSshKeyDbRowById = async (id: number): Promise => { + return SshKeyRepository.findSshKeyById(id); +}; + + +/** + * 根据 ID 获取解密后的 SSH 密钥详情 + * @param id 密钥 ID + * @returns Promise 解密后的密钥详情或 null + */ +export const getDecryptedSshKeyById = async (id: number): Promise => { + const dbRow = await SshKeyRepository.findSshKeyById(id); + if (!dbRow) { + return null; + } + + try { + const privateKey = decrypt(dbRow.encrypted_private_key); + const passphrase = dbRow.encrypted_passphrase ? decrypt(dbRow.encrypted_passphrase) : undefined; + return { + id: dbRow.id, + name: dbRow.name, + privateKey, + passphrase, + }; + } catch (error: any) { + console.error(`Service: 解密 SSH 密钥 ${id} 失败:`, error); + // 根据策略决定是抛出错误还是返回 null/部分信息 + throw new Error(`解密 SSH 密钥 ${id} 失败。`); + } +}; + + +/** + * 更新 SSH 密钥 + * @param id 要更新的密钥 ID + * @param input 包含要更新字段的对象 (明文凭证) + * @returns Promise 更新后的密钥基本信息或 null (如果未找到) + */ +export const updateSshKey = async (id: number, input: UpdateSshKeyInput): Promise => { + // 1. 检查密钥是否存在 + const existingKey = await SshKeyRepository.findSshKeyById(id); + if (!existingKey) { + return null; // 未找到 + } + + // 2. 准备要更新的数据 + const dataToUpdate: UpdateSshKeyData = {}; + let finalName = existingKey.name; // 保留现有名称,除非输入中提供了新名称 + + if (input.name !== undefined) { + if (!input.name) { + throw new Error('密钥名称不能为空。'); + } + dataToUpdate.name = input.name; + finalName = input.name; // 更新最终名称 + } + + // 只有当提供了新的私钥时,才更新私钥和密码短语 + if (input.private_key !== undefined) { + if (!input.private_key) { + throw new Error('私钥内容不能为空。'); + } + dataToUpdate.encrypted_private_key = encrypt(input.private_key); + // 如果更新了私钥,则密码短语也需要更新(即使是设为 null) + dataToUpdate.encrypted_passphrase = input.passphrase ? encrypt(input.passphrase) : null; + } else if (input.passphrase !== undefined && existingKey.encrypted_private_key) { + // 如果只提供了密码短语,且当前存在私钥,则只更新密码短语 + dataToUpdate.encrypted_passphrase = input.passphrase ? encrypt(input.passphrase) : null; + } + + + // 3. 如果有数据需要更新,则调用仓库 + if (Object.keys(dataToUpdate).length > 0) { + try { + const updated = await SshKeyRepository.updateSshKey(id, dataToUpdate); + if (!updated) { + // 理论上不应发生,因为我们已经检查过存在性 + throw new Error('更新 SSH 密钥记录失败。'); + } + } catch (error: any) { + // 处理可能的 UNIQUE constraint 错误 + if (error.message && error.message.includes('UNIQUE constraint failed: ssh_keys.name')) { + throw new Error(`SSH 密钥名称 "${input.name}" 已存在。`); + } + throw error; // 重新抛出其他错误 + } + } + + // 4. 返回更新后的基本信息 + return { id: id, name: finalName }; +}; + +/** + * 删除 SSH 密钥 + * @param id 要删除的密钥 ID + * @returns Promise 是否删除成功 + */ +export const deleteSshKey = async (id: number): Promise => { + // 注意:删除密钥前,相关的 connections 表中的 ssh_key_id 会被设为 NULL (ON DELETE SET NULL) + return SshKeyRepository.deleteSshKey(id); +}; \ No newline at end of file diff --git a/packages/backend/src/ssh_keys/ssh_keys.controller.ts b/packages/backend/src/ssh_keys/ssh_keys.controller.ts new file mode 100644 index 0000000..592ebb1 --- /dev/null +++ b/packages/backend/src/ssh_keys/ssh_keys.controller.ts @@ -0,0 +1,121 @@ +import { Request, Response } from 'express'; +import * as SshKeyService from '../services/ssh_key.service'; +import { CreateSshKeyInput, UpdateSshKeyInput } from '../services/ssh_key.service'; + +/** + * 获取所有 SSH 密钥的名称列表 (GET /api/v1/ssh-keys) + */ +export const getSshKeyNames = async (req: Request, res: Response): Promise => { + try { + const keys = await SshKeyService.getAllSshKeyNames(); + res.status(200).json(keys); + } catch (error: any) { + console.error('Controller: 获取 SSH 密钥列表失败:', error); + res.status(500).json({ message: error.message || '获取 SSH 密钥列表时发生内部服务器错误。' }); + } +}; + +/** + * 创建新的 SSH 密钥 (POST /api/v1/ssh-keys) + */ +export const createSshKey = async (req: Request, res: Response): Promise => { + try { + const input: CreateSshKeyInput = req.body; + // 基本验证,更详细的验证在 Service 层 + if (!input.name || !input.private_key) { + res.status(400).json({ message: '请求体必须包含 name 和 private_key。' }); + return; + } + const newKey = await SshKeyService.createSshKey(input); + res.status(201).json({ message: 'SSH 密钥创建成功。', key: newKey }); + } catch (error: any) { + console.error('Controller: 创建 SSH 密钥失败:', error); + // 检查是否是 Service 层抛出的特定错误 (如名称重复) + if (error.message.includes('已存在') || error.message.includes('必须提供')) { + res.status(400).json({ message: error.message }); + } else { + res.status(500).json({ message: error.message || '创建 SSH 密钥时发生内部服务器错误。' }); + } + } +}; + +/** + * 获取单个 SSH 密钥的详细信息 (包含解密后的凭证) - 谨慎使用,可能主要用于编辑回显 + * (GET /api/v1/ssh-keys/:id/details) - 使用不同的路径以示区分 + */ +export const getDecryptedSshKey = async (req: Request, res: Response): Promise => { + try { + const keyId = parseInt(req.params.id, 10); + if (isNaN(keyId)) { + res.status(400).json({ message: '无效的密钥 ID。' }); + return; + } + const keyDetails = await SshKeyService.getDecryptedSshKeyById(keyId); + if (!keyDetails) { + res.status(404).json({ message: 'SSH 密钥未找到。' }); + } else { + // 返回解密后的数据,前端需要妥善处理 + res.status(200).json(keyDetails); + } + } catch (error: any) { + console.error(`Controller: 获取解密后的 SSH 密钥 ${req.params.id} 失败:`, error); + res.status(500).json({ message: error.message || '获取 SSH 密钥详情时发生内部服务器错误。' }); + } + }; + + +/** + * 更新 SSH 密钥 (PUT /api/v1/ssh-keys/:id) + */ +export const updateSshKey = async (req: Request, res: Response): Promise => { + try { + const keyId = parseInt(req.params.id, 10); + if (isNaN(keyId)) { + res.status(400).json({ message: '无效的密钥 ID。' }); + return; + } + const input: UpdateSshKeyInput = req.body; + // 简单验证输入是否为空对象 + if (Object.keys(input).length === 0) { + res.status(400).json({ message: '请求体不能为空。' }); + return; + } + + const updatedKey = await SshKeyService.updateSshKey(keyId, input); + if (!updatedKey) { + res.status(404).json({ message: 'SSH 密钥未找到。' }); + } else { + res.status(200).json({ message: 'SSH 密钥更新成功。', key: updatedKey }); + } + } catch (error: any) { + console.error(`Controller: 更新 SSH 密钥 ${req.params.id} 失败:`, error); + // 检查是否是 Service 层抛出的特定错误 (如名称重复或验证失败) + if (error.message.includes('已存在') || error.message.includes('不能为空')) { + res.status(400).json({ message: error.message }); + } else { + res.status(500).json({ message: error.message || '更新 SSH 密钥时发生内部服务器错误。' }); + } + } +}; + +/** + * 删除 SSH 密钥 (DELETE /api/v1/ssh-keys/:id) + */ +export const deleteSshKey = async (req: Request, res: Response): Promise => { + try { + const keyId = parseInt(req.params.id, 10); + if (isNaN(keyId)) { + res.status(400).json({ message: '无效的密钥 ID。' }); + return; + } + const deleted = await SshKeyService.deleteSshKey(keyId); + if (!deleted) { + res.status(404).json({ message: 'SSH 密钥未找到。' }); + } else { + res.status(200).json({ message: 'SSH 密钥删除成功。' }); + } + } catch (error: any) { + console.error(`Controller: 删除 SSH 密钥 ${req.params.id} 失败:`, error); + res.status(500).json({ message: error.message || '删除 SSH 密钥时发生内部服务器错误。' }); + } +}; \ No newline at end of file diff --git a/packages/backend/src/ssh_keys/ssh_keys.routes.ts b/packages/backend/src/ssh_keys/ssh_keys.routes.ts new file mode 100644 index 0000000..4d33e39 --- /dev/null +++ b/packages/backend/src/ssh_keys/ssh_keys.routes.ts @@ -0,0 +1,31 @@ +import { Router } from 'express'; +import { isAuthenticated } from '../auth/auth.middleware'; +import { + getSshKeyNames, + createSshKey, + getDecryptedSshKey, + updateSshKey, + deleteSshKey +} from './ssh_keys.controller'; + +const router = Router(); + +// 应用认证中间件到所有 /ssh-keys 路由 +router.use(isAuthenticated); + +// GET /api/v1/ssh-keys - 获取所有 SSH 密钥的名称列表 +router.get('/', getSshKeyNames); + +// POST /api/v1/ssh-keys - 创建新的 SSH 密钥 +router.post('/', createSshKey); + +// GET /api/v1/ssh-keys/:id/details - 获取单个解密后的 SSH 密钥详情 (谨慎使用) +router.get('/:id/details', getDecryptedSshKey); + +// PUT /api/v1/ssh-keys/:id - 更新 SSH 密钥 +router.put('/:id', updateSshKey); + +// DELETE /api/v1/ssh-keys/:id - 删除 SSH 密钥 +router.delete('/:id', deleteSshKey); + +export default router; \ No newline at end of file diff --git a/packages/backend/src/types/connection.types.ts b/packages/backend/src/types/connection.types.ts index 0f49d79..cdbf689 100644 --- a/packages/backend/src/types/connection.types.ts +++ b/packages/backend/src/types/connection.types.ts @@ -28,7 +28,8 @@ export interface CreateConnectionInput { auth_method: 'password' | 'key'; password?: string; private_key?: string; - passphrase?: string; + passphrase?: string; + ssh_key_id?: number | null; // +++ Add ssh_key_id +++ proxy_id?: number | null; tag_ids?: number[]; } @@ -43,7 +44,8 @@ export interface UpdateConnectionInput { auth_method?: 'password' | 'key'; password?: string; private_key?: string; - passphrase?: string; + passphrase?: string; + ssh_key_id?: number | null; // +++ Add ssh_key_id +++ proxy_id?: number | null; tag_ids?: number[]; } @@ -60,6 +62,7 @@ export interface FullConnectionData { encrypted_password: string | null; encrypted_private_key: string | null; encrypted_passphrase: string | null; + ssh_key_id?: number | null; // +++ Add ssh_key_id +++ proxy_id: number | null; created_at: number; updated_at: number; diff --git a/packages/frontend/src/components/AddConnectionForm.vue b/packages/frontend/src/components/AddConnectionForm.vue index be385b2..9d06e26 100644 --- a/packages/frontend/src/components/AddConnectionForm.vue +++ b/packages/frontend/src/components/AddConnectionForm.vue @@ -6,7 +6,9 @@ import apiClient from '../utils/apiClient'; import { useConnectionsStore, ConnectionInfo } from '../stores/connections.store'; import { useProxiesStore } from '../stores/proxies.store'; import { useTagsStore } from '../stores/tags.store'; +import { useSshKeysStore } from '../stores/sshKeys.store'; // +++ Import SSH Key store +++ import TagInput from './TagInput.vue'; +import SshKeySelector from './SshKeySelector.vue'; // +++ Import SSH Key Selector +++ // 定义组件发出的事件 const emit = defineEmits(['close', 'connection-added', 'connection-updated']); @@ -33,8 +35,9 @@ const initialFormData = { username: '', auth_method: 'password' as 'password' | 'key', // SSH specific password: '', - private_key: '', // SSH specific - passphrase: '', // SSH specific + private_key: '', // SSH specific (for direct input) + passphrase: '', // SSH specific (for direct input) + selected_ssh_key_id: null as number | null, // +++ Add field for selected key ID +++ proxy_id: null as number | null, tag_ids: [] as number[], // 新增 tag_ids 字段 // Add RDP specific fields later if needed, e.g., domain @@ -138,8 +141,9 @@ const handleSubmit = async () => { formError.value = t('connections.form.errorPasswordRequired'); return; } - if (formData.auth_method === 'key' && !formData.private_key) { - formError.value = t('connections.form.errorPrivateKeyRequired'); + // 当认证方式为 key 时,必须选择一个已保存的密钥 + if (formData.auth_method === 'key' && !formData.selected_ssh_key_id) { + formError.value = t('connections.form.errorSshKeyRequired'); // 需要添加新的翻译键 return; } } @@ -153,14 +157,16 @@ const handleSubmit = async () => { } // 如果原始就是密码,编辑时密码可以不填(表示不修改) } - // 3. 编辑模式下,如果切换到密钥认证,则私钥必填 - else if (isEditMode.value && formData.auth_method === 'key' && !formData.private_key) { - // 检查原始连接的认证方式,如果原始不是密钥,则切换时必须提供私钥 + // 3. 编辑模式下,如果切换到密钥认证,必须选择一个密钥 + else if (isEditMode.value && formData.auth_method === 'key' && !formData.selected_ssh_key_id) { + // 检查原始连接的认证方式,如果原始不是密钥,则切换时必须选择一个密钥 if (props.connectionToEdit?.auth_method !== 'key') { - formError.value = t('connections.form.errorPrivateKeyRequiredOnSwitch'); + formError.value = t('connections.form.errorSshKeyRequiredOnSwitch'); // 需要添加新的翻译键 return; } - // 如果原始就是密钥,编辑时私钥可以不填(表示不修改) + // 如果原始就是密钥,编辑时可以不选择新的密钥(表示不修改关联的密钥) + // 但如果用户清除了选择,则需要提示 + // 注意:当前逻辑下,如果 selected_ssh_key_id 为 null,则会触发此验证 } // Use uppercase for comparison } else if (formData.type === 'RDP') { @@ -203,16 +209,21 @@ const handleSubmit = async () => { // 或者不发送 password 字段表示不修改 } } else if (formData.auth_method === 'key') { - // SSH 密钥处理 - if (formData.private_key) { - dataToSend.private_key = formData.private_key; - } - // SSH 密码短语处理 - if (formData.passphrase) { - dataToSend.passphrase = formData.passphrase; - } else if (isEditMode.value && formData.passphrase === '') { - // dataToSend.passphrase = null; // 发送 null 表示清空 + // +++ SSH 密钥处理 (只处理 selected_ssh_key_id) +++ + if (formData.selected_ssh_key_id) { + // 如果选择了已保存的密钥,只发送 ID + dataToSend.ssh_key_id = formData.selected_ssh_key_id; + } else if (isEditMode.value && props.connectionToEdit?.auth_method === 'key') { + // 编辑模式下,如果原始是密钥认证且未选择新密钥,则不发送 ssh_key_id (表示不更改) + // 如果原始不是密钥认证,切换到密钥时必须选择一个 (已在验证逻辑中处理) + } else { + // 添加模式下,如果 auth_method 是 key 但没有选择 key,验证逻辑会阻止提交 + // 因此这里不需要特殊处理,可以安全地将 ssh_key_id 设为 null 或不设置 + dataToSend.ssh_key_id = null; // 或者 delete dataToSend.ssh_key_id; } + // 确保不发送直接输入的密钥信息 + delete dataToSend.private_key; + delete dataToSend.passphrase; } // Use uppercase for comparison } else if (formData.type === 'RDP') { @@ -273,9 +284,11 @@ const handleTestConnection = async () => { username: formData.username, auth_method: formData.auth_method, password: formData.auth_method === 'password' ? formData.password : undefined, - private_key: formData.auth_method === 'key' ? formData.private_key : undefined, - passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined, + // private_key: formData.auth_method === 'key' ? formData.private_key : undefined, // Removed + // passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined, // Removed proxy_id: formData.proxy_id || null, + // +++ Add ssh_key_id for testing +++ + ssh_key_id: formData.auth_method === 'key' ? formData.selected_ssh_key_id : undefined, }; // 仅在添加模式下进行前端凭证验证 @@ -286,10 +299,11 @@ const handleTestConnection = async () => { // 在添加模式下,密码或密钥必须提供 if (dataToSend.auth_method === 'password' && !formData.password) { // 检查 formData 而不是 dataToSend.password throw new Error(t('connections.form.errorPasswordRequired')); // 复用表单提交的翻译键 - } - if (dataToSend.auth_method === 'key' && !formData.private_key) { // 检查 formData 而不是 dataToSend.private_key - throw new Error(t('connections.form.errorPrivateKeyRequired')); // 复用表单提交的翻译键 - } + } + // +++ Check selected key for testing +++ + if (dataToSend.auth_method === 'key' && !dataToSend.ssh_key_id) { + throw new Error(t('connections.form.errorSshKeyRequired')); // 使用新的翻译键 + } // 调用测试未保存连接的 API response = await apiClient.post('/connections/test-unsaved', dataToSend); @@ -409,19 +423,17 @@ const testButtonText = computed(() => {
+
- - -
-
- - -
-
- {{ t('connections.form.keyUpdateNote') }} + +
+ + + +
+ {{ t('connections.form.keyUpdateNoteSelected') }} +
diff --git a/packages/frontend/src/components/SshKeyManagementModal.vue b/packages/frontend/src/components/SshKeyManagementModal.vue new file mode 100644 index 0000000..45d6a56 --- /dev/null +++ b/packages/frontend/src/components/SshKeyManagementModal.vue @@ -0,0 +1,225 @@ + + + \ No newline at end of file diff --git a/packages/frontend/src/components/SshKeySelector.vue b/packages/frontend/src/components/SshKeySelector.vue new file mode 100644 index 0000000..9fd4afc --- /dev/null +++ b/packages/frontend/src/components/SshKeySelector.vue @@ -0,0 +1,76 @@ + + + \ No newline at end of file diff --git a/packages/frontend/src/locales/en-US.json b/packages/frontend/src/locales/en-US.json index 85cf1e0..06ab9ee 100644 --- a/packages/frontend/src/locales/en-US.json +++ b/packages/frontend/src/locales/en-US.json @@ -166,7 +166,11 @@ "sectionAuth": "Authentication", "sectionAdvanced": "Advanced Options", "testConnection": "Test Connection", - "testing": "Testing..." + "testing": "Testing...", + "sshKey": "SSH Key", + "privateKeyDirect": "Private Key Content", + "keyUpdateNoteDirect": "Leave private key and passphrase blank to keep the existing key when editing.", + "keyUpdateNoteSelected": "Select another key or use direct input to change the key when editing." }, "test": { "success": "Connection test successful!", @@ -981,5 +985,35 @@ }, "terminalTabBar": { "selectServerTitle": "Select server to connect" + }, + "sshKeys": { + "selector": { + "selectPlaceholder": "Select an SSH key...", + "useDirectInput": "Or input key content directly", + "manageKeysTitle": "Manage SSH Keys", + "loadingKeys": "Loading keys..." + }, + "modal": { + "title": "SSH Key Management", + "addKey": "Add Key", + "keyName": "Key Name", + "actions": "Actions", + "loading": "Loading...", + "noKeys": "No SSH keys found. Please add one.", + "close": "Close", + "addTitle": "Add New SSH Key", + "editTitle": "Edit SSH Key", + "privateKey": "Private Key Content", + "passphrase": "Passphrase", + "cancel": "Cancel", + "saveChanges": "Save Changes", + "edit": "Edit", + "delete": "Delete", + "errorFetchDetails": "Failed to fetch key details", + "errorRequiredFields": "Key name and private key content cannot be empty.", + "confirmDelete": "Are you sure you want to delete the key \"{name}\"? This cannot be undone.", + "keyUpdateNote": "Leave private key blank to keep the existing key. Passphrase always needs re-entry if required.", + "passphraseUpdateNote": "Leave blank to keep or remove the passphrase. Enter a new passphrase to update." + } } } diff --git a/packages/frontend/src/locales/ja-JP.json b/packages/frontend/src/locales/ja-JP.json index ce0fe78..6b25a62 100644 --- a/packages/frontend/src/locales/ja-JP.json +++ b/packages/frontend/src/locales/ja-JP.json @@ -138,7 +138,11 @@ "titleEdit": "接続の編集", "typeRdp": "RDP", "typeSsh": "SSH", - "username": "ユーザー名:" + "username": "ユーザー名:", + "sshKey": "SSH キー", + "privateKeyDirect": "秘密鍵の内容", + "keyUpdateNoteDirect": "編集時に既存のキーを保持するには、秘密鍵とパスフレーズを空のままにしてください。", + "keyUpdateNoteSelected": "編集時にキーを変更するには、別のキーを選択するか、直接入力を使用してください。" }, "noConnections": "接続がありません。'新しい接続を追加'をクリックして作成してください。", "noUntaggedConnections": "タグなしの接続はありません。", @@ -984,5 +988,35 @@ "noResults": "\"{searchTerm}\"に一致する接続は見つかりませんでした。", "searchPlaceholder": "名前またはホストを検索...", "untagged": "タグなし" + }, + "sshKeys": { + "selector": { + "selectPlaceholder": "SSH キーを選択...", + "useDirectInput": "またはキーの内容を直接入力", + "manageKeysTitle": "SSH キーを管理", + "loadingKeys": "キーを読み込み中..." + }, + "modal": { + "title": "SSH キー管理", + "addKey": "キーを追加", + "keyName": "キー名", + "actions": "操作", + "loading": "読み込み中...", + "noKeys": "SSH キーが見つかりません。追加してください。", + "close": "閉じる", + "addTitle": "新しい SSH キーを追加", + "editTitle": "SSH キーを編集", + "privateKey": "秘密鍵の内容", + "passphrase": "パスフレーズ", + "cancel": "キャンセル", + "saveChanges": "変更を保存", + "edit": "編集", + "delete": "削除", + "errorFetchDetails": "キーの詳細の取得に失敗しました", + "errorRequiredFields": "キー名と秘密鍵の内容は空にできません。", + "confirmDelete": "キー \"{name}\" を削除しますか?この操作は元に戻せません。", + "keyUpdateNote": "既存のキーを保持するには、秘密鍵を空のままにしてください。パスフレーズは必要に応じて再入力する必要があります。", + "passphraseUpdateNote": "パスフレーズを保持または削除するには空のままにします。更新するには新しいパスフレーズを入力してください。" + } } } \ No newline at end of file diff --git a/packages/frontend/src/locales/zh-CN.json b/packages/frontend/src/locales/zh-CN.json index 0e18248..1264dfa 100644 --- a/packages/frontend/src/locales/zh-CN.json +++ b/packages/frontend/src/locales/zh-CN.json @@ -166,7 +166,11 @@ "sectionAuth": "认证信息", "sectionAdvanced": "高级选项", "testConnection": "测试连接", - "testing": "测试中..." + "testing": "测试中...", + "sshKey": "SSH 密钥", + "privateKeyDirect": "私钥内容", + "keyUpdateNoteDirect": "编辑时将私钥和密码短语留空以保留现有密钥。", + "keyUpdateNoteSelected": "编辑时选择其他密钥或使用直接输入来更改密钥。" }, "test": { "success": "连接测试成功!", @@ -984,5 +988,35 @@ }, "terminalTabBar": { "selectServerTitle": "选择要连接的服务器" + }, + "sshKeys": { + "selector": { + "selectPlaceholder": "选择一个 SSH 密钥...", + "useDirectInput": "或直接输入密钥内容", + "manageKeysTitle": "管理 SSH 密钥", + "loadingKeys": "正在加载密钥..." + }, + "modal": { + "title": "SSH 密钥管理", + "addKey": "添加密钥", + "keyName": "密钥名称", + "actions": "操作", + "loading": "加载中...", + "noKeys": "没有找到 SSH 密钥。请添加一个。", + "close": "关闭", + "addTitle": "添加新 SSH 密钥", + "editTitle": "编辑 SSH 密钥", + "privateKey": "私钥内容", + "passphrase": "私钥密码", + "cancel": "取消", + "saveChanges": "保存更改", + "edit": "编辑", + "delete": "删除", + "errorFetchDetails": "获取密钥详情失败", + "errorRequiredFields": "密钥名称和私钥内容不能为空。", + "confirmDelete": "确定要删除密钥 \"{name}\" 吗?此操作不可撤销。", + "keyUpdateNote": "将私钥留空以保留现有密钥。密码短语始终需要重新输入(如果需要)。", + "passphraseUpdateNote": "留空表示不修改或移除密码短语。输入新密码短语以更新。" + } } } diff --git a/packages/frontend/src/stores/sshKeys.store.ts b/packages/frontend/src/stores/sshKeys.store.ts new file mode 100644 index 0000000..5d26be7 --- /dev/null +++ b/packages/frontend/src/stores/sshKeys.store.ts @@ -0,0 +1,153 @@ +import { defineStore } from 'pinia'; +import { ref } from 'vue'; +import apiClient from '../utils/apiClient'; +import { useUiNotificationsStore } from './uiNotifications.store'; // For displaying errors + +// Interface for basic SSH key info (for lists) +export interface SshKeyBasicInfo { + id: number; + name: string; +} + +// Interface for detailed SSH key info (including decrypted key for editing) +// Be cautious when handling decryptedPrivateKey in the UI +export interface SshKeyDetails extends SshKeyBasicInfo { + privateKey: string; // Decrypted private key + passphrase?: string; // Decrypted passphrase +} + +// Interface for creating/updating SSH keys (sending to backend) +export interface SshKeyInput { + name: string; + private_key: string; // Plain text private key + passphrase?: string; // Plain text passphrase +} + + +export const useSshKeysStore = defineStore('sshKeys', () => { + const uiNotificationsStore = useUiNotificationsStore(); + const sshKeys = ref([]); + const isLoading = ref(false); + const error = ref(null); + + // --- Actions --- + + // Fetch all SSH key names + async function fetchSshKeys() { + isLoading.value = true; + error.value = null; + try { + const response = await apiClient.get('/ssh-keys'); + sshKeys.value = response.data; + console.log('SSH Keys fetched:', sshKeys.value); + } catch (err: any) { + console.error('Failed to fetch SSH keys:', err); + error.value = err.response?.data?.message || err.message || '获取 SSH 密钥列表失败。'; + // Ensure error.value is not null before passing + uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' }); + } finally { + isLoading.value = false; + } + } + + // Add a new SSH key + async function addSshKey(keyInput: SshKeyInput): Promise { + isLoading.value = true; + error.value = null; + try { + const response = await apiClient.post<{ message: string, key: SshKeyBasicInfo }>('/ssh-keys', keyInput); + // Add the new key to the local list + sshKeys.value.push(response.data.key); + // Sort keys by name + sshKeys.value.sort((a, b) => a.name.localeCompare(b.name)); + uiNotificationsStore.addNotification({ message: response.data.message || 'SSH 密钥添加成功。', type: 'success' }); + return true; + } catch (err: any) { + console.error('Failed to add SSH key:', err); + error.value = err.response?.data?.message || err.message || '添加 SSH 密钥失败。'; + // Ensure error.value is not null before passing + uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' }); + return false; + } finally { + isLoading.value = false; + } + } + + // Fetch decrypted details for a single key (used for editing) + async function fetchDecryptedSshKey(id: number): Promise { + isLoading.value = true; // Consider a different loading state if needed + error.value = null; + try { + // Use the dedicated details endpoint + const response = await apiClient.get(`/ssh-keys/${id}/details`); + return response.data; + } catch (err: any) { + console.error(`Failed to fetch decrypted SSH key ${id}:`, err); + error.value = err.response?.data?.message || err.message || `获取密钥 ${id} 详情失败。`; + // Ensure error.value is not null before passing + uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' }); + return null; + } finally { + isLoading.value = false; // Reset loading state + } + } + + + // Update an existing SSH key + async function updateSshKey(id: number, keyInput: Partial): Promise { + isLoading.value = true; + error.value = null; + try { + const response = await apiClient.put<{ message: string, key: SshKeyBasicInfo }>(`/ssh-keys/${id}`, keyInput); + // Update the key in the local list + const index = sshKeys.value.findIndex(key => key.id === id); + if (index !== -1) { + sshKeys.value[index] = { ...sshKeys.value[index], ...response.data.key }; // Update with new basic info + // Sort keys by name again if name changed + sshKeys.value.sort((a, b) => a.name.localeCompare(b.name)); + } + uiNotificationsStore.addNotification({ message: response.data.message || 'SSH 密钥更新成功。', type: 'success' }); + return true; + } catch (err: any) { + console.error(`Failed to update SSH key ${id}:`, err); + error.value = err.response?.data?.message || err.message || `更新 SSH 密钥 ${id} 失败。`; + // Ensure error.value is not null before passing + uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' }); + return false; + } finally { + isLoading.value = false; + } + } + + // Delete an SSH key + async function deleteSshKey(id: number): Promise { + isLoading.value = true; + error.value = null; + try { + const response = await apiClient.delete<{ message: string }>(`/ssh-keys/${id}`); + // Remove the key from the local list + sshKeys.value = sshKeys.value.filter(key => key.id !== id); + uiNotificationsStore.addNotification({ message: response.data.message || 'SSH 密钥删除成功。', type: 'success' }); + return true; + } catch (err: any) { + console.error(`Failed to delete SSH key ${id}:`, err); + error.value = err.response?.data?.message || err.message || `删除 SSH 密钥 ${id} 失败。`; + // Ensure error.value is not null before passing + uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' }); + return false; + } finally { + isLoading.value = false; + } + } + + return { + sshKeys, + isLoading, + error, + fetchSshKeys, + addSshKey, + fetchDecryptedSshKey, + updateSshKey, + deleteSshKey, + }; +}); \ No newline at end of file