@@ -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<sqlite3.Database> => {
|
||||
|
||||
try {
|
||||
|
||||
// 运行初始表创建
|
||||
await runDatabaseInitializations(db);
|
||||
// +++ 运行数据库迁移 +++
|
||||
await runMigrations(db);
|
||||
console.log('[数据库] 初始化和迁移完成。'); // 添加日志确认
|
||||
resolve(db);
|
||||
} catch (initError) {
|
||||
console.error('[数据库] 连接后初始化失败,正在关闭连接...');
|
||||
|
||||
@@ -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<void> => {
|
||||
return new Promise<void>((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);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -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'))
|
||||
);
|
||||
`;
|
||||
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 { 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<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
|
||||
// 1. 验证输入 (包含 type)
|
||||
// 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) {
|
||||
throw new Error('SSH 密码认证方式需要提供 password。');
|
||||
}
|
||||
if (input.auth_method === 'key' && !input.private_key) {
|
||||
throw new Error('SSH 密钥认证方式需要提供 private_key。');
|
||||
// If using ssh_key_id, private_key is not required in the input
|
||||
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') {
|
||||
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
|
||||
}
|
||||
|
||||
// 2. 加密凭证 (根据 type)
|
||||
// 2. 处理凭证和 ssh_key_id (根据 type)
|
||||
let encryptedPassword = null;
|
||||
let encryptedPrivateKey = null;
|
||||
let encryptedPassphrase = null;
|
||||
let sshKeyIdToSave: number | null = null; // +++ Variable for ssh_key_id +++
|
||||
// Default to 'password' for DB compatibility, especially for RDP
|
||||
let authMethodForDb: 'password' | 'key' = 'password';
|
||||
|
||||
@@ -75,10 +84,28 @@ export const createConnection = async (input: CreateConnectionInput): Promise<Co
|
||||
authMethodForDb = input.auth_method!; // Already validated above
|
||||
if (input.auth_method === 'password') {
|
||||
encryptedPassword = encrypt(input.password!);
|
||||
} else { // key
|
||||
encryptedPrivateKey = encrypt(input.private_key!);
|
||||
if (input.passphrase) {
|
||||
encryptedPassphrase = encrypt(input.passphrase);
|
||||
sshKeyIdToSave = null; // Password auth cannot use ssh_key_id
|
||||
} else { // auth_method is 'key'
|
||||
if (input.ssh_key_id) {
|
||||
// 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')
|
||||
@@ -91,23 +118,30 @@ export const createConnection = async (input: CreateConnectionInput): Promise<Co
|
||||
|
||||
// 3. 准备仓库数据
|
||||
const defaultPort = input.type === 'RDP' ? 3389 : 22;
|
||||
// Explicitly type the object being passed to the repository
|
||||
const connectionData: Omit<ConnectionRepository.FullConnectionData, 'id' | 'created_at' | 'updated_at' | 'last_connected_at' | 'tag_ids'> = {
|
||||
// +++ 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<ConnectionRepository.FullConnectionData, 'id' | 'created_at' | 'updated_at' | 'last_connected_at' | 'tag_ids'>);
|
||||
|
||||
// 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<Omit<ConnectionRepository.FullConnectionData, 'id' | 'created_at' | 'last_connected_at' | 'tag_ids'>> = {};
|
||||
// Explicitly type dataToUpdate to match the repository's expected input, including ssh_key_id
|
||||
const dataToUpdate: Partial<Omit<ConnectionRepository.FullConnectionData & { ssh_key_id?: number | null }, 'id' | 'created_at' | 'last_connected_at' | 'tag_ids'>> = {};
|
||||
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<boolean> => {
|
||||
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.
|
||||
|
||||
@@ -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<Decryp
|
||||
port: rawConnInfo.port ?? (() => { 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} 的信息...`);
|
||||
|
||||
@@ -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';
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user