"use client"; import { useCallback, useMemo, useState } from "react"; import { Badge } from "@kandev/ui/badge"; import { Button } from "@kandev/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@kandev/ui/card"; import { Input } from "@kandev/ui/input"; import { Label } from "@kandev/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { IconCheck, IconLoader2, IconShieldLock, IconTerminal2, IconTestPipe, IconX, } from "@tabler/icons-react"; import { testSSHConnection } from "@/lib/api/domains/ssh-api"; import { FingerprintTrustBlock } from "@/components/settings/ssh-fingerprint-trust-block"; import type { SSHIdentitySource, SSHTestRequest, SSHTestResult, SSHTestStep, } from "@/lib/types/http-ssh"; // SSHExecutorConfig is the shape we persist into executor.Config on save. // The host_fingerprint is set only after a successful Test Connection has // completed and the user has ticked "Trust this host". export interface SSHExecutorConfig { name: string; host_alias?: string; host?: string; port?: number; user?: string; identity_source: SSHIdentitySource; identity_file?: string; proxy_jump?: string; host_fingerprint?: string; } export interface SSHConnectionCardProps { initial?: Partial; // Called when the user clicks Save after a successful test+trust. The // returned config carries the freshly pinned fingerprint. onSave: (config: SSHExecutorConfig) => Promise | void; // Existing running sessions for this executor. Triggers the // "this won't affect existing sessions" warning on save. runningSessionCount?: number; } interface SSHConnectionState { form: SSHExecutorConfig; testing: boolean; saving: boolean; result: SSHTestResult | null; // resultStale flips true when the user edits a connection-affecting field // after a successful test, so the prior fingerprint cannot be trusted for // the current form. The result stays visible (the trust-gate spec expects // the checkbox to render) but trust + save are gated off until the user // re-runs Test Connection. resultStale: boolean; trust: boolean; error: string | null; } // Fields whose value, if changed, could route the next connection to a // different machine — editing any of them invalidates the current trust tick // so the user must re-test against the new target. const CONNECTION_FIELDS = new Set([ "host_alias", "host", "port", "user", "identity_source", "identity_file", "proxy_jump", ]); const SSH_FORM_DEFAULTS: SSHExecutorConfig = { name: "", host_alias: "", host: "", port: 22, user: "", identity_source: "agent", identity_file: "", proxy_jump: "", host_fingerprint: undefined, }; function initialState(initial?: Partial): SSHConnectionState { return { form: { ...SSH_FORM_DEFAULTS, ...(initial ?? {}) }, testing: false, saving: false, result: null, resultStale: false, trust: false, error: null, }; } function useSSHConnection(props: SSHConnectionCardProps) { const [state, setState] = useState(() => initialState(props.initial)); const { form, testing, saving, result, resultStale, trust, error } = state; const update = useCallback( (key: K, value: SSHExecutorConfig[K]) => { setState((prev) => { const isConnectionField = CONNECTION_FIELDS.has(key); // A connection edit invalidates the prior result. Mark stale when // a test result is already on screen OR a test is mid-flight — in // the latter case handleTest will see the staleness on completion // and refuse to clear it, so a fingerprint returned for the old // form can't be trusted against the new one. const staleAfter = isConnectionField ? prev.result !== null || prev.testing || prev.resultStale : prev.resultStale; return { ...prev, form: { ...prev.form, [key]: value }, resultStale: staleAfter, trust: isConnectionField ? false : prev.trust, error: null, }; }); }, [], ); const setTrust = useCallback((v: boolean) => setState((prev) => ({ ...prev, trust: v })), []); const canTest = useMemo(() => { if (testing) return false; if (form.name.trim() === "") return false; if ((form.host ?? "").trim() === "" && (form.host_alias ?? "").trim() === "") return false; return true; }, [form, testing]); const handleTest = useCallback(async () => { setState((prev) => ({ ...prev, testing: true, result: null, resultStale: false, error: null, })); try { const req: SSHTestRequest = { name: form.name, host_alias: form.host_alias || undefined, host: form.host || undefined, port: form.port || undefined, user: form.user || undefined, identity_source: form.identity_source, identity_file: form.identity_file || undefined, proxy_jump: form.proxy_jump || undefined, }; const res = await testSSHConnection(req); setState((prev) => ({ ...prev, result: res, // Preserve resultStale if the user edited a connection field while // the test was in flight — the returned fingerprint is bound to the // old form and must not be trusted against the new target. resultStale: prev.resultStale, testing: false, })); } catch (e) { const msg = e instanceof Error ? e.message : "Failed to reach backend"; setState((prev) => ({ ...prev, error: msg, testing: false })); } }, [form]); const canSave = !!result?.success && !!result.fingerprint && trust && !resultStale && !saving; const confirmRunningSessions = useCallback( () => props.runningSessionCount ? window.confirm( `This executor has ${props.runningSessionCount} running session(s). ` + `They will keep running on the current host. Only new sessions started ` + `after save will use the updated config. Continue?`, ) : true, [props.runningSessionCount], ); const handleSave = useCallback(async () => { if (!canSave || !result?.fingerprint) return; if (!confirmRunningSessions()) return; setState((prev) => ({ ...prev, saving: true, error: null })); try { await props.onSave({ ...form, host_fingerprint: result.fingerprint }); setState((prev) => ({ ...prev, saving: false })); } catch (e) { const msg = e instanceof Error ? e.message : "Failed to save executor"; setState((prev) => ({ ...prev, saving: false, error: msg })); } }, [canSave, confirmRunningSessions, form, props, result]); return { form, testing, saving, result, resultStale, trust, error, canTest, canSave, update, setTrust, handleTest, handleSave, }; } export function SSHConnectionCard(props: SSHConnectionCardProps) { const c = useSSHConnection(props); return (
Connection Run an agent on any Linux box you can reach over SSH. linux/amd64 hosts only.
{c.form.host_fingerprint && } {c.error && (

{c.error}

)} {c.result && ( )}
); } type FieldOnChange = ( key: K, value: SSHExecutorConfig[K], ) => void; function SSHConnectionForm({ form, onChange, }: { form: SSHExecutorConfig; onChange: FieldOnChange; }) { return (
onChange("name", v)} /> onChange("host_alias", v)} /> onChange("host", v)} /> onChange("port", parseInt(v, 10) || 22)} /> onChange("user", v)} /> onChange("identity_source", v)} /> {form.identity_source === "file" && ( onChange("identity_file", v)} /> )} onChange("proxy_jump", v)} />
); } function TextField({ id, testId, label, hint, placeholder, type, value, onChange, }: { id: string; testId: string; label: string; hint?: string; placeholder?: string; type?: string; value: string; onChange: (v: string) => void; }) { return ( onChange(e.target.value)} /> ); } function IdentitySourceField({ value, onChange, }: { value: SSHIdentitySource; onChange: (v: SSHIdentitySource) => void; }) { return ( ); } function FieldShell({ id, label, hint, children, }: { id: string; label: string; hint?: string; children: React.ReactNode; }) { return (
{children} {hint &&

{hint}

}
); } function PinnedFingerprintRow({ fingerprint }: { fingerprint: string }) { return (
Pinned fingerprint:{" "} {fingerprint}
); } function SSHConnectionActions({ testing, saving, canTest, canSave, onTest, onSave, }: { testing: boolean; saving: boolean; canTest: boolean; canSave: boolean; onTest: () => void; onSave: () => void; }) { return (
); } function ConnectionBadge({ fingerprint }: { fingerprint?: string }) { if (!fingerprint) { return ( Unverified ); } return ( Trusted ); } function TestResultDisplay({ result, trust, resultStale, onTrustChange, currentlyPinned, }: { result: SSHTestResult; trust: boolean; resultStale: boolean; onTrustChange: (v: boolean) => void; currentlyPinned?: string; }) { return (
{result.steps.map((step: SSHTestStep) => ( ))} {result.error && !result.steps.some((s) => s.error) && (

{result.error}

)} {result.success && result.fingerprint && ( )}
); } function TestResultHeader({ success, totalMs }: { success: boolean; totalMs: number }) { return (
{success ? ( ) : ( )} {success ? "Connection test passed" : "Connection test failed"} ({totalMs}ms)
); } function StepRow({ step }: { step: SSHTestStep }) { const slug = step.name.toLowerCase().replace(/[^a-z0-9]+/g, "-"); return (
{step.success ? ( ) : ( )}
{step.name} ({step.duration_ms}ms)
{step.output && (

{step.output}

)} {step.error && (

{step.error}

)}
); }