feat: move vault ssh signing into a plugin (C5)

This commit is contained in:
LukeGus committed 2026-09-24 20:24:09 -05:00
1 parent b027717c46
commit 6e56c90aac
198 files changed
+19717 -3445

No files matched your search

@@ -0,0 +1,54 @@
import { toast } from "sonner";
import {
useTranslation,
type SettingsComponentProps,
} from "@termix/plugin-sdk/frontend";
import { Button, Input, copyToClipboard } from "@termix/plugin-sdk/ui";
const CALLBACK_PATH = "plugin-api/vault/oidc/callback";
const LEGACY_CALLBACK_PATH = "vault/oidc/callback";
/** The redirect URI to allow in the Vault OIDC role. */
export function redirectUri(
legacy: boolean,
baseUri = document.baseURI,
): string {
return new URL(
legacy ? LEGACY_CALLBACK_PATH : CALLBACK_PATH,
baseUri,
).toString();
}
export function RedirectUriSetting({ values }: SettingsComponentProps) {
const { t } = useTranslation();
const uri = redirectUri(values.legacyCallback === true);
return (
<div className="flex flex-col gap-2">
<span className="text-xs font-medium">
{t("settings.redirectUri.label")}
</span>
<div className="flex gap-2">
<Input
value={uri}
readOnly
className="rounded-none font-mono text-xs"
/>
<Button
type="button"
variant="outline"
className="rounded-none"
onClick={async () => {
if (await copyToClipboard(uri)) toast.success(t("common.copied"));
else toast.error(t("common.copyFailed"));
}}
>
{t("common.copy")}
</Button>
</div>
<p className="text-[10px] text-muted-foreground">
{t("settings.redirectUri.description")}
</p>
</div>
);
}
@@ -0,0 +1,108 @@
import { useCallback, useEffect, useState } from "react";
import {
usePermission,
usePluginApi,
useTranslation,
type SshAuthEditorProps,
} from "@termix/plugin-sdk/frontend";
import { Select2 } from "@termix/plugin-sdk/ui";
import { VaultProfileManager } from "./VaultProfileManager";
import type { VaultProfile } from "./types";
const PLUGIN_ID = "vault";
const DOCS_URL = "https://docs.termix.site/features/authentication/vault";
type PluginSettingsBag = Record<string, Record<string, unknown>>;
/**
* The host editor's "vault" auth method: pick a signer profile, and manage
* profiles in place. The choice is the profileId host setting, which the
* editor saves with the rest of the host's plugin settings.
*/
export function VaultAuthEditor({ form, setField }: SshAuthEditorProps) {
const { t } = useTranslation();
const api = usePluginApi();
const canUse = usePermission("use");
const [profiles, setProfiles] = useState<VaultProfile[]>([]);
const [showManager, setShowManager] = useState(false);
const bag = (form.pluginSettings as PluginSettingsBag | undefined) ?? {};
const profileId = bag[PLUGIN_ID]?.profileId;
const reload = useCallback(() => {
if (!canUse) return;
api
.get<VaultProfile[]>("/profiles")
.then(({ data }) => setProfiles(Array.isArray(data) ? data : []))
.catch(() => setProfiles([]));
}, [api, canUse]);
useEffect(() => {
reload();
}, [reload]);
const select = (value: string) => {
setField("pluginSettings", {
...bag,
[PLUGIN_ID]: {
...(bag[PLUGIN_ID] ?? {}),
profileId: value ? Number(value) : null,
},
});
};
return (
<>
<div className="flex flex-col gap-1.5 col-span-2">
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{t("editor.profile")}
</label>
<Select2
value={profileId != null ? String(profileId) : ""}
onChange={(e) => select(e.target.value)}
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
>
<option value="">{t("editor.selectProfile")}</option>
{profiles.map((profile) => (
<option key={profile.id} value={String(profile.id)}>
{profile.shared
? t("editor.sharedProfile", { name: profile.name })
: profile.name}
</option>
))}
</Select2>
<div className="flex items-center justify-between">
<p className="text-[10px] text-muted-foreground">
{t("editor.hint")}
</p>
<div className="flex items-center gap-2 shrink-0">
<a
href={DOCS_URL}
target="_blank"
rel="noreferrer"
className="text-[10px] text-accent-brand hover:underline"
>
{t("editor.docs")}
</a>
{canUse && (
<button
type="button"
className="text-[10px] text-accent-brand hover:text-accent-brand/80"
onClick={() => setShowManager((shown) => !shown)}
>
{t("profiles.manage")}
</button>
)}
</div>
</div>
</div>
{showManager && (
<VaultProfileManager
profiles={profiles}
onChanged={reload}
onClose={() => setShowManager(false)}
/>
)}
</>
);
}
+245
View File
@@ -0,0 +1,245 @@
import { useEffect, useRef, useState } from "react";
import { AlertCircle, KeyRound, Loader2 } from "lucide-react";
import { useTranslation } from "@termix/plugin-sdk/frontend";
import { Button } from "@termix/plugin-sdk/ui";
/** What the ssh-terminal plugin hands a "terminal.overlay" component. */
export interface TerminalOverlayProps {
host: { id: number | string; [key: string]: unknown } | undefined;
backgroundColor?: string;
subscribe: (
listener: (message: { type: string; [key: string]: unknown }) => void,
) => () => void;
holdConnectTimeout: (held: boolean) => void;
fail: (message: string) => void;
disconnect: () => void;
send: (type: string, data?: unknown) => void;
connectPayload: () => Record<string, unknown>;
}
interface DialogState {
stage: "waiting" | "error";
error?: string;
hostId?: unknown;
requestId?: string;
}
/** How long the dialog waits before giving up on the connection. */
const DIALOG_TIMEOUT_MS = 300_000;
const footerButton =
"rounded-none text-[10px] font-bold uppercase tracking-widest";
/**
* Runs the Vault OIDC sign-in for a terminal: asks the server to start it,
* opens Vault's auth URL in a popup, and reconnects once Vault has signed
* the certificate.
*/
export function VaultOverlay({
subscribe,
holdConnectTimeout,
fail,
disconnect,
send,
connectPayload,
backgroundColor,
}: TerminalOverlayProps) {
const { t } = useTranslation();
const [dialog, setDialog] = useState<DialogState | null>(null);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const popupRef = useRef<Window | null>(null);
const heldRef = useRef(false);
// A second "auth required" after a sign-in means the certificate did not work.
const failedRef = useRef(false);
useEffect(() => {
const clearTimer = () => {
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = null;
};
const closePopup = () => {
try {
popupRef.current?.close();
} catch {
// already closed
}
popupRef.current = null;
};
const hold = (held: boolean) => {
if (heldRef.current === held) return;
heldRef.current = held;
holdConnectTimeout(held);
};
const unsubscribe = subscribe((message) => {
switch (message.type) {
case "vault_auth_required":
hold(true);
if (failedRef.current) {
clearTimer();
hold(false);
setDialog({ stage: "error", error: t("dialog.failed") });
fail(t("dialog.failed"));
} else {
failedRef.current = true;
send("vault_start_auth", { hostId: message.hostId });
}
break;
case "vault_auth_url":
try {
popupRef.current = window.open(
String(message.url ?? ""),
"termix-vault-oidc",
"width=540,height=720",
);
} catch {
popupRef.current = null;
}
setDialog({
stage: "waiting",
hostId: message.hostId,
requestId:
typeof message.requestId === "string"
? message.requestId
: undefined,
});
clearTimer();
timerRef.current = setTimeout(() => {
setDialog(null);
hold(false);
disconnect();
}, DIALOG_TIMEOUT_MS);
break;
case "vault_completed":
clearTimer();
closePopup();
setDialog(null);
send("vault_auth_completed", connectPayload());
break;
case "vault_error":
failedRef.current = true;
clearTimer();
closePopup();
hold(false);
setDialog({ stage: "error", error: String(message.error ?? "") });
break;
case "connected":
case "sessionAttached":
failedRef.current = false;
hold(false);
break;
case "session_closed":
clearTimer();
setDialog(null);
hold(false);
break;
}
});
return () => {
unsubscribe();
clearTimer();
if (heldRef.current) {
heldRef.current = false;
holdConnectTimeout(false);
}
};
}, [
subscribe,
holdConnectTimeout,
fail,
disconnect,
send,
connectPayload,
t,
]);
if (!dialog) return null;
const close = () => {
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = null;
try {
popupRef.current?.close();
} catch {
// already closed
}
if (dialog.stage === "waiting") {
send("vault_cancel", {
hostId: dialog.hostId,
requestId: dialog.requestId,
});
}
setDialog(null);
if (heldRef.current) {
heldRef.current = false;
holdConnectTimeout(false);
}
};
return (
<div className="absolute inset-0 flex items-center justify-center z-500 animate-in fade-in duration-200">
<div
className="absolute inset-0 bg-canvas"
style={{ backgroundColor: backgroundColor || undefined }}
/>
<div className="bg-card border border-border w-full max-w-md mx-4 relative z-10">
<div className="p-4 border-b border-border">
<div className="flex items-center gap-2">
<KeyRound className="size-4 text-accent-brand" />
<h3 className="text-xs font-bold uppercase tracking-widest">
{dialog.stage === "error"
? t("dialog.failed")
: t("dialog.title")}
</h3>
</div>
</div>
<div className="p-4 flex flex-col gap-4">
{dialog.stage === "waiting" ? (
<div className="flex items-center gap-3 py-2">
<Loader2 className="size-4 animate-spin text-accent-brand shrink-0" />
<p className="text-xs text-muted-foreground">
{t("dialog.description")}
</p>
</div>
) : (
<div className="flex items-start gap-3 p-3 border border-destructive/20 bg-destructive/10">
<AlertCircle className="size-4 text-destructive shrink-0 mt-0.5" />
<p className="text-xs text-destructive/90 whitespace-pre-wrap break-words">
{dialog.error || t("dialog.failed")}
</p>
</div>
)}
<div className="flex justify-end gap-2">
{dialog.stage === "waiting" && (
<Button
type="button"
variant="outline"
className={footerButton}
onClick={() => {
try {
popupRef.current?.focus();
} catch {
// popup gone
}
}}
>
{t("dialog.reopen")}
</Button>
)}
<Button
type="button"
variant="ghost"
className={footerButton}
onClick={close}
>
{dialog.stage === "error"
? t("common.close")
: t("common.cancel")}
</Button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,286 @@
import { useState } from "react";
import { Pencil, Plus, Trash2, X } from "lucide-react";
import {
usePermission,
usePluginApi,
useToast,
useTranslation,
} from "@termix/plugin-sdk/frontend";
import { Button, Input, Select2 } from "@termix/plugin-sdk/ui";
import {
errorMessage,
type VaultProfile,
type VaultProfilePayload,
} from "./types";
type FormState = {
id?: number;
name: string;
vaultAddr: string;
vaultNamespace: string;
oidcMount: string;
oidcRole: string;
sshMount: string;
sshRole: string;
validPrincipals: string;
keyType: string;
shared: boolean;
};
type TextKey = Exclude<keyof FormState, "id" | "shared">;
const emptyForm: FormState = {
name: "",
vaultAddr: "",
vaultNamespace: "",
oidcMount: "oidc",
oidcRole: "",
sshMount: "ssh-client-signer",
sshRole: "",
validPrincipals: "",
keyType: "ssh-ed25519",
shared: false,
};
function toForm(p: VaultProfile): FormState {
return {
id: p.id,
name: p.name,
vaultAddr: p.vaultAddr,
vaultNamespace: p.vaultNamespace ?? "",
oidcMount: p.oidcMount ?? "oidc",
oidcRole: p.oidcRole ?? "",
sshMount: p.sshMount ?? "ssh-client-signer",
sshRole: p.sshRole,
validPrincipals: p.validPrincipals ?? "",
keyType: p.keyType ?? "ssh-ed25519",
shared: p.shared,
};
}
const blank = (value: string) => value.trim() || null;
/** Create, edit and delete the caller's Vault profiles. */
export function VaultProfileManager({
profiles,
onChanged,
onClose,
}: {
profiles: VaultProfile[];
onChanged: () => void;
onClose: () => void;
}) {
const { t } = useTranslation();
const api = usePluginApi();
const toast = useToast();
const canShare = usePermission("share");
const [form, setForm] = useState<FormState | null>(null);
const [saving, setSaving] = useState(false);
const setField = <K extends keyof FormState>(key: K, value: FormState[K]) =>
setForm((current) => (current ? { ...current, [key]: value } : current));
const handleSave = async () => {
if (!form) return;
if (!form.name.trim() || !form.vaultAddr.trim() || !form.sshRole.trim()) {
toast.error(t("profiles.validationError"));
return;
}
setSaving(true);
try {
const payload: VaultProfilePayload = {
name: form.name.trim(),
vaultAddr: form.vaultAddr.trim(),
vaultNamespace: blank(form.vaultNamespace),
oidcMount: blank(form.oidcMount),
oidcRole: blank(form.oidcRole),
sshMount: blank(form.sshMount),
sshRole: form.sshRole.trim(),
validPrincipals: blank(form.validPrincipals),
keyType: blank(form.keyType),
shared: canShare && form.shared,
};
if (form.id) {
await api.put(`/profiles/${form.id}`, payload);
toast.success(t("profiles.saved"));
} else {
await api.post("/profiles", payload);
toast.success(t("profiles.created"));
}
setForm(null);
onChanged();
} catch (error) {
toast.error(errorMessage(error, t("profiles.saveFailed")));
} finally {
setSaving(false);
}
};
const handleDelete = async (profile: VaultProfile) => {
try {
await api.delete(`/profiles/${profile.id}`);
toast.success(t("profiles.deleted"));
onChanged();
} catch (error) {
toast.error(errorMessage(error, t("profiles.deleteFailed")));
}
};
const field = (label: string, key: TextKey, placeholder?: string) => (
<div className="flex flex-col gap-1">
<label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
{label}
</label>
<Input
className="h-8 text-xs rounded-none"
placeholder={placeholder}
value={form?.[key] ?? ""}
onChange={(e) => setField(key, e.target.value)}
/>
</div>
);
return (
<div className="flex flex-col gap-3 col-span-2 border border-border bg-muted/20 p-3">
<div className="flex items-center justify-between">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{t("profiles.manage")}
</span>
<button
type="button"
aria-label={t("common.close")}
onClick={onClose}
className="text-muted-foreground hover:text-foreground"
>
<X className="size-3.5" />
</button>
</div>
{!form && (
<>
<div className="flex flex-col divide-y divide-border/50">
{profiles.length === 0 && (
<span className="text-[11px] text-muted-foreground py-1">
{t("profiles.none")}
</span>
)}
{profiles.map((profile) => (
<div
key={profile.id}
className="flex items-center justify-between py-1.5"
>
<div className="flex flex-col min-w-0">
<span className="text-xs text-foreground truncate">
{profile.name}
{profile.shared && (
<span className="ml-1 text-[9px] text-accent-brand">
{t("profiles.sharedBadge")}
</span>
)}
</span>
<span className="text-[10px] text-muted-foreground truncate">
{profile.vaultAddr}
</span>
</div>
{profile.owned && (
<div className="flex items-center gap-1 shrink-0">
<button
type="button"
title={t("profiles.edit")}
onClick={() => setForm(toForm(profile))}
className="size-7 flex items-center justify-center text-muted-foreground/60 hover:text-foreground hover:bg-muted-foreground/10"
>
<Pencil className="size-3.5" />
</button>
<button
type="button"
title={t("profiles.delete")}
onClick={() => handleDelete(profile)}
className="size-7 flex items-center justify-center text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10"
>
<Trash2 className="size-3.5" />
</button>
</div>
)}
</div>
))}
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-[10px] self-start rounded-none"
onClick={() => setForm({ ...emptyForm })}
>
<Plus className="size-3 mr-1" /> {t("profiles.new")}
</Button>
</>
)}
{form && (
<div className="flex flex-col gap-2">
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{field(t("profiles.name"), "name", "Production Vault")}
{field(t("profiles.vaultAddr"), "vaultAddr", "https://vault:8200")}
{field(t("profiles.namespace"), "vaultNamespace", "admin")}
{field(t("profiles.oidcMount"), "oidcMount", "oidc")}
{field(t("profiles.oidcRole"), "oidcRole", "default")}
{field(t("profiles.sshMount"), "sshMount", "ssh-client-signer")}
{field(t("profiles.sshRole"), "sshRole", "my-role")}
{field(
t("profiles.validPrincipals"),
"validPrincipals",
"root,deploy",
)}
</div>
<div className="flex flex-col gap-1">
<label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
{t("profiles.keyType")}
</label>
<Select2
value={form.keyType}
onChange={(e) => setField("keyType", e.target.value)}
className="flex h-8 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
>
<option value="ssh-ed25519">Ed25519</option>
<option value="ecdsa-sha2-nistp256">ECDSA (nistp256)</option>
<option value="ssh-rsa">RSA (4096)</option>
</Select2>
</div>
{canShare && (
<label className="flex items-center gap-2 text-xs text-foreground">
<input
type="checkbox"
checked={form.shared}
onChange={(e) => setField("shared", e.target.checked)}
/>
{t("profiles.shareWithAll")}
</label>
)}
<div className="flex justify-end gap-2">
<Button
type="button"
variant="ghost"
size="sm"
className="rounded-none"
onClick={() => setForm(null)}
disabled={saving}
>
{t("common.cancel")}
</Button>
<Button
type="button"
variant="outline"
size="sm"
className="rounded-none border-accent-brand/40 text-accent-brand"
onClick={handleSave}
disabled={saving}
>
{form.id ? t("profiles.save") : t("profiles.create")}
</Button>
</div>
</div>
)}
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import type { ComponentType } from "react";
import type { TermixApp } from "@termix/plugin-sdk/frontend";
import { VaultAuthEditor } from "./VaultAuthEditor";
import { VaultOverlay } from "./VaultOverlay";
import { RedirectUriSetting } from "./RedirectUriSetting";
export function activate(app: TermixApp): void {
app.registerSshAuthEditor({
authType: "vault",
titleKey: "hosts.filterAuthVault",
component: VaultAuthEditor,
});
// The Vault sign-in while a terminal connects to a Vault host.
app.registerSlotContribution("terminal.overlay", {
actionId: "vault.signIn",
titleKey: "dialog.title",
kind: "component",
component: VaultOverlay as unknown as ComponentType<
Record<string, unknown>
>,
});
app.registerSettingsComponent("redirectUri", RedirectUriSetting);
}
export function deactivate(): void {
// Registrations through app are disposed by core.
}
+34
View File
@@ -0,0 +1,34 @@
/** A Vault signer profile as GET /profiles returns it. */
export interface VaultProfile {
id: number;
name: string;
vaultAddr: string;
vaultNamespace: string | null;
oidcMount: string | null;
oidcRole: string | null;
sshMount: string | null;
sshRole: string;
validPrincipals: string | null;
keyType: string | null;
shared: boolean;
owned: boolean;
}
export interface VaultProfilePayload {
name: string;
vaultAddr: string;
vaultNamespace: string | null;
oidcMount: string | null;
oidcRole: string | null;
sshMount: string | null;
sshRole: string;
validPrincipals: string | null;
keyType: string | null;
shared: boolean;
}
export function errorMessage(error: unknown, fallback: string): string {
const data = (error as { response?: { data?: { error?: unknown } } })
?.response?.data;
return typeof data?.error === "string" ? data.error : fallback;
}