import {zodResolver} from "@hookform/resolvers/zod" import {Controller, useForm} from "react-hook-form" import {z} from "zod" import {Button} from "@/components/ui/button.tsx" import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form.tsx"; import {Input} from "@/components/ui/input.tsx"; import {PasswordInput} from "@/components/ui/password-input.tsx"; import {ScrollArea} from "@/components/ui/scroll-area.tsx" import {Separator} from "@/components/ui/separator.tsx"; import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs.tsx"; import React, {useEffect, useRef, useState} from "react"; import {Switch} from "@/components/ui/switch.tsx"; import {Alert, AlertDescription} from "@/components/ui/alert.tsx"; import {toast} from "sonner"; import {createSSHHost, updateSSHHost, getSSHHosts, getCredentials} from '@/ui/main-axios.ts'; import {useTranslation} from "react-i18next"; import {CredentialSelector} from "@/ui/Desktop/Apps/Credentials/CredentialSelector.tsx"; interface SSHHost { id: number; name: string; ip: string; port: number; username: string; folder: string; tags: string[]; pin: boolean; authType: string; password?: string; key?: string; keyPassword?: string; keyType?: string; enableTerminal: boolean; enableTunnel: boolean; enableFileManager: boolean; defaultPath: string; tunnelConnections: any[]; createdAt: string; updatedAt: string; credentialId?: number; } interface SSHManagerHostEditorProps { editingHost?: SSHHost | null; onFormSubmit?: (updatedHost?: SSHHost) => void; } export function HostManagerEditor({editingHost, onFormSubmit}: SSHManagerHostEditorProps) { const {t} = useTranslation(); const [hosts, setHosts] = useState([]); const [folders, setFolders] = useState([]); const [sshConfigurations, setSshConfigurations] = useState([]); const [credentials, setCredentials] = useState([]); const [loading, setLoading] = useState(true); const [authTab, setAuthTab] = useState<'password' | 'key' | 'credential'>('password'); const [keyInputMethod, setKeyInputMethod] = useState<'upload' | 'paste'>('upload'); const isSubmittingRef = useRef(false); // Ref for the IP address input to manage focus const ipInputRef = useRef(null); useEffect(() => { const fetchData = async () => { try { setLoading(true); const [hostsData, credentialsData] = await Promise.all([ getSSHHosts(), getCredentials() ]); setHosts(hostsData); setCredentials(credentialsData); const uniqueFolders = [...new Set( hostsData .filter(host => host.folder && host.folder.trim() !== '') .map(host => host.folder) )].sort(); const uniqueConfigurations = [...new Set( hostsData .filter(host => host.name && host.name.trim() !== '') .map(host => host.name) )].sort(); setFolders(uniqueFolders); setSshConfigurations(uniqueConfigurations); } catch (error) { } finally { setLoading(false); } }; fetchData(); }, []); // Listen for credential changes to refresh the credential list useEffect(() => { const handleCredentialChange = async () => { try { setLoading(true); const hostsData = await getSSHHosts(); setHosts(hostsData); const uniqueFolders = [...new Set( hostsData .filter(host => host.folder && host.folder.trim() !== '') .map(host => host.folder) )].sort(); const uniqueConfigurations = [...new Set( hostsData .filter(host => host.name && host.name.trim() !== '') .map(host => host.name) )].sort(); setFolders(uniqueFolders); setSshConfigurations(uniqueConfigurations); } catch (error) { // Handle error silently } finally { setLoading(false); } }; window.addEventListener('credentials:changed', handleCredentialChange); return () => { window.removeEventListener('credentials:changed', handleCredentialChange); }; }, []); const formSchema = z.object({ name: z.string().optional(), ip: z.string().min(1), port: z.coerce.number().min(1).max(65535), username: z.string().min(1), folder: z.string().optional(), tags: z.array(z.string().min(1)).default([]), pin: z.boolean().default(false), authType: z.enum(['password', 'key', 'credential']), credentialId: z.number().optional().nullable(), password: z.string().optional(), key: z.any().optional().nullable(), keyPassword: z.string().optional(), keyType: z.enum([ 'auto', 'ssh-rsa', 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'ssh-dss', 'ssh-rsa-sha2-256', 'ssh-rsa-sha2-512', ]).optional(), enableTerminal: z.boolean().default(true), enableTunnel: z.boolean().default(true), tunnelConnections: z.array(z.object({ sourcePort: z.coerce.number().min(1).max(65535), endpointPort: z.coerce.number().min(1).max(65535), endpointHost: z.string().min(1), maxRetries: z.coerce.number().min(0).max(100).default(3), retryInterval: z.coerce.number().min(1).max(3600).default(10), autoStart: z.boolean().default(false), })).default([]), enableFileManager: z.boolean().default(true), defaultPath: z.string().optional(), }).superRefine((data, ctx) => { if (data.authType === 'password') { if (!data.password || data.password.trim() === '') { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t('hosts.passwordRequired'), path: ['password'] }); } } else if (data.authType === 'key') { if (!data.key || (typeof data.key === 'string' && data.key.trim() === '')) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t('hosts.sshKeyRequired'), path: ['key'] }); } if (!data.keyType) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t('hosts.keyTypeRequired'), path: ['keyType'] }); } } else if (data.authType === 'credential') { if (!data.credentialId || (typeof data.credentialId === 'string' && data.credentialId.trim() === '')) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t('hosts.credentialRequired'), path: ['credentialId'] }); } } data.tunnelConnections.forEach((connection, index) => { if (connection.endpointHost && !sshConfigurations.includes(connection.endpointHost)) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t('hosts.mustSelectValidSshConfig'), path: ['tunnelConnections', index, 'endpointHost'] }); } }); }); type FormData = z.infer; const form = useForm({ resolver: zodResolver(formSchema) as any, defaultValues: { name: "", ip: "", port: 22, username: "", folder: "", tags: [], pin: false, authType: "password" as const, credentialId: null, password: "", key: null, keyPassword: "", keyType: "auto" as const, enableTerminal: true, enableTunnel: true, enableFileManager: true, defaultPath: "/", tunnelConnections: [], } }); // Update username when switching to credential tab and a credential is selected useEffect(() => { if (authTab === 'credential') { const currentCredentialId = form.getValues('credentialId'); if (currentCredentialId) { const selectedCredential = credentials.find(c => c.id === currentCredentialId); if (selectedCredential) { form.setValue('username', selectedCredential.username); } } } }, [authTab, credentials, form]); useEffect(() => { if (editingHost) { const cleanedHost = { ...editingHost }; if (cleanedHost.credentialId && cleanedHost.key) { cleanedHost.key = undefined; cleanedHost.keyPassword = undefined; cleanedHost.keyType = undefined; } else if (cleanedHost.credentialId && cleanedHost.password) { cleanedHost.password = undefined; } else if (cleanedHost.key && cleanedHost.password) { cleanedHost.password = undefined; } const defaultAuthType = cleanedHost.credentialId ? 'credential' : (cleanedHost.key ? 'key' : 'password'); setAuthTab(defaultAuthType); const formData = { name: cleanedHost.name || "", ip: cleanedHost.ip || "", port: cleanedHost.port || 22, username: cleanedHost.username || "", folder: cleanedHost.folder || "", tags: cleanedHost.tags || [], pin: Boolean(cleanedHost.pin), authType: defaultAuthType as 'password' | 'key' | 'credential', credentialId: null, password: "", key: null, keyPassword: "", keyType: "auto" as const, enableTerminal: Boolean(cleanedHost.enableTerminal), enableTunnel: Boolean(cleanedHost.enableTunnel), enableFileManager: Boolean(cleanedHost.enableFileManager), defaultPath: cleanedHost.defaultPath || "/", tunnelConnections: cleanedHost.tunnelConnections || [], }; // Only set the relevant authentication fields based on authType if (defaultAuthType === 'password') { formData.password = cleanedHost.password || ""; } else if (defaultAuthType === 'key') { formData.key = "existing_key"; // Placeholder to indicate existing key formData.keyPassword = cleanedHost.keyPassword || ""; formData.keyType = (cleanedHost.keyType as any) || "auto"; } else if (defaultAuthType === 'credential') { formData.credentialId = cleanedHost.credentialId || "existing_credential"; } form.reset(formData); } else { setAuthTab('password'); const defaultFormData = { name: "", ip: "", port: 22, username: "", folder: "", tags: [], pin: false, authType: "password" as const, credentialId: null, password: "", key: null, keyPassword: "", keyType: "auto" as const, enableTerminal: true, enableTunnel: true, enableFileManager: true, defaultPath: "/", tunnelConnections: [], }; form.reset(defaultFormData); } }, [editingHost?.id]); useEffect(() => { const focusTimer = setTimeout(() => { if (ipInputRef.current) { ipInputRef.current.focus(); } }, 300); return () => clearTimeout(focusTimer); }, [editingHost]); const onSubmit = async (data: FormData) => { try { isSubmittingRef.current = true; if (!data.name || data.name.trim() === '') { data.name = `${data.username}@${data.ip}`; } const submitData: any = { name: data.name, ip: data.ip, port: data.port, username: data.username, folder: data.folder || "", tags: data.tags || [], pin: Boolean(data.pin), authType: data.authType, enableTerminal: Boolean(data.enableTerminal), enableTunnel: Boolean(data.enableTunnel), enableFileManager: Boolean(data.enableFileManager), defaultPath: data.defaultPath || "/", tunnelConnections: data.tunnelConnections || [] }; submitData.credentialId = null; submitData.password = null; submitData.key = null; submitData.keyPassword = null; submitData.keyType = null; if (data.authType === 'credential') { if (data.credentialId === "existing_credential") { delete submitData.credentialId; } else { submitData.credentialId = data.credentialId; } } else if (data.authType === 'password') { submitData.password = data.password; } else if (data.authType === 'key') { if (data.key instanceof File) { const keyContent = await data.key.text(); submitData.key = keyContent; } else if (data.key === "existing_key") { delete submitData.key; } else { submitData.key = data.key; } submitData.keyPassword = data.keyPassword; submitData.keyType = data.keyType; } if (editingHost) { const updatedHost = await updateSSHHost(editingHost.id, submitData); toast.success(t('hosts.hostUpdatedSuccessfully', { name: data.name })); if (onFormSubmit) { onFormSubmit(updatedHost); } } else { const newHost = await createSSHHost(submitData); toast.success(t('hosts.hostAddedSuccessfully', { name: data.name })); if (onFormSubmit) { onFormSubmit(newHost); } } window.dispatchEvent(new CustomEvent('ssh-hosts:changed')); // Reset form after successful submission form.reset(); } catch (error) { toast.error(t('hosts.failedToSaveHost')); } finally { isSubmittingRef.current = false; } }; const [tagInput, setTagInput] = useState(""); const [folderDropdownOpen, setFolderDropdownOpen] = useState(false); const folderInputRef = useRef(null); const folderDropdownRef = useRef(null); const folderValue = form.watch('folder'); const filteredFolders = React.useMemo(() => { if (!folderValue) return folders; return folders.filter(f => f.toLowerCase().includes(folderValue.toLowerCase())); }, [folderValue, folders]); const handleFolderClick = (folder: string) => { form.setValue('folder', folder); setFolderDropdownOpen(false); }; useEffect(() => { function handleClickOutside(event: MouseEvent) { if ( folderDropdownRef.current && !folderDropdownRef.current.contains(event.target as Node) && folderInputRef.current && !folderInputRef.current.contains(event.target as Node) ) { setFolderDropdownOpen(false); } } if (folderDropdownOpen) { document.addEventListener('mousedown', handleClickOutside); } else { document.removeEventListener('mousedown', handleClickOutside); } return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, [folderDropdownOpen]); const keyTypeOptions = [ {value: 'auto', label: t('hosts.autoDetect')}, {value: 'ssh-rsa', label: t('hosts.rsa')}, {value: 'ssh-ed25519', label: t('hosts.ed25519')}, {value: 'ecdsa-sha2-nistp256', label: t('hosts.ecdsaNistP256')}, {value: 'ecdsa-sha2-nistp384', label: t('hosts.ecdsaNistP384')}, {value: 'ecdsa-sha2-nistp521', label: t('hosts.ecdsaNistP521')}, {value: 'ssh-dss', label: t('hosts.dsa')}, {value: 'ssh-rsa-sha2-256', label: t('hosts.rsaSha2256')}, {value: 'ssh-rsa-sha2-512', label: t('hosts.rsaSha2512')}, ]; const [keyTypeDropdownOpen, setKeyTypeDropdownOpen] = useState(false); const keyTypeButtonRef = useRef(null); const keyTypeDropdownRef = useRef(null); useEffect(() => { function onClickOutside(event: MouseEvent) { if ( keyTypeDropdownOpen && keyTypeDropdownRef.current && !keyTypeDropdownRef.current.contains(event.target as Node) && keyTypeButtonRef.current && !keyTypeButtonRef.current.contains(event.target as Node) ) { setKeyTypeDropdownOpen(false); } } document.addEventListener("mousedown", onClickOutside); return () => document.removeEventListener("mousedown", onClickOutside); }, [keyTypeDropdownOpen]); const [sshConfigDropdownOpen, setSshConfigDropdownOpen] = useState<{ [key: number]: boolean }>({}); const sshConfigInputRefs = useRef<{ [key: number]: HTMLInputElement | null }>({}); const sshConfigDropdownRefs = useRef<{ [key: number]: HTMLDivElement | null }>({}); const getFilteredSshConfigs = (index: number) => { const value = form.watch(`tunnelConnections.${index}.endpointHost`); const currentHostName = form.watch('name') || `${form.watch('username')}@${form.watch('ip')}`; let filtered = sshConfigurations.filter(config => config !== currentHostName); if (value) { filtered = filtered.filter(config => config.toLowerCase().includes(value.toLowerCase()) ); } return filtered; }; const handleSshConfigClick = (config: string, index: number) => { form.setValue(`tunnelConnections.${index}.endpointHost`, config); setSshConfigDropdownOpen(prev => ({...prev, [index]: false})); }; useEffect(() => { function handleSshConfigClickOutside(event: MouseEvent) { const openDropdowns = Object.keys(sshConfigDropdownOpen).filter(key => sshConfigDropdownOpen[parseInt(key)]); openDropdowns.forEach((indexStr: string) => { const index = parseInt(indexStr); if ( sshConfigDropdownRefs.current[index] && !sshConfigDropdownRefs.current[index]?.contains(event.target as Node) && sshConfigInputRefs.current[index] && !sshConfigInputRefs.current[index]?.contains(event.target as Node) ) { setSshConfigDropdownOpen(prev => ({...prev, [index]: false})); } }); } const hasOpenDropdowns = Object.values(sshConfigDropdownOpen).some(open => open); if (hasOpenDropdowns) { document.addEventListener('mousedown', handleSshConfigClickOutside); } else { document.removeEventListener('mousedown', handleSshConfigClickOutside); } return () => { document.removeEventListener('mousedown', handleSshConfigClickOutside); }; }, [sshConfigDropdownOpen]); return (
{t('hosts.general')} {t('hosts.terminal')} {t('hosts.tunnel')} {t('hosts.fileManager')} {t('hosts.connectionDetails')}
( {t('hosts.ipAddress')} { field.ref(e); ipInputRef.current = e; }} /> )} /> ( {t('hosts.port')} )} /> ( {t('hosts.username')} )} />
{t('hosts.organization')}
( {t('hosts.name')} )} /> ( {t('hosts.folder')} setFolderDropdownOpen(true)} onChange={e => { field.onChange(e); setFolderDropdownOpen(true); }} /> {folderDropdownOpen && filteredFolders.length > 0 && (
{filteredFolders.map((folder) => ( ))}
)}
)} /> ( {t('hosts.tags')}
{field.value.map((tag: string, idx: number) => ( {tag} ))} setTagInput(e.target.value)} onKeyDown={e => { if (e.key === " " && tagInput.trim() !== "") { e.preventDefault(); if (!field.value.includes(tagInput.trim())) { field.onChange([...field.value, tagInput.trim()]); } setTagInput(""); } else if (e.key === "Backspace" && tagInput === "" && field.value.length > 0) { field.onChange(field.value.slice(0, -1)); } }} placeholder={t('hosts.addTagsSpaceToAdd')} />
)} /> ( {t('hosts.pin')} )} />
{t('hosts.authentication')} { const newAuthType = value as 'password' | 'key' | 'credential'; setAuthTab(newAuthType); form.setValue('authType', newAuthType); // Clear authentication fields based on what we're switching away from if (newAuthType === 'password') { form.setValue('key', null); form.setValue('keyPassword', ''); form.setValue('keyType', 'auto'); form.setValue('credentialId', null); } else if (newAuthType === 'key') { form.setValue('password', ''); form.setValue('credentialId', null); } else if (newAuthType === 'credential') { form.setValue('password', ''); form.setValue('key', null); form.setValue('keyPassword', ''); form.setValue('keyType', 'auto'); } }} className="flex-1 flex flex-col h-full min-h-0" > {t('hosts.password')} {t('hosts.key')} {t('hosts.credential')} ( {t('hosts.password')} )} /> { setKeyInputMethod(value as 'upload' | 'paste'); // Clear the other field when switching if (value === 'upload') { form.setValue('key', null); } else { form.setValue('key', ''); } }} className="w-full" > {t('hosts.uploadFile')} {t('hosts.pasteKey')} ( {t('hosts.sshPrivateKey')}
{ const file = e.target.files?.[0]; field.onChange(file || null); }} className="absolute inset-0 w-full h-full opacity-0 cursor-pointer" />
)} />
( {t('hosts.sshPrivateKey')}