This commit is contained in:
Baobhan Sith
2025-04-20 16:10:52 +08:00
parent 82808ca716
commit 80a461d337
6 changed files with 452 additions and 26 deletions
@@ -166,13 +166,13 @@ export const testConnection = async (req: Request, res: Response): Promise<void>
return;
}
// 调用 SshService 进行连接测试
await SshService.testConnection(connectionId);
// 调用 SshService 进行连接测试,现在它会返回延迟
const { latency } = await SshService.testConnection(connectionId);
// 如果 SshService.testConnection 没有抛出错误,则表示成功
// 记录审计日志 (可选,看是否需要记录测试操作)
// auditLogService.logAction('CONNECTION_TESTED', { connectionId, success: true });
res.status(200).json({ success: true, message: '连接测试成功。' });
res.status(200).json({ success: true, message: '连接测试成功。', latency }); // 返回延迟
} catch (error: any) {
// 记录审计日志 (可选)
@@ -183,6 +183,70 @@ export const testConnection = async (req: Request, res: Response): Promise<void>
}
};
/**
* 测试未保存的连接信息 (POST /api/v1/connections/test-unsaved)
*/
export const testUnsavedConnection = async (req: Request, res: Response): Promise<void> => {
try {
// 从请求体中提取连接信息
const { host, port, username, auth_method, password, private_key, passphrase, proxy_id } = req.body;
// 基本验证
if (!host || !port || !username || !auth_method) {
res.status(400).json({ success: false, message: '缺少必要的连接信息 (host, port, username, auth_method)。' });
return;
}
// 密码认证时,password 字段必须存在,但可以为空字符串
if (auth_method === 'password' && password === undefined) {
res.status(400).json({ success: false, message: '密码认证方式需要提供 password 字段 (可以为空字符串)。' });
return;
}
// 密钥认证时,private_key 必须存在且不为空
if (auth_method === 'key' && !private_key) {
res.status(400).json({ success: false, message: '密钥认证方式需要提供 private_key。' });
return;
}
// 构建传递给服务层的连接配置对象
// 注意:这里传递的是未经验证和加密处理的原始数据
const connectionConfig = {
host,
port: parseInt(port, 10), // 确保 port 是数字
username,
auth_method,
password, // 传递原始密码
private_key, // 传递原始私钥
passphrase, // 传递原始密码短语
proxy_id: proxy_id ? parseInt(proxy_id, 10) : null // 确保 proxy_id 是数字或 null
};
// 验证 port 和 proxy_id 是否为有效数字
if (isNaN(connectionConfig.port)) {
res.status(400).json({ success: false, message: '端口号必须是有效的数字。' });
return;
}
if (proxy_id && isNaN(connectionConfig.proxy_id as number)) {
res.status(400).json({ success: false, message: '代理 ID 必须是有效的数字。' });
return;
}
// 调用 SshService 进行连接测试,现在它会返回延迟
// 注意:SshService.testUnsavedConnection 需要处理原始凭证
const { latency } = await SshService.testUnsavedConnection(connectionConfig);
// 如果 SshService.testUnsavedConnection 没有抛出错误,则表示成功
res.status(200).json({ success: true, message: '连接测试成功。', latency });
} catch (error: any) {
console.error(`Controller: 测试未保存连接时发生错误:`, error);
// SshService 会抛出包含具体原因的 Error
res.status(500).json({ success: false, message: error.message || '测试连接时发生内部服务器错误。' });
}
};
// --- TODO: 将以下逻辑迁移到 ImportExportService ---
/**
* 导出所有连接配置 (GET /api/v1/connections/export)
@@ -8,6 +8,7 @@ import {
updateConnection, // 引入更新连接的控制器
deleteConnection, // 引入删除连接的控制器
testConnection, // 引入测试连接的控制器
testUnsavedConnection, // 添加导入: 引入测试未保存连接的控制器
exportConnections, // 引入导出连接的控制器
importConnections // 引入导入连接的控制器
} from './connections.controller';
@@ -81,4 +82,7 @@ router.delete('/:id', deleteConnection);
// POST /api/v1/connections/:id/test - 测试连接
router.post('/:id/test', testConnection);
// POST /api/v1/connections/test-unsaved - 测试未保存的连接信息
router.post('/test-unsaved', testUnsavedConnection);
export default router;
+99 -4
View File
@@ -3,6 +3,7 @@ import { SocksClient, SocksClientOptions } from 'socks';
import http from 'http';
import net from 'net';
import * as ConnectionRepository from '../repositories/connection.repository';
import * as ProxyRepository from '../repositories/proxy.repository'; // 引入 ProxyRepository
import { decrypt } from '../utils/crypto';
const CONNECT_TIMEOUT = 20000; // 连接超时时间 (毫秒)
@@ -221,12 +222,13 @@ export const openShell = (sshClient: Client): Promise<ClientChannel> => {
/**
* 测试给定 ID 的 SSH 连接(包括代理)
* @param connectionId 连接 ID
* @returns Promise<void> - 如果连接成功则 resolve,否则 reject
* @returns Promise<{ latency: number }> - 如果连接成功则 resolve 包含延迟的对象,否则 reject
* @throws Error 如果连接失败或配置错误
*/
export const testConnection = async (connectionId: number): Promise<void> => {
export const testConnection = async (connectionId: number): Promise<{ latency: number }> => {
console.log(`SshService: 测试连接 ${connectionId}...`);
let sshClient: Client | null = null;
const startTime = Date.now(); // 开始计时
try {
// 1. 获取并解密连接信息
const connDetails = await getConnectionDetails(connectionId);
@@ -234,8 +236,10 @@ export const testConnection = async (connectionId: number): Promise<void> => {
// 2. 尝试建立连接 (使用较短的测试超时时间)
sshClient = await establishSshConnection(connDetails, TEST_TIMEOUT);
console.log(`SshService: 测试连接 ${connectionId} 成功。`);
// 测试成功,Promise 自动 resolve void
const endTime = Date.now(); // 结束计时
const latency = endTime - startTime;
console.log(`SshService: 测试连接 ${connectionId} 成功,延迟: ${latency}ms。`);
return { latency }; // 返回延迟
} catch (error) {
console.error(`SshService: 测试连接 ${connectionId} 失败:`, error);
throw error; // 将错误向上抛出
@@ -248,6 +252,97 @@ export const testConnection = async (connectionId: number): Promise<void> => {
}
};
/**
* 测试未保存的 SSH 连接信息(包括代理)
* @param connectionConfig - 包含连接参数的对象 (host, port, username, auth_method, password?, private_key?, passphrase?, proxy_id?)
* @returns Promise<{ latency: number }> - 如果连接成功则 resolve 包含延迟的对象,否则 reject
* @throws Error 如果连接失败或配置错误
*/
export const testUnsavedConnection = async (connectionConfig: {
host: string;
port: number;
username: string;
auth_method: 'password' | 'key';
password?: string;
private_key?: string; // 注意这里是 private_key
passphrase?: string;
proxy_id?: number | null;
}): Promise<{ latency: number }> => {
console.log(`SshService: 测试未保存的连接到 ${connectionConfig.host}:${connectionConfig.port}...`);
let sshClient: Client | null = null;
const startTime = Date.now(); // 开始计时
try {
// 1. 构建临时的 DecryptedConnectionDetails 结构
const tempConnDetails: DecryptedConnectionDetails = {
id: -1, // 临时 ID,不实际使用
name: `Test-${connectionConfig.host}`, // 临时名称
host: connectionConfig.host,
port: connectionConfig.port,
username: connectionConfig.username,
auth_method: connectionConfig.auth_method,
// 直接使用传入的凭证,因为它们是未加密的
password: connectionConfig.password,
privateKey: connectionConfig.private_key, // 映射 private_key
passphrase: connectionConfig.passphrase,
proxy: null, // 稍后填充
};
// 2. 如果提供了 proxy_id,获取并解密代理信息
if (connectionConfig.proxy_id) {
console.log(`SshService: 测试连接需要获取代理 ${connectionConfig.proxy_id} 的信息...`);
const rawProxyInfo = await ProxyRepository.findProxyById(connectionConfig.proxy_id);
if (!rawProxyInfo) {
throw new Error(`代理 ID ${connectionConfig.proxy_id} 未找到。`);
}
try {
// Add null checks for required proxy fields
const proxyName = rawProxyInfo.name ?? (() => { throw new Error(`Proxy ID ${connectionConfig.proxy_id} has null name.`); })();
const proxyType = rawProxyInfo.type ?? (() => { throw new Error(`Proxy ID ${connectionConfig.proxy_id} has null type.`); })();
const proxyHost = rawProxyInfo.host ?? (() => { throw new Error(`Proxy ID ${connectionConfig.proxy_id} has null host.`); })();
const proxyPort = rawProxyInfo.port ?? (() => { throw new Error(`Proxy ID ${connectionConfig.proxy_id} has null port.`); })();
// Ensure proxyType is one of the allowed values
if (proxyType !== 'SOCKS5' && proxyType !== 'HTTP') {
throw new Error(`Proxy ID ${connectionConfig.proxy_id} has invalid type: ${proxyType}`);
}
tempConnDetails.proxy = {
id: rawProxyInfo.id,
name: proxyName,
type: proxyType,
host: proxyHost,
port: proxyPort,
username: rawProxyInfo.username || undefined,
password: rawProxyInfo.encrypted_password ? decrypt(rawProxyInfo.encrypted_password) : undefined,
};
console.log(`SshService: 代理 ${connectionConfig.proxy_id} 信息获取并解密成功。`);
} catch (decryptError: any) {
console.error(`SshService: 处理代理 ${connectionConfig.proxy_id} 凭证失败:`, decryptError);
throw new Error(`处理代理凭证失败: ${decryptError.message}`);
}
}
// 3. 尝试建立连接 (使用较短的测试超时时间)
sshClient = await establishSshConnection(tempConnDetails, TEST_TIMEOUT);
const endTime = Date.now(); // 结束计时
const latency = endTime - startTime;
console.log(`SshService: 测试未保存的连接到 ${connectionConfig.host}:${connectionConfig.port} 成功,延迟: ${latency}ms。`);
return { latency }; // 返回延迟
} catch (error) {
console.error(`SshService: 测试未保存的连接到 ${connectionConfig.host}:${connectionConfig.port} 失败:`, error);
throw error; // 将错误向上抛出
} finally {
// 无论成功失败,都关闭 SSH 客户端
if (sshClient) {
sshClient.end();
console.log(`SshService: 测试未保存连接的客户端已关闭。`);
}
}
};
// --- 移除旧的函数 ---
// - connectAndOpenShell
// - sendInput
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from 'vue'; // 引入 onMounted
import { ref, reactive, watch, computed, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import apiClient from '../utils/apiClient'; // 修正导入路径和名称
import { useConnectionsStore, ConnectionInfo } from '../stores/connections.store';
import { useProxiesStore } from '../stores/proxies.store'; // 引入代理 Store
import { useTagsStore } from '../stores/tags.store'; // 引入标签 Store
@@ -43,6 +44,11 @@ const formError = ref<string | null>(null); // 表单级别的错误信息
const isLoading = computed(() => isConnLoading.value || isProxyLoading.value || isTagLoading.value);
const storeError = computed(() => connStoreError.value || proxyStoreError.value || tagStoreError.value);
// 测试连接状态
const testStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle');
const testResult = ref<string | number | null>(null); // 存储延迟或错误信息
const testLatency = ref<number | null>(null); // 单独存储延迟用于颜色计算
// 计算属性判断是否为编辑模式
const isEditMode = computed(() => !!props.connectionToEdit);
@@ -188,6 +194,96 @@ const handleSubmit = async () => {
}
}
};
// 处理测试连接
const handleTestConnection = async () => {
testStatus.value = 'testing';
testResult.value = null;
testLatency.value = null;
try {
let response;
if (isEditMode.value && props.connectionToEdit) {
// --- 编辑模式: 测试已保存的连接 ---
console.log(`Testing saved connection ID: ${props.connectionToEdit.id}`);
// 调用测试已保存连接的 API
response = await apiClient.post(`/connections/${props.connectionToEdit.id}/test`);
} else {
// --- 添加模式: 测试未保存的连接 ---
console.log("Testing unsaved connection data");
// 准备要发送的数据
const dataToSend = {
host: formData.host,
port: formData.port,
username: formData.username,
auth_method: formData.auth_method,
password: formData.auth_method === 'password' ? formData.password : undefined,
private_key: formData.auth_method === 'key' ? formData.private_key : undefined,
passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined,
proxy_id: formData.proxy_id || null,
};
// 仅在添加模式下进行前端凭证验证
if (!dataToSend.host || !dataToSend.port || !dataToSend.username || !dataToSend.auth_method) {
// 使用 Error 抛出,由下面的 catch 块统一处理显示
throw new Error(t('connections.test.errorMissingFields'));
}
// 在添加模式下,密码或密钥必须提供
if (dataToSend.auth_method === 'password' && !formData.password) { // 检查 formData 而不是 dataToSend.password
throw new Error(t('connections.form.errorPasswordRequired')); // 复用表单提交的翻译键
}
if (dataToSend.auth_method === 'key' && !formData.private_key) { // 检查 formData 而不是 dataToSend.private_key
throw new Error(t('connections.form.errorPrivateKeyRequired')); // 复用表单提交的翻译键
}
// 调用测试未保存连接的 API
response = await apiClient.post('/connections/test-unsaved', dataToSend);
}
// --- 处理 API 响应 (对两种模式通用) ---
if (response.data.success) {
testStatus.value = 'success';
testLatency.value = response.data.latency; // 两个测试 API 现在都返回 latency
testResult.value = `${response.data.latency} ms`;
} else {
// 如果后端 API 返回 success: false (理论上不应发生,但作为保险)
testStatus.value = 'error';
testResult.value = response.data.message || t('connections.test.errorUnknown');
}
} catch (error: any) {
// --- 统一处理错误 (前端验证错误或 API 调用错误) ---
console.error('测试连接失败:', error);
testStatus.value = 'error';
if (error.response && error.response.data && error.response.data.message) {
// API 返回的错误信息
testResult.value = error.response.data.message;
} else {
// 前端验证错误 (error.message) 或 网络/其他错误
testResult.value = error.message || t('connections.test.errorNetwork');
}
}
};
// 计算延迟颜色
const latencyColor = computed(() => {
if (testStatus.value !== 'success' || testLatency.value === null) {
return 'inherit'; // 默认颜色
}
const latency = testLatency.value;
if (latency < 100) return 'var(--color-success, #28a745)'; // 绿色
if (latency < 500) return 'var(--color-warning, #ffc107)'; // 黄色
return 'var(--color-danger, #dc3545)'; // 红色
});
// 计算测试按钮文本
const testButtonText = computed(() => {
if (testStatus.value === 'testing') {
return t('connections.form.testing'); // 新增翻译键
}
return t('connections.form.testConnection'); // 新增翻译键
});
</script>
<template>
@@ -280,10 +376,34 @@ const handleSubmit = async () => {
</div> <!-- 结束 form-sections -->
<div class="form-actions">
<button type="submit" :disabled="isLoading">
{{ submitButtonText }}
</button>
<button type="button" @click="emit('close')" :disabled="isLoading">{{ t('connections.form.cancel') }}</button>
<div class="test-action-area"> <!-- New container for button, icon, and result -->
<div class="test-button-wrapper"> <!-- Container for button and icon -->
<button type="button" @click="handleTestConnection" :disabled="isLoading || testStatus === 'testing'">
{{ testButtonText }}
</button>
<span class="info-icon">?
<span class="tooltip-text">{{ t('connections.test.latencyTooltip') }}</span>
</span>
</div>
<!-- Test result moved below the button -->
<div class="test-status-wrapper">
<div v-if="testStatus === 'testing'" class="test-status loading-small">
{{ t('connections.test.testingInProgress', '测试中...') }}
</div>
<div v-else-if="testStatus === 'success'" class="test-status success" :style="{ color: latencyColor }">
{{ testResult }}
</div>
<div v-else-if="testStatus === 'error'" class="test-status error">
{{ t('connections.test.errorPrefix', '错误:') }} {{ testResult }}
</div>
</div>
</div>
<div class="main-actions">
<button type="submit" :disabled="isLoading || testStatus === 'testing'">
{{ submitButtonText }}
</button>
<button type="button" @click="emit('close')" :disabled="isLoading || testStatus === 'testing'">{{ t('connections.form.cancel') }}</button>
</div>
</div>
</form>
</div>
@@ -464,7 +584,8 @@ select {
.form-actions {
display: flex;
justify-content: flex-end;
justify-content: space-between; /* 改为 space-between 对齐 */
align-items: center; /* 垂直居中对齐 */
margin-top: calc(var(--base-margin, 0.5rem) * 1.5); /* 减少顶部间距 */
padding-top: calc(var(--base-padding, 1rem) * 0.8); /* 减少按钮上方间距 */
border-top: 1px solid var(--border-color, #eee);
@@ -478,9 +599,9 @@ select {
margin-right: calc(var(--base-padding, 1rem) * -0.5);
}
.form-actions button {
margin-left: calc(var(--base-margin, 0.5rem) * 0.8); /* 减少按钮左边距 */
padding: calc(var(--base-padding, 1rem) * 0.5) calc(var(--base-padding, 1rem) * 1.2); /* 减少按钮内边距 */
.main-actions button { /* 主操作按钮(保存/取消) */
margin-left: calc(var(--base-margin, 0.5rem) * 0.8); /* 保持按钮间距 */
padding: calc(var(--base-padding, 1rem) * 0.5) calc(var(--base-padding, 1rem) * 1.2);
cursor: pointer;
border-radius: 3px; /* 稍小圆角 */
font-family: var(--font-family-sans-serif, sans-serif);
@@ -514,4 +635,126 @@ select {
opacity: 0.5; /* 调整禁用透明度 */
cursor: not-allowed;
}
/* 测试按钮、图标和结果的整体区域 */
.test-action-area {
display: flex;
flex-direction: column; /* 让结果显示在按钮下方 */
align-items: flex-start; /* 左对齐 */
gap: calc(var(--base-padding, 1rem) * 0.3); /* 按钮行和结果行之间的间距 */
}
/* 包裹测试按钮和信息图标的容器 */
.test-button-wrapper {
display: flex;
align-items: center;
gap: calc(var(--base-padding, 1rem) * 0.5); /* 按钮和图标之间的间距 */
}
/* 信息图标样式 & Tooltip Container */
.info-icon {
position: relative; /* Needed for absolute positioning of the tooltip text */
cursor: help;
color: var(--text-color-secondary, #666);
font-size: 1.1em;
line-height: 1;
user-select: none;
display: inline-block; /* Ensure it takes space for positioning */
}
/* Tooltip Text Style */
.tooltip-text {
visibility: hidden; /* Hide by default */
opacity: 0;
position: absolute;
bottom: 140%; /* Position above the icon */
left: 50%;
transform: translateX(-50%);
background-color: rgba(0, 0, 0, 0.85); /* Slightly darker background */
color: white;
padding: 8px 12px; /* Slightly more padding */
border-radius: 5px; /* Slightly larger radius */
font-size: 0.9em; /* Slightly larger font */
white-space: pre-wrap; /* Allow line breaks */
min-width: 180px; /* Adjust width as needed */
max-width: 320px;
text-align: left;
z-index: 10;
pointer-events: none; /* Prevent tooltip from blocking hover */
transition: opacity 0.25s ease, visibility 0.25s ease; /* Slightly longer transition */
box-shadow: 0 2px 5px rgba(0,0,0,0.2); /* Add subtle shadow */
}
/* Tooltip Arrow */
.tooltip-text::after {
content: '';
position: absolute;
top: 100%; /* Position arrow at the bottom of the tooltip */
left: 50%;
transform: translateX(-50%);
border-width: 6px; /* Slightly larger arrow */
border-style: solid;
border-color: rgba(0, 0, 0, 0.85) transparent transparent transparent;
}
/* Show tooltip on hover */
.info-icon:hover .tooltip-text {
visibility: visible;
opacity: 1;
}
/* 测试按钮样式 (从之前的 .test-result-container button 移过来) */
.test-button-wrapper button {
/* 测试按钮可以有自己的样式,或者继承 .form-actions button */
padding: calc(var(--base-padding, 1rem) * 0.5) calc(var(--base-padding, 1rem) * 1.2);
cursor: pointer;
border-radius: 3px;
font-family: var(--font-family-sans-serif, sans-serif);
font-weight: 500;
transition: background-color 0.2s ease, color 0.2s ease, border-color 0.2s ease, opacity 0.2s ease;
/* 可以给测试按钮一个不同的边框或背景色 */
background-color: transparent;
color: var(--text-color-secondary, #666);
border: 1px solid var(--border-color, #ccc);
}
.test-result-container button:hover:not(:disabled) {
background-color: var(--border-color, #eee);
border-color: var(--text-color-secondary, #bbb);
color: var(--text-color, #333);
}
.test-result-container button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* 包裹测试状态文本的容器 */
.test-status-wrapper {
min-height: 1.2em; /* 预留空间,防止布局跳动 */
padding-left: 2px; /* 轻微缩进,与按钮对齐 */
}
.test-status {
font-size: 0.9em;
font-weight: 500;
font-family: var(--font-family-sans-serif, sans-serif);
}
.test-status.loading-small {
color: var(--text-color-secondary, #666);
}
.test-status.success {
/* 颜色由 latencyColor 计算属性动态设置 */
}
.test-status.error {
color: var(--color-danger, #dc3545); /* 红色 */
}
/* 主操作按钮容器 */
.main-actions {
display: flex; /* 保持原有按钮布局 */
}
</style>
+15 -5
View File
@@ -172,7 +172,21 @@
"tags": "Tags:",
"sectionBasic": "Basic Information",
"sectionAuth": "Authentication",
"sectionAdvanced": "Advanced Options"
"sectionAdvanced": "Advanced Options",
"testConnection": "Test Connection",
"testing": "Testing..."
},
"test": {
"success": "Connection test successful!",
"failed": "Connection test failed: {error}",
"latencyTooltip": "This measures the time to establish a new SSH connection (TCP, Proxy, SSH Handshake, Auth). It's typically higher than interaction latency on an already established connection.",
"errorMissingFields": "Please fill in Host, Port, Username, and select an Auth Method.",
"errorPasswordUndefined": "Password field is required for password authentication.",
"errorPrivateKeyRequired": "Private key is required for key authentication.",
"errorUnknown": "An unknown error occurred during testing.",
"errorNetwork": "Network error or server unreachable.",
"testingInProgress": "Testing...",
"errorPrefix": "Error:"
},
"prompts": {
"confirmDelete": "Are you sure you want to delete the connection \"{name}\"? This cannot be undone."
@@ -186,10 +200,6 @@
"filterAllTags": "All Tags",
"untaggedGroup": "Untagged",
"noUntaggedConnections": "No untagged connections found.",
"test": {
"success": "Connection test successful!",
"failed": "Connection test failed: {error}"
},
"exportConnections": "Export Connections",
"importConnections": "Import Connections",
"exportError": "Failed to export connections: {message}",
+15 -5
View File
@@ -172,7 +172,21 @@
"tags": "标签:",
"sectionBasic": "基本信息",
"sectionAuth": "认证信息",
"sectionAdvanced": "高级选项"
"sectionAdvanced": "高级选项",
"testConnection": "测试连接",
"testing": "测试中..."
},
"test": {
"success": "连接测试成功!",
"failed": "连接测试失败: {error}",
"latencyTooltip": "此延迟测量建立全新 SSH 连接所需的时间(包括 TCP 连接、代理协商、SSH 握手、认证等步骤),通常高于已建立连接上的交互延迟。",
"errorMissingFields": "请填写主机、端口、用户名并选择认证方式。",
"errorPasswordUndefined": "密码认证方式需要提供密码字段。",
"errorPrivateKeyRequired": "密钥认证方式需要提供私钥。",
"errorUnknown": "测试过程中发生未知错误。",
"errorNetwork": "网络错误或服务器无法访问。",
"testingInProgress": "测试中...",
"errorPrefix": "错误:"
},
"prompts": {
"confirmDelete": "确定要删除连接 \"{name}\" 吗?此操作不可撤销。"
@@ -186,10 +200,6 @@
"filterAllTags": "所有标签",
"untaggedGroup": "未标记",
"noUntaggedConnections": "没有未标记的连接。",
"test": {
"success": "连接测试成功!",
"failed": "连接测试失败: {error}"
},
"exportConnections": "导出连接",
"importConnections": "导入连接",
"exportError": "导出连接失败: {message}",