feat: 添加跳板机功能

This commit is contained in:
Baobhan Sith
2025-05-26 19:18:17 +08:00
parent 9524351b90
commit 3c895d5bd7
14 changed files with 971 additions and 320 deletions
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, Teleport, nextTick } from 'vue';
import { ref, Teleport, nextTick, type Ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ConnectionInfo } from '../stores/connections.store'; // Keep ConnectionInfo type
import { useAddConnectionForm } from '../composables/useAddConnectionForm';
@@ -34,10 +34,14 @@ const {
submitButtonText,
proxies,
tags,
connections,
isProxyLoading,
proxyStoreError,
isTagLoading,
tagStoreError,
advancedConnectionMode,
addJumpHost,
removeJumpHost,
handleSubmit,
handleDeleteConnection,
handleTestConnection,
@@ -47,6 +51,10 @@ const {
testButtonText,
} = useAddConnectionForm(props, emit);
const handleAdvancedConnectionModeUpdate = (newMode: 'proxy' | 'jump') => {
advancedConnectionMode.value = newMode;
};
// Tooltip state and refs - Kept in component as it's purely view-related
const showHostTooltip = ref(false);
const hostTooltipStyle = ref({});
@@ -104,14 +112,19 @@ const handleHostIconMouseLeave = () => {
:form-data="formData"
:proxies="proxies"
:tags="tags"
:connections="connections"
:is-proxy-loading="isProxyLoading"
:proxy-store-error="proxyStoreError"
:is-tag-loading="isTagLoading"
:tag-store-error="tagStoreError"
:advanced-connection-mode="advancedConnectionMode"
@update:advancedConnectionMode="handleAdvancedConnectionModeUpdate"
:add-jump-host="addJumpHost"
:remove-jump-host="removeJumpHost"
@create-tag="handleCreateTag"
@delete-tag="handleDeleteTag"
/>
</template> <!-- End of v-if="!isScriptModeActive" -->
</template>
<!-- Script Mode Section Toggle -->
<div v-if="!isEditMode" class="space-y-4 p-4 border border-border rounded-md bg-header/30 mt-6">
@@ -1,33 +1,48 @@
<script setup lang="ts">
import { computed, watch, type Ref, type PropType } from 'vue';
import { useI18n } from 'vue-i18n';
import TagInput from './TagInput.vue'; // Assuming TagInput is used here
import type { ProxyInfo } from '../stores/proxies.store'; // Corrected Proxy to ProxyInfo
import type { TagInfo } from '../stores/tags.store'; // Corrected Tag to TagInfo
import TagInput from './TagInput.vue';
import type { ProxyInfo } from '../stores/proxies.store';
import type { TagInfo } from '../stores/tags.store';
import type { ConnectionInfo } from '../stores/connections.store';
// Define Props.
const props = defineProps<{
// Define Props
const props = defineProps({
formData: {
type: 'SSH' | 'RDP' | 'VNC'; // Needed to conditionally show proxy selector
proxy_id: number | null;
tag_ids: number[];
notes: string;
};
proxies: ProxyInfo[]; // List of available proxies
tags: TagInfo[]; // List of available tags
isProxyLoading: boolean;
proxyStoreError: string | null;
isTagLoading: boolean;
tagStoreError: string | null;
}>();
type: Object as PropType<{
id?: number;
type: 'SSH' | 'RDP' | 'VNC';
proxy_id: number | null;
jump_chain: Array<number | null> | null;
proxy_type?: 'proxy' | 'jump' | null;
tag_ids: number[];
notes: string;
}>,
required: true
},
proxies: { type: Array as PropType<ProxyInfo[]>, required: true },
connections: { type: Array as PropType<ConnectionInfo[]>, required: true },
tags: { type: Array as PropType<TagInfo[]>, required: true },
isProxyLoading: { type: Boolean, required: true },
proxyStoreError: { type: String as PropType<string | null>, required: false, default: null },
isTagLoading: { type: Boolean, required: true },
tagStoreError: { type: String as PropType<string | null>, required: false, default: null },
advancedConnectionMode: { type: String as PropType<'proxy' | 'jump'>, required: true },
addJumpHost: { type: Function as PropType<() => void>, required: true },
removeJumpHost: { type: Function as PropType<(index: number) => void>, required: true },
isEditMode: { type: Boolean, default: false }
});
// Define Emits for tag creation and deletion
// Define Emits
const emit = defineEmits<{
(e: 'create-tag', tagName: string): void;
(e: 'delete-tag', tagId: number): void;
(e: 'update:advancedConnectionMode', mode: 'proxy' | 'jump'): void;
}>();
const { t } = useI18n();
const handleCreateTagEvent = (tagName: string) => {
emit('create-tag', tagName);
};
@@ -35,6 +50,23 @@ const handleCreateTagEvent = (tagName: string) => {
const handleDeleteTagEvent = (tagId: number) => {
emit('delete-tag', tagId);
};
const setConnectionMode = (mode: 'proxy' | 'jump') => {
if (props.advancedConnectionMode === mode) return; // Access directly
emit('update:advancedConnectionMode', mode);
};
const getAvailableJumpHostsForIndex = (currentIndex: number): ConnectionInfo[] => {
return props.connections.filter(conn => {
if (conn.type !== 'SSH') return false;
if (props.isEditMode && props.formData.id === conn.id) return false;
return !props.formData.jump_chain?.some((jumpHostId, index) => {
return index !== currentIndex && jumpHostId === conn.id;
});
});
};
</script>
<template>
@@ -42,8 +74,31 @@ const handleDeleteTagEvent = (tagId: number) => {
<div class="space-y-4 p-4 border border-border rounded-md bg-header/30">
<h4 class="text-base font-semibold mb-3 pb-2 border-b border-border/50">{{ t('connections.form.sectionAdvanced', '高级选项') }}</h4>
<!-- Proxy Select - Show only for SSH -->
<!-- Connection Mode Switcher (Only for SSH) -->
<div v-if="props.formData.type === 'SSH'">
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.connectionMode', '连接方式') }}</label>
<div class="flex rounded-md shadow-sm mb-4">
<button
type="button"
@click="setConnectionMode('proxy')"
:class="['flex-1 px-3 py-2 border border-border text-sm font-medium focus:outline-none rounded-l-md',
props.advancedConnectionMode === 'proxy' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border']"
>
{{ t('connections.form.connectionModeProxy', '代理') }}
</button>
<button
type="button"
@click="setConnectionMode('jump')"
:class="['flex-1 px-3 py-2 border-t border-b border-r border-border text-sm font-medium focus:outline-none -ml-px rounded-r-md',
props.advancedConnectionMode === 'jump' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border']"
>
{{ t('connections.form.connectionModeJumpHost', '跳板机') }}
</button>
</div>
</div>
<!-- Proxy Select - Show only for SSH and if 'proxy' mode is selected -->
<div v-if="props.formData.type === 'SSH' && props.advancedConnectionMode === 'proxy'">
<label for="conn-proxy" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.proxy') }} ({{ t('connections.form.optional') }})</label>
<select id="conn-proxy" v-model="props.formData.proxy_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 appearance-none bg-no-repeat bg-right pr-8"
@@ -57,6 +112,39 @@ const handleDeleteTagEvent = (tagId: number) => {
<div v-if="props.proxyStoreError" class="mt-1 text-xs text-error">{{ t('proxies.error', { error: props.proxyStoreError }) }}</div>
</div>
<!-- Jump Host Configuration - Show only for SSH and if 'jump' mode is selected -->
<div v-if="props.formData.type === 'SSH' && props.advancedConnectionMode === 'jump'" class="space-y-3">
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.jumpHostsTitle', '跳板机链配置') }}</label>
<div v-if="!props.formData.jump_chain || props.formData.jump_chain.length === 0" class="text-sm text-muted-foreground italic">
</div>
<template v-if="props.formData.jump_chain">
<div v-for="(jumpHostId, index) in props.formData.jump_chain" :key="index" class="flex items-center space-x-2 p-2 border border-border rounded-md bg-background/50">
<span class="text-sm font-medium text-text-secondary whitespace-nowrap">{{ t('connections.form.jumpHostLabel', '跳板机') }} {{ index + 1 }}:</span>
<select v-model="props.formData.jump_chain[index]"
class="flex-grow px-3 py-1.5 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('connections.form.selectJumpHost', '请选择跳板机') }}</option>
<option v-for="host in getAvailableJumpHostsForIndex(index)" :key="host.id" :value="host.id">
{{ host.name }}
</option>
</select>
<button type="button" @click="props.removeJumpHost(index)"
class="p-1.5 text-destructive hover:text-destructive/80 focus:outline-none focus:ring-1 focus:ring-destructive rounded-md"
:title="t('connections.form.removeJumpHostTitle', '移除此跳板机')">
<svg xmlns="http://www.w3.org/2000/svg" width="1.1em" height="1.1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
</template>
<button type="button" @click="props.addJumpHost()"
class="w-full flex items-center justify-center space-x-2 px-3 py-2 border border-dashed border-primary text-primary rounded-md hover:bg-primary/10 focus:outline-none focus:ring-1 focus:ring-primary">
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
<span>{{ t('connections.form.addJumpHost', '添加跳板机') }}</span>
</button>
<div v-if="props.connections.filter(c => c.type === 'SSH' && (!props.isEditMode || c.id !== props.formData.id)).length === 0" class="text-xs text-warning-foreground p-2 bg-warning/20 rounded-md">
{{ t('connections.form.noAvailableSshConnectionsForJump', '没有可用的SSH连接作为跳板机请先创建一些SSH连接') }}
</div>
</div>
<div>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.tags') }} ({{ t('connections.form.optional') }})</label>
<TagInput
@@ -31,31 +31,35 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
const sshKeysStore = useSshKeysStore();
const uiNotificationsStore = useUiNotificationsStore();
const { isLoading: isConnLoading, error: connStoreError } = storeToRefs(connectionsStore);
const { isLoading: isConnLoading, error: connStoreError, connections } = storeToRefs(connectionsStore);
const { proxies, isLoading: isProxyLoading, error: proxyStoreError } = storeToRefs(proxiesStore);
const { tags, isLoading: isTagLoading, error: tagStoreError } = storeToRefs(tagsStore);
const { sshKeys, isLoading: isSshKeyLoading, error: sshKeyStoreError } = storeToRefs(sshKeysStore);
// 表单数据模型
const initialFormData = {
type: 'SSH' as 'SSH' | 'RDP' | 'VNC',
type: 'SSH' as 'SSH' | 'RDP' | 'VNC',
name: '',
host: '',
port: 22,
username: '',
auth_method: 'password' as 'password' | 'key',
auth_method: 'password' as 'password' | 'key',
password: '',
private_key: '',
passphrase: '',
private_key: '',
passphrase: '',
selected_ssh_key_id: null as number | null,
proxy_id: null as number | null,
tag_ids: [] as number[],
notes: '',
vncPassword: '',
jump_chain: null as Array<any> | null,
proxy_type: null as 'proxy' | 'jump' | null,
tag_ids: [] as number[],
notes: '',
vncPassword: '',
};
const formData = reactive({ ...initialFormData });
const formError = ref<string | null>(null); // 表单级别的错误信息
const advancedConnectionMode = ref<'proxy' | 'jump'>('proxy');
// 合并所有 store 的加载和错误状态
const isLoading = computed(() => isConnLoading.value || isProxyLoading.value || isTagLoading.value || isSshKeyLoading.value); // +++ Include SSH Key loading +++
const storeError = computed(() => connStoreError.value || proxyStoreError.value || tagStoreError.value || sshKeyStoreError.value); // +++ Include SSH Key error +++
@@ -103,6 +107,10 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
formData.username = newVal.username;
formData.auth_method = newVal.auth_method;
formData.proxy_id = newVal.proxy_id ?? null;
formData.proxy_type = newVal.proxy_type ?? null;
formData.jump_chain = newVal.jump_chain ? JSON.parse(JSON.stringify(newVal.jump_chain)) : null;
console.log('[Debug] watch connectionToEdit - newVal.jump_chain:', newVal.jump_chain);
console.log('[Debug] watch connectionToEdit - formData.jump_chain initialized:', formData.jump_chain);
formData.notes = newVal.notes ?? '';
formData.tag_ids = newVal.tag_ids ? [...newVal.tag_ids] : [];
@@ -112,13 +120,24 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
formData.selected_ssh_key_id = null;
}
if (newVal.proxy_type === 'jump' && newVal.jump_chain && newVal.jump_chain.length > 0) {
advancedConnectionMode.value = 'jump';
} else if (newVal.proxy_type === 'proxy' && newVal.proxy_id !== null && newVal.proxy_id !== undefined) {
advancedConnectionMode.value = 'proxy';
}
else if (newVal.jump_chain && newVal.jump_chain.length > 0 && (newVal.proxy_id === null || newVal.proxy_id === undefined)) {
advancedConnectionMode.value = 'jump';
} else {
advancedConnectionMode.value = 'proxy';
}
formData.password = '';
formData.private_key = '';
formData.passphrase = '';
if (newVal.type !== 'VNC') {
formData.vncPassword = '';
} else {
formData.vncPassword = '';
formData.vncPassword = ''; // 保持原逻辑或根据需求调整
}
} else {
Object.assign(formData, initialFormData);
@@ -126,7 +145,11 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
formData.selected_ssh_key_id = null;
formData.notes = '';
formData.vncPassword = '';
}
formData.jump_chain = null;
formData.proxy_type = null;
console.log('[Debug] watch connectionToEdit - formData.jump_chain reset');
advancedConnectionMode.value = 'proxy';
}
}, { immediate: true });
// 组件挂载时获取代理、标签和 SSH 密钥列表
@@ -151,6 +174,22 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
}
});
watch([() => formData.type, advancedConnectionMode], ([newType, newAdvMode], [oldType, oldAdvMode]) => {
if (newType === 'SSH') {
if (newAdvMode === 'proxy') {
formData.proxy_type = 'proxy';
} else if (newAdvMode === 'jump') {
formData.proxy_type = 'jump';
} else {
formData.proxy_type = null;
}
} else {
formData.proxy_type = null;
}
console.log(`[Debug] useAddConnectionForm: proxy_type set to ${formData.proxy_type} (type: ${newType}, mode: ${newAdvMode})`);
}, { immediate: true });
// Helper function to parse IP range
const parseIpRange = (ipRangeStr: string): string[] | { error: string } => {
if (!ipRangeStr.includes('~')) {
@@ -615,6 +654,7 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
notes: formData.notes,
proxy_id: formData.proxy_id || null,
tag_ids: currentSelectedValidTagIds,
proxy_type: formData.proxy_type,
};
if (formData.type === 'SSH') {
@@ -678,7 +718,9 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
notes: formData.notes,
username: formData.username,
proxy_id: formData.proxy_id || null,
proxy_type: formData.proxy_type,
tag_ids: currentSelectedValidTagIds,
jump_chain: formData.jump_chain ? JSON.parse(JSON.stringify(formData.jump_chain)) : null,
};
if (formData.type === 'SSH') {
@@ -839,6 +881,20 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
return t('connections.form.testConnection');
});
// --- Jump Host Chain Management ---
const addJumpHost = () => {
if (formData.jump_chain === null || formData.jump_chain === undefined) {
formData.jump_chain = [];
}
formData.jump_chain.push(null);
};
const removeJumpHost = (index: number) => {
if (formData.jump_chain && index >= 0 && index < formData.jump_chain.length) {
formData.jump_chain.splice(index, 1);
}
};
return {
formData,
isLoading,
@@ -863,7 +919,9 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
handleDeleteTag,
latencyColor,
testButtonText,
// Expose stores if child components or template parts need direct access, though usually not.
// uiNotificationsStore, // Used internally, not needed to be returned
advancedConnectionMode,
addJumpHost,
removeJumpHost,
connections,
};
}
+11 -1
View File
@@ -197,6 +197,9 @@
"tags": "Tags:",
"notes": "Notes:",
"notesPlaceholder": "Enter connection notes...",
"connectionMode": "Proxy Type:",
"connectionModeProxy": "Proxy Server",
"connectionModeJumpHost": "Jump Host",
"connectionType": "Connection Type:",
"typeSsh": "SSH",
"typeRdp": "RDP",
@@ -259,7 +262,14 @@
"scriptErrorInvalidUserHostPortFormat": "Invalid format for '{part}', expected format is 'user@host' or 'user@host:port'",
"scriptTagCreated": "Tag '{tagName}' created",
"scriptErrorTagCreationFailed": "Failed to create tag '{tagName}'",
"scriptModeAddingConnections": "Adding {count} connections via script mode..."
"scriptModeAddingConnections": "Adding {count} connections in script mode...",
"jumpHostsTitle": "Jump Host Chain Configuration",
"jumpHostLabel": "Jump Host",
"selectJumpHost": "Please select a jump host",
"removeJumpHostTitle": "Remove this jump host",
"addJumpHost": "Add Jump Host",
"noAvailableSshConnectionsForJump": "No available SSH connections for jump host. Please create some SSH connections first."
},
"test": {
"success": "Connection test successful!",
+12 -2
View File
@@ -176,7 +176,10 @@
"tags": "タグ:",
"notes": "備考:",
"notesPlaceholder": "接続に関する備考を入力してください...",
"testConnection": "接続をテスト",
"connectionMode": "プロキシタイプ:",
"connectionModeProxy": "プロキシサーバー",
"connectionModeJumpHost": "踏み台サーバー",
"testConnection": "接続をテスト",
"testing": "テスト中...",
"title": "新しい接続を追加",
"titleEdit": "接続の編集",
@@ -239,7 +242,14 @@
"scriptErrorInvalidUserHostPortFormat": "'{part}' の形式が無効です、期待される形式は 'user@host' または 'user@host:port' です",
"scriptTagCreated": "タグ '{tagName}' が作成されました",
"scriptErrorTagCreationFailed": "タグ '{tagName}' の作成に失敗しました",
"scriptModeAddingConnections": "スクリプトモードで {count} の接続を追加しています..."
"scriptModeAddingConnections": "スクリプトモードで {count} の接続を追加...",
"jumpHostsTitle": "ジャンプホストチェーン設定",
"jumpHostLabel": "ジャンプホスト",
"selectJumpHost": "ジャンプホストを選択してください",
"removeJumpHostTitle": "このジャンプホストを削除",
"addJumpHost": "ジャンプホストを追加",
"noAvailableSshConnectionsForJump": "ジャンプホストとして使用できるSSH接続がありません。先にSSH接続を作成してください。"
},
"noConnections": "接続がありません。'新しい接続を追加'をクリックして作成してください。",
"noUntaggedConnections": "タグなしの接続はありません。",
+10 -2
View File
@@ -1,5 +1,4 @@
{
"appName": "星枢终端",
"projectName": "星枢终端",
"slogan": "星垂平野阔,枢动万端通",
@@ -196,6 +195,9 @@
"tags": "标签:",
"notes": "备注:",
"notesPlaceholder": "输入连接备注...",
"connectionMode": "代理类型:",
"connectionModeProxy": "代理服务器",
"connectionModeJumpHost": "跳板机",
"connectionType": "连接类型",
"typeSsh": "SSH",
"typeRdp": "RDP",
@@ -259,7 +261,13 @@
"scriptErrorInvalidUserHostPortFormat": "'{part}' 部分格式无效,期望格式为 'user@host' 或 'user@host:port'",
"scriptTagCreated": "标签 '{tagName}' 已创建",
"scriptErrorTagCreationFailed": "创建标签 '{tagName}' 失败",
"scriptModeAddingConnections": "正在通过脚本模式添加 {count} 个连接..."
"scriptModeAddingConnections": "正在通过脚本模式添加 {count} 个连接...",
"jumpHostsTitle": "跳板机链配置",
"jumpHostLabel": "跳板机",
"selectJumpHost": "请选择跳板机",
"removeJumpHostTitle": "移除此跳板机",
"addJumpHost": "添加跳板机",
"noAvailableSshConnectionsForJump": "没有可用的SSH连接作为跳板机。请先创建一些SSH连接。"
},
"test": {
"success": "连接测试成功!",
@@ -11,13 +11,15 @@ export interface ConnectionInfo {
username: string;
auth_method: 'password' | 'key';
proxy_id?: number | null; // 关联的代理 ID (可选)
proxy_type?: 'proxy' | 'jump' | null;
tag_ids?: number[]; // 关联的标签 ID 数组 (可选)
ssh_key_id?: number | null; // +++ 关联的 SSH 密钥 ID (可选) +++
created_at: number;
updated_at: number;
last_connected_at: number | null;
notes?: string | null;
notes?: string | null;
vncPassword?: string; // VNC specific password
jump_chain?: number[] | null;
}
// 定义 Store State 的接口
@@ -98,7 +100,9 @@ export const useConnectionsStore = defineStore('connections', {
passphrase?: string; // SSH specific
vncPassword?: string; // VNC specific password
proxy_id?: number | null;
proxy_type?: 'proxy' | 'jump' | null;
tag_ids?: number[]; // 允许传入 tag_ids
jump_chain?: number[] | null;
}) {
this.isLoading = true;
this.error = null;
@@ -125,7 +129,7 @@ export const useConnectionsStore = defineStore('connections', {
// 更新连接 Action
// 更新参数类型以包含 proxy_id 和 tag_ids
// Update parameter type to include 'type' and VNC fields
async updateConnection(connectionId: number, updatedData: Partial<Omit<ConnectionInfo, 'id' | 'created_at' | 'updated_at' | 'last_connected_at'> & { type?: 'SSH' | 'RDP' | 'VNC'; password?: string; private_key?: string; passphrase?: string; vncPassword?: string; proxy_id?: number | null; tag_ids?: number[] }>) {
async updateConnection(connectionId: number, updatedData: Partial<Omit<ConnectionInfo, 'id' | 'created_at' | 'updated_at' | 'last_connected_at'> & { type?: 'SSH' | 'RDP' | 'VNC'; password?: string; private_key?: string; passphrase?: string; vncPassword?: string; proxy_id?: number | null; proxy_type?: 'proxy' | 'jump' | null; tag_ids?: number[]; jump_chain?: number[] | null; }>) {
this.isLoading = true;
this.error = null;
try {