feat: 新增密钥管理界面

#1
This commit is contained in:
Baobhan Sith
2025-05-01 17:40:36 +08:00
parent 2d7434d778
commit 2a201739cb
19 changed files with 1449 additions and 104 deletions
+5 -1
View File
@@ -3,7 +3,7 @@ import sqlite3, { OPEN_READWRITE, OPEN_CREATE } from 'sqlite3';
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
import { tableDefinitions } from './schema.registry'; import { tableDefinitions } from './schema.registry';
import { runMigrations } from './migrations'; // +++ Import runMigrations +++
const dbDir = path.join(__dirname, '..', '..', 'data'); const dbDir = path.join(__dirname, '..', '..', 'data');
const dbFilename = 'nexus-terminal.db'; const dbFilename = 'nexus-terminal.db';
@@ -103,7 +103,11 @@ export const getDbInstance = (): Promise<sqlite3.Database> => {
try { try {
// 运行初始表创建
await runDatabaseInitializations(db); await runDatabaseInitializations(db);
// +++ 运行数据库迁移 +++
await runMigrations(db);
console.log('[数据库] 初始化和迁移完成。'); // 添加日志确认
resolve(db); resolve(db);
} catch (initError) { } catch (initError) {
console.error('[数据库] 连接后初始化失败,正在关闭连接...'); console.error('[数据库] 连接后初始化失败,正在关闭连接...');
+152 -7
View File
@@ -1,17 +1,162 @@
import { Database } from 'sqlite3'; 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 数据库实例 * @param db 数据库实例
*/ */
export const runMigrations = (db: Database): Promise<void> => { export const runMigrations = (db: Database): Promise<void> => {
return new Promise<void>((resolve) => { return new Promise((resolve, reject) => {
console.log('[Migrations] 检查数据库迁移(当前无操作)。'); console.log('[Migrations] 开始检查和应用数据库迁移...');
resolve();
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);
});
});
});
}); });
}; };
+14 -1
View File
@@ -85,10 +85,23 @@ CREATE TABLE IF NOT EXISTS connections (
encrypted_private_key TEXT NULL, encrypted_private_key TEXT NULL,
encrypted_passphrase TEXT NULL, encrypted_passphrase TEXT NULL,
proxy_id INTEGER NULL, proxy_id INTEGER NULL,
ssh_key_id INTEGER NULL, -- 新增 ssh_key_id 列
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
last_connected_at INTEGER NULL, 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'))
); );
`; `;
+2
View File
@@ -20,6 +20,7 @@ import commandHistoryRoutes from './command-history/command-history.routes';
import quickCommandsRoutes from './quick-commands/quick-commands.routes'; import quickCommandsRoutes from './quick-commands/quick-commands.routes';
import terminalThemeRoutes from './terminal-themes/terminal-theme.routes'; import terminalThemeRoutes from './terminal-themes/terminal-theme.routes';
import appearanceRoutes from './appearance/appearance.routes'; import appearanceRoutes from './appearance/appearance.routes';
import sshKeysRouter from './ssh_keys/ssh_keys.routes'; // +++ Import SSH Key routes +++
import { initializeWebSocket } from './websocket'; import { initializeWebSocket } from './websocket';
import { ipWhitelistMiddleware } from './auth/ipWhitelist.middleware'; import { ipWhitelistMiddleware } from './auth/ipWhitelist.middleware';
@@ -259,6 +260,7 @@ const startServer = () => {
app.use('/api/v1/quick-commands', quickCommandsRoutes); app.use('/api/v1/quick-commands', quickCommandsRoutes);
app.use('/api/v1/terminal-themes', terminalThemeRoutes); app.use('/api/v1/terminal-themes', terminalThemeRoutes);
app.use('/api/v1/appearance', appearanceRoutes); 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) => { app.get('/api/v1/status', (req: Request, res: Response) => {
@@ -39,7 +39,9 @@ export interface FullConnectionData extends ConnectionBase {
// FullConnectionDbRow implicitly includes 'type' via FullConnectionData // 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 { interface FullConnectionDbRow extends FullConnectionData {
ssh_key_id?: number | null; // +++ Add ssh_key_id +++
proxy_db_id: number | null; proxy_db_id: number | null;
proxy_name: string | null; proxy_name: string | null;
proxy_type: string | null; proxy_type: string | null;
@@ -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<SshKeyDbRow, 'id' | 'created_at' | 'updated_at'>;
// 定义更新时需要的数据接口 (所有字段可选,除了 id)
export type UpdateSshKeyData = Partial<Omit<SshKeyDbRow, 'id' | 'created_at'>>;
/**
* 创建新的 SSH 密钥记录
* @param data - 包含密钥名称和加密后凭证的对象
* @returns Promise<number> 新创建记录的 ID
*/
export const createSshKey = async (data: CreateSshKeyData): Promise<number> => {
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<SshKeyDbRow | null> 找到的密钥记录或 null
*/
export const findSshKeyById = async (id: number): Promise<SshKeyDbRow | null> => {
const sql = `SELECT * FROM ssh_keys WHERE id = ?`;
try {
const db = await getDbInstance();
const row = await getDbRow<SshKeyDbRow>(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<boolean> 是否更新成功
*/
export const updateSshKey = async (id: number, data: UpdateSshKeyData): Promise<boolean> => {
// 过滤掉 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<boolean> 是否删除成功
*/
export const deleteSshKey = async (id: number): Promise<boolean> => {
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}`);
}
};
@@ -1,6 +1,7 @@
import * as ConnectionRepository from '../repositories/connection.repository'; import * as ConnectionRepository from '../repositories/connection.repository';
import { encrypt, decrypt } from '../utils/crypto'; 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 { import {
ConnectionBase, ConnectionBase,
ConnectionWithTags, ConnectionWithTags,
@@ -36,6 +37,9 @@ export const getConnectionById = async (id: number): Promise<ConnectionWithTags
* 创建新连接 * 创建新连接
*/ */
export const createConnection = async (input: CreateConnectionInput): Promise<ConnectionWithTags> => { export const createConnection = async (input: CreateConnectionInput): Promise<ConnectionWithTags> => {
// +++ Define a local type alias for clarity, including ssh_key_id +++
type ConnectionDataForRepo = Omit<FullConnectionData, 'id' | 'created_at' | 'updated_at' | 'last_connected_at' | 'tag_ids'>;
console.log('[Service:createConnection] Received input:', JSON.stringify(input, null, 2)); // Log input console.log('[Service:createConnection] Received input:', JSON.stringify(input, null, 2)); // Log input
// 1. 验证输入 (包含 type) // 1. 验证输入 (包含 type)
// Convert type to uppercase for validation and consistency // Convert type to uppercase for validation and consistency
@@ -54,8 +58,12 @@ export const createConnection = async (input: CreateConnectionInput): Promise<Co
if (input.auth_method === 'password' && !input.password) { if (input.auth_method === 'password' && !input.password) {
throw new Error('SSH 密码认证方式需要提供 password。'); throw new Error('SSH 密码认证方式需要提供 password。');
} }
if (input.auth_method === 'key' && !input.private_key) { // If using ssh_key_id, private_key is not required in the input
throw new Error('SSH 密钥认证方式需要提供 private_key'); if (input.auth_method === 'key' && !input.ssh_key_id && !input.private_key) {
throw new Error('SSH 密钥认证方式需要提供 private_key 或选择一个已保存的密钥 (ssh_key_id)。');
}
if (input.auth_method === 'key' && input.ssh_key_id && input.private_key) {
throw new Error('不能同时提供 private_key 和 ssh_key_id。');
} }
} else if (connectionType === 'RDP') { } else if (connectionType === 'RDP') {
if (!input.password) { if (!input.password) {
@@ -64,10 +72,11 @@ export const createConnection = async (input: CreateConnectionInput): Promise<Co
// For RDP, we'll ignore auth_method, private_key, passphrase from input if provided // For RDP, we'll ignore auth_method, private_key, passphrase from input if provided
} }
// 2. 加密凭证 (根据 type) // 2. 处理凭证和 ssh_key_id (根据 type)
let encryptedPassword = null; let encryptedPassword = null;
let encryptedPrivateKey = null; let encryptedPrivateKey = null;
let encryptedPassphrase = null; let encryptedPassphrase = null;
let sshKeyIdToSave: number | null = null; // +++ Variable for ssh_key_id +++
// Default to 'password' for DB compatibility, especially for RDP // Default to 'password' for DB compatibility, especially for RDP
let authMethodForDb: 'password' | 'key' = 'password'; let authMethodForDb: 'password' | 'key' = 'password';
@@ -75,10 +84,28 @@ export const createConnection = async (input: CreateConnectionInput): Promise<Co
authMethodForDb = input.auth_method!; // Already validated above authMethodForDb = input.auth_method!; // Already validated above
if (input.auth_method === 'password') { if (input.auth_method === 'password') {
encryptedPassword = encrypt(input.password!); encryptedPassword = encrypt(input.password!);
} else { // key sshKeyIdToSave = null; // Password auth cannot use ssh_key_id
encryptedPrivateKey = encrypt(input.private_key!); } else { // auth_method is 'key'
if (input.passphrase) { if (input.ssh_key_id) {
encryptedPassphrase = encrypt(input.passphrase); // 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} 无效或不存在。`);
}
sshKeyIdToSave = input.ssh_key_id;
// When using ssh_key_id, connection's own key fields should be null
encryptedPrivateKey = null;
encryptedPassphrase = null;
} else if (input.private_key) {
// Encrypt the provided private key and passphrase
encryptedPrivateKey = encrypt(input.private_key!);
if (input.passphrase) {
encryptedPassphrase = encrypt(input.passphrase);
}
sshKeyIdToSave = null; // Ensure ssh_key_id is null if providing key directly
} else {
// This case should be caught by validation above, but as a safeguard:
throw new Error('SSH 密钥认证方式内部错误:未提供 private_key 或 ssh_key_id。');
} }
} }
} else { // RDP (connectionType is 'RDP') } else { // RDP (connectionType is 'RDP')
@@ -91,23 +118,30 @@ export const createConnection = async (input: CreateConnectionInput): Promise<Co
// 3. 准备仓库数据 // 3. 准备仓库数据
const defaultPort = input.type === 'RDP' ? 3389 : 22; const defaultPort = input.type === 'RDP' ? 3389 : 22;
// Explicitly type the object being passed to the repository // +++ Explicitly type connectionData using the local alias +++
const connectionData: Omit<ConnectionRepository.FullConnectionData, 'id' | 'created_at' | 'updated_at' | 'last_connected_at' | 'tag_ids'> = { const connectionData: ConnectionDataForRepo = {
name: input.name || '', name: input.name || '',
type: connectionType, // Use the validated uppercase type type: connectionType,
host: input.host, host: input.host,
port: input.port ?? defaultPort, // Use type-specific default port port: input.port ?? defaultPort, // Use type-specific default port
username: input.username, username: input.username,
auth_method: authMethodForDb, // Use determined auth method auth_method: authMethodForDb, // Use determined auth method
encrypted_password: encryptedPassword, encrypted_password: encryptedPassword,
encrypted_private_key: encryptedPrivateKey, // Will be null for RDP encrypted_private_key: encryptedPrivateKey, // Null if using ssh_key_id or RDP
encrypted_passphrase: encryptedPassphrase, // Will be null for 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, 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. 在仓库中创建连接记录 // 4. 在仓库中创建连接记录
const newConnectionId = await ConnectionRepository.createConnection(connectionData); // Pass the potentially modified finalConnectionData
const newConnectionId = await ConnectionRepository.createConnection(finalConnectionData as Omit<ConnectionRepository.FullConnectionData, 'id' | 'created_at' | 'updated_at' | 'last_connected_at' | 'tag_ids'>);
// 5. 处理标签 // 5. 处理标签
const tagIds = input.tag_ids?.filter(id => typeof id === 'number' && id > 0) ?? []; 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. 准备更新数据 // 2. 准备更新数据
// Explicitly type dataToUpdate to match the repository's expected input // Explicitly type dataToUpdate to match the repository's expected input, including ssh_key_id
const dataToUpdate: Partial<Omit<ConnectionRepository.FullConnectionData, 'id' | 'created_at' | 'last_connected_at' | 'tag_ids'>> = {}; const dataToUpdate: Partial<Omit<ConnectionRepository.FullConnectionData & { ssh_key_id?: number | null }, 'id' | 'created_at' | 'last_connected_at' | 'tag_ids'>> = {};
let needsCredentialUpdate = false; let needsCredentialUpdate = false;
// Determine the final type, converting input type to uppercase if provided // Determine the final type, converting input type to uppercase if provided
const targetType = input.type?.toUpperCase() as 'SSH' | 'RDP' | undefined || currentFullConnection.type; 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.port !== undefined) dataToUpdate.port = input.port;
if (input.username !== undefined) dataToUpdate.username = input.username; if (input.username !== undefined) dataToUpdate.username = input.username;
if (input.proxy_id !== undefined) dataToUpdate.proxy_id = input.proxy_id; 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) // 处理认证方法更改或凭证更新 (根据 targetType)
// Use the validated targetType for logic // 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; dataToUpdate.encrypted_password = input.password ? encrypt(input.password) : null;
needsCredentialUpdate = true; needsCredentialUpdate = true;
} }
// When switching to password, clear key fields // When switching to password, clear key fields and ssh_key_id
if (finalAuthMethod !== currentAuthMethod) { if (finalAuthMethod !== currentAuthMethod) {
dataToUpdate.encrypted_private_key = null; dataToUpdate.encrypted_private_key = null;
dataToUpdate.encrypted_passphrase = null; dataToUpdate.encrypted_passphrase = null;
dataToUpdate.ssh_key_id = null; // Clear ssh_key_id when switching to password
} }
} else { // finalAuthMethod is 'key' } else { // finalAuthMethod is 'key'
let keyUpdated = false; // Handle ssh_key_id selection or direct key input
// If switching to key or updating key if (input.ssh_key_id !== undefined) {
if (input.private_key !== undefined) { // User selected a stored key
if (!input.private_key && finalAuthMethod !== currentAuthMethod) { if (input.ssh_key_id === null) {
// Switching to key requires a private key // User explicitly wants to clear the stored key association
throw new Error('切换到密钥认证时需要提供 private_key。'); dataToUpdate.ssh_key_id = null;
} // If clearing ssh_key_id, we might need a direct key, but validation should handle this?
// Encrypt if key is not empty, otherwise set to null (to clear) // Or assume clearing means switching back to direct key input (which might be empty)
dataToUpdate.encrypted_private_key = input.private_key ? encrypt(input.private_key) : null; // Let's assume clearing ssh_key_id means we expect a direct key or nothing
needsCredentialUpdate = true; if (input.private_key === undefined) {
keyUpdated = true; // If no direct key provided when clearing ssh_key_id, clear connection's key fields
} dataToUpdate.encrypted_private_key = null;
// Update passphrase only if key was updated OR passphrase itself was provided dataToUpdate.encrypted_passphrase = null;
if (keyUpdated || input.passphrase !== undefined) { } else {
// Encrypt if passphrase is not empty, otherwise set to null (to clear) // 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; 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) { if (finalAuthMethod !== currentAuthMethod) {
dataToUpdate.encrypted_password = null; 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.auth_method = 'password'; // RDP uses password auth method in DB
dataToUpdate.encrypted_private_key = null; dataToUpdate.encrypted_private_key = null;
dataToUpdate.encrypted_passphrase = 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<boolean> => {
export const getConnectionWithDecryptedCredentials = async ( export const getConnectionWithDecryptedCredentials = async (
id: number id: number
): Promise<{ connection: ConnectionWithTags; decryptedPassword?: string; decryptedPrivateKey?: string; decryptedPassphrase?: string } | null> => { ): Promise<{ connection: ConnectionWithTags; decryptedPassword?: string; decryptedPrivateKey?: string; decryptedPassphrase?: string } | null> => {
// 1. 获取完整的连接数据(包含加密字段) // 1. 获取完整的连接数据(包含加密字段和可能的 ssh_key_id
// Assuming findFullConnectionById exists and returns FullConnectionDbRow or null
const fullConnectionDbRow = await ConnectionRepository.findFullConnectionById(id); const fullConnectionDbRow = await ConnectionRepository.findFullConnectionById(id);
if (!fullConnectionDbRow) { if (!fullConnectionDbRow) {
console.log(`[Service:getConnWithDecrypt] Connection not found for ID: ${id}`); console.log(`[Service:getConnWithDecrypt] Connection not found for ID: ${id}`);
@@ -291,11 +363,11 @@ export const getConnectionWithDecryptedCredentials = async (
const fullConnection: FullConnectionData = { const fullConnection: FullConnectionData = {
...fullConnectionDbRow, ...fullConnectionDbRow,
encrypted_password: fullConnectionDbRow.encrypted_password ?? null, encrypted_password: fullConnectionDbRow.encrypted_password ?? null,
encrypted_private_key: fullConnectionDbRow.encrypted_private_key ?? null, encrypted_private_key: fullConnectionDbRow.encrypted_private_key ?? null, // May be null if using ssh_key_id
encrypted_passphrase: fullConnectionDbRow.encrypted_passphrase ?? null, 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 // Ensure other fields match FullConnectionData if necessary
// (Assuming FullConnectionDbRow includes all fields of FullConnectionData) } as FullConnectionData & { ssh_key_id: number | null }; // Type assertion
};
// 2. 获取带标签的连接数据(用于返回给调用者) // 2. 获取带标签的连接数据(用于返回给调用者)
const connectionWithTags: ConnectionWithTags | null = await ConnectionRepository.findConnectionByIdWithTags(id); const connectionWithTags: ConnectionWithTags | null = await ConnectionRepository.findConnectionByIdWithTags(id);
@@ -318,15 +390,31 @@ export const getConnectionWithDecryptedCredentials = async (
} }
// Decrypt key and passphrase if method is 'key' // Decrypt key and passphrase if method is 'key'
else if (fullConnection.auth_method === '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); decryptedPrivateKey = decrypt(fullConnection.encrypted_private_key);
} // Only decrypt passphrase if it exists alongside the direct key
// Only decrypt passphrase if it exists if (fullConnection.encrypted_passphrase) {
if (fullConnection.encrypted_passphrase) { decryptedPassphrase = decrypt(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); console.error(`[Service:getConnWithDecrypt] Failed to decrypt credentials for connection ID ${id}:`, error);
// Decide how to handle decryption errors. Throw? Return null password? // Decide how to handle decryption errors. Throw? Return null password?
// For now, we'll log and continue, returning undefined credentials. // For now, we'll log and continue, returning undefined credentials.
+60 -8
View File
@@ -5,6 +5,7 @@ import net from 'net';
import * as ConnectionRepository from '../repositories/connection.repository'; import * as ConnectionRepository from '../repositories/connection.repository';
import * as ProxyRepository from '../repositories/proxy.repository'; import * as ProxyRepository from '../repositories/proxy.repository';
import { decrypt } from '../utils/crypto'; import { decrypt } from '../utils/crypto';
import * as SshKeyService from './ssh_key.service'; // +++ Import SshKeyService +++
const CONNECT_TIMEOUT = 20000; // 连接超时时间 (毫秒) const CONNECT_TIMEOUT = 20000; // 连接超时时间 (毫秒)
const TEST_TIMEOUT = 15000; // 测试连接超时时间 (毫秒) const TEST_TIMEOUT = 15000; // 测试连接超时时间 (毫秒)
@@ -56,12 +57,41 @@ export const getConnectionDetails = async (connectionId: number): Promise<Decryp
port: rawConnInfo.port ?? (() => { throw new Error(`Connection ID ${connectionId} has null port.`); })(), port: rawConnInfo.port ?? (() => { throw new Error(`Connection ID ${connectionId} has null port.`); })(),
username: rawConnInfo.username ?? (() => { throw new Error(`Connection ID ${connectionId} has null username.`); })(), 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.`); })(), 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, // Initialize credentials
privateKey: (rawConnInfo.auth_method === 'key' && rawConnInfo.encrypted_private_key) ? decrypt(rawConnInfo.encrypted_private_key) : undefined, password: undefined,
passphrase: (rawConnInfo.auth_method === 'key' && rawConnInfo.encrypted_passphrase) ? decrypt(rawConnInfo.encrypted_passphrase) : undefined, privateKey: undefined,
passphrase: undefined,
proxy: null, 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) { if (rawConnInfo.proxy_db_id) {
// Add null checks for required proxy fields inside the if block // 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.`); })(); 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 * @returns Promise<{ latency: number }> - resolve reject
* @throws Error * @throws Error
*/ */
// Ensure ssh_key_id is part of the input type definition
export const testUnsavedConnection = async (connectionConfig: { export const testUnsavedConnection = async (connectionConfig: {
host: string; host: string;
port: number; port: number;
username: string; username: string;
auth_method: 'password' | 'key'; auth_method: 'password' | 'key';
password?: string; password?: string;
private_key?: string; // 注意这里是 private_key private_key?: string; // Keep this for direct input
passphrase?: string; passphrase?: string;
ssh_key_id?: number | null; // Ensure this is present
proxy_id?: number | null; proxy_id?: number | null;
}): Promise<{ latency: number }> => { }): Promise<{ latency: number }> => {
console.log(`SshService: 测试未保存的连接到 ${connectionConfig.host}:${connectionConfig.port}...`); console.log(`SshService: 测试未保存的连接到 ${connectionConfig.host}:${connectionConfig.port}...`);
@@ -329,13 +361,33 @@ export const testUnsavedConnection = async (connectionConfig: {
port: connectionConfig.port, port: connectionConfig.port,
username: connectionConfig.username, username: connectionConfig.username,
auth_method: connectionConfig.auth_method, auth_method: connectionConfig.auth_method,
// 直接使用传入的凭证,因为它们是未加密的 // Initialize credentials, will be populated based on input
password: connectionConfig.password, password: undefined,
privateKey: connectionConfig.private_key, // 映射 private_key privateKey: undefined,
passphrase: connectionConfig.passphrase, passphrase: undefined,
proxy: null, // 稍后填充 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,获取并解密代理信息 // 2. 如果提供了 proxy_id,获取并解密代理信息
if (connectionConfig.proxy_id) { if (connectionConfig.proxy_id) {
console.log(`SshService: 测试连接需要获取代理 ${connectionConfig.proxy_id} 的信息...`); console.log(`SshService: 测试连接需要获取代理 ${connectionConfig.proxy_id} 的信息...`);
@@ -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<SshKeyBasicInfo>
*/
export const createSshKey = async (input: CreateSshKeyInput): Promise<SshKeyBasicInfo> => {
// 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<SshKeyBasicInfo[]>
*/
export const getAllSshKeyNames = async (): Promise<SshKeyBasicInfo[]> => {
return SshKeyRepository.findAllSshKeyNames();
};
/**
* ID SSH ()
* 使
* @param id ID
* @returns Promise<SshKeyDbRow | null> null
*/
export const getSshKeyDbRowById = async (id: number): Promise<SshKeyDbRow | null> => {
return SshKeyRepository.findSshKeyById(id);
};
/**
* ID SSH
* @param id ID
* @returns Promise<DecryptedSshKeyDetails | null> null
*/
export const getDecryptedSshKeyById = async (id: number): Promise<DecryptedSshKeyDetails | null> => {
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<SshKeyBasicInfo | null> null ()
*/
export const updateSshKey = async (id: number, input: UpdateSshKeyInput): Promise<SshKeyBasicInfo | null> => {
// 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<boolean>
*/
export const deleteSshKey = async (id: number): Promise<boolean> => {
// 注意:删除密钥前,相关的 connections 表中的 ssh_key_id 会被设为 NULL (ON DELETE SET NULL)
return SshKeyRepository.deleteSshKey(id);
};
@@ -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<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
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 密钥时发生内部服务器错误。' });
}
};
@@ -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;
@@ -28,7 +28,8 @@ export interface CreateConnectionInput {
auth_method: 'password' | 'key'; auth_method: 'password' | 'key';
password?: string; password?: string;
private_key?: string; private_key?: string;
passphrase?: string; passphrase?: string;
ssh_key_id?: number | null; // +++ Add ssh_key_id +++
proxy_id?: number | null; proxy_id?: number | null;
tag_ids?: number[]; tag_ids?: number[];
} }
@@ -43,7 +44,8 @@ export interface UpdateConnectionInput {
auth_method?: 'password' | 'key'; auth_method?: 'password' | 'key';
password?: string; password?: string;
private_key?: string; private_key?: string;
passphrase?: string; passphrase?: string;
ssh_key_id?: number | null; // +++ Add ssh_key_id +++
proxy_id?: number | null; proxy_id?: number | null;
tag_ids?: number[]; tag_ids?: number[];
} }
@@ -60,6 +62,7 @@ export interface FullConnectionData {
encrypted_password: string | null; encrypted_password: string | null;
encrypted_private_key: string | null; encrypted_private_key: string | null;
encrypted_passphrase: string | null; encrypted_passphrase: string | null;
ssh_key_id?: number | null; // +++ Add ssh_key_id +++
proxy_id: number | null; proxy_id: number | null;
created_at: number; created_at: number;
updated_at: number; updated_at: number;
@@ -6,7 +6,9 @@ import apiClient from '../utils/apiClient';
import { useConnectionsStore, ConnectionInfo } from '../stores/connections.store'; import { useConnectionsStore, ConnectionInfo } from '../stores/connections.store';
import { useProxiesStore } from '../stores/proxies.store'; import { useProxiesStore } from '../stores/proxies.store';
import { useTagsStore } from '../stores/tags.store'; import { useTagsStore } from '../stores/tags.store';
import { useSshKeysStore } from '../stores/sshKeys.store'; // +++ Import SSH Key store +++
import TagInput from './TagInput.vue'; import TagInput from './TagInput.vue';
import SshKeySelector from './SshKeySelector.vue'; // +++ Import SSH Key Selector +++
// //
const emit = defineEmits(['close', 'connection-added', 'connection-updated']); const emit = defineEmits(['close', 'connection-added', 'connection-updated']);
@@ -33,8 +35,9 @@ const initialFormData = {
username: '', username: '',
auth_method: 'password' as 'password' | 'key', // SSH specific auth_method: 'password' as 'password' | 'key', // SSH specific
password: '', password: '',
private_key: '', // SSH specific private_key: '', // SSH specific (for direct input)
passphrase: '', // SSH specific 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, proxy_id: null as number | null,
tag_ids: [] as number[], // tag_ids tag_ids: [] as number[], // tag_ids
// Add RDP specific fields later if needed, e.g., domain // Add RDP specific fields later if needed, e.g., domain
@@ -138,8 +141,9 @@ const handleSubmit = async () => {
formError.value = t('connections.form.errorPasswordRequired'); formError.value = t('connections.form.errorPasswordRequired');
return; return;
} }
if (formData.auth_method === 'key' && !formData.private_key) { // key
formError.value = t('connections.form.errorPrivateKeyRequired'); if (formData.auth_method === 'key' && !formData.selected_ssh_key_id) {
formError.value = t('connections.form.errorSshKeyRequired'); //
return; return;
} }
} }
@@ -153,14 +157,16 @@ const handleSubmit = async () => {
} }
// //
} }
// 3. // 3.
else if (isEditMode.value && formData.auth_method === 'key' && !formData.private_key) { else if (isEditMode.value && formData.auth_method === 'key' && !formData.selected_ssh_key_id) {
// //
if (props.connectionToEdit?.auth_method !== 'key') { if (props.connectionToEdit?.auth_method !== 'key') {
formError.value = t('connections.form.errorPrivateKeyRequiredOnSwitch'); formError.value = t('connections.form.errorSshKeyRequiredOnSwitch'); //
return; return;
} }
// //
//
// selected_ssh_key_id null
} }
// Use uppercase for comparison // Use uppercase for comparison
} else if (formData.type === 'RDP') { } else if (formData.type === 'RDP') {
@@ -203,16 +209,21 @@ const handleSubmit = async () => {
// password // password
} }
} else if (formData.auth_method === 'key') { } else if (formData.auth_method === 'key') {
// SSH // +++ SSH ( selected_ssh_key_id) +++
if (formData.private_key) { if (formData.selected_ssh_key_id) {
dataToSend.private_key = formData.private_key; // ID
} dataToSend.ssh_key_id = formData.selected_ssh_key_id;
// SSH } else if (isEditMode.value && props.connectionToEdit?.auth_method === 'key') {
if (formData.passphrase) { // ssh_key_id ()
dataToSend.passphrase = formData.passphrase; // ()
} else if (isEditMode.value && formData.passphrase === '') { } else {
// dataToSend.passphrase = null; // null // 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 // Use uppercase for comparison
} else if (formData.type === 'RDP') { } else if (formData.type === 'RDP') {
@@ -273,9 +284,11 @@ const handleTestConnection = async () => {
username: formData.username, username: formData.username,
auth_method: formData.auth_method, auth_method: formData.auth_method,
password: formData.auth_method === 'password' ? formData.password : undefined, password: formData.auth_method === 'password' ? formData.password : undefined,
private_key: formData.auth_method === 'key' ? formData.private_key : undefined, // private_key: formData.auth_method === 'key' ? formData.private_key : undefined, // Removed
passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined, // passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined, // Removed
proxy_id: formData.proxy_id || null, 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 if (dataToSend.auth_method === 'password' && !formData.password) { // formData dataToSend.password
throw new Error(t('connections.form.errorPasswordRequired')); // throw new Error(t('connections.form.errorPasswordRequired')); //
} }
if (dataToSend.auth_method === 'key' && !formData.private_key) { // formData dataToSend.private_key // +++ Check selected key for testing +++
throw new Error(t('connections.form.errorPrivateKeyRequired')); // if (dataToSend.auth_method === 'key' && !dataToSend.ssh_key_id) {
} throw new Error(t('connections.form.errorSshKeyRequired')); // 使
}
// API // API
response = await apiClient.post('/connections/test-unsaved', dataToSend); response = await apiClient.post('/connections/test-unsaved', dataToSend);
@@ -409,19 +423,17 @@ const testButtonText = computed(() => {
</div> </div>
<div v-if="formData.auth_method === 'key'" class="space-y-4"> <div v-if="formData.auth_method === 'key'" class="space-y-4">
<!-- +++ SSH Key Selector +++ -->
<div> <div>
<label for="conn-private-key" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.privateKey') }}</label> <label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.sshKey') }}</label>
<textarea id="conn-private-key" v-model="formData.private_key" rows="4" :required="formData.auth_method === 'key' && !isEditMode" <SshKeySelector v-model="formData.selected_ssh_key_id" />
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary font-mono text-sm"></textarea>
</div>
<div>
<label for="conn-passphrase" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.passphrase') }} ({{ t('connections.form.optional') }})</label>
<input type="password" id="conn-passphrase" v-model="formData.passphrase" autocomplete="new-password"
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
<div v-if="isEditMode && formData.auth_method === 'key'">
<small class="block text-xs text-text-secondary">{{ t('connections.form.keyUpdateNote') }}</small>
</div> </div>
<!-- Direct Key Input Removed -->
<!-- Note for selected key -->
<div v-if="isEditMode && formData.auth_method === 'key' && formData.selected_ssh_key_id">
<small class="block text-xs text-text-secondary">{{ t('connections.form.keyUpdateNoteSelected') }}</small>
</div>
</div> </div>
</template> </template>
@@ -0,0 +1,225 @@
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSshKeysStore, SshKeyBasicInfo, SshKeyInput } from '../stores/sshKeys.store';
import { useUiNotificationsStore } from '../stores/uiNotifications.store';
const emit = defineEmits(['close']);
const { t } = useI18n();
const sshKeysStore = useSshKeysStore();
const uiNotificationsStore = useUiNotificationsStore();
const keys = computed(() => sshKeysStore.sshKeys);
const isLoading = computed(() => sshKeysStore.isLoading);
const isAddEditFormVisible = ref(false);
const keyToEdit = ref<SshKeyBasicInfo | null>(null); // Store basic info for editing
// Form data for adding/editing
const initialFormData: SshKeyInput = {
name: '',
private_key: '',
passphrase: '',
};
const formData = reactive({ ...initialFormData });
const formError = ref<string | null>(null);
// Fetch keys when the modal is mounted
onMounted(() => {
sshKeysStore.fetchSshKeys();
});
// Show the form for adding a new key
const showAddForm = () => {
keyToEdit.value = null;
Object.assign(formData, initialFormData); // Reset form
formError.value = null;
isAddEditFormVisible.value = true;
};
// Show the form for editing an existing key
const showEditForm = async (key: SshKeyBasicInfo) => {
formError.value = null;
keyToEdit.value = key; // Store the key being edited
// Fetch decrypted details to pre-fill the form (excluding passphrase for security)
const details = await sshKeysStore.fetchDecryptedSshKey(key.id);
if (details) {
formData.name = details.name;
formData.private_key = details.privateKey;
formData.passphrase = ''; // Do not pre-fill passphrase
isAddEditFormVisible.value = true;
} else {
// Handle error if details couldn't be fetched
uiNotificationsStore.addNotification({ message: t('sshKeys.modal.errorFetchDetails'), type: 'error' });
keyToEdit.value = null; // Reset edit state
}
};
// Handle form submission (add or edit)
const handleSubmit = async () => {
formError.value = null;
if (!formData.name || !formData.private_key) {
formError.value = t('sshKeys.modal.errorRequiredFields');
return;
}
let success = false;
const dataToSend: Partial<SshKeyInput> = {
name: formData.name,
private_key: formData.private_key,
// Only send passphrase if it's not empty
...(formData.passphrase && { passphrase: formData.passphrase }),
};
if (keyToEdit.value) {
// Edit mode
// Only send fields that changed? Or send all? Backend handles update logic.
// Let's send all potentially updatable fields for simplicity here.
success = await sshKeysStore.updateSshKey(keyToEdit.value.id, dataToSend);
} else {
// Add mode
success = await sshKeysStore.addSshKey(dataToSend as SshKeyInput); // Cast needed as all fields are required for add
}
if (success) {
isAddEditFormVisible.value = false; // Close form on success
} else {
// Error message is handled by the store and displayed via uiNotificationsStore
// Optionally set formError based on store error if needed for specific display
formError.value = sshKeysStore.error;
}
};
// Handle key deletion
const handleDelete = async (key: SshKeyBasicInfo) => {
// Simple confirmation dialog
if (confirm(t('sshKeys.modal.confirmDelete', { name: key.name }))) {
const success = await sshKeysStore.deleteSshKey(key.id);
if (!success) {
// Error handled by store
}
// If the deleted key was being edited, close the form
if (keyToEdit.value?.id === key.id) {
isAddEditFormVisible.value = false;
keyToEdit.value = null;
}
}
};
// Cancel add/edit form
const cancelForm = () => {
isAddEditFormVisible.value = false;
keyToEdit.value = null;
};
</script>
<template>
<div class="fixed inset-0 bg-overlay flex justify-center items-center z-50 p-4">
<div class="bg-background text-foreground p-6 rounded-lg shadow-xl border border-border w-full max-w-3xl max-h-[80vh] flex flex-col">
<!-- Main Modal Content -->
<div v-if="!isAddEditFormVisible" class="flex flex-col h-full">
<h3 class="text-xl font-semibold text-center mb-4 flex-shrink-0">{{ t('sshKeys.modal.title') }}</h3>
<div class="mb-4 flex justify-end flex-shrink-0">
<button @click="showAddForm"
class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50"
:disabled="isLoading">
<i class="fas fa-plus mr-2"></i>{{ t('sshKeys.modal.addKey') }}
</button>
</div>
<!-- Key List -->
<div class="flex-grow overflow-y-auto border border-border rounded-md">
<table class="min-w-full divide-y divide-border">
<thead class="bg-header sticky top-0">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('sshKeys.modal.keyName') }}
</th>
<th scope="col" class="px-6 py-3 text-right text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('sshKeys.modal.actions') }}
</th>
</tr>
</thead>
<tbody class="bg-background divide-y divide-border">
<tr v-if="isLoading">
<td colspan="2" class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary text-center">{{ t('sshKeys.modal.loading') }}</td>
</tr>
<tr v-else-if="keys.length === 0">
<td colspan="2" class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary text-center">{{ t('sshKeys.modal.noKeys') }}</td>
</tr>
<tr v-for="key in keys" :key="key.id">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">{{ key.name }}</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
<button @click="showEditForm(key)" class="text-primary hover:text-primary-hover disabled:opacity-50" :disabled="isLoading" :title="t('sshKeys.modal.edit')">
<i class="fas fa-pencil-alt"></i>
</button>
<button @click="handleDelete(key)" class="text-error hover:text-error-hover disabled:opacity-50" :disabled="isLoading" :title="t('sshKeys.modal.delete')">
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Close Button -->
<div class="mt-6 text-right flex-shrink-0">
<button @click="emit('close')"
class="px-4 py-2 bg-transparent text-text-secondary border border-border rounded-md shadow-sm hover:bg-border hover:text-foreground focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50"
:disabled="isLoading">
{{ t('sshKeys.modal.close') }}
</button>
</div>
</div>
<!-- Add/Edit Form -->
<div v-else class="flex flex-col h-full">
<h3 class="text-xl font-semibold text-center mb-6 flex-shrink-0">
{{ keyToEdit ? t('sshKeys.modal.editTitle') : t('sshKeys.modal.addTitle') }}
</h3>
<form @submit.prevent="handleSubmit" class="flex-grow overflow-y-auto pr-2 space-y-4">
<div>
<label for="key-name" class="block text-sm font-medium text-text-secondary mb-1">{{ t('sshKeys.modal.keyName') }}</label>
<input type="text" id="key-name" v-model="formData.name" required
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
<div>
<label for="key-private" class="block text-sm font-medium text-text-secondary mb-1">{{ t('sshKeys.modal.privateKey') }}</label>
<textarea id="key-private" v-model="formData.private_key" rows="8" required
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary font-mono text-sm"></textarea>
<small v-if="keyToEdit" class="block text-xs text-text-secondary mt-1">{{ t('sshKeys.modal.keyUpdateNote') }}</small>
</div>
<div>
<label for="key-passphrase" class="block text-sm font-medium text-text-secondary mb-1">{{ t('sshKeys.modal.passphrase') }} ({{ t('connections.form.optional') }})</label>
<input type="password" id="key-passphrase" v-model="formData.passphrase" autocomplete="new-password"
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
<small v-if="keyToEdit" class="block text-xs text-text-secondary mt-1">{{ t('sshKeys.modal.passphraseUpdateNote') }}</small>
</div>
<!-- Form Error -->
<div v-if="formError" class="text-error bg-error/10 border border-error/30 rounded-md p-3 text-sm text-center font-medium">
{{ formError }}
</div>
</form>
<!-- Form Actions -->
<div class="flex justify-end space-x-3 pt-5 mt-4 flex-shrink-0">
<button type="button" @click="cancelForm" :disabled="isLoading"
class="px-4 py-2 bg-transparent text-text-secondary border border-border rounded-md shadow-sm hover:bg-border hover:text-foreground focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50">
{{ t('sshKeys.modal.cancel') }}
</button>
<button type="submit" @click="handleSubmit" :disabled="isLoading"
class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50">
{{ keyToEdit ? t('sshKeys.modal.saveChanges') : t('sshKeys.modal.addKey') }}
</button>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSshKeysStore } from '../stores/sshKeys.store';
import SshKeyManagementModal from './SshKeyManagementModal.vue'; // Import the modal
const props = defineProps<{
modelValue: number | null; // The selected ssh_key_id (v-model)
}>();
const emit = defineEmits(['update:modelValue']); // Removed 'use-direct-input' event
const { t } = useI18n();
const sshKeysStore = useSshKeysStore();
const keys = computed(() => sshKeysStore.sshKeys);
const isLoading = computed(() => sshKeysStore.isLoading);
const isManagementModalVisible = ref(false);
// Internal state for the selected key ID
const selectedKeyId = ref<number | null>(props.modelValue); // Removed string type
// Watch for external changes to modelValue
watch(() => props.modelValue, (newVal) => {
selectedKeyId.value = newVal;
});
// Watch for internal changes and emit update or switch mode
watch(selectedKeyId, (newVal) => {
// Removed 'direct_input' check
if (typeof newVal === 'number') {
emit('update:modelValue', newVal); // Emit the selected key ID
} else {
emit('update:modelValue', null); // Handle clearing selection (when newVal is null)
}
});
const openManagementModal = () => {
isManagementModalVisible.value = true;
// Refresh keys list when modal opens, in case keys were added/deleted elsewhere
sshKeysStore.fetchSshKeys();
};
const closeManagementModal = () => {
isManagementModalVisible.value = false;
// Refresh keys list after modal closes
sshKeysStore.fetchSshKeys();
};
</script>
<template>
<div class="space-y-2">
<div class="flex items-center space-x-3">
<select id="ssh-key-select" v-model="selectedKeyId" :disabled="isLoading"
class="flex-grow px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary appearance-none bg-no-repeat bg-right pr-8"
style="background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 16 16\'%3e%3cpath fill=\'none\' stroke=\'%236c757d\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M2 5l6 6 6-6\'/%3e%3c/svg%3e'); background-position: right 0.75rem center; background-size: 16px 12px;">
<option :value="null">{{ t('sshKeys.selector.selectPlaceholder') }}</option>
<option v-for="key in keys" :key="key.id" :value="key.id">
{{ key.name }}
</option>
<!-- Removed direct input option -->
</select>
<button type="button" @click="openManagementModal" :disabled="isLoading"
class="px-3 py-2 border border-border rounded-md text-sm font-medium text-text-secondary bg-background hover:bg-border focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
:title="t('sshKeys.selector.manageKeysTitle')">
<i class="fas fa-cog"></i>
</button>
</div>
<div v-if="isLoading" class="text-xs text-text-secondary">{{ t('sshKeys.selector.loadingKeys') }}</div>
<div v-if="sshKeysStore.error" class="text-xs text-error">{{ t('sshKeys.selector.errorLoading', { error: sshKeysStore.error }) }}</div>
<!-- Key Management Modal -->
<SshKeyManagementModal v-if="isManagementModalVisible" @close="closeManagementModal" />
</div>
</template>
+35 -1
View File
@@ -166,7 +166,11 @@
"sectionAuth": "Authentication", "sectionAuth": "Authentication",
"sectionAdvanced": "Advanced Options", "sectionAdvanced": "Advanced Options",
"testConnection": "Test Connection", "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": { "test": {
"success": "Connection test successful!", "success": "Connection test successful!",
@@ -981,5 +985,35 @@
}, },
"terminalTabBar": { "terminalTabBar": {
"selectServerTitle": "Select server to connect" "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."
}
} }
} }
+35 -1
View File
@@ -138,7 +138,11 @@
"titleEdit": "接続の編集", "titleEdit": "接続の編集",
"typeRdp": "RDP", "typeRdp": "RDP",
"typeSsh": "SSH", "typeSsh": "SSH",
"username": "ユーザー名:" "username": "ユーザー名:",
"sshKey": "SSH キー",
"privateKeyDirect": "秘密鍵の内容",
"keyUpdateNoteDirect": "編集時に既存のキーを保持するには、秘密鍵とパスフレーズを空のままにしてください。",
"keyUpdateNoteSelected": "編集時にキーを変更するには、別のキーを選択するか、直接入力を使用してください。"
}, },
"noConnections": "接続がありません。'新しい接続を追加'をクリックして作成してください。", "noConnections": "接続がありません。'新しい接続を追加'をクリックして作成してください。",
"noUntaggedConnections": "タグなしの接続はありません。", "noUntaggedConnections": "タグなしの接続はありません。",
@@ -984,5 +988,35 @@
"noResults": "\"{searchTerm}\"に一致する接続は見つかりませんでした。", "noResults": "\"{searchTerm}\"に一致する接続は見つかりませんでした。",
"searchPlaceholder": "名前またはホストを検索...", "searchPlaceholder": "名前またはホストを検索...",
"untagged": "タグなし" "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": "パスフレーズを保持または削除するには空のままにします。更新するには新しいパスフレーズを入力してください。"
}
} }
} }
+35 -1
View File
@@ -166,7 +166,11 @@
"sectionAuth": "认证信息", "sectionAuth": "认证信息",
"sectionAdvanced": "高级选项", "sectionAdvanced": "高级选项",
"testConnection": "测试连接", "testConnection": "测试连接",
"testing": "测试中..." "testing": "测试中...",
"sshKey": "SSH 密钥",
"privateKeyDirect": "私钥内容",
"keyUpdateNoteDirect": "编辑时将私钥和密码短语留空以保留现有密钥。",
"keyUpdateNoteSelected": "编辑时选择其他密钥或使用直接输入来更改密钥。"
}, },
"test": { "test": {
"success": "连接测试成功!", "success": "连接测试成功!",
@@ -984,5 +988,35 @@
}, },
"terminalTabBar": { "terminalTabBar": {
"selectServerTitle": "选择要连接的服务器" "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": "留空表示不修改或移除密码短语。输入新密码短语以更新。"
}
} }
} }
@@ -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<SshKeyBasicInfo[]>([]);
const isLoading = ref(false);
const error = ref<string | null>(null);
// --- Actions ---
// Fetch all SSH key names
async function fetchSshKeys() {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.get<SshKeyBasicInfo[]>('/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<boolean> {
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<SshKeyDetails | null> {
isLoading.value = true; // Consider a different loading state if needed
error.value = null;
try {
// Use the dedicated details endpoint
const response = await apiClient.get<SshKeyDetails>(`/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<SshKeyInput>): Promise<boolean> {
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<boolean> {
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,
};
});