Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(plugins): add interactive prompts and richer connection forms

Jinpye4bda693fb89
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 46fb68a8a8..4d0e38d1dd 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -3610,7 +3610,7 @@ const connectionLabelSmallPaddedClass = `${connectionLabelClass} pt-2 text-xs`;
function pluginFieldValue(field: PluginFormField): PluginFormFieldValue {
if (field.binding === "name") return form.value.name;
- return pluginFormValues.value[field.key] ?? field.default;
+ return pluginFormValues.value[field.key] ?? field.default ?? undefined;
}
function pluginFieldHasValue(field: PluginFormField): boolean {
diff --git a/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts b/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts
index 8e2f87e370..ef243dda82 100644
--- a/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts
+++ b/apps/desktop/src/components/plugins/PluginConnectionFields.spec.ts
@@ -4,9 +4,19 @@ import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import PluginConnectionFields from "./PluginConnectionFields.vue";
-import type { PluginConnectionProviderContribution, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
+import type { PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
const invokePluginMock = vi.fn();
+const { pickPluginFieldFileMock, tauriRuntime } = vi.hoisted(() => ({
+ pickPluginFieldFileMock: vi.fn(),
+ tauriRuntime: { value: false },
+}));
+
+vi.mock("@/lib/plugins/pluginFieldPicker", () => ({
+ PLUGIN_PICKER_MAX_BYTES: 1_048_576,
+ pickPluginFieldFile: (...args: unknown[]) => pickPluginFieldFileMock(...args),
+}));
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => tauriRuntime.value }));
vi.mock("@/lib/backend/api", () => ({
listLocalSshKeys: vi.fn(async () => [
@@ -56,6 +66,72 @@ async function mountFields(initialValues: Record<string, PluginFormFieldValue> =
return state;
}
+describe("PluginConnectionFields file picker", () => {
+ const pickerContribution = (picker: PluginFormField["picker"], contentField = true): PluginConnectionProviderContribution => ({
+ type: "connection-provider",
+ id: "ssh.connection",
+ label: "SSH",
+ database_type: "ssh",
+ fields: [{ key: "private_key_path", label: "Private key path", type: "text", picker }, ...(contentField ? [{ key: "private_key", label: "Private key", type: "textarea" as const, binding: "secret" as const }] : [])],
+ });
+
+ it("stores the chosen client path on desktop and drops a stale uploaded copy", async () => {
+ tauriRuntime.value = true;
+ pickPluginFieldFileMock.mockReset().mockResolvedValue({ path: "/Users/dev/.ssh/id_rsa", name: "id_rsa" });
+ const provider = pickerContribution({ kind: "file", accept: [".pem"], content_field: "private_key" });
+ const state = await mountContribution(provider, { private_key: "OLD-UPLOADED-KEY" });
+
+ const browse = document.querySelector<HTMLButtonElement>("#ssh-connection-private_key_path-picker");
+ expect(browse?.textContent).toContain("Choose file");
+ browse?.click();
+
+ await vi.waitFor(() => expect(state.values.private_key_path).toBe("/Users/dev/.ssh/id_rsa"));
+ // The plugin prefers content over a path, so picking a path must clear the
+ // previously uploaded key or the stale one would keep winning.
+ expect(state.values.private_key).toBeUndefined();
+ });
+
+ it("uploads the file content into the paired field on browser hosts", async () => {
+ tauriRuntime.value = false;
+ pickPluginFieldFileMock.mockReset().mockResolvedValue({ content: "UPLOADED-KEY", name: "id_rsa" });
+ const provider = pickerContribution({ kind: "file", accept: [".pem"], content_field: "private_key" });
+ const state = await mountContribution(provider, { private_key_path: "/Users/dev/.ssh/id_rsa" });
+
+ const upload = document.querySelector<HTMLButtonElement>("#ssh-connection-private_key_path-picker");
+ expect(upload?.textContent).toContain("Upload file");
+ upload?.click();
+
+ await vi.waitFor(() => expect(state.values.private_key).toBe("UPLOADED-KEY"));
+ // A browser path would point at the user's machine, not the host's.
+ expect(state.values.private_key_path).toBeUndefined();
+ });
+
+ it("hides a browser-unsupported picker and keeps the desktop one available", async () => {
+ const provider = pickerContribution({ kind: "file" }, false);
+
+ tauriRuntime.value = false;
+ await mountContribution(provider, {});
+ expect(document.querySelector("#ssh-connection-private_key_path-picker")).toBeNull();
+
+ tauriRuntime.value = true;
+ await mountContribution(provider, {});
+ expect(document.querySelector("#ssh-connection-private_key_path-picker")).not.toBeNull();
+ });
+
+ it("surfaces a picker failure without touching the form", async () => {
+ tauriRuntime.value = false;
+ pickPluginFieldFileMock.mockReset().mockRejectedValue(new Error("File is larger than 1024 KiB"));
+ const provider = pickerContribution({ kind: "file", content_field: "private_key" });
+ const state = await mountContribution(provider, { private_key: "KEEP-ME" });
+
+ document.querySelector<HTMLButtonElement>("#ssh-connection-private_key_path-picker")?.click();
+
+ await vi.waitFor(() => expect(pickPluginFieldFileMock).toHaveBeenCalled());
+ await nextTick();
+ expect(state.values).toEqual({ private_key: "KEEP-ME" });
+ });
+});
+
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = "";
@@ -111,6 +187,39 @@ describe("PluginConnectionFields", () => {
expect(state.values).toEqual({ password: "secret", host: "db.internal" });
});
+ it('renders a null value as an empty field instead of the text "null"', async () => {
+ // Hosts before the manifest serialization fix hydrated untouched fields with
+ // `null`, and a null reaching an <input> is coerced to the string "null" by
+ // the DOM — a password field then looked non-empty without any user input.
+ const provider: PluginConnectionProviderContribution = {
+ type: "connection-provider",
+ id: "null.connection",
+ label: "Nulls",
+ database_type: "nulls",
+ fields: [
+ { key: "sudo_password", label: "Sudo password", type: "password", binding: "secret" },
+ { key: "sudo_command", label: "Sudo command", type: "text", binding: "config" },
+ { key: "set_env", label: "Env", type: "textarea", binding: "config" },
+ ],
+ };
+ const state = await mountContribution(provider, {
+ sudo_password: null,
+ sudo_command: null,
+ set_env: null,
+ } as unknown as Record<string, PluginFormFieldValue>);
+
+ expect(document.querySelector<HTMLInputElement>("#null-connection-sudo_password")?.value).toBe("");
+ expect(document.querySelector<HTMLInputElement>("#null-connection-sudo_command")?.value).toBe("");
+ expect(document.querySelector<HTMLTextAreaElement>("#null-connection-set_env")?.value).toBe("");
+
+ // Editing still emits a real value, so a null never survives the dialog.
+ const command = document.querySelector<HTMLInputElement>("#null-connection-sudo_command")!;
+ command.value = "sudo -n true";
+ command.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ expect(state.values.sudo_command).toBe("sudo -n true");
+ });
+
it("can hide host-owned common bindings", async () => {
contribution.fields[0].binding = "host";
await mountFields({}, ["host"]);
@@ -222,6 +331,69 @@ describe("PluginConnectionFields", () => {
expect(document.querySelector("#kafka-connection-msk_region")).toBeNull();
});
+ it("renders a field only while every clause of an all_of condition holds (sudo_source + read_only)", async () => {
+ // The SSH plugin cannot express "sudo_source = custom AND read_only =
+ // false" with one clause per field; all_of + a boolean literal covers it.
+ const ssh: PluginConnectionProviderContribution = {
+ type: "connection-provider",
+ id: "ssh.connection",
+ label: "SSH",
+ database_type: "ssh",
+ fields: [
+ {
+ key: "read_only",
+ label: "Read only",
+ type: "boolean",
+ default: false,
+ },
+ {
+ key: "sudo_source",
+ label: "Sudo source",
+ type: "select",
+ default: "none",
+ options: [
+ { label: "None", value: "none" },
+ { label: "Custom", value: "custom" },
+ ],
+ },
+ {
+ key: "sudo_command",
+ label: "Sudo command",
+ type: "text",
+ visible_when: {
+ all_of: [
+ { field: "sudo_source", one_of: ["custom"] },
+ { field: "read_only", one_of: [false] },
+ ],
+ },
+ required_when: {
+ all_of: [
+ { field: "sudo_source", one_of: ["custom"] },
+ { field: "read_only", one_of: [false] },
+ ],
+ },
+ },
+ ],
+ };
+ const state = await mountContribution(ssh, {});
+
+ expect(document.querySelector("#ssh-connection-sudo_command")).toBeNull();
+
+ state.values = { sudo_source: "custom", read_only: false };
+ await nextTick();
+ expect(document.querySelector("#ssh-connection-sudo_command")).not.toBeNull();
+ expect(document.querySelector('label[for="ssh-connection-sudo_command"]')?.textContent).toContain("*");
+
+ // Read-only sessions ignore the sudo block entirely.
+ state.values = { sudo_source: "custom", read_only: true };
+ await nextTick();
+ expect(document.querySelector("#ssh-connection-sudo_command")).toBeNull();
+
+ state.values = { sudo_source: "none", read_only: false };
+ await nextTick();
+ expect(document.querySelector("#ssh-connection-sudo_command")).toBeNull();
+ });
+
it("offers local SSH keys on private_key_path fields and fills the chosen path", async () => {
const withKey: PluginConnectionProviderContribution = {
type: "connection-provider",
diff --git a/apps/desktop/src/components/plugins/PluginConnectionFields.vue b/apps/desktop/src/components/plugins/PluginConnectionFields.vue
index 37913d5a62..b7d22d3a55 100644
--- a/apps/desktop/src/components/plugins/PluginConnectionFields.vue
+++ b/apps/desktop/src/components/plugins/PluginConnectionFields.vue
@@ -1,14 +1,19 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
+import { FolderOpen } from "@lucide/vue";
import { Input } from "@/components/ui/input";
import PasswordInput from "@/components/ui/PasswordInput.vue";
import PasswordTextarea from "@/components/ui/PasswordTextarea.vue";
+import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
+import { useToast } from "@/composables/useToast";
import { pluginFieldIsRequired, pluginFieldIsVisible, type PluginFieldResolver } from "@/lib/plugins/pluginFieldConditions";
+import { pickPluginFieldFile } from "@/lib/plugins/pluginFieldPicker";
import { invokePlugin, listLocalSshKeys } from "@/lib/backend/api";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import type { LocalSshKey, PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldOption, PluginFormFieldValue } from "@/types/database";
const props = defineProps<{
@@ -24,12 +29,13 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
+const { toast } = useToast();
const formValues = computed(() => props.modelValue);
/** Value of any sibling field by key (condition evaluation reads current form values). */
function readFieldValue(key: string): PluginFormFieldValue {
const field = props.contribution.fields.find((candidate) => candidate.key === key);
- return field ? (formValues.value[key] ?? field.default) : undefined;
+ return field ? (formValues.value[key] ?? field.default ?? undefined) : undefined;
}
const resolveSiblingField: PluginFieldResolver = (key) => props.contribution.fields.find((candidate) => candidate.key === key);
function fieldVisible(field: PluginFormField): boolean {
@@ -43,7 +49,18 @@ const visibleFields = computed(() => props.contribution.fields.filter((field) =>
const isConnectionDialogLayout = computed(() => props.layout === "connection-dialog");
function fieldValue(field: PluginFormField): PluginFormFieldValue {
- return formValues.value[field.key] ?? field.default ?? defaultValueFor(field);
+ // `null` is "unset": hosts used to hydrate untouched fields with a null
+ // default, and a null reaching an input must not look like a stored value.
+ const raw = formValues.value[field.key];
+ const value = raw ?? field.default ?? defaultValueFor(field);
+ return value === null ? undefined : value;
+}
+
+/** Text/number inputs render any primitive as text; `null` stays empty. */
+function fieldInputValue(field: PluginFormField): string | number {
+ const value = fieldValue(field);
+ if (typeof value === "boolean") return String(value);
+ return value ?? "";
}
function updateField(field: PluginFormField, value: PluginFormFieldValue) {
@@ -174,7 +191,74 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
const selected = localSshKeys.value.find((key) => key.path === select.value);
select.value = "";
if (!selected) return;
- updateField(field, selected.path);
+ pickPluginFieldPath(field, selected.path);
+}
+
+// ---------------------------------------------------------------------------
+// Manifest-declared local file action (`picker`, Host API 1.1)
+// ---------------------------------------------------------------------------
+
+/** Fields whose picker acts on the working copy; the plugin reads the file. */
+function pickerField(field: PluginFormField) {
+ return field.picker;
+}
+
+/**
+ * Browser hosts cannot hand a path to the plugin, so the picker uploads the
+ * file content into the declared `content_field` instead. A picker without a
+ * `content_field` is desktop-only and stays hidden in the browser.
+ */
+function pickerVisible(field: PluginFormField): boolean {
+ const picker = pickerField(field);
+ if (!picker) return false;
+ if (isTauriRuntime()) return true;
+ return picker.kind === "file" && Boolean(picker.content_field);
+}
+
+const pickerBusyField = ref<string | null>(null);
+
+function pickerLabelKey(field: PluginFormField): string {
+ const picker = pickerField(field);
+ if (picker?.kind === "directory") return isTauriRuntime() ? "connection.pluginFieldSelectDirectory" : "connection.pluginFieldSelectFile";
+ return isTauriRuntime() ? "connection.pluginFieldSelectFile" : "connection.pluginFieldUploadFile";
+}
+
+/** Path selection (desktop) and the SSH key dropdown share this entry point. */
+function pickPluginFieldPath(field: PluginFormField, path: string) {
+ const picker = pickerField(field);
+ const next = { ...formValues.value, [field.key]: path };
+ // The plugin treats content as more specific than a path, so selecting a path
+ // must clear the uploaded copy — otherwise a stale upload keeps winning.
+ if (picker?.content_field) delete next[picker.content_field];
+ emit("update:modelValue", next);
+}
+
+/** Upload content into the paired field and clear the (meaningless) path. */
+function pickPluginFieldContent(field: PluginFormField, contentKey: string, content: string) {
+ const next = { ...formValues.value, [contentKey]: content };
+ delete next[field.key];
+ emit("update:modelValue", next);
+}
+
+async function runPluginFieldPicker(field: PluginFormField) {
+ const picker = pickerField(field);
+ if (!picker || pickerBusyField.value) return;
+ pickerBusyField.value = field.key;
+ try {
+ const picked = await pickPluginFieldFile(picker);
+ if (!picked) return;
+ if (picked.path !== undefined) {
+ pickPluginFieldPath(field, picked.path);
+ return;
+ }
+ if (picked.content !== undefined && picker.content_field) {
+ pickPluginFieldContent(field, picker.content_field, picked.content);
+ }
+ } catch (error) {
+ toast(error instanceof Error ? error.message : String(error));
+ } finally {
+ pickerBusyField.value = null;
+ }
}
</script>
@@ -207,7 +291,7 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
</SelectContent>
</Select>
<div v-else-if="isLocalSshKeyField(field)" class="flex items-center gap-1.5">
- <Input :id="fieldId(field)" type="text" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" class="min-w-0 flex-1" @update:model-value="updateTextField(field, $event)" />
+ <Input :id="fieldId(field)" type="text" :model-value="fieldInputValue(field)" :placeholder="field.placeholder" class="min-w-0 flex-1" @update:model-value="updateTextField(field, $event)" />
<select
class="h-9 w-40 shrink-0 rounded-md border border-input bg-transparent px-2 text-xs outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="localSshKeys.length === 0"
@@ -219,7 +303,7 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
<option v-for="key in localSshKeys" :key="key.path" :value="key.path" :title="key.path">{{ localSshKeyLabel(key) }}</option>
</select>
</div>
- <Input v-else :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" />
+ <Input v-else :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldInputValue(field)" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" />
</template>
<PasswordInput v-else-if="field.type === 'password'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
<PasswordTextarea v-else-if="field.type === 'textarea' && field.binding === 'secret'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
@@ -244,6 +328,12 @@ function applyLocalSshKey(field: PluginFormField, event: Event) {
<div v-else-if="field.type === 'boolean'" class="flex h-9 items-center">
<Switch :id="fieldId(field)" :model-value="Boolean(fieldValue(field))" size="sm" @update:model-value="updateBooleanField(field, $event)" />
</div>
+ <div v-if="pickerVisible(field)" class="flex items-center gap-2">
+ <Button :id="`${fieldId(field)}-picker`" variant="outline" size="sm" class="h-8 gap-1.5 text-xs" :disabled="pickerBusyField === field.key" @click="runPluginFieldPicker(field)">
+ <FolderOpen class="size-3.5" aria-hidden="true" />
+ {{ t(pickerLabelKey(field)) }}
+ </Button>
+ </div>
<div v-if="field.description" class="text-[11px] leading-5 text-muted-foreground">{{ field.description }}</div>
</div>
</div>
diff --git a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
index 5e93330ab3..341246a3aa 100644
--- a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
+++ b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { ref, computed, onMounted, onBeforeUnmount } from "vue";
+import { ref, computed, watch, onMounted, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n";
import { invoke } from "@tauri-apps/api/core";
import { TriangleAlert } from "@lucide/vue";
@@ -12,7 +12,7 @@ import { apiUrl } from "@/lib/common/webPath";
interface SshPromptRequest {
id: string;
- kind: "HostKeyVerify" | "HostKeyChanged" | "SecretInput" | "WorkerUploadConsent";
+ kind: "HostKeyVerify" | "HostKeyChanged" | "SecretInput" | "WorkerUploadConsent" | "UserInput";
host: string;
port: number;
key_type?: string | null;
@@ -20,6 +20,14 @@ interface SshPromptRequest {
previous_fingerprint?: string | null;
prompt?: string | null;
echo?: boolean;
+ /** UserInput: who asked (plugin display name). */
+ source?: string | null;
+ /** UserInput: caller-provided heading, already localized by the caller. */
+ title?: string | null;
+ /** UserInput: preset answer offered in the input. */
+ default_value?: string | null;
+ /** UserInput: fixed answers; empty means free-form input. */
+ options?: Array<{ value: string; label: string }> | null;
}
interface SshHostKeyNotice {
@@ -39,20 +47,39 @@ const { toast } = useToast();
const queue = ref<SshPromptRequest[]>([]);
const current = computed<SshPromptRequest | null>(() => queue.value[0] ?? null);
const isSecretPrompt = computed(() => current.value?.kind === "SecretInput");
+const isPluginInputPrompt = computed(() => current.value?.kind === "UserInput");
+const isTextPrompt = computed(() => isSecretPrompt.value || isPluginInputPrompt.value);
const isWorkerUploadPrompt = computed(() => current.value?.kind === "WorkerUploadConsent");
const isHostKeyChanged = computed(() => current.value?.kind === "HostKeyChanged");
+const promptOptions = computed(() => current.value?.options ?? []);
const titleKey = computed(() => {
if (isSecretPrompt.value) return "connection.sshInteractiveTitle";
+ if (isPluginInputPrompt.value) return "connection.sshPluginInputTitle";
if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentTitle";
if (isHostKeyChanged.value) return "connection.sshHostKeyChangedTitle";
return "connection.sshHostKeyVerifyTitle";
});
const messageKey = computed(() => {
if (isSecretPrompt.value) return "connection.sshInteractiveMessage";
+ if (isPluginInputPrompt.value) return "connection.sshPluginInputMessage";
if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentMessage";
if (isHostKeyChanged.value) return "connection.sshHostKeyChangedMessage";
return "connection.sshHostKeyVerifyMessage";
});
+/**
+ * A plugin's question carries its own heading and body, so the dialog shows
+ * what was asked instead of the host's SSH wording. The origin line names the
+ * plugin so a bastion MFA prompt is never mistaken for a host-owned one.
+ */
+const dialogTitle = computed(() => current.value?.title?.trim() || t(titleKey.value));
+const dialogDescription = computed(() => {
+ if (isPluginInputPrompt.value) {
+ const source = current.value?.source?.trim();
+ return source ? t("connection.sshPluginInputMessage", { source }) : t("connection.sshPluginInputMessageNoSource");
+ }
+ return t(messageKey.value, { host: current.value?.host ?? "", port: current.value?.port ?? "" });
+});
+const promptBody = computed(() => (isPluginInputPrompt.value ? current.value?.prompt?.trim() || t("connection.sshInteractiveDefaultPrompt") : ""));
const visible = ref(false);
const remember = ref(true);
@@ -236,7 +263,9 @@ function dismissPrompt(id: string) {
function resetPromptState() {
remember.value = true;
- secretCode.value = "";
+ // A caller may suggest an answer (e.g. a remembered bastion account); the
+ // user still has to submit it.
+ secretCode.value = current.value?.kind === "UserInput" ? (current.value?.default_value ?? "") : "";
}
function fingerprintBody(value: string | null | undefined): string {
@@ -264,6 +293,19 @@ function reject() {
function submitSecret() {
void resolve("secret");
}
+
+/** A fixed-choice plugin prompt is answered by picking an option. */
+function submitOption(value: string) {
+ secretCode.value = value;
+ void resolve("secret");
+}
+
+// Every prompt gets a clean slate (and its own preset answer) when it reaches
+// the front of the queue.
+watch(
+ () => current.value?.id,
+ () => resetPromptState(),
+);
</script>
<template>
@@ -279,9 +321,9 @@ function submitSecret() {
100). -->
<DialogContent class="flex max-h-[min(36rem,calc(var(--dbx-viewport-height)-2rem))] w-full max-w-[32rem] flex-col gap-4 overflow-hidden" overlay-class="z-[200]" portal-class="z-[200]" :show-close-button="false" @interact-outside.prevent @escape-key-down.prevent>
<DialogHeader class="shrink-0">
- <DialogTitle>{{ t(titleKey) }}</DialogTitle>
+ <DialogTitle>{{ dialogTitle }}</DialogTitle>
<DialogDescription class="text-muted-foreground">
- {{ t(messageKey, { host: current?.host ?? "", port: current?.port ?? "" }) }}
+ {{ dialogDescription }}
</DialogDescription>
</DialogHeader>
@@ -323,6 +365,24 @@ function submitSecret() {
<span>{{ current.kind === "WorkerUploadConsent" ? t("connection.sshWorkerUploadConsentRemember") : t("connection.sshHostKeyVerifyRemember") }}</span>
</label>
+ <div v-else-if="isPluginInputPrompt" class="space-y-3">
+ <p class="whitespace-pre-wrap text-sm text-muted-foreground">{{ promptBody }}</p>
+ <div v-if="promptOptions.length" class="flex flex-col gap-2">
+ <Button v-for="option in promptOptions" :key="option.value" variant="outline" class="h-auto w-full justify-start py-2 text-left whitespace-normal" :disabled="resolving" @click="submitOption(option.value)">
+ {{ option.label }}
+ </Button>
+ </div>
+ <input
+ v-else
+ v-model="secretCode"
+ :type="current.echo ? 'text' : 'password'"
+ autocomplete="one-time-code"
+ class="w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-sm outline-none focus:ring-2 focus:ring-ring"
+ :placeholder="t('connection.sshInteractivePlaceholder')"
+ @keydown.enter="submitSecret"
+ />
+ </div>
+
<div v-else-if="current.kind === 'SecretInput'" class="space-y-2">
<p class="whitespace-pre-wrap text-sm text-muted-foreground">
{{ current.prompt || t("connection.sshInteractiveDefaultPrompt") }}
@@ -340,7 +400,7 @@ function submitSecret() {
<DialogFooter class="shrink-0">
<Button variant="outline" :disabled="resolving" @click="reject">
- {{ t(isSecretPrompt ? "connection.sshInteractiveCancel" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentReject" : isHostKeyChanged ? "connection.sshHostKeyChangedClose" : "connection.sshHostKeyVerifyReject") }}
+ {{ t(isTextPrompt ? "connection.sshInteractiveCancel" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentReject" : isHostKeyChanged ? "connection.sshHostKeyChangedClose" : "connection.sshHostKeyVerifyReject") }}
</Button>
<template v-if="isHostKeyChanged">
<Button variant="outline" :disabled="resolving" @click="acceptSessionOnly">
@@ -350,11 +410,13 @@ function submitSecret() {
{{ t("connection.sshHostKeyChangedUpdate") }}
</Button>
</template>
- <Button v-else-if="current?.kind !== 'SecretInput'" :disabled="resolving" @click="accept">
- {{ t(isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentAccept" : "connection.sshHostKeyVerifyAccept") }}
+ <!-- A fixed-choice plugin prompt is answered by the option buttons in
+ the body, so it needs no submit button here. -->
+ <Button v-else-if="isTextPrompt && !(isPluginInputPrompt && promptOptions.length)" :disabled="resolving || !secretCode" @click="submitSecret">
+ {{ t(isSecretPrompt ? "connection.sshInteractiveSubmit" : "connection.sshPluginInputSubmit") }}
</Button>
- <Button v-else :disabled="resolving || !secretCode" @click="submitSecret">
- {{ t("connection.sshInteractiveSubmit") }}
+ <Button v-else-if="!isTextPrompt" :disabled="resolving" @click="accept">
+ {{ t(isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentAccept" : "connection.sshHostKeyVerifyAccept") }}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
index 8913639228..89f713a863 100644
--- a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
+++ b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
@@ -432,4 +432,122 @@ describe("SshHostKeyPromptDialog web bridge", () => {
});
});
});
+
+ it("relays a plugin question and submits the typed answer", async () => {
+ // Host API `host/requestUserInput`: a plugin backend (e.g. the SSH plugin
+ // answering a bastion's keyboard-interactive MFA) asks through the same
+ // dialog, and the host only carries the question and the typed value.
+ await mountDialog();
+
+ const eventSource = MockEventSource.instances[0];
+ eventSource?.emit({
+ type: "prompt",
+ request: {
+ id: "plugin-input-1",
+ kind: "UserInput",
+ host: "",
+ port: 0,
+ prompt: "Verification code (6 digits)",
+ title: "JumpServer login",
+ source: "SSH Terminal",
+ echo: false,
+ default_value: "12",
+ },
+ });
+ await nextTick();
+
+ expect(document.body.textContent).toContain("JumpServer login");
+ expect(document.body.textContent).toContain("SSH Terminal needs input before it can continue.");
+ expect(document.body.textContent).toContain("Verification code (6 digits)");
+
+ const input = document.body.querySelector<HTMLInputElement>("input");
+ expect(input?.type).toBe("password");
+ // A caller-provided default is offered but still has to be submitted.
+ expect(input?.value).toBe("12");
+ if (!input) throw new Error("plugin prompt input was not rendered");
+ input.value = "654321";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+
+ const buttons = [...document.body.querySelectorAll<HTMLButtonElement>("button")];
+ expect(buttons.map((button) => button.textContent?.trim())).toEqual(["Cancel", "Submit"]);
+ buttons[buttons.length - 1].click();
+
+ await vi.waitFor(() => {
+ expect(resolveSshPromptMock).toHaveBeenCalledWith({
+ id: "plugin-input-1",
+ action: "secret",
+ remember: undefined,
+ secret: "654321",
+ });
+ });
+ });
+
+ it("answers a fixed-choice plugin question by picking an option", async () => {
+ await mountDialog();
+
+ const eventSource = MockEventSource.instances[0];
+ eventSource?.emit({
+ type: "prompt",
+ request: {
+ id: "plugin-choice-1",
+ kind: "UserInput",
+ host: "",
+ port: 0,
+ title: "Select account",
+ prompt: "Which bastion account should be used?",
+ source: "LDAP Directory",
+ options: [
+ { value: "jinpy", label: "jinpy (admin)" },
+ { value: "deploy", label: "deploy (read-only)" },
+ ],
+ },
+ });
+ await nextTick();
+
+ expect(document.body.textContent).toContain("Which bastion account should be used?");
+ const buttons = [...document.body.querySelectorAll<HTMLButtonElement>("button")];
+ // Options replace the free-form input, so only the choices plus Cancel show.
+ expect(buttons.map((button) => button.textContent?.trim())).toEqual(["jinpy (admin)", "deploy (read-only)", "Cancel"]);
+ expect(document.body.querySelector("input")).toBeNull();
+
+ buttons.find((button) => button.textContent?.trim() === "deploy (read-only)")?.click();
+ await vi.waitFor(() => {
+ expect(resolveSshPromptMock).toHaveBeenCalledWith({
+ id: "plugin-choice-1",
+ action: "secret",
+ remember: undefined,
+ secret: "deploy",
+ });
+ });
+ });
+
+ it("cancels a plugin question without answering it", async () => {
+ await mountDialog();
+
+ const eventSource = MockEventSource.instances[0];
+ eventSource?.emit({
+ type: "prompt",
+ request: {
+ id: "plugin-input-cancel",
+ kind: "UserInput",
+ host: "",
+ port: 0,
+ prompt: "Verification code",
+ source: "SSH Terminal",
+ },
+ });
+ await nextTick();
+
+ const cancel = [...document.body.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Cancel");
+ cancel?.click();
+ await vi.waitFor(() => {
+ expect(resolveSshPromptMock).toHaveBeenCalledWith({
+ id: "plugin-input-cancel",
+ action: "reject",
+ remember: undefined,
+ secret: undefined,
+ });
+ });
+ });
});
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 6be484542f..f34ce4b8e1 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -1183,6 +1183,13 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Yoxlama kodunu daxil edin",
sshInteractiveSubmit: "Yoxla",
sshInteractiveCancel: "Ləğv et",
+ pluginFieldSelectFile: "Fayl seç…",
+ pluginFieldUploadFile: "Fayl yüklə…",
+ pluginFieldSelectDirectory: "Qovluq seç…",
+ sshPluginInputTitle: "Giriş tələb olunur",
+ sshPluginInputMessage: "Davam etmək üçün {source} giriş tələb edir.",
+ sshPluginInputMessageNoSource: "Davam etmək üçün plagin giriş tələb edir.",
+ sshPluginInputSubmit: "Göndər",
sshHostKeyNoticeChanged: "{host}:{port} üçün host açarı dəyişib — bu, araya girən tərəfin hücumuna işarə edə bilər. Yalnız bu dəyişikliyi gözləyirsinizsə, köhnə qeydi silin və yenidən əlaqə qurun.",
sshHostKeyNoticeRejected: "{host}:{port} üçün host açarını rədd etdiniz; əlaqə dayandırıldı və kimlik məlumatları göndərilmədi.",
sshHostKeyNoticeLearnFailed: "{host}:{port} üçün host açarını yadda saxlamaq mümkün olmadı — hosta yalnız bu sessiya üçün etibar edilir və növbəti dəfə onu yenidən yoxlamağınız istəniləcək.",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 2a94e32afc..a72b7ff181 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1146,6 +1146,9 @@ export default {
pluginProviderUnavailable: "This plugin connection provider is unavailable. Reinstall or enable the plugin, then try again.",
pluginRequiredField: "{field} is required",
pluginSshKeyPickerPlaceholder: "Pick local SSH key…",
+ pluginFieldSelectFile: "Choose file…",
+ pluginFieldUploadFile: "Upload file…",
+ pluginFieldSelectDirectory: "Choose folder…",
pluginSshKeyPickerEmpty: "No local SSH keys found",
pluginSshKeyEncrypted: "encrypted",
jdbcConnection: "JDBC connection",
@@ -1328,6 +1331,10 @@ export default {
sshInteractivePlaceholder: "Enter verification code",
sshInteractiveSubmit: "Verify",
sshInteractiveCancel: "Cancel",
+ sshPluginInputTitle: "Input Required",
+ sshPluginInputMessage: "{source} needs input before it can continue.",
+ sshPluginInputMessageNoSource: "A plugin needs input before it can continue.",
+ sshPluginInputSubmit: "Submit",
sshHostKeyNoticeChanged: "Host key for {host}:{port} changed — this may indicate a man-in-the-middle attack. Remove the old entry and reconnect only if you expect this change.",
sshHostKeyNoticeRejected: "You rejected the host key for {host}:{port}; the connection was aborted and no credentials were sent.",
sshHostKeyNoticeLearnFailed: "Could not save the host key for {host}:{port} — the host is trusted for this session only and you will be asked to verify it again next time.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index d7b1b38513..fd791f3f2c 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1298,6 +1298,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Introducir código de verificación",
sshInteractiveSubmit: "Verificar",
sshInteractiveCancel: "Cancelar",
+ sshPluginInputTitle: "Se requiere entrada",
+ sshPluginInputMessage: "{source} necesita una entrada para continuar.",
+ sshPluginInputMessageNoSource: "Un complemento necesita una entrada para continuar.",
+ sshPluginInputSubmit: "Enviar",
sshHostKeyNoticeChanged: "La clave del host {host}:{port} ha cambiado, puede haber un ataque de intermediario. Si es esperado, elimine el registro antiguo y vuelva a conectar.",
sshHostKeyNoticeRejected: "Ha rechazado la verificación de la clave del host {host}:{port}. La conexión se ha abortado, no se enviaron credenciales.",
sshHostKeyNoticeGeneric: "Falló la verificación de la clave del host SSH {host}:{port}.",
@@ -1416,6 +1420,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "Muestra las tablas integradas de control de versiones de Dolt en la lista de tablas de la conexión actual.",
clientCertHint: "Cuando se requiere mTLS, el certificado de cliente y la clave privada deben completarse juntos.",
pluginSshKeyPickerPlaceholder: "Seleccionar clave SSH local…",
+ pluginFieldSelectFile: "Elegir archivo…",
+ pluginFieldUploadFile: "Subir archivo…",
+ pluginFieldSelectDirectory: "Elegir carpeta…",
pluginSshKeyPickerEmpty: "No se encontraron claves",
pluginSshKeyEncrypted: "Cifrado",
objectCacheRefreshFailed: "Error al actualizar la caché de objetos: {message}",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 2e1ac4bb12..5448877195 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1296,6 +1296,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Inserisci il codice di verifica",
sshInteractiveSubmit: "Verifica",
sshInteractiveCancel: "Annulla",
+ sshPluginInputTitle: "Input richiesto",
+ sshPluginInputMessage: "{source} richiede un input per continuare.",
+ sshPluginInputMessageNoSource: "Un plugin richiede un input per continuare.",
+ sshPluginInputSubmit: "Invia",
sshHostKeyNoticeChanged: "La chiave dell'host {host}:{port} è cambiata, potrebbe esserci un attacco man-in-the-middle. Se il cambiamento è previsto, elimina il vecchio record e riconnettiti.",
sshHostKeyNoticeRejected: "Hai rifiutato la verifica della chiave host di {host}:{port}, la connessione è stata interrotta e le credenziali non sono state inviate.",
sshHostKeyNoticeGeneric: "Verifica della chiave host SSH {host}:{port} fallita.",
@@ -1414,6 +1418,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "Mostra le tabelle di controllo versione integrate di Dolt nell'elenco delle tabelle della connessione corrente.",
clientCertHint: "Quando è richiesto mTLS, il certificato client e la chiave privata devono essere inseriti insieme.",
pluginSshKeyPickerPlaceholder: "Seleziona chiave SSH locale…",
+ pluginFieldSelectFile: "Scegli file…",
+ pluginFieldUploadFile: "Carica file…",
+ pluginFieldSelectDirectory: "Scegli cartella…",
pluginSshKeyPickerEmpty: "Nessuna chiave trovata",
pluginSshKeyEncrypted: "Crittografata",
objectCacheRefreshFailed: "Aggiornamento della cache degli oggetti non riuscito: {message}",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 7355981ad4..20eaeca787 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1296,6 +1296,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "検証コードを入力",
sshInteractiveSubmit: "検証",
sshInteractiveCancel: "キャンセル",
+ sshPluginInputTitle: "入力が必要です",
+ sshPluginInputMessage: "続行するには {source} への入力が必要です。",
+ sshPluginInputMessageNoSource: "続行するにはプラグインへの入力が必要です。",
+ sshPluginInputSubmit: "送信",
sshHostKeyNoticeChanged: "ホスト {host}:{port} のキーが変更されました。中間者攻撃の可能性があります。予期された変更である場合は、古いレコードを削除して再接続してください。",
sshHostKeyNoticeRejected: "ホスト {host}:{port} のホストキー検証を拒否しました。接続は中止され、資格情報は送信されませんでした。",
sshHostKeyNoticeGeneric: "SSHホスト {host}:{port} のキー検証に失敗しました。",
@@ -1435,6 +1439,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "現在の接続のテーブルリストに Dolt 組み込みのバージョン管理テーブルを表示します。",
clientCertHint: "mTLS が要求される場合、クライアント証明書と秘密鍵は一緒に入力する必要があります。",
pluginSshKeyPickerPlaceholder: "ローカルの SSH キーを選択…",
+ pluginFieldSelectFile: "ファイルを選択…",
+ pluginFieldUploadFile: "ファイルをアップロード…",
+ pluginFieldSelectDirectory: "フォルダーを選択…",
pluginSshKeyPickerEmpty: "キーが見つかりません",
pluginSshKeyEncrypted: "暗号化済み",
objectCacheRefreshFailed: "オブジェクトキャッシュの更新に失敗しました:{message}",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 009dc2935a..252a73229f 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1212,6 +1212,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "인증 코드 입력",
sshInteractiveSubmit: "인증",
sshInteractiveCancel: "취소",
+ sshPluginInputTitle: "입력 필요",
+ sshPluginInputMessage: "계속하려면 {source}에 입력해야 합니다.",
+ sshPluginInputMessageNoSource: "계속하려면 플러그인에 입력해야 합니다.",
+ sshPluginInputSubmit: "제출",
sshHostKeyNoticeChanged: "{host}:{port}의 호스트 키가 변경되었습니다 — 이는 중간자 공격을 나타낼 수 있습니다. 이 변경을 예상한 경우에만 이전 항목을 제거하고 다시 연결하세요.",
sshHostKeyNoticeRejected: "{host}:{port}의 호스트 키를 거부했습니다. 연결이 중단되고 자격 증명이 전송되지 않았습니다.",
sshHostKeyNoticeLearnFailed: "{host}:{port}의 호스트 키를 저장할 수 없습니다 — 이 호스트는 이 세션에만 신뢰되며 다음에 다시 확인을 요청받습니다.",
@@ -1333,6 +1337,9 @@ export default withEnglishFallback({
pluginProviderUnavailable: "이 플러그인 연결 제공자를 사용할 수 없습니다. 플러그인을 다시 설치하거나 활성화한 후 다시 시도하세요.",
pluginRequiredField: "{field}을(를) 입력하세요.",
pluginSshKeyPickerPlaceholder: "로컬 SSH 키 선택…",
+ pluginFieldSelectFile: "파일 선택…",
+ pluginFieldUploadFile: "파일 업로드…",
+ pluginFieldSelectDirectory: "폴더 선택…",
pluginSshKeyPickerEmpty: "키를 찾을 수 없음",
pluginSshKeyEncrypted: "암호화됨",
objectCacheRefreshFailed: "개체 캐시 새로 고침 실패: {message}",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index cec7134680..28c0592be3 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1297,6 +1297,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Digite o código de verificação",
sshInteractiveSubmit: "Verificar",
sshInteractiveCancel: "Cancelar",
+ sshPluginInputTitle: "Entrada necessária",
+ sshPluginInputMessage: "{source} precisa de uma entrada para continuar.",
+ sshPluginInputMessageNoSource: "Um plugin precisa de uma entrada para continuar.",
+ sshPluginInputSubmit: "Enviar",
sshHostKeyNoticeChanged: "A chave do host {host}:{port} foi alterada, pode haver um ataque man-in-the-middle. Se esta alteração era esperada, exclua o registro antigo e reconecte.",
sshHostKeyNoticeRejected: "Você rejeitou a verificação da chave do host {host}:{port}. A conexão foi abortada e as credenciais não foram enviadas.",
sshHostKeyNoticeGeneric: "Falha na verificação da chave do host SSH {host}:{port}.",
@@ -1415,6 +1419,9 @@ export default withEnglishFallback({
doltShowSystemTablesHint: "Exibir as tabelas de controle de versão internas do Dolt na lista de tabelas da conexão atual.",
clientCertHint: "Quando o mTLS for exigido, o certificado do cliente e a chave privada devem ser preenchidos juntos.",
pluginSshKeyPickerPlaceholder: "Selecionar chave SSH local…",
+ pluginFieldSelectFile: "Escolher arquivo…",
+ pluginFieldUploadFile: "Enviar arquivo…",
+ pluginFieldSelectDirectory: "Escolher pasta…",
pluginSshKeyPickerEmpty: "Nenhuma chave encontrada",
pluginSshKeyEncrypted: "Criptografada",
objectCacheRefreshFailed: "Falha ao atualizar o cache de objetos: {message}",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 7010ebfad3..d5ecf18038 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -1185,6 +1185,13 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "Doğrulama kodunu girin",
sshInteractiveSubmit: "Doğrula",
sshInteractiveCancel: "İptal",
+ pluginFieldSelectFile: "Dosya seç…",
+ pluginFieldUploadFile: "Dosya yükle…",
+ pluginFieldSelectDirectory: "Klasör seç…",
+ sshPluginInputTitle: "Girdi gerekli",
+ sshPluginInputMessage: "Devam etmek için {source} bir girdi bekliyor.",
+ sshPluginInputMessageNoSource: "Devam etmek için bir eklenti girdi bekliyor.",
+ sshPluginInputSubmit: "Gönder",
sshHostKeyNoticeChanged: "{host}:{port} için sunucu anahtarı değişti — bu, ortadaki adam saldırısına işaret edebilir. Yalnızca bu değişikliği bekliyorsanız eski kaydı silip yeniden bağlanın.",
sshHostKeyNoticeRejected: "{host}:{port} için sunucu anahtarını reddettiniz; bağlantı iptal edildi ve hiçbir kimlik bilgisi gönderilmedi.",
sshHostKeyNoticeLearnFailed: "{host}:{port} için sunucu anahtarı kaydedilemedi — sunucuya yalnızca bu oturum için güvenilecek ve bir sonraki seferde yeniden doğrulamanız istenecek.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f641d19d95..9ffe4fd19d 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1061,6 +1061,9 @@ export default withEnglishFallback({
pluginProviderUnavailable: "此插件连接提供者不可用,请重新安装或启用插件后再试。",
pluginRequiredField: "请填写{field}",
pluginSshKeyPickerPlaceholder: "选择本机 SSH 密钥…",
+ pluginFieldSelectFile: "选择文件…",
+ pluginFieldUploadFile: "上传文件…",
+ pluginFieldSelectDirectory: "选择文件夹…",
pluginSshKeyPickerEmpty: "未发现密钥",
pluginSshKeyEncrypted: "已加密",
jdbcConnection: "JDBC 连接",
@@ -1246,6 +1249,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "输入验证码",
sshInteractiveSubmit: "验证",
sshInteractiveCancel: "取消",
+ sshPluginInputTitle: "需要输入",
+ sshPluginInputMessage: "{source} 需要你提供输入才能继续。",
+ sshPluginInputMessageNoSource: "插件需要你提供输入才能继续。",
+ sshPluginInputSubmit: "提交",
sshHostKeyNoticeChanged: "主机 {host}:{port} 的密钥已变更,可能存在中间人攻击。如确属预期,请删除旧记录后重新连接。",
sshHostKeyNoticeRejected: "你已拒绝 {host}:{port} 的主机密钥验证,连接已中止,凭据未发送。",
sshHostKeyNoticeLearnFailed: "无法保存 {host}:{port} 的主机密钥 — 该主机仅在本次会话内受信任,下次连接仍需重新确认。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 5f14b2549c..cb1261844c 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -946,6 +946,9 @@ export default withEnglishFallback({
pluginProviderUnavailable: "此外掛連線提供者不可用,請重新安裝或啟用外掛後再試。",
pluginRequiredField: "請填寫{field}",
pluginSshKeyPickerPlaceholder: "選擇本機 SSH 金鑰…",
+ pluginFieldSelectFile: "選擇檔案…",
+ pluginFieldUploadFile: "上傳檔案…",
+ pluginFieldSelectDirectory: "選擇資料夾…",
pluginSshKeyPickerEmpty: "未發現金鑰",
pluginSshKeyEncrypted: "已加密",
jdbcConnection: "JDBC 連線",
@@ -1302,6 +1305,10 @@ export default withEnglishFallback({
sshInteractivePlaceholder: "輸入驗證碼",
sshInteractiveSubmit: "驗證",
sshInteractiveCancel: "取消",
+ sshPluginInputTitle: "需要輸入",
+ sshPluginInputMessage: "{source} 需要你提供輸入才能繼續。",
+ sshPluginInputMessageNoSource: "外掛需要你提供輸入才能繼續。",
+ sshPluginInputSubmit: "提交",
sshHostKeyNoticeChanged: "主機 {host}:{port} 的金鑰已變更,可能存在中間人攻擊。如確屬預期,請刪除舊記錄後重新連線。",
sshHostKeyNoticeRejected: "您已拒絕 {host}:{port} 的主機金鑰驗證,連線已中止,憑證未發送。",
sshHostKeyNoticeGeneric: "SSH 主機 {host}:{port} 的金鑰驗證失敗。",
diff --git a/apps/desktop/src/lib/connection/connectionPassword.ts b/apps/desktop/src/lib/connection/connectionPassword.ts
index 9f62012e72..9296c72826 100644
--- a/apps/desktop/src/lib/connection/connectionPassword.ts
+++ b/apps/desktop/src/lib/connection/connectionPassword.ts
@@ -46,7 +46,7 @@ export function pluginConnectionNeedsPasswordPrompt(fields: readonly PluginFormF
if (!passwordFields.length) return false;
const readValue = (key: string): PluginFormFieldValue => {
const stored = isRecord(externalConfig) ? (externalConfig[key] as PluginFormFieldValue) : undefined;
- return stored !== undefined ? stored : fields.find((candidate) => candidate.key === key)?.default;
+ return stored !== undefined ? stored : (fields.find((candidate) => candidate.key === key)?.default ?? undefined);
};
return passwordFields.some((field) => pluginFieldIsRequired(field, readValue));
}
diff --git a/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts b/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts
index 65ccc5c8a6..dea3dd11b5 100644
--- a/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts
+++ b/apps/desktop/src/lib/plugins/frontendPlugin.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import type { InstalledPlugin, PluginConnectionProviderContribution } from "@/types/database";
+import type { InstalledPlugin, PluginConnectionProviderContribution, PluginFormFieldValue } from "@/types/database";
import { buildPluginConnectionConfig, createFrontendPluginRegistry, initialPluginFormValues, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "./frontendPlugin";
function installedPlugin(id: string, contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin {
@@ -324,6 +324,91 @@ describe("FrontendPluginRegistry", () => {
expect(values).not.toHaveProperty("host");
});
+ it("treats a host-serialized null default as unset instead of a value", () => {
+ // Hosts before the manifest serialization fix sent `"default": null` for
+ // every field that declares no default, so an untouched password field
+ // turned into the four-character string "null" once it was saved.
+ const provider = connectionProvider({
+ fields: [
+ { key: "sudo_password", label: "Sudo password", type: "password", binding: "secret", default: null },
+ { key: "mode", label: "Mode", type: "text", binding: "config", default: null },
+ { key: "read_only", label: "Read only", type: "boolean", binding: "config", default: false },
+ ],
+ });
+
+ expect(initialPluginFormValues(provider)).toEqual({ read_only: false });
+
+ const config = buildPluginConnectionConfig("io.dbx.ssh", provider, {
+ sudo_password: null,
+ mode: null,
+ read_only: false,
+ } as unknown as Record<string, string>);
+
+ expect(config.connection_secrets?.sudo_password).toBeUndefined();
+ expect(config.external_config).toEqual({ read_only: false });
+ });
+
+ it("preserves opaque 'null' credentials when reopening and saving connections", () => {
+ const provider = connectionProvider({
+ fields: [
+ { key: "sudo_password", label: "Sudo password", type: "password", binding: "secret" },
+ { key: "totp_secret", label: "TOTP secret", type: "textarea", binding: "secret" },
+ { key: "sudo_source", label: "Sudo source", type: "text", binding: "config" },
+ ],
+ });
+ const existing = buildPluginConnectionConfig("io.dbx.ssh", provider, {});
+ existing.connection_secrets = { sudo_password: "null", totp_secret: "JBSWY3DPEHPK3PXP" };
+ existing.external_config = { sudo_source: "custom", stale: null };
+
+ const values = pluginConnectionFormValues(provider, existing);
+
+ expect(values.sudo_password).toBe("null");
+ expect(values.totp_secret).toBe("JBSWY3DPEHPK3PXP");
+ expect(values.stale).toBeUndefined();
+ expect(values.sudo_source).toBe("custom");
+
+ const saved = buildPluginConnectionConfig("io.dbx.ssh", provider, values, existing);
+ expect(saved.connection_secrets?.sudo_password).toBe("null");
+ expect(saved.connection_secrets?.totp_secret).toBe("JBSWY3DPEHPK3PXP");
+ });
+
+ it.each([undefined, "secret", "password"] as const)("round-trips explicit 'null' credentials with binding %s", (binding) => {
+ const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password", binding }] });
+ const saved = buildPluginConnectionConfig("example.plugin", provider, { credential: "null" });
+ expect(binding === "password" ? saved.password : saved.connection_secrets?.credential).toBe("null");
+ expect(pluginConnectionFormValues(provider, saved)).toEqual({ credential: "null" });
+ const reopened = buildPluginConnectionConfig("example.plugin", provider, pluginConnectionFormValues(provider, saved), saved);
+ expect(pluginConnectionFormValues(provider, reopened)).toEqual({ credential: "null" });
+ });
+
+ it("migrates an opaque 'null' credential from config to secret storage without losing it", () => {
+ const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password" }] });
+ const existing = buildPluginConnectionConfig("example.plugin", provider, {});
+ existing.external_config = { credential: "null" };
+ const values = pluginConnectionFormValues(provider, existing);
+ expect(values).toEqual({ credential: "null" });
+ const saved = buildPluginConnectionConfig("example.plugin", provider, values, existing);
+ expect(saved.connection_secrets).toEqual({ credential: "null" });
+ expect(saved.external_config).toEqual({});
+ });
+
+ it.each([null, undefined, ""])("keeps an unset credential %s absent without a default", (credential) => {
+ const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password" }] });
+ const existing = buildPluginConnectionConfig("example.plugin", provider, {});
+ existing.connection_secrets = { credential: "old-secret" };
+ const saved = buildPluginConnectionConfig("example.plugin", provider, { credential } as unknown as Record<string, PluginFormFieldValue>, existing);
+ expect(saved.connection_secrets).toEqual({});
+ expect(pluginConnectionFormValues(provider, saved)).toEqual({});
+ });
+
+ it("uses an explicit string default only for missing input, not a cleared input", () => {
+ const provider = connectionProvider({ fields: [{ key: "credential", label: "Credential", type: "password", default: "null" }] });
+ expect(initialPluginFormValues(provider)).toEqual({ credential: "null" });
+ expect(buildPluginConnectionConfig("example.plugin", provider, {}).connection_secrets).toEqual({ credential: "null" });
+ expect(buildPluginConnectionConfig("example.plugin", provider, { credential: null } as unknown as Record<string, PluginFormFieldValue>).connection_secrets).toEqual({});
+ expect(buildPluginConnectionConfig("example.plugin", provider, { credential: "" }).connection_secrets).toEqual({});
+ });
+
it("maps provider fields into common, config, and secret storage", () => {
const provider: PluginConnectionProviderContribution = {
type: "connection-provider",
diff --git a/apps/desktop/src/lib/plugins/frontendPlugin.ts b/apps/desktop/src/lib/plugins/frontendPlugin.ts
index c2d54f7dd6..774a9de625 100644
--- a/apps/desktop/src/lib/plugins/frontendPlugin.ts
+++ b/apps/desktop/src/lib/plugins/frontendPlugin.ts
@@ -115,7 +115,9 @@ export function pluginConnectionActionsForDialog(contribution: PluginConnectionP
}
export function initialPluginFormValues(contribution: PluginConnectionProviderContribution): Record<string, PluginFormFieldValue> {
- return Object.fromEntries(contribution.fields.filter((field) => field.default !== undefined).map((field) => [field.key, field.default])) as Record<string, PluginFormFieldValue>;
+ // `null` means "no default" (older hosts serialized the absent case that way),
+ // so it must not seed the form with a value the user never typed.
+ return Object.fromEntries(contribution.fields.filter((field) => field.default !== undefined && field.default !== null).map((field) => [field.key, field.default])) as Record<string, PluginFormFieldValue>;
}
export function pluginConnectionFormValues(contribution: PluginConnectionProviderContribution, config?: ConnectionConfig): Record<string, PluginFormFieldValue> {
@@ -125,22 +127,9 @@ export function pluginConnectionFormValues(contribution: PluginConnectionProvide
const secrets = config.connection_secrets || {};
for (const field of contribution.fields) {
const binding = effectiveFieldBinding(field);
+ const secret = secrets[field.key] ?? externalConfig[field.key];
const value =
- binding === "name"
- ? config.name
- : binding === "host"
- ? config.host
- : binding === "port"
- ? config.port
- : binding === "username"
- ? config.username
- : binding === "password"
- ? config.password
- : binding === "database"
- ? config.database
- : binding === "secret"
- ? (secrets[field.key] ?? externalConfig[field.key])
- : externalConfig[field.key];
+ binding === "name" ? config.name : binding === "host" ? config.host : binding === "port" ? config.port : binding === "username" ? config.username : binding === "password" ? config.password : binding === "database" ? config.database : binding === "secret" ? secret : externalConfig[field.key];
// Port 0 is the stored representation of an optional, automatic port.
// Keep that input empty on reopen so its protocol-default hint remains visible.
if (binding === "port" && value === 0 && field.default === undefined) delete values[field.key];
@@ -180,7 +169,11 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
production_databases: existing?.production_databases || [],
};
for (const field of contribution.fields) {
- const value = values[field.key] ?? field.default;
+ // A `null` coming from the form (or from a host that hydrated absent
+ // defaults as `null`) means "unset": fall back to the declared default and
+ // otherwise clear the stored value instead of persisting a null.
+ const raw = values[field.key];
+ const value = raw === null ? undefined : (raw ?? field.default ?? undefined);
const binding = effectiveFieldBinding(field);
if (binding === "config") {
if (value === undefined) delete externalConfig[field.key];
diff --git a/apps/desktop/src/lib/plugins/pluginFieldConditions.spec.ts b/apps/desktop/src/lib/plugins/pluginFieldConditions.spec.ts
index 85cf834e0e..be193f7130 100644
--- a/apps/desktop/src/lib/plugins/pluginFieldConditions.spec.ts
+++ b/apps/desktop/src/lib/plugins/pluginFieldConditions.spec.ts
@@ -1,22 +1,84 @@
import { describe, expect, it } from "vitest";
-import { pluginFieldConditionMatches, pluginFieldIsRequired, pluginFieldIsVisible } from "./pluginFieldConditions";
-import type { PluginFormField, PluginFormFieldValue } from "@/types/database";
+import { pluginConditionValueText, pluginFieldConditionMatches, pluginFieldConditionReferencedFields, pluginFieldIsRequired, pluginFieldIsVisible } from "./pluginFieldConditions";
+import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database";
function field(overrides: Partial<PluginFormField>): PluginFormField {
return { key: "demo", label: "Demo", type: "text", ...overrides } as PluginFormField;
}
-const readValue = (key: string) => (key === "mode" ? "custom" : undefined);
+const readValue = (key: string): PluginFormFieldValue => (key === "mode" ? "custom" : undefined);
+/** Reads a fixed map, so a condition can be evaluated against known values. */
+function reader(values: Record<string, PluginFormFieldValue>): (key: string) => PluginFormFieldValue {
+ return (key) => values[key];
+}
describe("pluginFieldConditionMatches", () => {
it("matches a missing condition and a listed value", () => {
- expect(pluginFieldConditionMatches(undefined, undefined)).toBe(true);
- expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "custom")).toBe(true);
+ expect(pluginFieldConditionMatches(undefined, () => undefined)).toBe(true);
+ expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({ mode: "custom" }))).toBe(true);
});
it("rejects an unlisted or empty value", () => {
- expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "direct")).toBe(false);
- expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, undefined)).toBe(false);
+ expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({ mode: "direct" }))).toBe(false);
+ expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({}))).toBe(false);
+ expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, reader({ mode: " " }))).toBe(false);
+ });
+
+ it("compares boolean and number literals by canonical string form", () => {
+ // `read_only = false` is the composite-condition driver the SSH plugin needs.
+ const readOnly = { field: "read_only", one_of: [false] } as PluginFieldCondition;
+ expect(pluginFieldConditionMatches(readOnly, reader({ read_only: false }))).toBe(true);
+ expect(pluginFieldConditionMatches(readOnly, reader({ read_only: true }))).toBe(false);
+ expect(pluginFieldConditionMatches({ field: "read_only", one_of: ["false"] }, reader({ read_only: false }))).toBe(true);
+ expect(pluginFieldConditionMatches({ field: "port", one_of: [2222] }, reader({ port: 2222 }))).toBe(true);
+ expect(pluginFieldConditionMatches({ field: "port", one_of: [2222.0] }, reader({ port: 2222 }))).toBe(true);
+ expect(pluginConditionValueText(false)).toBe("false");
+ expect(pluginConditionValueText(22)).toBe("22");
+ });
+
+ it("composes clauses with all_of, any_of and not", () => {
+ const allOf = {
+ all_of: [
+ { field: "sudo_source", one_of: ["custom"] },
+ { field: "read_only", one_of: [false] },
+ ],
+ } as PluginFieldCondition;
+ expect(pluginFieldConditionMatches(allOf, reader({ sudo_source: "custom", read_only: false }))).toBe(true);
+ expect(pluginFieldConditionMatches(allOf, reader({ sudo_source: "custom", read_only: true }))).toBe(false);
+ expect(pluginFieldConditionMatches(allOf, reader({ sudo_source: "default", read_only: false }))).toBe(false);
+
+ const anyOf = {
+ any_of: [
+ { field: "authentication", one_of: ["password"] },
+ { field: "authentication", one_of: ["keyboard-interactive"] },
+ ],
+ } as PluginFieldCondition;
+ expect(pluginFieldConditionMatches(anyOf, reader({ authentication: "keyboard-interactive" }))).toBe(true);
+ expect(pluginFieldConditionMatches(anyOf, reader({ authentication: "agent" }))).toBe(false);
+
+ const not = { not: { field: "read_only", one_of: [true] } } as PluginFieldCondition;
+ expect(pluginFieldConditionMatches(not, reader({ read_only: false }))).toBe(true);
+ expect(pluginFieldConditionMatches(not, reader({ read_only: true }))).toBe(false);
+
+ const nested = { all_of: [anyOf, not, { any_of: [{ all_of: [{ field: "read_only", one_of: [false] }] }] }] } as PluginFieldCondition;
+ expect(pluginFieldConditionMatches(nested, reader({ authentication: "password", read_only: false }))).toBe(true);
+ expect(pluginFieldConditionMatches(nested, reader({ authentication: "password", read_only: true }))).toBe(false);
+ });
+
+ it("lists every referenced field of a nested expression", () => {
+ expect(
+ pluginFieldConditionReferencedFields({
+ all_of: [
+ {
+ any_of: [
+ { field: "a", one_of: ["1"] },
+ { field: "b", one_of: ["1"] },
+ ],
+ },
+ { not: { field: "c", one_of: ["1"] } },
+ ],
+ }),
+ ).toEqual(["a", "b", "c"]);
});
});
@@ -35,6 +97,19 @@ describe("pluginFieldIsRequired", () => {
expect(pluginFieldIsRequired(conditional, () => "direct")).toBe(false);
expect(pluginFieldIsRequired(conditional, () => undefined)).toBe(false);
});
+
+ it("requires a field only while every clause of an all_of required_when matches", () => {
+ const conditional = field({
+ required_when: {
+ all_of: [
+ { field: "sudo_source", one_of: ["custom"] },
+ { field: "read_only", one_of: [false] },
+ ],
+ },
+ });
+ expect(pluginFieldIsRequired(conditional, reader({ sudo_source: "custom", read_only: false }))).toBe(true);
+ expect(pluginFieldIsRequired(conditional, reader({ sudo_source: "custom", read_only: true }))).toBe(false);
+ });
});
describe("pluginFieldIsVisible", () => {
@@ -45,6 +120,62 @@ describe("pluginFieldIsVisible", () => {
expect(pluginFieldIsVisible(conditional, () => "direct")).toBe(false);
});
+ it("renders a field only while every clause of an all_of visible_when matches", () => {
+ const conditional = field({
+ visible_when: {
+ all_of: [
+ { field: "sudo_source", one_of: ["custom"] },
+ { field: "read_only", one_of: [false] },
+ ],
+ },
+ });
+ expect(pluginFieldIsVisible(conditional, reader({ sudo_source: "custom", read_only: false }))).toBe(true);
+ expect(pluginFieldIsVisible(conditional, reader({ sudo_source: "custom", read_only: true }))).toBe(false);
+ expect(pluginFieldIsVisible(conditional, reader({ read_only: false }))).toBe(false);
+ });
+
+ it("keeps an unused any_of branch from hiding a matching field", () => {
+ // `visible_when.any_of` matches through the first clause; the second clause
+ // references a sibling that is itself hidden, and that must not matter.
+ const fields: Record<string, PluginFormField> = {
+ source: field({ key: "source", default: "custom" }),
+ hidden_controller: field({ key: "hidden_controller", default: "on", visible_when: { field: "source", one_of: ["remote"] } }),
+ target: field({
+ key: "target",
+ visible_when: {
+ any_of: [
+ { field: "source", one_of: ["custom"] },
+ { field: "hidden_controller", one_of: ["on"] },
+ ],
+ },
+ }),
+ };
+ const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default ?? undefined;
+ const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
+
+ expect(pluginFieldIsVisible(fields.target, read, resolve)).toBe(true);
+ // ...while a match that *depends* on the hidden controller stays dormant.
+ const onlyHidden = field({
+ key: "only_hidden",
+ visible_when: { any_of: [{ field: "hidden_controller", one_of: ["on"] }] },
+ });
+ expect(pluginFieldIsVisible(onlyHidden, read, resolve)).toBe(false);
+ });
+
+ it("treats a hidden operand of `not` as dormant instead of lighting the field up", () => {
+ const fields: Record<string, PluginFormField> = {
+ mode: field({ key: "mode", default: "remote" }),
+ read_only: field({ key: "read_only", default: false, visible_when: { field: "mode", one_of: ["local"] } }),
+ writable_options: field({ key: "writable_options", visible_when: { not: { field: "read_only", one_of: [true] } } }),
+ };
+ const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default ?? undefined;
+ const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
+
+ expect(pluginFieldIsVisible(fields.writable_options, read, resolve)).toBe(false);
+ const localRead = reader({ mode: "local", read_only: false });
+ expect(pluginFieldIsVisible(fields.writable_options, localRead, resolve)).toBe(true);
+ });
+
it("keeps a condition dormant while its referenced sibling is hidden, even when the sibling default would match", () => {
// kafka-shaped chain: sasl_mechanism (default PLAIN, hidden) →
// oauth_token_source (visible only for OAUTHBEARER, defaults msk_iam) →
@@ -56,16 +187,49 @@ describe("pluginFieldIsVisible", () => {
oauth_token_source: field({ key: "oauth_token_source", default: "msk_iam", visible_when: { field: "sasl_mechanism", one_of: ["OAUTHBEARER"] } }),
msk_region: field({ key: "msk_region", visible_when: { field: "oauth_token_source", one_of: ["msk_iam"] } }),
};
- const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default;
+ const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default ?? undefined;
const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
expect(pluginFieldIsVisible(fields.msk_region, read, resolve)).toBe(false);
// Turning OAUTHBEARER on makes the whole chain visible again.
- const readOauth: (key: string) => PluginFormFieldValue = (key) => (key === "sasl_mechanism" ? "OAUTHBEARER" : key === "security_protocol" ? "SASL_SSL" : fields[key]?.default);
+ const readOauth: (key: string) => PluginFormFieldValue = (key) => (key === "sasl_mechanism" ? "OAUTHBEARER" : key === "security_protocol" ? "SASL_SSL" : (fields[key]?.default ?? undefined));
expect(pluginFieldIsVisible(fields.oauth_token_source, readOauth, resolve)).toBe(true);
expect(pluginFieldIsVisible(fields.msk_region, readOauth, resolve)).toBe(true);
});
+ it.each([false, true])("keeps sibling branches path-local with reverse order %s", (reverse) => {
+ const fields: Record<string, PluginFormField> = {
+ mode: field({ key: "mode" }),
+ auth: field({ key: "auth", visible_when: { field: "mode", one_of: ["enabled"] } }),
+ };
+ const clause: PluginFieldCondition = { field: "auth", one_of: ["password"] };
+ const branches: PluginFieldCondition[] = [{ all_of: [clause, { field: "flag", one_of: [true] }] }, { all_of: [{ field: "flag", one_of: [false] }, clause] }];
+ if (reverse) branches.reverse();
+ const resolve = (key: string) => fields[key];
+ for (const flag of [false, true]) {
+ const hidden = reader({ mode: "disabled", auth: "password", flag });
+ const visible = reader({ mode: "enabled", auth: "password", flag });
+ for (const condition of [clause, { any_of: [clause, clause] }, { any_of: branches }, { all_of: [clause, clause] }] satisfies PluginFieldCondition[]) {
+ const target = field({ key: "target", visible_when: condition });
+ expect(pluginFieldIsVisible(target, hidden, resolve)).toBe(false);
+ expect(pluginFieldIsVisible(target, visible, resolve)).toBe(true);
+ }
+ const negated = field({ visible_when: { not: { any_of: [clause, clause] } } });
+ expect(pluginFieldIsVisible(negated, hidden, resolve)).toBe(false);
+ expect(pluginFieldIsVisible(negated, reader({ mode: "enabled", auth: "token", flag }), resolve)).toBe(true);
+ }
+ });
+
+ it("preserves true mutual-cycle compatibility without bypassing value checks", () => {
+ const fields: Record<string, PluginFormField> = {
+ first: field({ key: "first", visible_when: { field: "second", one_of: ["on"] } }),
+ second: field({ key: "second", visible_when: { field: "first", one_of: ["on"] } }),
+ };
+ const resolve = (key: string) => fields[key];
+ expect(pluginFieldIsVisible(fields.first, reader({ first: "on", second: "on" }), resolve)).toBe(true);
+ expect(pluginFieldIsVisible(fields.first, reader({ first: "off", second: "on" }), resolve)).toBe(false);
+ });
+
it("ignores unknown condition fields and survives self-referencing cycles", () => {
const unknown = field({ visible_when: { field: "missing", one_of: ["x"] } });
expect(
diff --git a/apps/desktop/src/lib/plugins/pluginFieldConditions.ts b/apps/desktop/src/lib/plugins/pluginFieldConditions.ts
index 93fc6856ee..6ba8870f7d 100644
--- a/apps/desktop/src/lib/plugins/pluginFieldConditions.ts
+++ b/apps/desktop/src/lib/plugins/pluginFieldConditions.ts
@@ -1,14 +1,67 @@
import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database";
+/**
+ * Canonical string form of a form value, matching the Rust host
+ * (`condition_value_text` in `crates/dbx-core/src/plugins/manifest.rs`).
+ * `false` renders as `"false"` and `22.0` as `"22"`.
+ */
+export function pluginConditionValueText(value: PluginFormFieldValue): string {
+ if (value === undefined || value === null) return "";
+ return String(value);
+}
+
+/** Reads the current value of a sibling form field by key. */
+export type PluginFieldValueReader = (key: string) => PluginFormFieldValue;
+
+/** A leaf clause matches when the sibling value equals one of its literals. */
+function conditionClauseMatches(clause: { field: string; one_of: readonly (string | number | boolean)[] }, value: PluginFormFieldValue): boolean {
+ if (value === undefined || value === null || (typeof value === "string" && value.trim().length === 0)) return false;
+ const text = pluginConditionValueText(value);
+ return clause.one_of.some((literal) => pluginConditionValueText(literal) === text);
+}
+
/**
* Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
- * Host API 1.1). A condition matches when the current value of the referenced
- * sibling field is listed in `one_of`. Missing conditions always match.
+ * Host API 1.1+). A leaf matches when the current value of the referenced
+ * sibling field is listed in `one_of`; `all_of` / `any_of` / `not` compose
+ * clauses, so a manifest can express `sudo_source = custom AND read_only =
+ * false`. Missing conditions always match; a missing or empty sibling value
+ * never matches.
*/
-export function pluginFieldConditionMatches(condition: PluginFieldCondition | undefined, value: PluginFormFieldValue): boolean {
+export function pluginFieldConditionMatches(condition: PluginFieldCondition | undefined, readValue: PluginFieldValueReader): boolean {
if (!condition) return true;
- if (value === undefined || value === null || (typeof value === "string" && value.trim().length === 0)) return false;
- return condition.one_of.includes(String(value));
+ return conditionExpressionMatches(condition, readValue);
+}
+
+function conditionExpressionMatches(condition: PluginFieldCondition, readValue: PluginFieldValueReader): boolean {
+ if (isConditionClause(condition)) return conditionClauseMatches(condition, readValue(condition.field));
+ if (isConditionAllOf(condition)) {
+ return condition.all_of.every((child) => conditionExpressionMatches(child, readValue));
+ }
+ if (isConditionAnyOf(condition)) {
+ return condition.any_of.some((child) => conditionExpressionMatches(child, readValue));
+ }
+ return !conditionExpressionMatches(condition.not, readValue);
+}
+
+/** Field keys the expression reads, in evaluation order (duplicates kept). */
+export function pluginFieldConditionReferencedFields(condition: PluginFieldCondition): string[] {
+ if (isConditionClause(condition)) return [condition.field];
+ if (isConditionAllOf(condition)) return condition.all_of.flatMap(pluginFieldConditionReferencedFields);
+ if (isConditionAnyOf(condition)) return condition.any_of.flatMap(pluginFieldConditionReferencedFields);
+ return pluginFieldConditionReferencedFields(condition.not);
+}
+
+function isConditionClause(condition: PluginFieldCondition): condition is { field: string; one_of: (string | number | boolean)[] } {
+ return typeof (condition as { field?: unknown }).field === "string";
+}
+
+function isConditionAllOf(condition: PluginFieldCondition): condition is { all_of: PluginFieldCondition[] } {
+ return Array.isArray((condition as { all_of?: unknown }).all_of);
+}
+
+function isConditionAnyOf(condition: PluginFieldCondition): condition is { any_of: PluginFieldCondition[] } {
+ return Array.isArray((condition as { any_of?: unknown }).any_of);
}
/** Looks a sibling field up by key; returns undefined when the key is unknown. */
@@ -28,11 +81,40 @@ export function pluginFieldIsVisible(field: PluginFormField, readValue: (key: st
function pluginFieldIsVisibleCached(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
const condition = field.visible_when;
if (!condition) return true;
- if (!pluginFieldConditionMatches(condition, readValue(condition.field))) return false;
- const target = resolveField?.(condition.field);
+ return conditionExpressionVisible(condition, readValue, resolveField, seen);
+}
+
+/**
+ * Visibility-aware evaluation of one condition expression.
+ *
+ * A clause only counts while the sibling it reads is visible *and* its own
+ * `visible_when` chain is satisfied, so a hidden controller's stored default
+ * cannot light a field up. `not` additionally requires every operand to be
+ * visible: an inverted hidden value is not a usable answer.
+ */
+function conditionExpressionVisible(condition: PluginFieldCondition, readValue: PluginFieldValueReader, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
+ if (isConditionClause(condition)) {
+ if (!conditionClauseMatches(condition, readValue(condition.field))) return false;
+ return conditionOperandVisible(condition.field, readValue, resolveField, seen);
+ }
+ if (isConditionAllOf(condition)) {
+ return condition.all_of.every((child) => conditionExpressionVisible(child, readValue, resolveField, seen));
+ }
+ if (isConditionAnyOf(condition)) {
+ return condition.any_of.some((child) => conditionExpressionVisible(child, readValue, resolveField, seen));
+ }
+ const operandsVisible = pluginFieldConditionReferencedFields(condition.not).every((key) => conditionOperandVisible(key, readValue, resolveField, seen));
+ return operandsVisible && !conditionExpressionMatches(condition.not, readValue);
+}
+
+/** Whether the sibling behind one clause is itself rendered. Cycles count as visible. */
+function conditionOperandVisible(key: string, readValue: PluginFieldValueReader, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
+ const target = resolveField?.(key);
if (!target || seen.has(target.key)) return true;
seen.add(target.key);
- return pluginFieldIsVisibleCached(target, readValue, resolveField, seen);
+ const visible = pluginFieldIsVisibleCached(target, readValue, resolveField, seen);
+ seen.delete(target.key);
+ return visible;
}
/** Effective required = static `required` OR a matching `required_when`. */
@@ -43,5 +125,5 @@ export function pluginFieldIsRequired(field: PluginFormField, readValue: (key: s
// for visibility), so it must not be consulted here — that used to mark
// every plugin field required and dead-locked the connection footer.
if (!field.required_when) return false;
- return pluginFieldConditionMatches(field.required_when, readValue(field.required_when.field));
+ return pluginFieldConditionMatches(field.required_when, readValue);
}
diff --git a/apps/desktop/src/lib/plugins/pluginFieldPicker.spec.ts b/apps/desktop/src/lib/plugins/pluginFieldPicker.spec.ts
new file mode 100644
index 0000000000..f5159d5e1f
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginFieldPicker.spec.ts
@@ -0,0 +1,86 @@
+// @vitest-environment happy-dom
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { tauriRuntime, openMock } = vi.hoisted(() => ({ tauriRuntime: { value: false }, openMock: vi.fn() }));
+
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => tauriRuntime.value }));
+vi.mock("@tauri-apps/plugin-dialog", () => ({ open: openMock }));
+
+import { PLUGIN_PICKER_MAX_BYTES, pickPluginFieldFile } from "./pluginFieldPicker";
+
+/** Captures the hidden `<input type="file">` the browser path creates. */
+function stubFileSelection(files: File[]) {
+ const original = document.createElement.bind(document);
+ const created: HTMLInputElement[] = [];
+ const spy = vi.spyOn(document, "createElement").mockImplementation(((tag: string, options?: ElementCreationOptions) => {
+ const element = original(tag, options as never);
+ if (tag === "input") {
+ created.push(element as HTMLInputElement);
+ setTimeout(() => {
+ Object.defineProperty(element, "files", { value: files, configurable: true });
+ element.dispatchEvent(new Event("change"));
+ }, 0);
+ }
+ return element;
+ }) as typeof document.createElement);
+ return { created, restore: () => spy.mockRestore() };
+}
+
+beforeEach(() => {
+ tauriRuntime.value = false;
+ openMock.mockReset();
+});
+
+describe("pickPluginFieldFile", () => {
+ it("returns the client path on desktop so the plugin can read the file itself", async () => {
+ tauriRuntime.value = true;
+ openMock.mockResolvedValue("/Users/dev/.ssh/id_rsa");
+
+ const picked = await pickPluginFieldFile({ kind: "file", accept: [".pem", ".key"] });
+
+ expect(picked).toEqual({ path: "/Users/dev/.ssh/id_rsa", name: "id_rsa" });
+ expect(openMock).toHaveBeenCalledWith({
+ directory: false,
+ multiple: false,
+ filters: [{ name: "Files", extensions: ["pem", "key"] }],
+ });
+ });
+
+ it("offers a folder dialog for directory pickers and ignores a dismissal", async () => {
+ tauriRuntime.value = true;
+ openMock.mockResolvedValue(null);
+
+ expect(await pickPluginFieldFile({ kind: "directory" })).toBeNull();
+ expect(openMock).toHaveBeenCalledWith({ directory: true, multiple: false, filters: undefined });
+ });
+
+ it("reads the file content on browser hosts, which cannot hand over a path", async () => {
+ const files = [new File(["-----BEGIN PRIVATE KEY-----\nkey\n"], "id_rsa", { type: "text/plain" })];
+ const selection = stubFileSelection(files);
+ try {
+ const picked = await pickPluginFieldFile({ kind: "file", accept: [".pem", "text/plain"] });
+
+ expect(picked).toEqual({ content: "-----BEGIN PRIVATE KEY-----\nkey\n", name: "id_rsa" });
+ expect(selection.created[0]?.accept).toBe(".pem,text/plain");
+ expect(selection.created[0]?.multiple).toBe(false);
+ } finally {
+ selection.restore();
+ }
+ });
+
+ it("has no browser equivalent for a folder picker", async () => {
+ expect(await pickPluginFieldFile({ kind: "directory" })).toBeNull();
+ });
+
+ it("rejects an oversized upload instead of loading it", async () => {
+ const oversized = new File(["x"], "big.key", { type: "text/plain" });
+ Object.defineProperty(oversized, "size", { value: PLUGIN_PICKER_MAX_BYTES + 1 });
+ const selection = stubFileSelection([oversized]);
+ try {
+ await expect(pickPluginFieldFile({ kind: "file" })).rejects.toThrow(/larger than 1024 KiB/);
+ } finally {
+ selection.restore();
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/pluginFieldPicker.ts b/apps/desktop/src/lib/plugins/pluginFieldPicker.ts
new file mode 100644
index 0000000000..9b05930d2b
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/pluginFieldPicker.ts
@@ -0,0 +1,69 @@
+import type { PluginFormFieldPicker } from "@/types/database";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+
+/** Uploads larger than this are rejected instead of being held in memory. */
+export const PLUGIN_PICKER_MAX_BYTES = 1_048_576;
+
+export interface PluginPickedFile {
+ /** Absolute path of the selected file; desktop hosts only. */
+ path?: string;
+ /** File content; browser hosts only (they cannot produce a usable path). */
+ content?: string;
+ /** File name, for messages. */
+ name: string;
+}
+
+/**
+ * Runs the manifest's picker action for one field.
+ *
+ * Desktop hosts (Tauri) open the native dialog and return the absolute path, so
+ * the plugin — which runs on the same machine — can read the file itself.
+ * Browser hosts have no client filesystem: they read the selected file and hand
+ * back its content, which the form stores in the declared `content_field`
+ * (the browser build cannot hand the server a path to a client file).
+ *
+ * Returns `null` when the user cancels.
+ */
+export async function pickPluginFieldFile(picker: PluginFormFieldPicker): Promise<PluginPickedFile | null> {
+ const accepted = (picker.accept || []).slice();
+ if (isTauriRuntime()) {
+ const { open } = await import("@tauri-apps/plugin-dialog");
+ const extensions = accepted.filter((entry) => entry.startsWith(".")).map((entry) => entry.replace(/^\./, ""));
+ const selected = await open({
+ directory: picker.kind === "directory",
+ multiple: false,
+ filters: extensions.length ? [{ name: picker.kind === "directory" ? "Folders" : "Files", extensions }] : undefined,
+ });
+ if (typeof selected !== "string" || !selected) return null;
+ return { path: selected, name: selected.replaceAll("\\", "/").split("/").pop() || selected };
+ }
+
+ if (picker.kind === "directory") return null;
+ const file = await selectBrowserFile(accepted);
+ if (!file) return null;
+ if (file.size > PLUGIN_PICKER_MAX_BYTES) {
+ throw new Error(`File is larger than ${Math.round(PLUGIN_PICKER_MAX_BYTES / 1024)} KiB`);
+ }
+ return { content: await file.text(), name: file.name };
+}
+
+function selectBrowserFile(accept: string[]): Promise<File | null> {
+ return new Promise((resolve) => {
+ const input = document.createElement("input");
+ input.type = "file";
+ input.multiple = false;
+ if (accept.length) input.accept = accept.join(",");
+ // Chrome fires `cancel` when the dialog is dismissed; older engines only
+ // fire `change` without files, which the handler below already treats as a
+ // cancellation.
+ input.addEventListener("cancel", () => resolve(null), { once: true });
+ input.addEventListener(
+ "change",
+ () => {
+ resolve(input.files?.[0] ?? null);
+ },
+ { once: true },
+ );
+ input.click();
+ });
+}
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 0c160ad992..3f4396e3dd 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -295,13 +295,53 @@ export interface PluginFormFieldOption {
value: string;
}
-export interface PluginFieldCondition {
- /** Key of another plugin form field whose current value drives the condition. */
+/** A literal a `one_of` clause may list; compared by canonical string form. */
+export type PluginFieldConditionLiteral = string | number | boolean;
+
+/** Legacy single-field clause: `{ field, one_of }`. */
+export interface PluginFieldConditionClause {
+ /** Key of another plugin form field whose current value drives the clause. */
field: string;
- /** The condition matches when the referenced field's value is in this list. */
- one_of: string[];
+ /** The clause matches when the referenced field's value is in this list. */
+ one_of: PluginFieldConditionLiteral[];
+}
+
+/** Every nested condition must match. */
+export interface PluginFieldConditionAllOf {
+ all_of: PluginFieldCondition[];
+}
+
+/** At least one nested condition must match. */
+export interface PluginFieldConditionAnyOf {
+ any_of: PluginFieldCondition[];
+}
+
+/** Inverts the nested condition. */
+export interface PluginFieldConditionNot {
+ not: PluginFieldCondition;
}
+/** Host API 1.1: local-file action on a plugin connection field. */
+export interface PluginFormFieldPicker {
+ /** `directory` is desktop-only. */
+ kind: "file" | "directory";
+ /** Extensions (`.pem`) or MIME types (`text/plain`) offered by the picker. */
+ accept?: string[];
+ /**
+ * Declared sibling field that receives the file content on hosts without a
+ * client filesystem (the browser build). Desktop hosts store the chosen path
+ * in the declaring field and clear this one instead.
+ */
+ content_field?: string;
+}
+
+/**
+ * `visible_when` / `required_when` expression. The legacy `{ field, one_of }`
+ * clause keeps its exact meaning; `all_of` / `any_of` / `not` compose clauses
+ * (e.g. `sudo_source = custom AND read_only = false`).
+ */
+export type PluginFieldCondition = PluginFieldConditionClause | PluginFieldConditionAllOf | PluginFieldConditionAnyOf | PluginFieldConditionNot;
+
export interface PluginFormField {
key: string;
label: string;
@@ -309,11 +349,15 @@ export interface PluginFormField {
description?: string;
placeholder?: string;
required?: boolean;
- default?: PluginFormFieldValue;
+ /** Declared default. Hosts older than the manifest serialization fix send
+ * `null` for "no default", which the form treats as unset. */
+ default?: PluginFormFieldValue | null;
options?: PluginFormFieldOption[];
/** Plugin method returning `{ options: [{ value, label }] }` for dynamic
* select rendering; falls back to the declared type when unavailable. */
options_action?: string;
+ /** Host API 1.1: offer a local-file action on this field. */
+ picker?: PluginFormFieldPicker;
binding?: PluginFormFieldBinding;
visible_when?: PluginFieldCondition;
required_when?: PluginFieldCondition;
diff --git a/crates/dbx-core/src/connection_secrets.rs b/crates/dbx-core/src/connection_secrets.rs
index 7ade9bf1b6..26de9af744 100644
--- a/crates/dbx-core/src/connection_secrets.rs
+++ b/crates/dbx-core/src/connection_secrets.rs
@@ -1606,4 +1606,60 @@ mod tests {
let loaded = load_connections_from_file(&path, &store).unwrap();
assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret"));
}
+
+ #[test]
+ fn load_connections_preserves_opaque_null_plugin_secrets() {
+ let path = temp_connections_file("plugin-null-secret");
+ let store = MemorySecretStore::default();
+ let mut config = connection("plugin-connection", "", "");
+ config.db_type = DatabaseType::Plugin;
+ config.plugin_id = Some("io.dbx.ssh".to_string());
+ config.plugin_connection_provider = Some("ssh.connection".to_string());
+ config.plugin_connection_type = Some("ssh".to_string());
+ config.external_config = Some(serde_json::json!({ "sudo_source": "custom" }));
+ config.connection_secrets.insert("sudo_password".to_string(), "null".to_string());
+ config.connection_secrets.insert("totp_secret".to_string(), "".to_string());
+ config.connection_secrets.insert("private_key_passphrase".to_string(), "real-passphrase".to_string());
+
+ save_connections_to_file(&path, &[config], &store).unwrap();
+ store.set_existing("plugin-connection", &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}totp_secret"), "null");
+ let stored = store.values.borrow().clone();
+ let deleted = store.deleted.borrow().clone();
+ let raw_config = std::fs::read(&path).unwrap();
+
+ let loaded = load_connections_from_file(&path, &store).unwrap();
+ let secrets = &loaded[0].connection_secrets;
+ assert_eq!(secrets.get("sudo_password").map(String::as_str), Some("null"));
+ assert_eq!(secrets.get("totp_secret").map(String::as_str), Some("null"));
+ assert_eq!(secrets.get("private_key_passphrase").map(String::as_str), Some("real-passphrase"));
+ assert_eq!(load_connections_from_file(&path, &store).unwrap()[0].connection_secrets, *secrets);
+ assert_eq!(*store.values.borrow(), stored);
+ assert_eq!(*store.deleted.borrow(), deleted);
+ assert_eq!(std::fs::read(&path).unwrap(), raw_config);
+ save_connections_to_file(&path, &loaded, &store).unwrap();
+ assert_eq!(load_connections_from_file(&path, &store).unwrap()[0].connection_secrets, *secrets);
+ assert_eq!(*store.values.borrow(), stored);
+ }
+
+ #[test]
+ fn file_secret_store_preserves_opaque_null_credentials() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("connections.json");
+ let secret_path = dir.path().join("secrets.json");
+ let store = super::FileSecretStore::new(secret_path.clone());
+ let mut config = connection("plugin-connection", "", "");
+ config.db_type = DatabaseType::Plugin;
+ config.connection_secrets.insert("credential".to_string(), "null".to_string());
+ save_connections_to_file(&path, &[config], &store).unwrap();
+ let raw_config = std::fs::read(&path).unwrap();
+ let raw_secrets = std::fs::read(&secret_path).unwrap();
+
+ for _ in 0..2 {
+ let reopened_store = super::FileSecretStore::new(secret_path.clone());
+ let loaded = load_connections_from_file(&path, &reopened_store).unwrap();
+ assert_eq!(loaded[0].connection_secrets.get("credential").map(String::as_str), Some("null"));
+ assert_eq!(std::fs::read(&path).unwrap(), raw_config);
+ assert_eq!(std::fs::read(&secret_path).unwrap(), raw_secrets);
+ }
+ }
}
diff --git a/crates/dbx-core/src/db/sqlite_worker.rs b/crates/dbx-core/src/db/sqlite_worker.rs
index 8b5dd3c457..7640482a84 100644
--- a/crates/dbx-core/src/db/sqlite_worker.rs
+++ b/crates/dbx-core/src/db/sqlite_worker.rs
@@ -437,6 +437,10 @@ async fn ensure_worker_consent(data_dir: &Path, identity: &str, dest: &str, dige
previous_fingerprint: None,
prompt: Some(dest.to_string()),
echo: false,
+ source: None,
+ title: None,
+ default_value: None,
+ options: Vec::new(),
};
let Some(rx) = ssh_prompt::request_ssh_prompt(request) else {
return Err("Uploading a SQLite worker requires explicit consent in the Desktop UI".to_string());
diff --git a/crates/dbx-core/src/db/ssh_prompt.rs b/crates/dbx-core/src/db/ssh_prompt.rs
index ac7927d70c..a6208f4c85 100644
--- a/crates/dbx-core/src/db/ssh_prompt.rs
+++ b/crates/dbx-core/src/db/ssh_prompt.rs
@@ -8,6 +8,12 @@
//! suspend on a `oneshot` while the Tauri layer forwards the request to the UI
//! and the UI answers through a command.
//!
+//! The same gateway carries generic [`SshPromptKind::UserInput`] questions that
+//! are not part of a host-owned SSH transport, e.g. a plugin backend asking for
+//! a bastion MFA code through the `host/requestUserInput` Host API method. The
+//! channel is intentionally transport-agnostic: the host only relays a question
+//! and the typed answer, and it never answers on the user's behalf.
+//!
//! The gateway is installed once at app startup by the Tauri layer
//! (`install_ssh_prompt_gateway`). In headless / test contexts where no
//! gateway is installed, `request_ssh_prompt` returns `None` and callers MUST
@@ -30,6 +36,20 @@ pub enum SshPromptKind {
SecretInput,
/// Confirm uploading the SQLite worker binary onto the file host.
WorkerUploadConsent,
+ /// A caller that is not a host-owned transport (today: a plugin backend
+ /// through the `host/requestUserInput` Host API method) needs a value typed
+ /// by the user. Unlike [`SshPromptKind::SecretInput`] the host never
+ /// synthesizes or auto-answers it: without a user there is no answer.
+ UserInput,
+}
+
+/// A fixed answer a [`SshPromptKind::UserInput`] request offers.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SshPromptOption {
+ /// Value returned to the caller when the user picks this option.
+ pub value: String,
+ /// Text the dialog shows.
+ pub label: String,
}
/// A request for user input, sent from the backend to the UI.
@@ -56,19 +76,52 @@ pub struct SshPromptRequest {
/// Passwords and verification codes normally set this to false.
#[serde(default)]
pub echo: bool,
+ /// UserInput: who is asking (e.g. the plugin display name), shown so the
+ /// user can tell a bastion login prompt from a host-owned one.
+ #[serde(default)]
+ pub source: Option<String>,
+ /// UserInput: heading above `prompt`, already localized by the caller.
+ #[serde(default)]
+ pub title: Option<String>,
+ /// UserInput: preset answer offered in the input.
+ #[serde(default)]
+ pub default_value: Option<String>,
+ /// UserInput: fixed answers; empty means free-form input.
+ #[serde(default)]
+ pub options: Vec<SshPromptOption>,
}
/// The user's answer, sent from the UI back to the backend.
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SshPromptAnswer {
/// Accept and (for HostKeyVerify) optionally persist the key.
Accept { remember: bool },
/// Reject.
Reject,
- /// A typed secret (SecretInput).
+ /// A typed value (SecretInput / UserInput).
Secret(String),
}
+impl Default for SshPromptRequest {
+ fn default() -> Self {
+ Self {
+ id: String::new(),
+ kind: SshPromptKind::HostKeyVerify,
+ host: String::new(),
+ port: 0,
+ key_type: None,
+ fingerprint: None,
+ previous_fingerprint: None,
+ prompt: None,
+ echo: false,
+ source: None,
+ title: None,
+ default_value: None,
+ options: Vec::new(),
+ }
+ }
+}
+
/// Internal envelope: the request plus the channel to deliver the answer on.
pub struct SshPromptEnvelope {
pub request: SshPromptRequest,
@@ -88,6 +141,18 @@ pub fn clear_ssh_prompt_gateway() {
*PROMPT_GATEWAY.lock().unwrap() = None;
}
+/// Serializes every test that mutates the process-global prompt gateway.
+///
+/// One gateway serves the host's SSH transports, the SQLite worker consent
+/// prompt and plugin Host API questions, so tests in any module must hold this
+/// lock while a gateway is installed — otherwise one test's gateway (or the
+/// fail-closed checks that rely on *no* gateway) clobbers another's.
+#[cfg(test)]
+pub fn prompt_gateway_test_lock() -> &'static tokio::sync::Mutex<()> {
+ static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+ &LOCK
+}
+
/// Request input from the UI. Returns the receiver the caller should await, or
/// `None` if no gateway is installed (caller must fail closed).
pub fn request_ssh_prompt(request: SshPromptRequest) -> Option<oneshot::Receiver<SshPromptAnswer>> {
@@ -117,6 +182,10 @@ pub fn host_key_verify_request(
previous_fingerprint: None,
prompt: None,
echo: false,
+ source: None,
+ title: None,
+ default_value: None,
+ options: Vec::new(),
}
}
@@ -138,6 +207,10 @@ pub fn host_key_changed_request(
previous_fingerprint,
prompt: None,
echo: false,
+ source: None,
+ title: None,
+ default_value: None,
+ options: Vec::new(),
}
}
@@ -153,6 +226,74 @@ pub fn secret_input_request(host: &str, port: u16, prompt: String, echo: bool) -
previous_fingerprint: None,
prompt: Some(prompt),
echo,
+ source: None,
+ title: None,
+ default_value: None,
+ options: Vec::new(),
+ }
+}
+
+/// A generic question from a caller the host does not own (today: a plugin
+/// backend). Built through [`UserInputRequest::into_request`], which allocates
+/// the prompt id the UI answers with.
+#[derive(Debug, Clone)]
+pub struct UserInputRequest {
+ pub prompt: String,
+ pub echo: bool,
+ pub title: Option<String>,
+ pub source: Option<String>,
+ pub default_value: Option<String>,
+ pub options: Vec<SshPromptOption>,
+}
+
+impl UserInputRequest {
+ pub fn new(prompt: impl Into<String>) -> Self {
+ Self { prompt: prompt.into(), echo: false, title: None, source: None, default_value: None, options: Vec::new() }
+ }
+
+ pub fn with_title(mut self, title: Option<String>) -> Self {
+ self.title = title;
+ self
+ }
+
+ pub fn with_source(mut self, source: Option<String>) -> Self {
+ self.source = source;
+ self
+ }
+
+ pub fn with_default(mut self, default_value: Option<String>) -> Self {
+ self.default_value = default_value;
+ self
+ }
+
+ pub fn with_options(mut self, options: Vec<SshPromptOption>) -> Self {
+ self.options = options;
+ self
+ }
+
+ pub fn with_echo(mut self, echo: bool) -> Self {
+ self.echo = echo;
+ self
+ }
+
+ /// Turn the question into a prompt request. `host`/`port` are display-only
+ /// context a caller outside the host's own transports usually leaves empty.
+ pub fn into_request(self, host: &str, port: u16) -> SshPromptRequest {
+ SshPromptRequest {
+ id: Uuid::new_v4().to_string(),
+ kind: SshPromptKind::UserInput,
+ host: host.to_string(),
+ port,
+ key_type: None,
+ fingerprint: None,
+ previous_fingerprint: None,
+ prompt: Some(self.prompt),
+ echo: self.echo,
+ source: self.source,
+ title: self.title,
+ default_value: self.default_value,
+ options: self.options,
+ }
}
}
diff --git a/crates/dbx-core/src/db/ssh_tunnel.rs b/crates/dbx-core/src/db/ssh_tunnel.rs
index 353acca54d..67cb4d40c8 100644
--- a/crates/dbx-core/src/db/ssh_tunnel.rs
+++ b/crates/dbx-core/src/db/ssh_tunnel.rs
@@ -1877,11 +1877,13 @@ pub(crate) fn effective_hop_timeout(hop: &SshTunnelConfig) -> u64 {
}
}
-/// Serializes every test that mutates the process-global SSH prompt gateway so
-/// they cannot clobber each other's gateway (or the MITM fail-closed test,
-/// which relies on *no* gateway being installed). Test-only.
+/// Serializes every test that mutates the process-global prompt gateway. The
+/// lock lives in `db::ssh_prompt` because the gateway is shared with the plugin
+/// Host API, so prompt tests in other modules must take the same lock. Test-only.
#[cfg(test)]
-static PROMPT_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+fn prompt_test_lock() -> &'static tokio::sync::Mutex<()> {
+ crate::db::ssh_prompt::prompt_gateway_test_lock()
+}
#[cfg(test)]
fn plan_chain(
@@ -1918,10 +1920,10 @@ fn plan_chain(
#[cfg(test)]
mod tests {
+ use super::prompt_test_lock;
#[cfg(unix)]
use super::resolve_ssh_agent_socket_path;
use super::SshClient;
- use super::PROMPT_TEST_LOCK;
use super::{
bind_tunnel_listener, connect_and_authenticate, describe_terminal_auth_failure, effective_hop_timeout,
netcat_proxy_command, openssh_padding_len, plan_chain, read_ssh_string,
@@ -2404,7 +2406,7 @@ mod tests {
#[tokio::test]
async fn unknown_host_prompt_accept_learns_key() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path.clone());
@@ -2428,7 +2430,7 @@ mod tests {
#[tokio::test]
async fn unknown_host_prompt_accept_without_remember_is_session_only() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path.clone());
@@ -2454,7 +2456,7 @@ mod tests {
#[tokio::test]
async fn unknown_host_prompt_reject_aborts_handshake() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path.clone());
@@ -2480,7 +2482,7 @@ mod tests {
#[tokio::test]
async fn unknown_host_without_gateway_fails_closed() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
// Ensure no gateway is installed so request_ssh_prompt returns None.
ssh_prompt::clear_ssh_prompt_gateway();
let dir = tempdir().unwrap();
@@ -2501,7 +2503,7 @@ mod tests {
#[tokio::test]
async fn trusted_host_skips_prompt() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
let verifier = HostKeyVerifier::new(path);
@@ -2531,7 +2533,7 @@ mod tests {
#[tokio::test]
async fn changed_host_prompt_update_replaces_key() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
seed_changed_host_key(&path);
@@ -2559,7 +2561,7 @@ mod tests {
#[tokio::test]
async fn changed_host_prompt_continue_is_session_only() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
seed_changed_host_key(&path);
@@ -2587,7 +2589,7 @@ mod tests {
#[tokio::test]
async fn changed_host_prompt_reject_aborts_handshake() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
let dir = tempdir().unwrap();
let path = dir.path().join("known_hosts");
seed_changed_host_key(&path);
@@ -2735,7 +2737,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn password_auth_continues_with_keyboard_interactive_totp() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let (port, server_task) = start_password_then_totp_server().await;
let dir = tempdir().unwrap();
@@ -2781,7 +2783,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn public_key_auth_continues_with_keyboard_interactive_totp() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let (port, server_task) = start_password_then_totp_server().await;
let dir = tempdir().unwrap();
@@ -2901,7 +2903,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn socks5_proxy_forwards_requested_target_over_ssh() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
let server_config = server::Config { keys: vec![server_key], ..Default::default() };
@@ -3052,7 +3054,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn tunnel_falls_back_to_netcat_when_direct_tcpip_is_prohibited() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
let server_config = server::Config { keys: vec![server_key], ..Default::default() };
@@ -3107,7 +3109,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn prohibited_direct_tcpip_does_not_run_netcat_by_default() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
let server_config = server::Config { keys: vec![server_key], ..Default::default() };
@@ -3157,7 +3159,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn forwarded_connection_checks_logical_host_identity() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let (connect_port, server_task) = start_accept_none_server().await;
let dir = tempdir().unwrap();
@@ -3205,7 +3207,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
/// wait must not be charged against `connect_timeout_secs`.
#[tokio::test]
async fn slow_host_key_acceptance_does_not_time_out_the_connection() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let (connect_port, server_task) = start_accept_none_server().await;
let dir = tempdir().unwrap();
@@ -3248,7 +3250,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn concurrent_tunnel_starts_share_one_handshake() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let (connect_port, server_task) = start_accept_none_server().await;
let dir = tempdir().unwrap();
@@ -3342,7 +3344,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn unknown_host_without_persist_permission_does_not_leak_password() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
// This test proves the client never sends a password to an untrusted
// host. It must run with NO prompt gateway installed so the handshake
// fails closed (no UI to confirm the key -> reject before auth).
@@ -3479,7 +3481,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn reconnect_auth_failure_is_reported_instead_of_a_dead_local_port() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
let publickey_attempts = Arc::new(AtomicUsize::new(0));
@@ -3573,7 +3575,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
#[tokio::test]
async fn rejected_public_key_reports_what_the_server_refused() {
- let _guard = PROMPT_TEST_LOCK.lock().await;
+ let _guard = prompt_test_lock().lock().await;
ssh_prompt::clear_ssh_prompt_gateway();
// Every publickey attempt is refused, so this exercises the initial
diff --git a/crates/dbx-core/src/plugins.rs b/crates/dbx-core/src/plugins.rs
index 1a542e8154..b676f5aa42 100644
--- a/crates/dbx-core/src/plugins.rs
+++ b/crates/dbx-core/src/plugins.rs
@@ -40,16 +40,17 @@ pub use manifest::{
current_plugin_target, resolve_safe_plugin_path, PluginBackendEntrypoint, PluginBackendTransport,
PluginCompatibility, PluginConnectionActionContribution, PluginConnectionActionVariant, PluginConnectionActionWhen,
PluginConnectionCapability, PluginConnectionProviderContribution, PluginContribution, PluginDriverManifest,
- PluginEngines, PluginEntrypoints, PluginFieldCondition, PluginFilesystemCapability,
- PluginFilesystemProviderContribution, PluginFormFieldBinding, PluginFormFieldDefinition, PluginFormFieldOption,
+ PluginEngines, PluginEntrypoints, PluginFieldCondition, PluginFieldConditionClause, PluginFieldConditionLiteral,
+ PluginFilesystemCapability, PluginFilesystemProviderContribution, PluginFormFieldBinding,
+ PluginFormFieldDefinition, PluginFormFieldOption, PluginFormFieldPicker, PluginFormFieldPickerKind,
PluginFormFieldType, PluginManifest, PluginUiEntrypoint, PluginWorkbenchContribution,
PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD,
- PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_MANIFEST_VERSION,
- SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
+ PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_HOST_FEATURES,
+ SUPPORTED_PLUGIN_MANIFEST_VERSION, SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
};
pub use runtime::{
PluginBinaryMessage, PluginEvent, PluginHandshake, PluginHandshakeIdentity, PluginSessionState,
- PluginSessionStatus, PluginSidecarSession, PLUGIN_REQUEST_TIMEOUT,
+ PluginSessionStatus, PluginSidecarSession, PLUGIN_REQUEST_TIMEOUT, PLUGIN_REQUEST_USER_INPUT_METHOD,
};
#[derive(Debug, Clone)]
diff --git a/crates/dbx-core/src/plugins/host.rs b/crates/dbx-core/src/plugins/host.rs
index 6b1f8a5989..1710a65c55 100644
--- a/crates/dbx-core/src/plugins/host.rs
+++ b/crates/dbx-core/src/plugins/host.rs
@@ -546,39 +546,36 @@ fn plugin_field_value_is_empty(value: Option<&serde_json::Value>) -> bool {
}
}
+/// Resolves the stored value of one plugin form field (a condition's operand).
+fn plugin_condition_field_value(
+ key: &str,
+ config: &ConnectionConfig,
+ provider: &PluginConnectionProviderContribution,
+) -> Option<serde_json::Value> {
+ let sibling = provider.fields.iter().find(|field| field.key == key)?;
+ plugin_connection_field_value(config, sibling)
+}
+
/// Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
/// Host API 1.1) against the stored connection values. Mirrors the frontend
-/// `pluginFieldConditions.ts` semantics: the condition matches when the current
-/// value of the referenced sibling field is listed in `one_of`; a missing
-/// sibling field or an unset/empty value never matches.
+/// `pluginFieldConditions.ts` semantics: a leaf matches when the current value
+/// of the referenced sibling field is listed in `one_of`, and a missing sibling
+/// field or an unset/empty value never matches; `all_of` / `any_of` / `not`
+/// compose those clauses.
fn plugin_field_condition_matches(
condition: &super::PluginFieldCondition,
config: &ConnectionConfig,
provider: &PluginConnectionProviderContribution,
) -> bool {
- let Some(sibling) = provider.fields.iter().find(|field| field.key == condition.field) else {
- return false;
- };
- let Some(value) = plugin_connection_field_value(config, sibling) else {
- return false;
- };
- let text = match value {
- serde_json::Value::Null => return false,
- serde_json::Value::String(text) => text,
- other => other.to_string(),
- };
- if text.trim().is_empty() {
- return false;
- }
- condition.one_of.iter().any(|option| option == &text)
+ condition.matches(&|key| plugin_condition_field_value(key, config, provider))
}
/// A field participates in the form when its `visible_when` (if any) matches.
-/// Mirrors the frontend cascade (`pluginFieldConditions.ts`): once the raw
-/// condition matches, the referenced sibling must itself be visible — a hidden
-/// container field's stored default (e.g. `krb_credential_type: "password"`
-/// while auth is simple) must not mark grandchild fields visible + required,
-/// otherwise non-dialog write paths reject connections the dialog accepts.
+/// Mirrors the frontend cascade (`pluginFieldConditions.ts`): a clause only
+/// counts while the sibling it reads is itself visible — a hidden container
+/// field's stored default (e.g. `krb_credential_type: "password"` while auth is
+/// simple) must not mark grandchild fields visible + required, otherwise
+/// non-dialog write paths reject connections the dialog accepts.
fn plugin_field_is_visible(
field: &PluginFormFieldDefinition,
config: &ConnectionConfig,
@@ -598,19 +595,59 @@ fn plugin_field_is_visible_cached(
let Some(condition) = &field.visible_when else {
return true;
};
- if !plugin_field_condition_matches(condition, config, provider) {
- return false;
+ plugin_field_condition_is_visible(condition, config, provider, seen)
+}
+
+/// Visibility-aware evaluation of one condition expression, mirroring the
+/// frontend `conditionExpressionVisible`: a clause only counts while the field
+/// it reads is itself visible, `any_of`/`all_of` compose those verdicts, and
+/// `not` additionally requires every operand to be visible (an inverted hidden
+/// value is not a usable answer).
+fn plugin_field_condition_is_visible(
+ condition: &super::PluginFieldCondition,
+ config: &ConnectionConfig,
+ provider: &PluginConnectionProviderContribution,
+ seen: &mut HashSet<String>,
+) -> bool {
+ match condition {
+ super::PluginFieldCondition::Field(clause) => {
+ if !plugin_field_condition_matches(condition, config, provider) {
+ return false;
+ }
+ plugin_field_key_is_visible(&clause.field, config, provider, seen)
+ }
+ super::PluginFieldCondition::AllOf { all_of } => {
+ all_of.iter().all(|child| plugin_field_condition_is_visible(child, config, provider, seen))
+ }
+ super::PluginFieldCondition::AnyOf { any_of } => {
+ any_of.iter().any(|child| plugin_field_condition_is_visible(child, config, provider, seen))
+ }
+ super::PluginFieldCondition::Not { not } => {
+ let operands_visible =
+ not.referenced_fields().iter().all(|key| plugin_field_key_is_visible(key, config, provider, seen));
+ operands_visible && !plugin_field_condition_matches(not, config, provider)
+ }
}
- // The condition matched, so the sibling exists (its value was readable);
- // guard cycles anyway and fall through to visible, mirroring the frontend.
- let Some(sibling) = provider.fields.iter().find(|candidate| candidate.key == condition.field) else {
+}
+
+/// Whether the sibling field behind one referenced key is itself rendered.
+/// Cycles count as visible, mirroring the frontend's `seen` guard.
+fn plugin_field_key_is_visible(
+ key: &str,
+ config: &ConnectionConfig,
+ provider: &PluginConnectionProviderContribution,
+ seen: &mut HashSet<String>,
+) -> bool {
+ let Some(sibling) = provider.fields.iter().find(|candidate| candidate.key == key) else {
return true;
};
if seen.contains(&sibling.key) {
return true;
}
seen.insert(sibling.key.clone());
- plugin_field_is_visible_cached(sibling, config, provider, seen)
+ let visible = plugin_field_is_visible_cached(sibling, config, provider, seen);
+ seen.remove(&sibling.key);
+ visible
}
/// Effective required = static `required` OR a matching `required_when`
@@ -695,8 +732,8 @@ fn ensure_permission(plugin: &super::InstalledPlugin, required_permission: Optio
#[cfg(test)]
mod tests {
use super::{
- plugin_connection_action_result, plugin_invoke_connection_action, validate_plugin_connection_values,
- validate_plugin_connection_values_for_action,
+ plugin_connection_action_result, plugin_field_is_visible, plugin_invoke_connection_action,
+ validate_plugin_connection_values, validate_plugin_connection_values_for_action,
};
use crate::models::connection::ConnectionConfig;
use crate::plugins::PluginConnectionProviderContribution;
@@ -1117,4 +1154,191 @@ mod tests {
let cyclic_config = config_for(serde_json::json!({ "a": "x", "b": "x" }));
assert!(validate_plugin_connection_values(&cyclic_config, &cyclic).is_ok());
}
+
+ #[test]
+ fn condition_sibling_branches_keep_cycle_detection_path_local() {
+ let mut provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "test.connection",
+ "database_type": "test",
+ "fields": [
+ { "key": "mode", "label": "Mode", "type": "text" },
+ {
+ "key": "auth", "label": "Auth", "type": "text",
+ "visible_when": { "field": "mode", "one_of": ["enabled"] }
+ },
+ { "key": "flag", "label": "Flag", "type": "boolean" },
+ { "key": "target", "label": "Target", "type": "text", "required": true }
+ ]
+ }))
+ .unwrap();
+ let mut config: ConnectionConfig = serde_json::from_value(serde_json::json!({
+ "id": "plugin-connection", "name": "Test", "db_type": "plugin",
+ "host": "", "port": 0, "username": "", "password": ""
+ }))
+ .unwrap();
+ let clause = serde_json::json!({ "field": "auth", "one_of": ["password"] });
+ let branches = [
+ serde_json::json!({ "all_of": [clause, { "field": "flag", "one_of": [true] }] }),
+ serde_json::json!({ "all_of": [{ "field": "flag", "one_of": [false] }, clause] }),
+ ];
+ for condition in [
+ clause.clone(),
+ serde_json::json!({ "any_of": [clause, clause] }),
+ serde_json::json!({ "all_of": [clause, clause] }),
+ serde_json::json!({ "any_of": [branches[0], branches[1]] }),
+ serde_json::json!({ "any_of": [branches[1], branches[0]] }),
+ ] {
+ provider.fields[3].visible_when = Some(serde_json::from_value(condition.clone()).unwrap());
+ for flag in [false, true] {
+ for (mode, expected) in [("disabled", false), ("enabled", true)] {
+ config.external_config =
+ Some(serde_json::json!({ "mode": mode, "auth": "password", "flag": flag }));
+ assert_eq!(
+ plugin_field_is_visible(&provider.fields[3], &config, &provider),
+ expected,
+ "{condition}"
+ );
+ assert_eq!(validate_plugin_connection_values(&config, &provider).is_err(), expected, "{condition}");
+ }
+ }
+ }
+ provider.fields[3].visible_when = Some(
+ serde_json::from_value(serde_json::json!({
+ "not": { "any_of": [clause, clause] }
+ }))
+ .unwrap(),
+ );
+ for (mode, expected) in [("disabled", false), ("enabled", true)] {
+ config.external_config = Some(serde_json::json!({ "mode": mode, "auth": "token" }));
+ assert_eq!(plugin_field_is_visible(&provider.fields[3], &config, &provider), expected);
+ }
+ }
+
+ #[test]
+ fn condition_cycles_still_require_matching_values() {
+ let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "test.connection",
+ "database_type": "test",
+ "fields": [
+ { "key": "first", "label": "First", "type": "text", "visible_when": { "field": "second", "one_of": ["on"] } },
+ { "key": "second", "label": "Second", "type": "text", "visible_when": { "field": "first", "one_of": ["on"] } },
+ { "key": "self", "label": "Self", "type": "text", "visible_when": { "field": "self", "one_of": ["on"] } },
+ { "key": "unknown", "label": "Unknown", "type": "text", "visible_when": { "field": "missing", "one_of": ["on"] } }
+ ]
+ }))
+ .unwrap();
+ let mut config: ConnectionConfig = serde_json::from_value(serde_json::json!({
+ "id": "plugin-connection", "name": "Test", "db_type": "plugin",
+ "host": "", "port": 0, "username": "", "password": ""
+ }))
+ .unwrap();
+ for (value, expected) in [("on", true), ("off", false)] {
+ config.external_config =
+ Some(serde_json::json!({ "first": value, "second": "on", "self": value, "missing": value }));
+ for field in &provider.fields {
+ assert_eq!(
+ plugin_field_is_visible(field, &config, &provider),
+ expected && field.key != "unknown",
+ "{}",
+ field.key
+ );
+ }
+ }
+ }
+
+ /// Mirrors the SSH plugin shape the composite contract was added for:
+ /// `sudo_command` is required only while `sudo_source = custom` **and**
+ /// `read_only = false`, which the single-clause contract could not express.
+ #[test]
+ fn composite_condition_gates_required_fields_like_the_dialog() {
+ let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
+ "id": "ssh.connection",
+ "label": "SSH",
+ "database_type": "ssh",
+ "fields": [
+ {
+ "key": "read_only",
+ "label": "Read only",
+ "type": "boolean",
+ "binding": "config",
+ "default": false
+ },
+ {
+ "key": "sudo_source",
+ "label": "Sudo source",
+ "type": "select",
+ "binding": "config",
+ "default": "none",
+ "options": [
+ { "value": "none", "label": "None" },
+ { "value": "custom", "label": "Custom" }
+ ]
+ },
+ {
+ "key": "sudo_command",
+ "label": "Sudo command",
+ "type": "text",
+ "binding": "config",
+ "visible_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "field": "read_only", "one_of": [false] }
+ ]
+ },
+ "required_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "not": { "field": "read_only", "one_of": [true] } }
+ ]
+ }
+ }
+ ]
+ }))
+ .unwrap();
+ let config_for = |external: serde_json::Value| -> ConnectionConfig {
+ serde_json::from_value(serde_json::json!({
+ "id": "plugin-connection",
+ "name": "Prod SSH",
+ "db_type": "plugin",
+ "host": "ssh.example.com",
+ "port": 22,
+ "username": "root",
+ "password": "",
+ "database": null,
+ "plugin_id": "io.dbx.ssh",
+ "plugin_connection_provider": "ssh.connection",
+ "plugin_connection_type": "ssh",
+ "external_config": external
+ }))
+ .unwrap()
+ };
+
+ // Read-only sessions ignore the sudo block: nothing is required.
+ assert!(validate_plugin_connection_values(
+ &config_for(serde_json::json!({ "sudo_source": "custom", "read_only": true })),
+ &provider
+ )
+ .is_ok());
+ // Sudo stays off: nothing is required either.
+ assert!(validate_plugin_connection_values(
+ &config_for(serde_json::json!({ "sudo_source": "none", "read_only": false })),
+ &provider
+ )
+ .is_ok());
+ // Custom sudo on a writable connection: the command becomes required.
+ assert!(validate_plugin_connection_values(
+ &config_for(serde_json::json!({ "sudo_source": "custom", "read_only": false })),
+ &provider
+ )
+ .unwrap_err()
+ .contains("Sudo command' is required"));
+ // ...and passes once it is filled in.
+ assert!(validate_plugin_connection_values(
+ &config_for(
+ serde_json::json!({ "sudo_source": "custom", "read_only": false, "sudo_command": "sudo -n true" })
+ ),
+ &provider
+ )
+ .is_ok());
+ }
}
diff --git a/crates/dbx-core/src/plugins/manifest.rs b/crates/dbx-core/src/plugins/manifest.rs
index 5c61122212..b0428f167c 100644
--- a/crates/dbx-core/src/plugins/manifest.rs
+++ b/crates/dbx-core/src/plugins/manifest.rs
@@ -5,7 +5,15 @@ use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};
pub const SUPPORTED_PLUGIN_MANIFEST_VERSION: u32 = 1;
-pub const SUPPORTED_PLUGIN_HOST_API_VERSION: &str = "1.0.0";
+/// Host API version the host advertises at `plugin/initialize`.
+///
+/// 1.1 adds the plugin-initiated `host/requestUserInput` method (see
+/// `plugins/runtime.rs`). It is additive: 1.0 plugins keep working, and a
+/// plugin that wants the capability must check the advertised version (or the
+/// `host.requestUserInput` entry in `host.features`) before calling it.
+pub const SUPPORTED_PLUGIN_HOST_API_VERSION: &str = "1.1.0";
+/// Capabilities the host advertises to a plugin backend at `plugin/initialize`.
+pub const SUPPORTED_PLUGIN_HOST_FEATURES: &[&str] = &["host.requestUserInput"];
pub const SUPPORTED_PLUGIN_PROTOCOL_VERSION: u32 = 1;
pub const PLUGIN_CONNECTION_TEST_METHOD: &str = "connection/test";
pub const PLUGIN_CONNECTION_CONNECT_METHOD: &str = "connection/connect";
@@ -16,6 +24,13 @@ pub const SUPPORTED_PLUGIN_PERMISSIONS: &[&str] = &["host.events", "host.binary"
/// Cap the number of `host.network:<origin>` entries so a manifest cannot bloat
/// the sandbox CSP or enumerate large origin lists.
pub const MAX_PLUGIN_NETWORK_ORIGINS: usize = 8;
+/// Bound the `visible_when` / `required_when` expression tree so a hostile
+/// manifest cannot make the host or the dialog evaluator do unbounded work.
+pub const MAX_PLUGIN_FIELD_CONDITION_DEPTH: usize = 8;
+pub const MAX_PLUGIN_FIELD_CONDITION_NODES: usize = 64;
+/// Cap the file filters a picker may declare so one manifest cannot bloat the
+/// native dialog or the browser `accept` attribute.
+pub const MAX_PLUGIN_PICKER_FILTERS: usize = 16;
const HOST_NETWORK_PERMISSION_PREFIX: &str = "host.network:";
/// Parse a `host.network:https://host[:port]` permission into the origin that
@@ -104,9 +119,9 @@ pub struct PluginEngines {
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginEntrypoints {
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<PluginBackendEntrypoint>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub ui: Option<PluginUiEntrypoint>,
}
@@ -157,7 +172,7 @@ pub struct PluginDriverManifest {
pub id: String,
pub label: String,
pub kind: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub database_type: Option<String>,
}
@@ -236,18 +251,27 @@ pub struct PluginFormFieldDefinition {
pub label: String,
#[serde(rename = "type")]
pub field_type: PluginFormFieldType,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub placeholder: Option<String>,
#[serde(default)]
pub required: bool,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub default: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<PluginFormFieldOption>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub binding: Option<PluginFormFieldBinding>,
+ /// Optional local-file action on a text/password/textarea field.
+ ///
+ /// Desktop (client-side) hosts open a native picker and store the chosen
+ /// **absolute path** in this field. Browser hosts cannot read a client
+ /// path, so the same action becomes an **upload**: the host reads the file
+ /// and stores its content in `content_field` instead. Contract documented
+ /// in `plugins/README.md`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub picker: Option<PluginFormFieldPicker>,
/// Plugin method returning `{ options: [{ value, label }] }`; the host
/// connection form fetches it and renders the field as a dynamic select.
/// Optional and forward/backward compatible: older hosts reject the
@@ -260,11 +284,189 @@ pub struct PluginFormFieldDefinition {
pub required_when: Option<PluginFieldCondition>,
}
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+/// A `visible_when` / `required_when` expression.
+///
+/// The legacy single-field form `{ "field": "mode", "one_of": ["custom"] }`
+/// keeps its exact meaning. Composite forms (`all_of`, `any_of`, `not`) let a
+/// manifest express combinations such as
+/// `sudo_source = custom AND read_only = false`, which a single-field
+/// condition cannot. Composite nodes nest arbitrarily; [`MAX_PLUGIN_FIELD_CONDITION_DEPTH`]
+/// bounds the evaluation cost of a hostile manifest.
+///
+/// Semantics are shared with the frontend evaluator
+/// (`apps/desktop/src/lib/plugins/pluginFieldConditions.ts`): a leaf matches
+/// when the referenced sibling field holds a non-empty value that equals one of
+/// the listed literals (compared by canonical string form, so the boolean
+/// `false` matches both the literal `false` and the literal `"false"`).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(untagged, deny_unknown_fields)]
+pub enum PluginFieldCondition {
+ /// Legacy single-field clause: `{ "field": "...", "one_of": [...] }`.
+ Field(PluginFieldConditionClause),
+ /// Every nested condition must match.
+ AllOf { all_of: Vec<PluginFieldCondition> },
+ /// At least one nested condition must match.
+ AnyOf { any_of: Vec<PluginFieldCondition> },
+ /// Inverts the nested condition.
+ Not { not: Box<PluginFieldCondition> },
+}
+
+/// The legacy single-field clause of a [`PluginFieldCondition`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
-pub struct PluginFieldCondition {
+pub struct PluginFieldConditionClause {
pub field: String,
- pub one_of: Vec<String>,
+ pub one_of: Vec<PluginFieldConditionLiteral>,
+}
+
+/// A value a manifest may list in `one_of`. Plugins mostly compare strings,
+/// but booleans and numbers are allowed so a condition can be written exactly
+/// like the value the form produces (`"read_only": [false]` instead of
+/// `["false"]`).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum PluginFieldConditionLiteral {
+ String(String),
+ Bool(bool),
+ Number(serde_json::Number),
+}
+
+impl PluginFieldConditionLiteral {
+ /// Canonical string form used for comparison. This is the rule the
+ /// frontend has always applied (`String(value)`), so every manifest written
+ /// against the string-only contract keeps matching.
+ pub fn canonical(&self) -> String {
+ match self {
+ Self::String(value) => value.clone(),
+ Self::Bool(value) => value.to_string(),
+ // `serde_json::Number` prints `22.0` for a float that JavaScript
+ // renders as `22`; normalize integral floats so the two sides agree.
+ Self::Number(value) => normalize_condition_number(value),
+ }
+ }
+}
+
+fn normalize_condition_number(number: &serde_json::Number) -> String {
+ if let Some(value) = number.as_i64() {
+ return value.to_string();
+ }
+ if let Some(value) = number.as_u64() {
+ return value.to_string();
+ }
+ if let Some(value) = number.as_f64() {
+ if value.fract() == 0.0 && value.abs() < 9_007_199_254_740_992.0 {
+ return format!("{}", value as i64);
+ }
+ }
+ number.to_string()
+}
+
+impl PluginFieldCondition {
+ /// Every sibling field key the expression reads, in declaration order.
+ /// Duplicates are preserved; callers de-duplicate when they need to.
+ pub fn referenced_fields(&self) -> Vec<&str> {
+ let mut fields = Vec::new();
+ self.collect_referenced_fields(&mut fields);
+ fields
+ }
+
+ fn collect_referenced_fields<'a>(&'a self, fields: &mut Vec<&'a str>) {
+ match self {
+ Self::Field(clause) => fields.push(clause.field.as_str()),
+ Self::AllOf { all_of } => all_of.iter().for_each(|child| child.collect_referenced_fields(fields)),
+ Self::AnyOf { any_of } => any_of.iter().for_each(|child| child.collect_referenced_fields(fields)),
+ Self::Not { not } => not.collect_referenced_fields(fields),
+ }
+ }
+
+ /// Structural validation shared by every condition site. Returns
+ /// human-readable problems without a location prefix.
+ pub fn validate(&self) -> Vec<String> {
+ let mut errors = Vec::new();
+ if self.node_count() > MAX_PLUGIN_FIELD_CONDITION_NODES {
+ errors.push(format!("condition uses more than {MAX_PLUGIN_FIELD_CONDITION_NODES} nodes"));
+ return errors;
+ }
+ self.validate_at_depth(0, &mut errors);
+ errors
+ }
+
+ fn validate_at_depth(&self, depth: usize, errors: &mut Vec<String>) {
+ if depth > MAX_PLUGIN_FIELD_CONDITION_DEPTH {
+ errors.push(format!("condition nesting exceeds {MAX_PLUGIN_FIELD_CONDITION_DEPTH} levels"));
+ return;
+ }
+ match self {
+ Self::Field(clause) => {
+ if clause.field.trim().is_empty() {
+ errors.push("condition field cannot be empty".to_string());
+ }
+ if clause.one_of.is_empty() {
+ errors.push("condition one_of cannot be empty".to_string());
+ }
+ }
+ Self::AllOf { all_of } => {
+ if all_of.is_empty() {
+ errors.push("condition all_of cannot be empty".to_string());
+ }
+ for child in all_of {
+ child.validate_at_depth(depth + 1, errors);
+ }
+ }
+ Self::AnyOf { any_of } => {
+ if any_of.is_empty() {
+ errors.push("condition any_of cannot be empty".to_string());
+ }
+ for child in any_of {
+ child.validate_at_depth(depth + 1, errors);
+ }
+ }
+ Self::Not { not } => not.validate_at_depth(depth + 1, errors),
+ }
+ }
+
+ /// Number of nodes in this expression tree (including this one).
+ pub fn node_count(&self) -> usize {
+ match self {
+ Self::Field(_) => 1,
+ Self::AllOf { all_of } => 1 + all_of.iter().map(Self::node_count).sum::<usize>(),
+ Self::AnyOf { any_of } => 1 + any_of.iter().map(Self::node_count).sum::<usize>(),
+ Self::Not { not } => 1 + not.node_count(),
+ }
+ }
+
+ /// Raw expression evaluation against a field-value reader. Visibility
+ /// cascade handling (a referenced field that is itself hidden) is applied
+ /// by callers, exactly like the single-field contract behaved.
+ pub fn matches(&self, read: &impl Fn(&str) -> Option<serde_json::Value>) -> bool {
+ match self {
+ Self::Field(clause) => {
+ let Some(value) = read(&clause.field) else {
+ return false;
+ };
+ let text = condition_value_text(&value);
+ if text.trim().is_empty() {
+ return false;
+ }
+ clause.one_of.iter().any(|literal| literal.canonical() == text)
+ }
+ Self::AllOf { all_of } => all_of.iter().all(|child| child.matches(read)),
+ Self::AnyOf { any_of } => any_of.iter().any(|child| child.matches(read)),
+ Self::Not { not } => !not.matches(read),
+ }
+ }
+}
+
+/// Canonical string form of a stored field value, mirroring the frontend
+/// (`String(value)`) so a boolean `false` and the literal `"false"` agree.
+pub fn condition_value_text(value: &serde_json::Value) -> String {
+ match value {
+ serde_json::Value::Null => String::new(),
+ serde_json::Value::String(text) => text.clone(),
+ serde_json::Value::Bool(value) => value.to_string(),
+ serde_json::Value::Number(value) => normalize_condition_number(value),
+ other => other.to_string(),
+ }
}
impl PluginFormFieldDefinition {
@@ -309,22 +511,50 @@ pub struct PluginFormFieldOption {
pub value: String,
}
+/// A file action on a plugin connection field (see
+/// [`PluginFormFieldDefinition::picker`]).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PluginFormFieldPicker {
+ pub kind: PluginFormFieldPickerKind,
+ /// File filters offered by the picker, e.g. `[".pem", ".key"]`. Entries are
+ /// extensions (`.ext`) or MIME types (`text/plain`); non-empty entries only.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub accept: Vec<String>,
+ /// Field that receives the file **content** on hosts without a client
+ /// filesystem (the browser build), which cannot produce a usable path.
+ /// Required for the picker to appear in the browser; on desktop the chosen
+ /// path goes into the declaring field and this field is cleared so the two
+ /// sources cannot disagree.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub content_field: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum PluginFormFieldPickerKind {
+ /// Pick one existing file.
+ File,
+ /// Pick one existing directory (desktop only; no browser equivalent).
+ Directory,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginConnectionProviderContribution {
pub id: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub database_type: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default)]
pub fields: Vec<PluginFormFieldDefinition>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub workbench: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub filesystem_provider: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<PluginConnectionCapability>,
@@ -351,17 +581,17 @@ pub enum PluginConnectionCapability {
pub struct PluginConnectionActionContribution {
pub id: String,
pub label: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub variant: Option<PluginConnectionActionVariant>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub when: Option<PluginConnectionActionWhen>,
#[serde(default, skip_serializing_if = "is_false")]
pub close_on_success: bool,
#[serde(default = "default_action_requires_valid_form", skip_serializing_if = "is_true")]
pub requires_valid_form: bool,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_ms: Option<u64>,
}
@@ -400,9 +630,9 @@ pub enum PluginConnectionActionWhen {
pub struct PluginWorkbenchContribution {
pub id: String,
pub label: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
@@ -414,9 +644,9 @@ pub struct PluginWorkbenchContribution {
pub struct PluginContextMenuContribution {
pub id: String,
pub label: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
/// Menu surface the item belongs to; currently only `connection`.
#[serde(default)]
@@ -430,9 +660,9 @@ pub struct PluginContextMenuContribution {
pub struct PluginResultViewContribution {
pub id: String,
pub label: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
@@ -442,13 +672,13 @@ pub struct PluginFilesystemProviderContribution {
pub id: String,
pub label: String,
pub schemes: Vec<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(default)]
pub capabilities: Vec<PluginFilesystemCapability>,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub root_uri: Option<String>,
}
@@ -979,6 +1209,78 @@ fn validate_connection_actions(
}
}
+/// A picker action only makes sense on a field the user can type into, and the
+/// field that receives uploaded content must be a declared sibling.
+fn validate_form_field_picker(
+ field: &PluginFormFieldDefinition,
+ fields: &[PluginFormFieldDefinition],
+ contribution_index: usize,
+ field_index: usize,
+ errors: &mut Vec<String>,
+) {
+ let Some(picker) = &field.picker else {
+ return;
+ };
+ let location = format!("Contribution at index {contribution_index} field {field_index} picker");
+ if !matches!(
+ field.field_type,
+ PluginFormFieldType::Text | PluginFormFieldType::Password | PluginFormFieldType::Textarea
+ ) {
+ errors.push(format!("{location} is only supported on text, password, or textarea fields"));
+ }
+ if picker.accept.len() > MAX_PLUGIN_PICKER_FILTERS {
+ errors.push(format!("{location} declares more than {MAX_PLUGIN_PICKER_FILTERS} filters"));
+ }
+ for filter in &picker.accept {
+ if !valid_picker_filter(filter) {
+ errors.push(format!("{location} filter '{filter}' must look like '.pem' or 'text/plain'"));
+ }
+ }
+ if picker.kind == PluginFormFieldPickerKind::Directory && picker.content_field.is_some() {
+ errors.push(format!("{location} cannot upload a directory into a content field"));
+ }
+ let Some(content_key) = &picker.content_field else {
+ return;
+ };
+ match fields.iter().find(|candidate| candidate.key == *content_key) {
+ None => errors.push(format!("{location} content_field references unknown field '{content_key}'")),
+ Some(content) => {
+ if content.key == field.key {
+ errors.push(format!("{location} content_field cannot be the declaring field"));
+ }
+ if !matches!(
+ content.field_type,
+ PluginFormFieldType::Text | PluginFormFieldType::Password | PluginFormFieldType::Textarea
+ ) {
+ errors.push(format!("{location} content_field '{content_key}' must be a text or textarea field"));
+ }
+ }
+ }
+}
+
+/// Accept entries are file extensions (`.pem`) or MIME types (`text/plain`), so
+/// the browser `<input accept>` attribute and the native dialog filters can use
+/// them directly. Anything else is rejected instead of silently ignored.
+fn valid_picker_filter(filter: &str) -> bool {
+ if let Some(extension) = filter.strip_prefix('.') {
+ return !extension.is_empty()
+ && extension.len() <= 16
+ && extension.chars().all(|character| character.is_ascii_alphanumeric());
+ }
+ let mut parts = filter.split('/');
+ let (Some(kind), Some(subtype), None) = (parts.next(), parts.next(), parts.next()) else {
+ return false;
+ };
+ let valid_part = |part: &str| {
+ !part.is_empty()
+ && part.len() <= 64
+ && part
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '+' | '-' | '.' | '_' | '*'))
+ };
+ valid_part(kind) && valid_part(subtype)
+}
+
fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index: usize, errors: &mut Vec<String>) {
let mut seen_keys = HashSet::new();
let field_keys = fields.iter().map(|field| field.key.as_str()).collect::<HashSet<_>>();
@@ -993,6 +1295,7 @@ fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index
&format!("Contribution at index {contribution_index} field {field_index} label"),
errors,
);
+ validate_form_field_picker(field, fields, contribution_index, field_index, errors);
for (name, condition) in
[("visible_when", field.visible_when.as_ref()), ("required_when", field.required_when.as_ref())]
@@ -1000,16 +1303,15 @@ fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index
let Some(condition) = condition else {
continue;
};
- if condition.one_of.is_empty() {
- errors.push(format!(
- "Contribution at index {contribution_index} field {field_index} {name} one_of cannot be empty"
- ));
- }
- if !field_keys.contains(condition.field.as_str()) {
- errors.push(format!(
- "Contribution at index {contribution_index} field {field_index} {name} references unknown field '{}'",
- condition.field
- ));
+ let location = format!("Contribution at index {contribution_index} field {field_index} {name}");
+ errors.extend(condition.validate().into_iter().map(|error| format!("{location} {error}")));
+ for referenced in condition.referenced_fields() {
+ // Self-references are tolerated for backward compatibility (a
+ // single-field manifest could always point a field at itself);
+ // unknown targets were already rejected by the v1 contract.
+ if !field_keys.contains(referenced) {
+ errors.push(format!("{location} references unknown field '{referenced}'"));
+ }
}
}
@@ -1713,6 +2015,55 @@ mod tests {
assert!(errors.iter().any(|error| error.contains("timeout_ms must be between")));
}
+ /// The manifest the frontend receives is a re-serialization of the parsed
+ /// manifest, so an absent optional must stay absent. Emitting `null`
+ /// instead made the connection form treat "no default" as a real `null`
+ /// value: untouched fields showed a literal "null" and a save persisted the
+ /// four-character string "null" into `connection_secrets`.
+ #[test]
+ fn serialized_form_fields_omit_absent_optionals() {
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.nulls",
+ "name": "Nulls",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "nulls.connection",
+ "label": "Nulls",
+ "database_type": "nulls",
+ "fields": [
+ { "key": "sudo_password", "label": "Sudo password", "type": "password", "binding": "secret" },
+ { "key": "with_default", "label": "With default", "type": "text", "default": "root" },
+ { "key": "explicit_null", "label": "Explicit null", "type": "text", "default": null },
+ { "key": "mode", "label": "Mode", "type": "text" }
+ ]
+ }]
+ }))
+ .unwrap();
+
+ let serialized = serde_json::to_value(&manifest).unwrap();
+ let fields = serialized["contributions"][0]["fields"].as_array().unwrap();
+
+ // A field that declares nothing optional carries none of those keys, so
+ // the frontend can never mistake "absent" for a `null` value.
+ for key in ["default", "binding", "description", "placeholder"] {
+ assert!(fields[3].get(key).is_none(), "bare field must not serialize `{key}`: {}", fields[3]);
+ }
+ // Declared values survive the round trip; an explicit `null` default
+ // means "no default" and normalizes to an absent key rather than a
+ // value the form would try to render.
+ assert_eq!(fields[0]["binding"], "secret");
+ assert_eq!(fields[1]["default"], "root");
+ assert!(fields[2].get("default").is_none());
+ // Provider-level optionals follow the same rule.
+ assert!(serialized["contributions"][0].get("icon").is_none());
+ assert!(serialized["contributions"][0].get("workbench").is_none());
+ assert!(serialized["contributions"][0].get("filesystem_provider").is_none());
+ }
+
#[test]
fn parses_form_field_conditions() {
let dir = tempfile::tempdir().unwrap();
@@ -1754,9 +2105,21 @@ mod tests {
assert!(compatibility.compatible, "{:?}", compatibility.errors);
let visible_when = provider.fields[1].visible_when.as_ref().unwrap();
- assert_eq!(visible_when.field, "mode");
- assert_eq!(visible_when.one_of, vec!["custom".to_string()]);
- assert_eq!(provider.fields[1].required_when.as_ref().unwrap().one_of, vec!["custom".to_string()]);
+ let super::PluginFieldCondition::Field(clause) = visible_when else {
+ panic!("legacy single-field condition must deserialize into the field clause");
+ };
+ assert_eq!(clause.field, "mode");
+ assert_eq!(clause.one_of, vec![super::PluginFieldConditionLiteral::String("custom".to_string())]);
+ // Serializing a legacy clause keeps the exact v1 manifest shape.
+ assert_eq!(
+ serde_json::to_value(visible_when).unwrap(),
+ serde_json::json!({ "field": "mode", "one_of": ["custom"] })
+ );
+ let required = provider.fields[1].required_when.as_ref().unwrap();
+ let super::PluginFieldCondition::Field(required_clause) = required else {
+ panic!("legacy single-field condition must deserialize into the field clause");
+ };
+ assert_eq!(required_clause.one_of, vec![super::PluginFieldConditionLiteral::String("custom".to_string())]);
}
#[test]
@@ -1815,10 +2178,222 @@ mod tests {
let compatibility = manifest.compatibility(dir.path(), "0.5.68");
assert!(!compatibility.compatible);
- assert!(compatibility.errors.iter().any(|error| error.contains("visible_when one_of cannot be empty")));
+ assert!(compatibility
+ .errors
+ .iter()
+ .any(|error| error.contains("visible_when condition one_of cannot be empty")));
assert!(compatibility
.errors
.iter()
.any(|error| error.contains("visible_when references unknown field 'missing'")));
}
+
+ #[test]
+ fn parses_composite_form_field_conditions() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.conditions",
+ "name": "Conditions",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "conditions.connection",
+ "database_type": "conditions",
+ "fields": [
+ { "key": "authentication", "label": "Auth", "type": "text" },
+ { "key": "read_only", "label": "Read only", "type": "boolean" },
+ { "key": "sudo_source", "label": "Sudo source", "type": "text" },
+ {
+ "key": "sudo_command",
+ "label": "Sudo command",
+ "type": "text",
+ "visible_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "field": "read_only", "one_of": [false] }
+ ]
+ },
+ "required_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "not": { "field": "read_only", "one_of": [true] } }
+ ]
+ }
+ }
+ ]
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.6.14");
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+
+ let provider = manifest.connection_provider("conditions.connection").unwrap().unwrap();
+ let visible_when = provider.fields[3].visible_when.as_ref().unwrap();
+ assert_eq!(visible_when.referenced_fields(), vec!["sudo_source", "read_only"]);
+ assert_eq!(visible_when.node_count(), 3);
+ assert!(matches!(visible_when, super::PluginFieldCondition::AllOf { .. }));
+ }
+
+ #[test]
+ fn rejects_malformed_composite_form_field_conditions() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.conditions",
+ "name": "Conditions",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "conditions.connection",
+ "database_type": "conditions",
+ "fields": [
+ { "key": "mode", "label": "Mode", "type": "text" },
+ {
+ "key": "empty_all_of",
+ "label": "Empty",
+ "type": "text",
+ "visible_when": { "all_of": [] }
+ },
+ {
+ "key": "unknown_nested",
+ "label": "Unknown",
+ "type": "text",
+ "required_when": { "any_of": [{ "field": "ghost", "one_of": ["x"] }] }
+ }
+ ]
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.6.14");
+ assert!(!compatibility.compatible);
+ assert!(compatibility.errors.iter().any(|error| error.contains("condition all_of cannot be empty")));
+ assert!(compatibility
+ .errors
+ .iter()
+ .any(|error| error.contains("required_when references unknown field 'ghost'")));
+ }
+
+ /// The SSH plugin asks the host for a key file: desktop hosts store the
+ /// client path, browser hosts upload the content into a paired field.
+ #[test]
+ fn parses_and_validates_file_pickers() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.ssh",
+ "name": "SSH",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "ssh.connection",
+ "label": "SSH",
+ "database_type": "ssh",
+ "fields": [
+ {
+ "key": "private_key_path",
+ "label": "Private key path",
+ "type": "text",
+ "binding": "config",
+ "picker": {
+ "kind": "file",
+ "accept": [".pem", ".key", "text/plain"],
+ "content_field": "private_key"
+ }
+ },
+ { "key": "private_key", "label": "Private key", "type": "textarea", "binding": "secret" }
+ ]
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.6.15");
+ assert!(compatibility.compatible, "{:?}", compatibility.errors);
+ let provider = manifest.connection_provider("ssh.connection").unwrap().unwrap();
+ let picker = provider.fields[0].picker.as_ref().unwrap();
+ assert_eq!(picker.kind, super::PluginFormFieldPickerKind::File);
+ assert_eq!(picker.accept, vec![".pem", ".key", "text/plain"]);
+ assert_eq!(picker.content_field.as_deref(), Some("private_key"));
+ // The picker round-trips through the manifest the UI receives.
+ let serialized = serde_json::to_value(&manifest).unwrap();
+ assert_eq!(serialized["contributions"][0]["fields"][0]["picker"]["kind"], "file");
+ }
+
+ #[test]
+ fn rejects_invalid_file_pickers() {
+ let dir = tempfile::tempdir().unwrap();
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "io.dbx.ssh",
+ "name": "SSH",
+ "version": "1.0.0",
+ "publisher": "example",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "contributions": [{
+ "type": "connection-provider",
+ "id": "ssh.connection",
+ "label": "SSH",
+ "database_type": "ssh",
+ "fields": [
+ { "key": "port", "label": "Port", "type": "number", "picker": { "kind": "file" } },
+ {
+ "key": "private_key_path",
+ "label": "Private key path",
+ "type": "text",
+ "picker": {
+ "kind": "file",
+ "accept": ["pem", ".", "text/"],
+ "content_field": "missing"
+ }
+ },
+ {
+ "key": "self_reference",
+ "label": "Self",
+ "type": "text",
+ "picker": { "kind": "file", "content_field": "self_reference" }
+ },
+ {
+ "key": "folder",
+ "label": "Folder",
+ "type": "text",
+ "picker": { "kind": "directory", "content_field": "private_key_path" }
+ },
+ { "key": "private_key", "label": "Private key", "type": "textarea", "binding": "secret" }
+ ]
+ }]
+ }))
+ .unwrap();
+
+ let compatibility = manifest.compatibility(dir.path(), "0.6.15");
+ assert!(!compatibility.compatible);
+ let errors = compatibility.errors.join("\n");
+ assert!(errors.contains("picker is only supported on text, password, or textarea fields"), "{errors}");
+ assert!(errors.contains("filter 'pem' must look like '.pem' or 'text/plain'"), "{errors}");
+ assert!(errors.contains("filter 'text/' must look like '.pem' or 'text/plain'"), "{errors}");
+ assert!(errors.contains("content_field references unknown field 'missing'"), "{errors}");
+ assert!(errors.contains("content_field cannot be the declaring field"), "{errors}");
+ assert!(errors.contains("cannot upload a directory into a content field"), "{errors}");
+ }
+
+ #[test]
+ fn rejects_unknown_keys_and_mixed_condition_shapes() {
+ // A clause may not smuggle composite keys, and a composite node may not
+ // smuggle `field`/`one_of`; both must fail to deserialize.
+ assert!(serde_json::from_value::<super::PluginFieldCondition>(serde_json::json!({
+ "field": "mode",
+ "one_of": ["custom"],
+ "all_of": [{ "field": "mode", "one_of": ["custom"] }]
+ }))
+ .is_err());
+ assert!(serde_json::from_value::<super::PluginFieldCondition>(serde_json::json!({})).is_err());
+ assert!(serde_json::from_value::<super::PluginFieldCondition>(serde_json::json!({ "not": 1 })).is_err());
+ }
}
diff --git a/crates/dbx-core/src/plugins/runtime.rs b/crates/dbx-core/src/plugins/runtime.rs
index 5074cffa56..7ada689514 100644
--- a/crates/dbx-core/src/plugins/runtime.rs
+++ b/crates/dbx-core/src/plugins/runtime.rs
@@ -11,14 +11,35 @@ use serde::{Deserialize, Serialize};
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::sync::{broadcast, oneshot, watch, Mutex, RwLock};
-use tokio::time::timeout;
+use tokio::time::Instant;
use super::{
InstalledPlugin, PluginBackendTransport, PluginRuntimeEnv, SUPPORTED_PLUGIN_HOST_API_VERSION,
- SUPPORTED_PLUGIN_PROTOCOL_VERSION,
+ SUPPORTED_PLUGIN_HOST_FEATURES, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
};
+use crate::db::ssh_prompt;
pub const PLUGIN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
+/// Host API method a plugin backend calls to ask the user for input
+/// (`user_input.rs` semantics). Plugin-initiated requests use string ids, which
+/// is what lets one stream carry both directions (see `dispatch_json`).
+pub const PLUGIN_REQUEST_USER_INPUT_METHOD: &str = "host/requestUserInput";
+/// Namespace reserved for host-initiated requests, i.e. calls a plugin makes
+/// back into the host. Plugin manifests never receive methods from it.
+pub const PLUGIN_HOST_REQUEST_PREFIX: &str = "host/";
+/// Cap on user prompts a single plugin session may have open at once, so a
+/// broken or hostile backend cannot stack dialogs.
+const MAX_PLUGIN_PROMPTS_IN_FLIGHT: usize = 4;
+/// Total time one request may spend paused on user input before it fails.
+const MAX_PROMPT_PAUSE: Duration = Duration::from_secs(600);
+const USER_INPUT_DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
+const USER_INPUT_MIN_TIMEOUT: Duration = Duration::from_secs(5);
+const USER_INPUT_MAX_TIMEOUT: Duration = Duration::from_secs(600);
+const USER_INPUT_MAX_PROMPT_CHARS: usize = 2_000;
+const USER_INPUT_MAX_TITLE_CHARS: usize = 200;
+const USER_INPUT_MAX_DEFAULT_CHARS: usize = 1_000;
+const USER_INPUT_MAX_OPTIONS: usize = 8;
+const USER_INPUT_MAX_OPTION_CHARS: usize = 200;
const MAX_JSON_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
const MAX_BINARY_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
const FRAME_KIND_JSON: u8 = 0;
@@ -93,6 +114,9 @@ struct PluginHostDescription<'a> {
dbx_version: &'a str,
host_api_version: &'static str,
protocol_versions: [u32; 1],
+ /// Host capabilities a plugin can rely on for this session. Feature names
+ /// are the Host API methods the plugin may call.
+ features: &'static [&'static str],
}
#[derive(Debug, Serialize)]
@@ -135,6 +159,45 @@ pub struct PluginSidecarSession {
binary_messages: broadcast::Sender<PluginBinaryMessage>,
status: watch::Sender<PluginSessionStatus>,
handshake: RwLock<Option<PluginHandshake>>,
+ /// Open `host/requestUserInput` prompts. While non-zero the host pauses the
+ /// request deadlines of this session so a user typing an MFA code cannot
+ /// fail a plugin `connection/test` or `connection/connect` call.
+ prompts: PromptActivity,
+}
+
+/// Tracks whether this plugin session has a user prompt open, and wakes the
+/// requests that are waiting on a response so they can start or stop pausing
+/// their deadline.
+#[derive(Default)]
+struct PromptActivity {
+ state: watch::Sender<PromptState>,
+}
+
+#[derive(Clone, Copy, Default)]
+struct PromptState {
+ open: usize,
+ closed: bool,
+}
+
+impl PromptActivity {
+ fn begin(&self) {
+ self.state.send_modify(|state| state.open += 1);
+ }
+
+ fn end(&self) {
+ self.state.send_modify(|state| state.open -= 1);
+ }
+
+ /// Releases every open prompt when the session goes away, so the dialog
+ /// does not linger in front of a plugin that can no longer answer.
+ fn close(&self) {
+ self.state.send_modify(|state| state.closed = true);
+ }
+
+ async fn wait_close(&self) {
+ let mut state = self.state.subscribe();
+ let _ = state.wait_for(|state| state.closed).await;
+ }
}
impl PluginSidecarSession {
@@ -167,6 +230,7 @@ impl PluginSidecarSession {
binary_messages,
status,
handshake: RwLock::new(None),
+ prompts: PromptActivity::default(),
});
session.spawn_stdout_reader(stdout);
@@ -285,6 +349,8 @@ impl PluginSidecarSession {
pub async fn shutdown(&self) {
self.status.send_replace(PluginSessionStatus::new(PluginSessionState::Stopping, None));
+ // Let any open user prompt resolve and close its dialog.
+ self.prompts.close();
let kill_result = self.child.lock().await.kill().await;
let message = kill_result.err().map(|error| error.to_string());
fail_pending(&self.pending, "Plugin session stopped").await;
@@ -301,6 +367,7 @@ impl PluginSidecarSession {
dbx_version: &self.app_version,
host_api_version: SUPPORTED_PLUGIN_HOST_API_VERSION,
protocol_versions: [SUPPORTED_PLUGIN_PROTOCOL_VERSION],
+ features: SUPPORTED_PLUGIN_HOST_FEATURES,
},
plugin: PluginDescription { id: &self.plugin.manifest.id, version: &self.plugin.manifest.version },
permissions: &self.plugin.manifest.permissions,
@@ -342,23 +409,86 @@ impl PluginSidecarSession {
return Err(error);
}
- let receive = async {
- receiver.await.map_err(|_| format!("Plugin '{}' response channel closed", self.plugin.manifest.id))?
- };
match timeout_duration {
- Some(duration) => match timeout(duration, receive).await {
- Ok(result) => result,
- Err(_) => {
+ Some(duration) => {
+ let result = self.await_response(receiver, method, duration).await;
+ if result.is_err() {
self.pending.lock().await.remove(&request_id);
- Err(format!(
+ }
+ result
+ }
+ None => {
+ receiver.await.map_err(|_| format!("Plugin '{}' response channel closed", self.plugin.manifest.id))?
+ }
+ }
+ }
+
+ /// Waits for a host -> plugin response under `duration`, pausing the
+ /// deadline while the plugin has a user prompt open. `connection/test` and
+ /// `connection/connect` share the connection's connect timeout, which is
+ /// far shorter than a human reading a bastion MFA challenge; without the
+ /// pause the host would time out while the user is still typing and the
+ /// answer would arrive at a dead request.
+ async fn await_response(
+ &self,
+ mut receiver: oneshot::Receiver<Result<serde_json::Value, String>>,
+ method: &str,
+ duration: Duration,
+ ) -> Result<serde_json::Value, String> {
+ let mut prompt_state = self.prompts.state.subscribe();
+ let start = Instant::now();
+ let mut paused_total = Duration::ZERO;
+ loop {
+ let state = *prompt_state.borrow_and_update();
+ if state.closed {
+ return Err("Plugin session stopped".to_string());
+ }
+ let active = start.elapsed().saturating_sub(paused_total);
+ if active >= duration {
+ return Err(format!(
+ "Plugin '{}' request '{}' timed out after {} seconds",
+ self.plugin.manifest.id,
+ method,
+ duration.as_secs()
+ ));
+ }
+ if state.open > 0 {
+ // The user is answering: hold the deadline and re-measure when
+ // the prompt state changes.
+ let tick = Instant::now();
+ tokio::select! {
+ result = &mut receiver => {
+ return result
+ .map_err(|_| format!("Plugin '{}' response channel closed", self.plugin.manifest.id))?;
+ }
+ _ = prompt_state.changed() => {}
+ }
+ paused_total += tick.elapsed();
+ if paused_total > MAX_PROMPT_PAUSE {
+ return Err(format!(
+ "Plugin '{}' request '{}' was waiting for user input for more than {} seconds",
+ self.plugin.manifest.id,
+ method,
+ MAX_PROMPT_PAUSE.as_secs()
+ ));
+ }
+ continue;
+ }
+ tokio::select! {
+ result = &mut receiver => {
+ return result
+ .map_err(|_| format!("Plugin '{}' response channel closed", self.plugin.manifest.id))?;
+ }
+ _ = prompt_state.changed() => {}
+ _ = tokio::time::sleep(duration - active) => {
+ return Err(format!(
"Plugin '{}' request '{}' timed out after {} seconds",
self.plugin.manifest.id,
method,
duration.as_secs()
- ))
+ ));
}
- },
- None => receive.await,
+ }
}
}
@@ -415,6 +545,8 @@ impl PluginSidecarSession {
Err(error) => error,
};
fail_pending(&session.pending, &message).await;
+ // A plugin that died mid-prompt can no longer answer it.
+ session.prompts.close();
if matches!(session.status().state, PluginSessionState::Stopping | PluginSessionState::Stopped) {
return;
}
@@ -466,7 +598,7 @@ impl PluginSidecarSession {
}
}
- async fn dispatch_json(&self, payload: &[u8]) -> Result<(), String> {
+ async fn dispatch_json(self: &Arc<Self>, payload: &[u8]) -> Result<(), String> {
let value: serde_json::Value = serde_json::from_slice(payload).map_err(|error| {
format!("Failed to parse plugin '{}' protocol message: {error}", self.plugin.manifest.id)
})?;
@@ -483,6 +615,23 @@ impl PluginSidecarSession {
}
return Ok(());
}
+ // Host API requests initiated by the plugin sidecar. The host owns
+ // numeric ids (its own requests and the responses to them), the plugin
+ // owns string ids, so one stream carries both directions without
+ // changing the wire format older hosts already parse. Only `host/*`
+ // methods qualify, which keeps a plugin event that happens to carry a
+ // string id on the legacy path.
+ if let Some(request_id) = value.get("id").and_then(serde_json::Value::as_str) {
+ let method = value.get("method").and_then(serde_json::Value::as_str).unwrap_or_default();
+ if method.starts_with(PLUGIN_HOST_REQUEST_PREFIX) {
+ let request_id = request_id.to_string();
+ let method = method.to_string();
+ let params = value.get("params").cloned().unwrap_or(serde_json::Value::Null);
+ let session = self.clone();
+ session.spawn_plugin_request(request_id, method, params);
+ return Ok(());
+ }
+ }
if let Some(method) = value.get("method").and_then(serde_json::Value::as_str) {
if !self.plugin.manifest.is_legacy() {
validate_protocol_name(method)?;
@@ -518,9 +667,234 @@ impl PluginSidecarSession {
let _ = self.binary_messages.send(message);
Ok(())
}
+
+ /// Answers one plugin-initiated Host API request in the background. The
+ /// stdout reader must keep draining plugin output while a prompt is open
+ /// (the plugin may still emit events), so the work is spawned instead of
+ /// being awaited inline.
+ fn spawn_plugin_request(self: &Arc<Self>, id: String, method: String, params: serde_json::Value) {
+ let session = self.clone();
+ tokio::spawn(async move {
+ let result = session.handle_plugin_request(&method, params).await;
+ if let Err(error) = session.respond_to_plugin_request(&id, result).await {
+ log::warn!("[plugin:{}] failed to answer '{method}': {error}", session.plugin.manifest.id);
+ }
+ });
+ }
+
+ /// Dispatches a Host API method a plugin called. Errors use JSON-RPC codes
+ /// so a plugin can tell "the host cannot ask the user" from "you asked for
+ /// something invalid" and degrade accordingly.
+ async fn handle_plugin_request(
+ &self,
+ method: &str,
+ params: serde_json::Value,
+ ) -> Result<serde_json::Value, PluginHostRequestError> {
+ match method {
+ PLUGIN_REQUEST_USER_INPUT_METHOD => self.request_user_input(params).await,
+ other => Err(PluginHostRequestError::method_not_found(other)),
+ }
+ }
+
+ /// `host/requestUserInput` (Host API 1.1): relay one question to the user
+ /// and return the answer. The host only carries the question and the typed
+ /// value — it never answers on the user's behalf, and without an attached
+ /// UI it fails immediately so the plugin can fail closed instead of waiting.
+ async fn request_user_input(&self, params: serde_json::Value) -> Result<serde_json::Value, PluginHostRequestError> {
+ let spec = UserInputSpec::parse(params)?;
+ let state = *self.prompts.state.borrow();
+ if state.closed {
+ return Ok(serde_json::json!({ "action": "cancel" }));
+ }
+ if state.open >= MAX_PLUGIN_PROMPTS_IN_FLIGHT {
+ return Err(PluginHostRequestError::new(
+ -32002,
+ format!("Plugin already has {MAX_PLUGIN_PROMPTS_IN_FLIGHT} input prompts open"),
+ ));
+ }
+
+ let prompt = ssh_prompt::UserInputRequest::new(spec.prompt.clone())
+ .with_title(spec.title.clone())
+ .with_source(Some(self.plugin.manifest.name.clone()))
+ .with_default(spec.default_value.clone())
+ .with_options(spec.options.clone())
+ .with_echo(spec.echo)
+ .into_request("", 0);
+ let Some(receiver) = ssh_prompt::request_ssh_prompt(prompt) else {
+ return Err(PluginHostRequestError::new(-32001, "The DBX host cannot ask the user for input right now"));
+ };
+
+ self.prompts.begin();
+ let answer = tokio::select! {
+ result = tokio::time::timeout(spec.timeout, receiver) => Some(result),
+ // Session gone: drop the receiver so the dialog is dismissed.
+ _ = self.prompts.wait_close() => None,
+ };
+ self.prompts.end();
+
+ Ok(match answer {
+ Some(Ok(Ok(answer))) => user_input_result(answer),
+ // The prompt was dismissed mid-flight (the dialog closed, the
+ // session went away) or the UI is gone: report a cancel, never a
+ // synthesized answer.
+ Some(Ok(Err(_))) | None => serde_json::json!({ "action": "cancel" }),
+ Some(Err(_)) => serde_json::json!({ "action": "timeout" }),
+ })
+ }
+
+ async fn respond_to_plugin_request(
+ &self,
+ id: &str,
+ result: Result<serde_json::Value, PluginHostRequestError>,
+ ) -> Result<(), String> {
+ let value = match result {
+ Ok(result) => serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": result }),
+ Err(error) => serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "error": { "code": error.code, "message": error.message }
+ }),
+ };
+ let payload = serde_json::to_vec(&value).map_err(|error| error.to_string())?;
+ self.write_json(&payload).await
+ }
+}
+
+/// A JSON-RPC error returned to a plugin-initiated Host API call.
+#[derive(Debug)]
+struct PluginHostRequestError {
+ code: i64,
+ message: String,
}
-async fn read_json_lines(session: &PluginSidecarSession, mut reader: BufReader<ChildStdout>) -> Result<(), String> {
+impl PluginHostRequestError {
+ fn new(code: i64, message: impl Into<String>) -> Self {
+ Self { code, message: message.into() }
+ }
+
+ fn method_not_found(method: &str) -> Self {
+ Self::new(-32601, format!("Method not found: {method}"))
+ }
+
+ fn invalid_params(message: impl Into<String>) -> Self {
+ Self::new(-32602, message)
+ }
+}
+
+/// Validated `host/requestUserInput` params. Bounded so a plugin cannot push an
+/// unbounded payload or an unusable timeout into the dialog.
+#[derive(Debug)]
+struct UserInputSpec {
+ prompt: String,
+ echo: bool,
+ title: Option<String>,
+ default_value: Option<String>,
+ options: Vec<ssh_prompt::SshPromptOption>,
+ timeout: Duration,
+}
+
+impl UserInputSpec {
+ fn parse(params: serde_json::Value) -> Result<Self, PluginHostRequestError> {
+ let object =
+ params.as_object().ok_or_else(|| PluginHostRequestError::invalid_params("params must be an object"))?;
+ let prompt = match object.get("prompt") {
+ Some(serde_json::Value::String(prompt)) if !prompt.trim().is_empty() => prompt.clone(),
+ _ => return Err(PluginHostRequestError::invalid_params("'prompt' must be a non-empty string")),
+ };
+ if prompt.chars().count() > USER_INPUT_MAX_PROMPT_CHARS {
+ return Err(PluginHostRequestError::invalid_params(format!(
+ "'prompt' must be at most {USER_INPUT_MAX_PROMPT_CHARS} characters"
+ )));
+ }
+
+ let title = optional_text(object.get("title"), "title", USER_INPUT_MAX_TITLE_CHARS)?;
+ let default_value = optional_text(object.get("default"), "default", USER_INPUT_MAX_DEFAULT_CHARS)?;
+ let echo = match object.get("echo") {
+ None | Some(serde_json::Value::Null) => false,
+ Some(serde_json::Value::Bool(echo)) => *echo,
+ Some(_) => return Err(PluginHostRequestError::invalid_params("'echo' must be a boolean")),
+ };
+
+ let mut options = Vec::new();
+ if let Some(value) = object.get("options") {
+ let list =
+ value.as_array().ok_or_else(|| PluginHostRequestError::invalid_params("'options' must be an array"))?;
+ if list.len() > USER_INPUT_MAX_OPTIONS {
+ return Err(PluginHostRequestError::invalid_params(format!(
+ "'options' supports at most {USER_INPUT_MAX_OPTIONS} entries"
+ )));
+ }
+ for entry in list {
+ let entry = entry
+ .as_object()
+ .ok_or_else(|| PluginHostRequestError::invalid_params("each option must be an object"))?;
+ let value = entry
+ .get("value")
+ .and_then(serde_json::Value::as_str)
+ .filter(|value| !value.is_empty())
+ .ok_or_else(|| PluginHostRequestError::invalid_params("each option needs a non-empty 'value'"))?;
+ let label = entry
+ .get("label")
+ .and_then(serde_json::Value::as_str)
+ .filter(|label| !label.trim().is_empty())
+ .unwrap_or(value);
+ if value.chars().count() > USER_INPUT_MAX_OPTION_CHARS
+ || label.chars().count() > USER_INPUT_MAX_OPTION_CHARS
+ {
+ return Err(PluginHostRequestError::invalid_params(format!(
+ "option values and labels must be at most {USER_INPUT_MAX_OPTION_CHARS} characters"
+ )));
+ }
+ if options.iter().any(|existing: &ssh_prompt::SshPromptOption| existing.value == value) {
+ return Err(PluginHostRequestError::invalid_params("option values must be unique"));
+ }
+ options.push(ssh_prompt::SshPromptOption { value: value.to_string(), label: label.to_string() });
+ }
+ }
+
+ let timeout = match object.get("timeoutSecs") {
+ None | Some(serde_json::Value::Null) => USER_INPUT_DEFAULT_TIMEOUT,
+ Some(value) => match value.as_u64() {
+ Some(seconds) => Duration::from_secs(seconds).clamp(USER_INPUT_MIN_TIMEOUT, USER_INPUT_MAX_TIMEOUT),
+ None => return Err(PluginHostRequestError::invalid_params("'timeoutSecs' must be a number")),
+ },
+ };
+
+ Ok(Self { prompt, echo, title, default_value, options, timeout })
+ }
+}
+
+fn optional_text(
+ value: Option<&serde_json::Value>,
+ name: &str,
+ maximum: usize,
+) -> Result<Option<String>, PluginHostRequestError> {
+ match value {
+ None | Some(serde_json::Value::Null) => Ok(None),
+ Some(serde_json::Value::String(text)) if text.chars().count() <= maximum => Ok(Some(text.clone())),
+ Some(serde_json::Value::String(_)) => {
+ Err(PluginHostRequestError::invalid_params(format!("'{name}' must be at most {maximum} characters")))
+ }
+ Some(_) => Err(PluginHostRequestError::invalid_params(format!("'{name}' must be a string"))),
+ }
+}
+
+/// Maps a user's answer to the `host/requestUserInput` result payload. Only a
+/// typed value counts as a submission: host-key wording or a dismissal is a
+/// cancel, so a plugin can never mistake "the dialog went away" for an answer.
+fn user_input_result(answer: ssh_prompt::SshPromptAnswer) -> serde_json::Value {
+ match answer {
+ ssh_prompt::SshPromptAnswer::Secret(value) => serde_json::json!({ "action": "submit", "value": value }),
+ ssh_prompt::SshPromptAnswer::Reject | ssh_prompt::SshPromptAnswer::Accept { .. } => {
+ serde_json::json!({ "action": "cancel" })
+ }
+ }
+}
+
+async fn read_json_lines(
+ session: &Arc<PluginSidecarSession>,
+ mut reader: BufReader<ChildStdout>,
+) -> Result<(), String> {
loop {
let Some(line) = read_limited_line(&mut reader, MAX_JSON_MESSAGE_BYTES)
.await
@@ -545,7 +919,7 @@ async fn read_json_lines(session: &PluginSidecarSession, mut reader: BufReader<C
}
}
-async fn read_framed(session: &PluginSidecarSession, mut stdout: ChildStdout) -> Result<(), String> {
+async fn read_framed(session: &Arc<PluginSidecarSession>, mut stdout: ChildStdout) -> Result<(), String> {
loop {
let kind = match stdout.read_u8().await {
Ok(kind) => kind,
@@ -704,11 +1078,69 @@ mod tests {
use std::time::Duration;
use super::{
- decode_response_value, read_limited_line, trim_ascii_whitespace, PluginSessionState, PluginSidecarSession,
+ decode_response_value, read_limited_line, trim_ascii_whitespace, user_input_result, PluginSessionState,
+ PluginSidecarSession, PromptActivity, UserInputSpec, USER_INPUT_DEFAULT_TIMEOUT, USER_INPUT_MAX_OPTIONS,
+ USER_INPUT_MAX_TIMEOUT, USER_INPUT_MIN_TIMEOUT,
};
use crate::plugins::{InstalledPlugin, PluginManifest, PluginRuntimeEnv};
use tokio::io::BufReader;
+ async fn assert_pending<F: std::future::Future>(mut future: std::pin::Pin<&mut F>) {
+ std::future::poll_fn(|context| {
+ assert!(future.as_mut().poll(context).is_pending());
+ std::task::Poll::Ready(())
+ })
+ .await;
+ }
+
+ #[tokio::test]
+ async fn prompt_activity_closes_all_waiters_and_stays_closed() {
+ let prompts = PromptActivity::default();
+ let first = prompts.wait_close();
+ let second = prompts.wait_close();
+ tokio::pin!(first, second);
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+
+ prompts.close();
+ tokio::time::timeout(Duration::from_secs(1), async {
+ tokio::join!(first, second);
+ })
+ .await
+ .expect("every registered waiter must observe closure");
+ prompts.begin();
+ prompts.end();
+ prompts.close();
+ tokio::time::timeout(Duration::from_secs(1), prompts.wait_close())
+ .await
+ .expect("closure must persist for late subscribers after activity changes");
+ }
+
+ #[tokio::test]
+ async fn prompt_activity_preserves_changes_between_read_and_wait() {
+ let prompts = PromptActivity::default();
+ let mut first = prompts.state.subscribe();
+ let mut second = prompts.state.subscribe();
+ for receiver in [&mut first, &mut second] {
+ assert_eq!(receiver.borrow_and_update().open, 0);
+ }
+ prompts.begin();
+ for receiver in [&mut first, &mut second] {
+ tokio::time::timeout(Duration::from_secs(1), receiver.changed()).await.unwrap().unwrap();
+ assert_eq!(receiver.borrow_and_update().open, 1);
+ }
+ prompts.end();
+ for receiver in [&mut first, &mut second] {
+ tokio::time::timeout(Duration::from_secs(1), receiver.changed()).await.unwrap().unwrap();
+ assert_eq!(receiver.borrow_and_update().open, 0);
+ }
+ prompts.close();
+ for receiver in [&mut first, &mut second] {
+ tokio::time::timeout(Duration::from_secs(1), receiver.changed()).await.unwrap().unwrap();
+ assert!(receiver.borrow_and_update().closed);
+ }
+ }
+
#[tokio::test]
async fn rejects_oversized_json_lines_before_unbounded_growth() {
let mut reader = BufReader::new(std::io::Cursor::new(b"123456\n"));
@@ -734,6 +1166,447 @@ mod tests {
assert_eq!(trim_ascii_whitespace(b" \n{}\r\n"), b"{}");
}
+ /// Installs a sidecar that forwards two questions to the host over string
+ /// ids and echoes whatever it got back, so a test can assert the Host API
+ /// answers: `host/requestUserInput` plus an unknown `host/*` method.
+ #[cfg(unix)]
+ fn write_questioning_sidecar(dir: &std::path::Path) -> std::path::PathBuf {
+ use std::os::unix::fs::PermissionsExt;
+
+ let executable = dir.join("plugin.sh");
+ std::fs::write(
+ &executable,
+ r#"#!/bin/sh
+IFS= read -r initialize
+initialize_id=$(printf '%s' "$initialize" | sed -E 's/.*"id":([0-9]+).*/\1/')
+printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"capabilities":[],"plugin":{"id":"sample.sidecar","version":"1.0.0"}}}\n' "$initialize_id"
+IFS= read -r echo_request
+echo_id=$(printf '%s' "$echo_request" | sed -E 's/.*"id":([0-9]+).*/\1/')
+printf '{"jsonrpc":"2.0","id":"prompt-1","method":"host/requestUserInput","params":{"prompt":"Verification code","echo":true}}\n'
+printf '{"jsonrpc":"2.0","id":"prompt-2","method":"host/unknown","params":{}}\n'
+IFS= read -r first_answer
+IFS= read -r second_answer
+printf '{"jsonrpc":"2.0","id":%s,"result":{"first":%s,"second":%s}}\n' "$echo_id" "$first_answer" "$second_answer"
+sleep 30
+"#,
+ )
+ .unwrap();
+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&executable, permissions).unwrap();
+ executable
+ }
+
+ #[cfg(unix)]
+ async fn questioning_session(dir: &std::path::Path) -> std::sync::Arc<PluginSidecarSession> {
+ let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
+ "manifest_version": 1,
+ "id": "sample.sidecar",
+ "name": "Sample Sidecar",
+ "version": "1.0.0",
+ "publisher": "dbx",
+ "engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
+ "entrypoints": {
+ "backend": {
+ "protocol_versions": [1],
+ "transport": "stdio-jsonl",
+ "executable": "plugin.sh"
+ }
+ }
+ }))
+ .unwrap();
+ let plugin = InstalledPlugin::new(manifest, dir.to_path_buf(), "0.6.14");
+ PluginSidecarSession::start(plugin, "0.6.14", PluginRuntimeEnv::default())
+ .await
+ .expect("v1 sidecar should initialize")
+ }
+
+ /// The sidecar echoes both answers, and the unknown method answers first, so
+ /// tests must look responses up by id instead of by position.
+ #[cfg(unix)]
+ fn echoed_answer<'a>(echoed: &'a serde_json::Value, id: &str) -> &'a serde_json::Value {
+ ["first", "second"]
+ .iter()
+ .map(|slot| &echoed[*slot])
+ .find(|response| response["id"] == id)
+ .unwrap_or_else(|| panic!("no answer for {id} in {echoed}"))
+ }
+
+ /// Installs a prompt gateway that records every request it relays and
+ /// answers after `delay` — the test-visible stand-in for the desktop dialog.
+ #[cfg(unix)]
+ fn install_prompt_harness(
+ delay: Duration,
+ answer: crate::db::ssh_prompt::SshPromptAnswer,
+ ) -> tokio::sync::mpsc::UnboundedReceiver<(
+ crate::db::ssh_prompt::SshPromptRequest,
+ crate::db::ssh_prompt::SshPromptAnswer,
+ )> {
+ use crate::db::ssh_prompt;
+
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<ssh_prompt::SshPromptEnvelope>(4);
+ ssh_prompt::install_ssh_prompt_gateway(tx);
+ let (seen_tx, seen_rx) = tokio::sync::mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ while let Some(envelope) = rx.recv().await {
+ let _ = seen_tx.send((envelope.request.clone(), answer.clone()));
+ tokio::time::sleep(delay).await;
+ let _ = envelope.responder.send(answer.clone());
+ }
+ });
+ seen_rx
+ }
+
+ /// Installs a prompt gateway that relays requests to the test and never
+ /// answers, so the test can watch what happens to a prompt nobody answers.
+ #[cfg(unix)]
+ fn install_silent_prompt_harness() -> tokio::sync::mpsc::UnboundedReceiver<(
+ crate::db::ssh_prompt::SshPromptRequest,
+ tokio::sync::oneshot::Sender<crate::db::ssh_prompt::SshPromptAnswer>,
+ )> {
+ use crate::db::ssh_prompt;
+
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<ssh_prompt::SshPromptEnvelope>(4);
+ ssh_prompt::install_ssh_prompt_gateway(tx);
+ let (seen_tx, seen_rx) = tokio::sync::mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ while let Some(envelope) = rx.recv().await {
+ let _ = seen_tx.send((envelope.request, envelope.responder));
+ }
+ });
+ seen_rx
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn fails_plugin_prompts_closed_without_a_prompt_ui() {
+ use crate::db::ssh_prompt;
+
+ let _guard = ssh_prompt::prompt_gateway_test_lock().lock().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+
+ let echoed: serde_json::Value = session
+ .invoke("sample/echo", serde_json::Value::Null)
+ .await
+ .expect("host should answer every plugin-initiated request");
+ session.shutdown().await;
+
+ // A headless host (tests, MCP) must refuse instead of hanging the
+ // plugin until the prompt timeout expires.
+ let prompt = echoed_answer(&echoed, "prompt-1");
+ assert_eq!(prompt["error"]["code"], -32001);
+ let unknown = echoed_answer(&echoed, "prompt-2");
+ assert_eq!(unknown["error"]["code"], -32601);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn relays_plugin_user_input_through_the_prompt_gateway() {
+ use crate::db::ssh_prompt::{self, SshPromptAnswer, SshPromptKind};
+
+ let _guard = ssh_prompt::prompt_gateway_test_lock().lock().await;
+ let mut prompts = install_prompt_harness(Duration::ZERO, SshPromptAnswer::Secret("123456".to_string()));
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+
+ let echoed: serde_json::Value = session
+ .invoke("sample/echo", serde_json::Value::Null)
+ .await
+ .expect("host should answer every plugin-initiated request");
+ session.shutdown().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+
+ let prompt = echoed_answer(&echoed, "prompt-1");
+ assert_eq!(prompt["result"]["action"], "submit");
+ assert_eq!(prompt["result"]["value"], "123456");
+
+ // The host relays the question and the answer, nothing else: the plugin
+ // asked, the user typed, and the host never synthesizes a value.
+ let (request, answer) = prompts.recv().await.expect("the host should relay exactly one prompt");
+ assert_eq!(request.kind, SshPromptKind::UserInput);
+ assert_eq!(request.source.as_deref(), Some("Sample Sidecar"));
+ assert_eq!(request.prompt.as_deref(), Some("Verification code"));
+ assert!(request.echo);
+ assert_eq!(answer, SshPromptAnswer::Secret("123456".to_string()));
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn reports_plugin_user_input_cancel_when_the_user_dismisses_the_prompt() {
+ use crate::db::ssh_prompt::{self, SshPromptAnswer};
+
+ let _guard = ssh_prompt::prompt_gateway_test_lock().lock().await;
+ install_prompt_harness(Duration::ZERO, SshPromptAnswer::Reject);
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+
+ let echoed: serde_json::Value = session
+ .invoke("sample/echo", serde_json::Value::Null)
+ .await
+ .expect("host should answer every plugin-initiated request");
+ session.shutdown().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+
+ let prompt = echoed_answer(&echoed, "prompt-1");
+ assert_eq!(prompt["result"]["action"], "cancel");
+ assert!(prompt["result"].get("value").is_none());
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn connection_request_timeout_pauses_while_the_user_types() {
+ use crate::db::ssh_prompt::{self, SshPromptAnswer};
+
+ let _guard = ssh_prompt::prompt_gateway_test_lock().lock().await;
+ // The user needs longer than the caller's connect timeout. `connection/
+ // test` and `connection/connect` share that timeout, so without the
+ // prompt pause the plugin would answer a request the host had already
+ // abandoned — exactly the bug this channel exists to avoid.
+ install_prompt_harness(Duration::from_millis(700), SshPromptAnswer::Secret("123456".to_string()));
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+
+ let echoed: serde_json::Value = session
+ .invoke_with_timeout("sample/echo", serde_json::Value::Null, None, Some(Duration::from_millis(300)))
+ .await
+ .expect("a prompt must pause the request deadline instead of failing it");
+ session.shutdown().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+
+ assert_eq!(echoed_answer(&echoed, "prompt-1")["result"]["value"], "123456");
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn stopping_a_plugin_session_releases_its_open_prompt() {
+ use crate::db::ssh_prompt;
+
+ let _guard = ssh_prompt::prompt_gateway_test_lock().lock().await;
+ let mut prompts = install_silent_prompt_harness();
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+
+ let caller = {
+ let session = session.clone();
+ tokio::spawn(
+ async move { session.invoke::<serde_json::Value>("sample/echo", serde_json::Value::Null).await },
+ )
+ };
+ let (request, responder) = prompts.recv().await.expect("the plugin should ask before answering");
+ assert_eq!(request.kind, crate::db::ssh_prompt::SshPromptKind::UserInput);
+ assert!(!responder.is_closed());
+
+ session.shutdown().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+
+ // The request fails (the session is gone) and the prompt's responder is
+ // dropped, which is how the dialog learns to dismiss itself instead of
+ // waiting for a plugin that will never answer.
+ let error = tokio::time::timeout(Duration::from_secs(5), async { caller.await.unwrap().unwrap_err() })
+ .await
+ .expect("stopping the session must not strand the caller");
+ assert!(error.contains("stopped") || error.contains("closed"), "{error}");
+ assert!(responder.is_closed(), "the prompt must be released when the session stops");
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn stopping_a_plugin_session_releases_all_open_prompts() {
+ use crate::db::ssh_prompt;
+
+ let _guard = ssh_prompt::prompt_gateway_test_lock().lock().await;
+ let mut prompts = install_silent_prompt_harness();
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+ let first = session.request_user_input(serde_json::json!({ "prompt": "First code" }));
+ let second = session.request_user_input(serde_json::json!({ "prompt": "Second code" }));
+ tokio::pin!(first, second);
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ let (_, first_responder) = prompts.recv().await.unwrap();
+ let (_, second_responder) = prompts.recv().await.unwrap();
+ assert!(!first_responder.is_closed());
+ assert!(!second_responder.is_closed());
+ assert_eq!(session.prompts.state.borrow().open, 2);
+
+ session.shutdown().await;
+ let (first_answer, second_answer) =
+ tokio::time::timeout(Duration::from_secs(1), async { tokio::join!(first, second) })
+ .await
+ .expect("stopping the session must cancel all prompts without waiting for their deadlines");
+ assert_eq!(first_answer.unwrap(), serde_json::json!({ "action": "cancel" }));
+ assert_eq!(second_answer.unwrap(), serde_json::json!({ "action": "cancel" }));
+ assert!(first_responder.is_closed());
+ assert!(second_responder.is_closed());
+ assert_eq!(session.prompts.state.borrow().open, 0);
+ assert_eq!(
+ session.request_user_input(serde_json::json!({ "prompt": "Too late" })).await.unwrap(),
+ serde_json::json!({ "action": "cancel" })
+ );
+ assert!(prompts.try_recv().is_err());
+ ssh_prompt::clear_ssh_prompt_gateway();
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn concurrent_response_deadlines_pause_and_resume_together() {
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+ tokio::time::pause();
+ let (_first_sender, first_receiver) = tokio::sync::oneshot::channel();
+ let (_second_sender, second_receiver) = tokio::sync::oneshot::channel();
+ let first = session.await_response(first_receiver, "sample/first", Duration::from_secs(30));
+ let second = session.await_response(second_receiver, "sample/second", Duration::from_secs(30));
+ tokio::pin!(first, second);
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+
+ tokio::time::advance(Duration::from_secs(10)).await;
+ session.prompts.begin();
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ tokio::time::advance(Duration::from_secs(60)).await;
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ session.prompts.begin();
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ session.prompts.end();
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ tokio::time::advance(Duration::from_secs(60)).await;
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ session.prompts.end();
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+
+ tokio::time::advance(Duration::from_secs(19)).await;
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ tokio::time::advance(Duration::from_secs(1)).await;
+ let (first_result, second_result) =
+ tokio::time::timeout(Duration::from_secs(1), async { tokio::join!(first, second) })
+ .await
+ .expect("every response deadline must resume when the final prompt ends");
+ for result in [first_result, second_result] {
+ assert!(result.unwrap_err().contains("timed out after 30 seconds"));
+ }
+ tokio::time::resume();
+ session.shutdown().await;
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn concurrent_paused_responses_still_accept_success_and_channel_closure() {
+ let dir = tempfile::tempdir().unwrap();
+ write_questioning_sidecar(dir.path());
+ let session = questioning_session(dir.path()).await;
+ let (first_sender, first_receiver) = tokio::sync::oneshot::channel();
+ let (second_sender, second_receiver) = tokio::sync::oneshot::channel();
+ session.prompts.begin();
+ let first = session.await_response(first_receiver, "sample/first", Duration::from_secs(30));
+ let second = session.await_response(second_receiver, "sample/second", Duration::from_secs(30));
+ tokio::pin!(first, second);
+ assert_pending(first.as_mut()).await;
+ assert_pending(second.as_mut()).await;
+ first_sender.send(Ok(serde_json::json!({ "ok": true }))).unwrap();
+ drop(second_sender);
+ assert_eq!(first.await.unwrap(), serde_json::json!({ "ok": true }));
+ assert!(second.await.unwrap_err().contains("response channel closed"));
+ session.prompts.end();
+ session.shutdown().await;
+ }
+
+ #[test]
+ fn maps_user_answers_to_host_request_user_input_results() {
+ use crate::db::ssh_prompt::SshPromptAnswer;
+
+ assert_eq!(
+ user_input_result(SshPromptAnswer::Secret("123456".to_string())),
+ serde_json::json!({ "action": "submit", "value": "123456" })
+ );
+ // Host-key wording and a dismissal are never an answer.
+ assert_eq!(user_input_result(SshPromptAnswer::Reject), serde_json::json!({ "action": "cancel" }));
+ assert_eq!(
+ user_input_result(SshPromptAnswer::Accept { remember: true }),
+ serde_json::json!({ "action": "cancel" })
+ );
+ }
+
+ #[test]
+ fn parses_and_bounds_host_request_user_input_params() {
+ let spec = UserInputSpec::parse(serde_json::json!({
+ "prompt": "Verification code",
+ "title": "Bastion MFA",
+ "secret": true,
+ "echo": true,
+ "default": "000000",
+ "options": [{ "value": "totp", "label": "TOTP" }],
+ "timeoutSecs": 90
+ }))
+ .unwrap();
+ assert_eq!(spec.prompt, "Verification code");
+ assert_eq!(spec.title.as_deref(), Some("Bastion MFA"));
+ assert_eq!(spec.default_value.as_deref(), Some("000000"));
+ assert!(spec.echo);
+ assert_eq!(spec.options.len(), 1);
+ assert_eq!(spec.options[0].value, "totp");
+ assert_eq!(spec.timeout, Duration::from_secs(90));
+
+ // An option without a label falls back to its value; the host clamps
+ // timeouts and defaults `echo` to masked input.
+ let spec = UserInputSpec::parse(serde_json::json!({
+ "prompt": "Pick one",
+ "options": [{ "value": "a" }],
+ "timeoutSecs": 1
+ }))
+ .unwrap();
+ assert_eq!(spec.options[0].label, "a");
+ assert!(!spec.echo);
+ assert_eq!(spec.timeout, USER_INPUT_MIN_TIMEOUT);
+
+ let spec = UserInputSpec::parse(serde_json::json!({
+ "prompt": "Pick one",
+ "timeoutSecs": 100_000
+ }))
+ .unwrap();
+ assert_eq!(spec.timeout, USER_INPUT_MAX_TIMEOUT);
+ assert_eq!(
+ UserInputSpec::parse(serde_json::json!({ "prompt": "x" })).unwrap().timeout,
+ USER_INPUT_DEFAULT_TIMEOUT
+ );
+
+ for invalid in [
+ serde_json::json!("not-an-object"),
+ serde_json::json!({}),
+ serde_json::json!({ "prompt": " " }),
+ serde_json::json!({ "prompt": "x".repeat(2001) }),
+ serde_json::json!({ "prompt": "x", "title": 1 }),
+ serde_json::json!({ "prompt": "x", "echo": "yes" }),
+ serde_json::json!({ "prompt": "x", "timeoutSecs": -1 }),
+ serde_json::json!({ "prompt": "x", "options": { "value": "a" } }),
+ serde_json::json!({ "prompt": "x", "options": [{ "label": "A" }] }),
+ serde_json::json!({ "prompt": "x", "options": [{ "value": "a" }, { "value": "a" }] }),
+ serde_json::json!({
+ "prompt": "x",
+ "options": (0..USER_INPUT_MAX_OPTIONS + 1).map(|index| serde_json::json!({ "value": index.to_string() })).collect::<Vec<_>>()
+ }),
+ ] {
+ let error = UserInputSpec::parse(invalid.clone()).expect_err("params should be rejected");
+ assert_eq!(error.code, -32602, "unexpected error for {invalid}: {}", error.message);
+ }
+ }
+
#[cfg(unix)]
#[tokio::test]
async fn negotiates_routes_concurrent_responses_and_forwards_events() {
diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs
index dd62acf58d..195e1d07f0 100644
--- a/crates/dbx-core/src/storage.rs
+++ b/crates/dbx-core/src/storage.rs
@@ -6730,6 +6730,58 @@ mod tests {
assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret"));
}
+ #[tokio::test]
+ async fn load_connections_preserves_opaque_null_plugin_secrets() {
+ let path = temp_db_path("plugin-null-secret");
+ let storage = Storage::open(&path).await.unwrap();
+ let mut config = mq_connection("plugin-connection", "");
+ config.name = "SSH plugin".to_string();
+ config.db_type = DatabaseType::Plugin;
+ config.driver_profile = Some("plugin".to_string());
+ config.plugin_id = Some("io.dbx.ssh".to_string());
+ config.plugin_connection_provider = Some("io.dbx.ssh.connection".to_string());
+ config.plugin_connection_type = Some("ssh".to_string());
+ config.connection_secrets.insert("sudo_password".to_string(), "null".to_string());
+ config.connection_secrets.insert("totp_secret".to_string(), "".to_string());
+ config.connection_secrets.insert("private_key_passphrase".to_string(), "real-passphrase".to_string());
+
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+ storage
+ .set_secret("plugin-connection", &plugin_connection_secret_key("totp_secret").unwrap(), "null")
+ .await
+ .unwrap();
+ let loaded = storage.load_connections().await.unwrap();
+ let secrets = &loaded[0].connection_secrets;
+ assert_eq!(secrets.len(), 3);
+ assert_eq!(secrets.get("sudo_password").map(String::as_str), Some("null"));
+ assert_eq!(secrets.get("totp_secret").map(String::as_str), Some("null"));
+ assert_eq!(secrets.get("private_key_passphrase").map(String::as_str), Some("real-passphrase"));
+ assert_eq!(
+ storage
+ .get_secret("plugin-connection", &plugin_connection_secret_key("sudo_password").unwrap())
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("null")
+ );
+ assert_eq!(
+ storage
+ .get_secret("plugin-connection", &plugin_connection_secret_key("totp_secret").unwrap())
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("null")
+ );
+ assert_eq!(storage.load_connections().await.unwrap()[0].connection_secrets, *secrets);
+ storage.save_connections(&loaded).await.unwrap();
+ assert_eq!(storage.load_connections().await.unwrap()[0].connection_secrets, *secrets);
+ drop(storage);
+ let reopened = Storage::open(&path).await.unwrap();
+ assert_eq!(reopened.load_connections().await.unwrap()[0].connection_secrets, *secrets);
+
+ let _ = std::fs::remove_file(path);
+ }
+
#[tokio::test]
async fn metadata_save_scrubs_mq_auth_token_and_preserves_existing_secret() {
let path = temp_db_path("mq-token-metadata");
diff --git a/crates/dbx-web/src/ssh_prompt.rs b/crates/dbx-web/src/ssh_prompt.rs
index 48e32274f1..2987651a33 100644
--- a/crates/dbx-web/src/ssh_prompt.rs
+++ b/crates/dbx-web/src/ssh_prompt.rs
@@ -132,9 +132,7 @@ mod tests {
port: 22,
key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()),
- previous_fingerprint: None,
- prompt: None,
- echo: false,
+ ..Default::default()
}
}
diff --git a/docs/content/docs/plugin-development.cn.mdx b/docs/content/docs/plugin-development.cn.mdx
index b742f624af..de955695a8 100644
--- a/docs/content/docs/plugin-development.cn.mdx
+++ b/docs/content/docs/plugin-development.cn.mdx
@@ -152,6 +152,51 @@ Manifest 中的路径相对于包根目录,不能以 `/` 开头、不能包含
每个字段必须声明 `key`、`label`、`type`,可选 `description`、`placeholder`、`required`、`default`、`options` 和 `binding`;默认值必须符合字段类型。省略 binding 的 `password` 字段默认按 `secret` 处理。`database_type` 是插件自定义类型标识,不会给 DBX 内置数据库枚举添加成员。
+字段还支持条件显隐/条件必填。`visible_when` 与 `required_when` 接受单条子句 `{ "field": "mode", "one_of": ["custom"] }`(引用字段取到列表中的值时命中,按字符串比较,因此 `[false]` 与 `["false"]` 都能匹配布尔 `false`),并用 `all_of` / `any_of` / `not` 组合:
+
+```json
+{
+ "key": "sudo_command",
+ "label": "Sudo command",
+ "type": "text",
+ "visible_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "field": "read_only", "one_of": [false] }
+ ]
+ }
+}
+```
+
+条件会级联:子句引用的字段自身处于隐藏状态时该子句不参与判定,因此隐藏容器的默认值不会把孙级字段点亮;未填写或空值永不命中;组合树最多 8 层、64 个节点。DBX 在对话框与保存/测试/连接校验中使用同一套求值,不会出现「表单放行、宿主拒绝」的分歧。
+
+`text`、`password`、`textarea` 字段可以用 `picker` 声明**本机文件选择**(例如 SSH 私钥、keystore):
+
+```json
+{
+ "key": "private_key_path",
+ "label": "Private key path",
+ "type": "text",
+ "binding": "config",
+ "picker": { "kind": "file", "accept": [".pem", ".key"], "content_field": "private_key" }
+}
+```
+
+桌面端打开系统文件选择器,把选中的**绝对路径**写回该字段(插件后端同机运行,可自行读取文件);网页端拿不到客户端路径,同一操作变成**上传**:DBX 读取文件内容写入声明的 `content_field` 兄弟字段,并清空路径字段。两者互相清除——选了路径就丢弃已上传内容,上传内容就清空路径,避免同时存在两份互相矛盾的来源。`kind` 还支持 `directory`(仅桌面端),`accept` 最多 16 条扩展名或 MIME 过滤,上传上限 1 MiB。
+
+插件在连接过程中需要用户输入时(堡垒机登录期 keyboard-interactive 验证码、主机密钥确认、账号选择等),可以调用 Host API 1.1 新增的 `host/requestUserInput`,通过 DBX 同一个阻塞对话框拿到用户输入,`连接测试` 与真实连接走同一条通道:
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": "prompt-1",
+ "method": "host/requestUserInput",
+ "params": { "prompt": "Verification code (6 digits)", "title": "JumpServer login", "echo": false, "timeoutSecs": 300 }
+}
+```
+
+返回值为 `{ "action": "submit", "value": "123456" }`、`{ "action": "cancel" }` 或 `{ "action": "timeout" }`;只有 `submit` 带值,其余必须按「没有答案」处理并失败关闭。插件发起的请求使用字符串 id,DBX 自己的请求与响应继续使用数字 id;提示期间 DBX 会暂停等待该回答的请求超时计时,用户输入验证码不会被误判成连接超时。错误码 `-32001` 表示没有可用的用户界面(headless/MCP),`-32602` 参数非法,`-32601` 宿主不支持该方法,三种情况都要优雅降级。调用前请确认 `plugin/initialize` 通告的 `hostApiVersion` 为 `1.1.0`(或 `host.features` 含 `host.requestUserInput`);Rust SDK 对应 `dbx_plugin_sdk::host_client()` 与 `HostClient::supports("host/requestUserInput")`、`HostClient::request_user_input(&UserInputPrompt::secret("Verification code"))`。
+
连接生命周期使用固定的 `connection/test`、`connection/connect`、`connection/disconnect`,自定义表单动作使用 `connection/action`,参数包含 `provider`、`connection`、`runtime`;动作额外包含 `action: { id }`。后端使用 `connection.id` 保存会话,并使用 `runtime.host`/`runtime.port` 连接经过 DBX 隧道或代理转换后的端点。仅在后端生命周期请求中接收补齐 Secret 的连接;前端通过 `connectionId` 使用已经建立的会话。
动作的 `when` 可为 `always`、`create`、`edit`;`variant` 可为 `default`、`outline`、`secondary`、`destructive`、`ghost`;`timeout_ms` 为 1–120000。`requires_valid_form` 决定是否要求完整表单,`close_on_success` 决定成功后是否关闭。返回 `{ "success": true, "message": "...", "fieldValues": { "port": 443 } }` 可以更新已声明的字段;返回 `success: false` 表示失败。
diff --git a/docs/content/docs/plugin-development.mdx b/docs/content/docs/plugin-development.mdx
index be14fbf3c6..44402c72b5 100644
--- a/docs/content/docs/plugin-development.mdx
+++ b/docs/content/docs/plugin-development.mdx
@@ -152,6 +152,51 @@ Field types are `text`, `password`, `number`, `boolean`, `select`, `radio`, and
Fields require `key`, `label`, and `type`; optional fields are `description`, `placeholder`, `required`, `default`, `options`, and `binding`. Defaults must match the field type. A password field without an explicit binding defaults to `secret`. `database_type` is a plugin-defined identifier, not an extension to DBX's built-in database enum.
+Fields can also be conditional. `visible_when` and `required_when` take a clause `{ "field": "mode", "one_of": ["custom"] }` — matching when the sibling holds one of the listed values, compared as strings so `[false]` and `["false"]` both match a boolean `false` — and compose clauses with `all_of`, `any_of`, and `not`:
+
+```json
+{
+ "key": "sudo_command",
+ "label": "Sudo command",
+ "type": "text",
+ "visible_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "field": "read_only", "one_of": [false] }
+ ]
+ }
+}
+```
+
+Conditions cascade: while the field a clause reads is hidden, the clause does not count, so a hidden option's stored default never surfaces a grandchild field. DBX evaluates the same expression for the dialog and for save/test/connect validation, an unset or empty value never matches, and composite trees are capped at 8 levels and 64 nodes.
+
+Text, password, and textarea fields can offer a **local file action** — for example an SSH private key or a keystore — with `picker`:
+
+```json
+{
+ "key": "private_key_path",
+ "label": "Private key path",
+ "type": "text",
+ "binding": "config",
+ "picker": { "kind": "file", "accept": [".pem", ".key"], "content_field": "private_key" }
+}
+```
+
+The desktop app opens a native picker and stores the chosen absolute path, which the plugin backend (same machine) can read. The browser build cannot resolve a client path, so the action becomes an upload: DBX reads the file and stores its content in the declared `content_field` sibling, and clears the path field — picking a path clears the uploaded content and vice versa, so the two alternatives never disagree. `kind` also accepts `directory` (desktop only), `accept` takes up to 16 extension or MIME filters, and uploads are capped at 1 MiB.
+
+When a plugin needs the user mid-flight — a bastion's keyboard-interactive MFA code, a host-key confirmation, a choice of account — it can call the Host API method `host/requestUserInput` (Host API 1.1) and receive the typed answer. The request goes through the same blocking dialog DBX uses for its own prompts, including during `connection/test` and `connection/connect`:
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": "prompt-1",
+ "method": "host/requestUserInput",
+ "params": { "prompt": "Verification code (6 digits)", "title": "JumpServer login", "echo": false, "timeoutSecs": 300 }
+}
+```
+
+The result is `{ "action": "submit", "value": "123456" }`, `{ "action": "cancel" }`, or `{ "action": "timeout" }`; only `submit` carries a value and the plugin must fail closed on the other two. Plugin-initiated requests use string ids while DBX keeps numeric ids, and DBX pauses the request deadline of the call waiting on a prompt, so a user typing a code is not mistaken for a connect timeout. An error code of `-32001` means no user interface is attached (headless/MCP), `-32602` invalid params, `-32601` unsupported method — degrade gracefully in every case. Gate the call on `plugin/initialize` advertising `hostApiVersion` `1.1.0` (or `host.requestUserInput` in `host.features`). With the Rust SDK that is `HostClient::supports("host/requestUserInput")` plus `HostClient::request_user_input(&UserInputPrompt::secret("Verification code"))` from `dbx_plugin_sdk::host_client()`.
+
The fixed lifecycle methods are `connection/test`, `connection/connect`, and `connection/disconnect`; custom form actions use `connection/action`. Parameters include `provider`, `connection`, and `runtime`, plus `action: { id }` for actions. Keep sessions keyed by `connection.id` and connect to `runtime.host`/`runtime.port`, which include DBX tunnel/proxy resolution. Hydrated secrets are provided only to backend lifecycle requests; the frontend uses `connectionId` to access an established session.
Action `when` accepts `always`, `create`, or `edit`; `variant` accepts `default`, `outline`, `secondary`, `destructive`, or `ghost`; `timeout_ms` is 1–120000. `requires_valid_form` requires a complete form and `close_on_success` closes the dialog on success. Return `{ "success": true, "message": "...", "fieldValues": { "port": 443 } }` to update declared fields; `success: false` is a failure.
diff --git a/plugins/README.md b/plugins/README.md
index 627568e64d..16e31c312c 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -222,6 +222,58 @@ Field bindings:
Password fields default to `secret` when `binding` is omitted. DBX validates required values and value types before calling the plugin. The plugin receives the hydrated connection only in its backend lifecycle request; the workbench UI receives a connection ID and non-secret navigation context.
+Absent optional fields stay absent: when DBX hands the manifest to its own UI it omits `description`, `placeholder`, `default`, and `binding` for fields that do not declare them, and `"default": null` means "no default" exactly like omitting the key. Treat a missing value as unset — never as an empty string, and never as the literal text `null`, which is not a storable plugin value.
+
+#### Local file fields
+
+A `text`, `password`, or `textarea` field may declare `picker` when the user should choose a local file (private keys, keystores, credential files):
+
+```json
+{
+ "key": "private_key_path",
+ "label": "Private key path",
+ "type": "text",
+ "binding": "config",
+ "picker": { "kind": "file", "accept": [".pem", ".key", ".ppk"], "content_field": "private_key" }
+}
+```
+
+- **Desktop hosts** open a native picker and store the chosen **absolute path** in the declaring field. The plugin backend runs on the same machine, so it can read the file itself.
+- **Browser hosts** cannot resolve a path on the user's machine, so the same action becomes an **upload**: DBX reads the selected file and stores its **content** in `content_field` (which must be a declared `text` / `password` / `textarea` sibling), and clears the declaring field. A picker without `content_field` is therefore desktop-only and stays hidden in the browser.
+- Switching source clears the other one: choosing a path removes the uploaded content and vice versa. This matters for fields that are alternatives — a plugin that prefers `private_key` content over `private_key_path` must not keep serving a stale upload after the user re-picked a path.
+- `kind` is `file` (default use case) or `directory` (desktop-only: a browser cannot hand a folder to the plugin). `accept` lists up to 16 filters as extensions (`.pem`) or MIME types (`text/plain`) and is passed to the native dialog and the browser file input unchanged. Uploads are capped at 1 MiB.
+
+`picker` is additive; hosts older than the release that ships it reject the manifest, so keep `engines.dbx` at or above that release when the form relies on it.
+
+#### Conditional fields
+
+A field may declare `visible_when` and `required_when`. A leaf clause matches when the referenced sibling field holds a non-empty value listed in `one_of`; listed values may be strings, numbers, or booleans and are compared by canonical string form, so `false` and `"false"` both match a boolean `false`. Clauses compose with `all_of`, `any_of`, and `not`:
+
+```json
+{
+ "key": "sudo_command",
+ "label": "Sudo command",
+ "type": "text",
+ "visible_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "field": "read_only", "one_of": [false] }
+ ]
+ },
+ "required_when": {
+ "all_of": [
+ { "field": "sudo_source", "one_of": ["custom"] },
+ { "not": { "field": "read_only", "one_of": [true] } }
+ ]
+ }
+}
+```
+
+- `all_of` / `any_of` must contain at least one nested condition, nesting is limited to 8 levels and 64 nodes, and every referenced field must be a sibling declared by the same provider.
+- Conditions cascade: while the field a clause reads is itself hidden, the clause does not count. A hidden container's stored default therefore cannot surface a grandchild field, and a hidden operand of `not` keeps the field dormant instead of lighting it up.
+- DBX evaluates the same conditions for the dialog and for save/test/connect validation, so a manifest can never produce a form DBX itself rejects.
+- Composite conditions were added after the single-clause contract; keep `engines.dbx` at or above the DBX release that ships them if the form relies on them.
+
Lifecycle methods receive:
```json
@@ -385,6 +437,36 @@ Every entry has `name`, canonical `uri`, `kind` (`file`, `directory`, `symlink`,
Mutation methods return `{ success, message?, entry? }` and are rejected unless the provider declares the matching capability. Inline read/write payloads are capped at 4 MiB. The built-in file manager currently owns directory navigation, pagination, and bounded file preview. Large upload/download and PTY/SFTP streams use `stdio-framed` binary channels with plugin-defined transfer methods, chunk acknowledgements, cancellation, and progress events; they must not be encoded as one large JSON value.
+### Host API methods a plugin may call
+
+Plugins normally answer requests, but Host API 1.1 adds one method a plugin backend may call back into DBX. Plugin-initiated requests use **string** ids (`"prompt-1"`), while DBX-owned requests and their responses keep numeric ids, so one stream carries both directions and older hosts that only understand numeric ids ignore the new frames instead of failing.
+
+- `host/requestUserInput` asks the user a question through the DBX UI and returns the answer. It is the channel for anything the host cannot answer on the user's behalf: a bastion's keyboard-interactive MFA code, a one-time approval, a host-key confirmation, or a choice between accounts.
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": "prompt-1",
+ "method": "host/requestUserInput",
+ "params": {
+ "prompt": "Verification code (6 digits)",
+ "title": "JumpServer login",
+ "echo": false,
+ "default": "000000",
+ "options": [{ "value": "jinpy", "label": "jinpy (admin)" }],
+ "timeoutSecs": 300
+ }
+}
+```
+
+- `prompt` is required (≤2000 characters). `title` (≤200), `default` (≤1000), and `options` (≤8 entries, unique values, ≤200 characters each) are optional; `echo` defaults to `false`, so the dialog masks input unless the plugin says otherwise. `timeoutSecs` is clamped to 5-600 and defaults to 300.
+- The result is `{ "action": "submit", "value": "123456" }`, `{ "action": "cancel" }`, or `{ "action": "timeout" }`. Only `submit` carries a value; treat `cancel` and `timeout` as "no answer" and fail closed — never fall back to a guess.
+- The prompt is delivered through the same blocking dialog the host uses for its own host-key and keyboard-interactive prompts, so it also appears for `connection/test` and `connection/connect`. While a prompt is open DBX pauses the request deadline of the call that is waiting on it, so a user typing a code is never mistaken for a connect timeout.
+- Errors come back as JSON-RPC errors: `-32001` means no user interface is attached (headless/MCP runs, or the desktop dialog is not mounted), `-32602` means the params are invalid, `-32601` means the host does not implement the method. A plugin must degrade gracefully on all three instead of blocking forever.
+- DBX answers only with what the user typed. It never auto-fills, caches, or logs the value, and it allows at most four open prompts per plugin session.
+- Capability gating: `plugin/initialize` advertises `host.hostApiVersion` (`1.1.0` or later) and `host.features` (containing `host.requestUserInput` when available). Only call the method when it is advertised; an older host reports `1.0.0` and drops the frame.
+- The Rust SDK (`dbx-plugin-sdk`) wraps this: `dbx_plugin_sdk::host_client()`, `HostClient::supports("host/requestUserInput")`, and `HostClient::request_user_input(&UserInputPrompt::secret("Verification code"))`.
+
## Backend protocol
The backend is a persistent child process with stdin/stdout reserved for the DBX protocol. Diagnostics must go to stderr.
diff --git a/plugins/manifest.schema.json b/plugins/manifest.schema.json
index 16320e9e9c..9661ce13f9 100644
--- a/plugins/manifest.schema.json
+++ b/plugins/manifest.schema.json
@@ -104,6 +104,32 @@
"value": { "type": "string" }
}
},
+ "fieldPicker": {
+ "description": "Local-file action on a text/password/textarea field. Desktop hosts store the chosen absolute path in the declaring field; browser hosts cannot read a client path and upload the file content into 'content_field' instead.",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["kind"],
+ "properties": {
+ "kind": {
+ "description": "'directory' is desktop-only: a browser cannot hand a folder to the plugin.",
+ "enum": ["file", "directory"]
+ },
+ "accept": {
+ "description": "Filters offered by the picker: file extensions ('.pem') or MIME types ('text/plain').",
+ "type": "array",
+ "maxItems": 16,
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "pattern": "^(\\.[A-Za-z0-9]{1,16}|[A-Za-z0-9+*._-]{1,64}/[A-Za-z0-9+*._-]{1,64})$"
+ }
+ },
+ "content_field": {
+ "description": "Declared sibling field that receives the file content on hosts without a client filesystem.",
+ "$ref": "#/$defs/identifier"
+ }
+ }
+ },
"formFieldLocalization": {
"type": "object",
"additionalProperties": false,
@@ -142,12 +168,64 @@
}
},
"fieldCondition": {
+ "oneOf": [
+ { "$ref": "#/$defs/fieldConditionClause" },
+ { "$ref": "#/$defs/fieldConditionAllOf" },
+ { "$ref": "#/$defs/fieldConditionAnyOf" },
+ { "$ref": "#/$defs/fieldConditionNot" }
+ ]
+ },
+ "fieldConditionClause": {
"type": "object",
"additionalProperties": false,
"required": ["field", "one_of"],
"properties": {
"field": { "$ref": "#/$defs/identifier" },
- "one_of": { "type": "array", "items": { "type": "string" }, "minItems": 1 }
+ "one_of": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "description": "Compared against the referenced field's value by canonical string form, so `false` and `\"false\"` both match a boolean false.",
+ "type": ["string", "boolean", "number"]
+ }
+ }
+ }
+ },
+ "fieldConditionAllOf": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["all_of"],
+ "properties": {
+ "all_of": {
+ "description": "Matches only when every nested condition matches.",
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#/$defs/fieldCondition" }
+ }
+ }
+ },
+ "fieldConditionAnyOf": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["any_of"],
+ "properties": {
+ "any_of": {
+ "description": "Matches when at least one nested condition matches.",
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#/$defs/fieldCondition" }
+ }
+ }
+ },
+ "fieldConditionNot": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["not"],
+ "properties": {
+ "not": {
+ "description": "Inverts the nested condition.",
+ "$ref": "#/$defs/fieldCondition"
+ }
}
},
"formField": {
@@ -164,6 +242,7 @@
"default": { "type": ["string", "number", "boolean", "null"] },
"options": { "type": "array", "items": { "$ref": "#/$defs/selectOption" } },
"binding": { "enum": ["config", "secret", "name", "host", "port", "username", "password", "database"] },
+ "picker": { "$ref": "#/$defs/fieldPicker" },
"visible_when": { "$ref": "#/$defs/fieldCondition" },
"required_when": { "$ref": "#/$defs/fieldCondition" }
},
diff --git a/plugins/sdk/dev-host/sidecar.mjs b/plugins/sdk/dev-host/sidecar.mjs
index 172cfd64dc..5b3ab4a014 100644
--- a/plugins/sdk/dev-host/sidecar.mjs
+++ b/plugins/sdk/dev-host/sidecar.mjs
@@ -113,6 +113,26 @@ export class Sidecar extends EventEmitter {
const message = packet.message;
if (message.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC message");
if (message.id !== undefined) {
+ // Host API 1.1: a plugin may call back into the host with a *string*
+ // id. The dev host has no user interface, so answer like a headless
+ // host does and never leave the plugin waiting for a dialog.
+ if (typeof message.id === "string" && message.method) {
+ void this.write(
+ 0,
+ Buffer.from(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ id: message.id,
+ error: {
+ code: -32001,
+ message: `The DBX development host cannot answer '${message.method}': run the plugin in DBX to reach the user interface`,
+ },
+ }),
+ ),
+ ).catch(() => undefined);
+ this.emit("diagnostic", { level: "info", message: "宿主请求无法在开发宿主中应答", details: { method: protocolName(message.method) } });
+ return;
+ }
const waiter = this.pending.get(message.id);
if (!waiter) return;
this.pending.delete(message.id);
diff --git a/plugins/sdk/dev-host/tests/echo-sidecar.mjs b/plugins/sdk/dev-host/tests/echo-sidecar.mjs
index e880bca09f..395220787f 100644
--- a/plugins/sdk/dev-host/tests/echo-sidecar.mjs
+++ b/plugins/sdk/dev-host/tests/echo-sidecar.mjs
@@ -5,8 +5,16 @@ const send = (message) => {
const bytes = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...message }));
process.stdout.write(jsonl ? Buffer.concat([bytes, Buffer.from("\n")]) : frame(0, bytes));
};
+let pendingAsk = null;
const decoder = new (jsonl ? JsonLineDecoder : FrameDecoder)((packet) => {
if (packet.kind === 1) return process.stdout.write(frame(1, binaryPayload(packet.channel, packet.data)));
+ // Host API 1.1: the dev host answers a plugin-initiated (string-id) request
+ // with an error, which this sidecar forwards as the `ask-user` result.
+ if (packet.message.id === "plugin-1") {
+ const waiting = pendingAsk;
+ pendingAsk = null;
+ return send({ id: waiting, result: packet.message });
+ }
const { id, method, params } = packet.message;
if (method === "plugin/initialize") return send({ id, result: { protocolVersion: 1, plugin: { id: "example.echo", version: "1.0.0" } } });
if (method === "die") return process.exit(1);
@@ -18,6 +26,12 @@ const decoder = new (jsonl ? JsonLineDecoder : FrameDecoder)((packet) => {
if (method === "emit") return send({ method: "example/event", params });
if (method === "fail") return send({ id, error: { code: -32000, message: "Example failure", data: { category: "example" } } });
if (method === "slow") return setTimeout(() => send({ id, result: params }), 80);
+ // Plugins ask the user through string ids. The dev host has no UI, so it must
+ // answer instead of leaving the plugin waiting.
+ if (method === "ask-user") {
+ pendingAsk = id;
+ return send({ id: "plugin-1", method: "host/requestUserInput", params: { prompt: "Verification code" } });
+ }
if (id !== undefined) send({ id, result: method.startsWith("connection/") ? { success: true } : params });
});
process.stdin.on("data", (data) => decoder.push(data));
diff --git a/plugins/sdk/dev-host/tests/sidecar.test.mjs b/plugins/sdk/dev-host/tests/sidecar.test.mjs
index 8fb23887fe..2cec6d5626 100644
--- a/plugins/sdk/dev-host/tests/sidecar.test.mjs
+++ b/plugins/sdk/dev-host/tests/sidecar.test.mjs
@@ -130,3 +130,16 @@ test("JSONL supports split lines, concurrent RPC, events and rejects binary chan
assert.equal((await event)[0].params.ok, true);
await assert.rejects(sidecar.sendBinary("bytes", Buffer.from("data")), /framed/);
});
+
+test("answers plugin-initiated host requests instead of leaving them pending", async (t) => {
+ // Host API 1.1 lets a plugin ask the user through `host/requestUserInput`
+ // (string ids). The dev host has no dialog, so it must fail that call fast
+ // rather than let the plugin block until its own timeout.
+ const sidecar = new Sidecar(config);
+ t.after(() => sidecar.stop());
+ await sidecar.start();
+ const answer = await sidecar.request("ask-user");
+ assert.equal(answer.id, "plugin-1");
+ assert.equal(answer.error.code, -32001);
+ assert.match(answer.error.message, /host\/requestUserInput/);
+});
diff --git a/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs b/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs
index 767336b9b6..c8381d8902 100644
--- a/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs
+++ b/plugins/sdk/rust/dbx-plugin-sdk/src/lib.rs
@@ -1,6 +1,9 @@
+use std::collections::HashMap;
use std::io::{self, BufRead, BufReader, Read, Write};
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
+use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -11,6 +14,12 @@ const MAX_BINARY_BYTES: usize = 64 * 1024 * 1024;
const FRAME_KIND_JSON: u8 = 0;
const FRAME_KIND_BINARY: u8 = 1;
const DEFAULT_WORK_QUEUE_CAPACITY: usize = 256;
+/// How long a plugin waits for a host answer before giving up. User prompts are
+/// bounded by their own `timeoutSecs`, so the default covers one prompt plus a
+/// little slack.
+const DEFAULT_HOST_REQUEST_TIMEOUT: Duration = Duration::from_secs(330);
+/// Host API method that relays a question to the DBX user interface.
+pub const HOST_REQUEST_USER_INPUT_METHOD: &str = "host/requestUserInput";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginTransport {
@@ -124,22 +133,307 @@ impl PluginEmitter {
if payload.len() > MAX_JSON_BYTES {
return Err(PluginError::new(-32600, "JSON message is too large"));
}
- let mut output = self.output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
- match self.transport {
- PluginTransport::JsonLines => {
- output.write_all(&payload).map_err(io_error)?;
- output.write_all(b"\n").map_err(io_error)?;
+ write_json_frame(&self.output, self.transport, &payload)
+ }
+}
+
+fn write_json_frame(
+ output: &Arc<Mutex<Box<dyn Write + Send>>>,
+ transport: PluginTransport,
+ payload: &[u8],
+) -> Result<(), PluginError> {
+ let mut output = output.lock().map_err(|_| PluginError::new(-32000, "Plugin output lock is poisoned"))?;
+ match transport {
+ PluginTransport::JsonLines => {
+ output.write_all(payload).map_err(io_error)?;
+ output.write_all(b"\n").map_err(io_error)?;
+ }
+ PluginTransport::Framed => {
+ output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?;
+ output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?;
+ output.write_all(payload).map_err(io_error)?;
+ }
+ }
+ output.flush().map_err(io_error)
+}
+
+/// A question the plugin asks the user through the host, e.g. a bastion's
+/// keyboard-interactive MFA challenge or a host-key confirmation. Serializes
+/// into the `host/requestUserInput` params of Host API 1.1.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UserInputPrompt {
+ /// Text the user answers, already localized by the plugin.
+ pub prompt: String,
+ /// Optional heading shown above `prompt`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title: Option<String>,
+ /// Show the typed characters (defaults to masked input).
+ #[serde(default)]
+ pub echo: bool,
+ /// Preset answer the user may keep or replace.
+ #[serde(rename = "default", skip_serializing_if = "Option::is_none")]
+ pub default_value: Option<String>,
+ /// Fixed answers; leave empty for free-form input (at most 8).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub options: Vec<UserInputOption>,
+ /// How long the user has to answer, in seconds (host clamps to 5..600).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub timeout_secs: Option<u64>,
+}
+
+/// One fixed answer of a [`UserInputPrompt`].
+#[derive(Debug, Clone, Serialize)]
+pub struct UserInputOption {
+ pub value: String,
+ pub label: String,
+}
+
+impl UserInputPrompt {
+ /// A masked free-form question (verification codes, passwords, tokens).
+ pub fn secret(prompt: impl Into<String>) -> Self {
+ Self { prompt: prompt.into(), title: None, echo: false, default_value: None, options: Vec::new(), timeout_secs: None }
+ }
+
+ /// A question whose answer is visible while typing (account names, paths).
+ pub fn text(prompt: impl Into<String>) -> Self {
+ Self { echo: true, ..Self::secret(prompt) }
+ }
+
+ /// A multiple-choice question; the host shows the options as buttons.
+ pub fn choice(prompt: impl Into<String>, options: Vec<UserInputOption>) -> Self {
+ Self { options, ..Self::text(prompt) }
+ }
+
+ pub fn with_title(mut self, title: impl Into<String>) -> Self {
+ self.title = Some(title.into());
+ self
+ }
+
+ pub fn with_default(mut self, value: impl Into<String>) -> Self {
+ self.default_value = Some(value.into());
+ self
+ }
+
+ pub fn with_timeout_secs(mut self, seconds: u64) -> Self {
+ self.timeout_secs = Some(seconds);
+ self
+ }
+}
+
+/// The user's answer to a [`UserInputPrompt`].
+#[derive(Debug, Clone, Deserialize)]
+pub struct UserInputAnswer {
+ /// `submit`, `cancel`, or `timeout`.
+ pub action: String,
+ /// The typed value or chosen option value; only present on `submit`.
+ #[serde(default)]
+ pub value: Option<String>,
+}
+
+impl UserInputAnswer {
+ /// The submitted value, or `None` when the user cancelled and the host gave
+ /// up waiting. Callers must fail closed on `None`.
+ pub fn submitted(&self) -> Option<&str> {
+ if self.action == "submit" {
+ self.value.as_deref()
+ } else {
+ None
+ }
+ }
+
+ pub fn is_cancelled(&self) -> bool {
+ self.action == "cancel"
+ }
+
+ pub fn is_timeout(&self) -> bool {
+ self.action == "timeout"
+ }
+}
+
+/// What the host told the plugin about itself at `plugin/initialize`.
+#[derive(Debug, Default, Clone)]
+struct HostDescription {
+ api_version: Option<String>,
+ features: Vec<String>,
+}
+
+/// Client for Host API methods the plugin calls back into DBX. Create it by
+/// running a [`PluginServer`]; [`host_client`] returns the running instance.
+///
+/// Calls block the calling thread until the host answers, so call them from a
+/// plugin worker (a `connection/connect` handler is already one) rather than
+/// from the thread that runs the server loop. While a user prompt is open the
+/// host pauses the deadline of the request that is waiting on it, so a human
+/// typing an MFA code is never mistaken for a connect timeout.
+#[derive(Clone)]
+pub struct HostClient {
+ output: Arc<Mutex<Box<dyn Write + Send>>>,
+ transport: PluginTransport,
+ pending: Arc<Mutex<HashMap<String, mpsc::Sender<Result<Value, PluginError>>>>>,
+ next_request_id: Arc<AtomicU64>,
+ host: Arc<Mutex<HostDescription>>,
+}
+
+impl HostClient {
+ fn new(output: Arc<Mutex<Box<dyn Write + Send>>>, transport: PluginTransport) -> Self {
+ Self {
+ output,
+ transport,
+ pending: Arc::new(Mutex::new(HashMap::new())),
+ next_request_id: Arc::new(AtomicU64::new(1)),
+ host: Arc::new(Mutex::new(HostDescription::default())),
+ }
+ }
+
+ /// Host API version DBX reported at `plugin/initialize`.
+ pub fn host_api_version(&self) -> Option<String> {
+ self.host.lock().ok().and_then(|host| host.api_version.clone())
+ }
+
+ /// Whether DBX advertised `method` for this session. Gate optional calls on
+ /// this (or on [`HostClient::host_api_version`]) so a plugin still works
+ /// against an older host that predates the capability.
+ pub fn supports(&self, method: &str) -> bool {
+ self.host.lock().map(|host| host.features.iter().any(|feature| feature == method)).unwrap_or(false)
+ }
+
+ /// Calls one Host API method and waits for the answer.
+ pub fn request(&self, method: &str, params: Value) -> Result<Value, PluginError> {
+ self.request_with_timeout(method, params, DEFAULT_HOST_REQUEST_TIMEOUT)
+ }
+
+ pub fn request_with_timeout(
+ &self,
+ method: &str,
+ params: Value,
+ timeout: Duration,
+ ) -> Result<Value, PluginError> {
+ validate_protocol_name(method)?;
+ let id = format!("plugin-{}", self.next_request_id.fetch_add(1, Ordering::Relaxed));
+ let (sender, receiver) = mpsc::channel();
+ self.pending
+ .lock()
+ .map_err(|_| PluginError::new(-32000, "Host request lock is poisoned"))?
+ .insert(id.clone(), sender);
+ let message = serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "method": method,
+ "params": params,
+ });
+ if let Err(error) = self.write(&message) {
+ if let Ok(mut pending) = self.pending.lock() {
+ pending.remove(&id);
+ }
+ return Err(error);
+ }
+ match receiver.recv_timeout(timeout) {
+ Ok(result) => result,
+ Err(mpsc::RecvTimeoutError::Timeout) => {
+ if let Ok(mut pending) = self.pending.lock() {
+ pending.remove(&id);
+ }
+ Err(PluginError::new(-32001, format!("Host did not answer '{method}' in time")))
}
- PluginTransport::Framed => {
- output.write_all(&[FRAME_KIND_JSON]).map_err(io_error)?;
- output.write_all(&(payload.len() as u32).to_be_bytes()).map_err(io_error)?;
- output.write_all(&payload).map_err(io_error)?;
+ Err(mpsc::RecvTimeoutError::Disconnected) => {
+ Err(PluginError::new(-32000, format!("Host dropped the answer to '{method}'")))
}
}
- output.flush().map_err(io_error)
+ }
+
+ /// Asks the user a question through the DBX UI. Fails when the host has no
+ /// user interface attached (headless/MCP runs), so the plugin can fall back
+ /// to its own behaviour instead of waiting for an answer that cannot come.
+ pub fn request_user_input(&self, prompt: &UserInputPrompt) -> Result<UserInputAnswer, PluginError> {
+ let params = serde_json::to_value(prompt).map_err(|error| PluginError::new(-32603, error.to_string()))?;
+ let answer = self.request(HOST_REQUEST_USER_INPUT_METHOD, params)?;
+ serde_json::from_value(answer)
+ .map_err(|error| PluginError::new(-32002, format!("Host returned an invalid input answer: {error}")))
+ }
+
+ fn write(&self, value: &Value) -> Result<(), PluginError> {
+ let payload = serde_json::to_vec(value).map_err(|error| PluginError::new(-32603, error.to_string()))?;
+ if payload.len() > MAX_JSON_BYTES {
+ return Err(PluginError::new(-32600, "JSON message is too large"));
+ }
+ write_json_frame(&self.output, self.transport, &payload)
+ }
+
+ /// Remembers what the host advertised at `plugin/initialize`.
+ fn note_host_description(&self, params: &Value) {
+ let host = params.get("host");
+ let api_version = host
+ .and_then(|host| host.get("hostApiVersion"))
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let features = host
+ .and_then(|host| host.get("features"))
+ .and_then(Value::as_array)
+ .map(|features| features.iter().filter_map(Value::as_str).map(str::to_string).collect())
+ .unwrap_or_default();
+ if let Ok(mut description) = self.host.lock() {
+ *description = HostDescription { api_version, features };
+ }
+ }
+
+ /// Routes an answer from the host to the waiting caller. Returns `false`
+ /// when the message is not a response to a plugin-initiated request, so the
+ /// server loop can keep handling host -> plugin requests.
+ fn deliver_response(&self, value: &Value) -> bool {
+ if value.get("method").is_some() {
+ return false;
+ }
+ let Some(id) = value.get("id").and_then(Value::as_str) else {
+ return false;
+ };
+ let Some(sender) = self.pending.lock().ok().and_then(|mut pending| pending.remove(id)) else {
+ return false;
+ };
+ let result = match value.get("error") {
+ Some(error) => {
+ let code = error.get("code").and_then(Value::as_i64).unwrap_or(-32603) as i32;
+ let message = error
+ .get("message")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .unwrap_or_else(|| error.to_string());
+ Err(PluginError::new(code, message))
+ }
+ None => match value.get("result") {
+ Some(result) => Ok(result.clone()),
+ None => Err(PluginError::new(-32603, "Host answer has neither result nor error")),
+ },
+ };
+ let _ = sender.send(result);
+ true
+ }
+}
+
+static HOST_CLIENT: Mutex<Option<HostClient>> = Mutex::new(None);
+
+/// The host client of the running plugin server, if any.
+pub fn host_client() -> Option<HostClient> {
+ HOST_CLIENT.lock().ok().and_then(|client| client.clone())
+}
+
+/// Installs the process-wide host client. [`PluginServer::serve`] calls this;
+/// tests may replace it.
+pub fn install_host_client(client: HostClient) {
+ if let Ok(mut current) = HOST_CLIENT.lock() {
+ *current = Some(client);
}
}
+/// Convenience wrapper for [`HostClient::request_user_input`] on the running
+/// server. Fails when the plugin server is not running.
+pub fn request_user_input(prompt: &UserInputPrompt) -> Result<UserInputAnswer, PluginError> {
+ let Some(client) = host_client() else {
+ return Err(PluginError::new(-32000, "Host API is unavailable: the plugin server is not running"));
+ };
+ client.request_user_input(prompt)
+}
+
pub struct PluginServer<H> {
metadata: PluginMetadata,
handler: Arc<H>,
@@ -175,7 +469,11 @@ impl<H: PluginHandler> PluginServer<H> {
}
pub fn serve(self) -> io::Result<()> {
- let emitter = PluginEmitter { output: Arc::new(Mutex::new(Box::new(io::stdout()))), transport: self.transport };
+ let output: Arc<Mutex<Box<dyn Write + Send>>> = Arc::new(Mutex::new(Box::new(io::stdout())));
+ let emitter = PluginEmitter { output: output.clone(), transport: self.transport };
+ // Publish the client before serving so a handler (including the very
+ // first request) can call back into the host.
+ install_host_client(HostClient::new(output, self.transport));
let workers = WorkerPool::new(self.worker_threads, self.work_queue_capacity)?;
match self.transport {
PluginTransport::JsonLines => self.serve_json_lines(BufReader::new(io::stdin()), emitter, &workers),
@@ -235,13 +533,24 @@ impl<H: PluginHandler> PluginServer<H> {
}
fn dispatch_json(&self, payload: &[u8], emitter: PluginEmitter, workers: &WorkerPool) -> Result<(), String> {
- let request: ProtocolRequest = serde_json::from_slice(payload).map_err(|error| error.to_string())?;
+ let value: Value = serde_json::from_slice(payload).map_err(|error| error.to_string())?;
+ // Answers to Host API calls the plugin made (string ids). Everything
+ // else is a host -> plugin request, whose ids are numeric.
+ if let Some(host) = host_client() {
+ if host.deliver_response(&value) {
+ return Ok(());
+ }
+ }
+ let request: ProtocolRequest = serde_json::from_value(value).map_err(|error| error.to_string())?;
if request.jsonrpc.as_deref() != Some("2.0") {
return Err("request does not declare jsonrpc 2.0".to_string());
}
validate_protocol_name(&request.method).map_err(|error| error.message)?;
if request.method == "plugin/initialize" {
let id = request.id.ok_or("plugin/initialize must be a request")?;
+ if let Some(host) = host_client() {
+ host.note_host_description(&request.params);
+ }
let supported = request
.params
.get("host")
@@ -425,6 +734,162 @@ mod tests {
let mut reader = Cursor::new(b"12345\n".to_vec());
assert!(read_limited_line(&mut reader, 4).unwrap_err().to_string().contains("too large"));
}
+
+ use super::{
+ host_client, install_host_client, request_user_input, HostClient, PluginTransport, UserInputAnswer,
+ UserInputOption, UserInputPrompt, HOST_CLIENT, HOST_REQUEST_USER_INPUT_METHOD,
+ };
+ use std::thread;
+ use std::sync::{Arc, Mutex};
+
+ /// Output sink that records every frame the plugin writes.
+ #[derive(Clone, Default)]
+ struct RecordingOutput(Arc<Mutex<Vec<u8>>>);
+
+ impl RecordingOutput {
+ fn lines(&self) -> Vec<Value> {
+ let bytes = self.0.lock().unwrap().clone();
+ String::from_utf8(bytes)
+ .unwrap()
+ .lines()
+ .filter(|line| !line.trim().is_empty())
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect()
+ }
+ }
+
+ impl std::io::Write for RecordingOutput {
+ fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buffer);
+ Ok(buffer.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ fn recording_client() -> (HostClient, RecordingOutput) {
+ let output = RecordingOutput::default();
+ let sink: Arc<Mutex<Box<dyn std::io::Write + Send>>> = Arc::new(Mutex::new(Box::new(output.clone())));
+ let client = HostClient::new(sink, PluginTransport::JsonLines);
+ install_host_client(client.clone());
+ (client, output)
+ }
+
+ #[test]
+ fn host_client_routes_answers_and_gates_on_advertised_features() {
+ let (client, output) = recording_client();
+ assert!(!client.supports(HOST_REQUEST_USER_INPUT_METHOD));
+ assert_eq!(client.host_api_version(), None);
+
+ client.note_host_description(&serde_json::json!({
+ "host": { "hostApiVersion": "1.1.0", "features": [HOST_REQUEST_USER_INPUT_METHOD] }
+ }));
+ assert_eq!(client.host_api_version().as_deref(), Some("1.1.0"));
+ assert!(client.supports(HOST_REQUEST_USER_INPUT_METHOD));
+
+ let prompt = UserInputPrompt::secret("Verification code")
+ .with_title("Bastion MFA")
+ .with_default("000000")
+ .with_timeout_secs(120);
+ let caller = {
+ let client = client.clone();
+ thread::spawn(move || client.request_user_input(&prompt))
+ };
+
+ // Simulate the host answering the outbound request.
+ let request = loop {
+ if let Some(request) = output
+ .lines()
+ .into_iter()
+ .find(|line| line["method"] == HOST_REQUEST_USER_INPUT_METHOD)
+ {
+ break request;
+ }
+ thread::sleep(Duration::from_millis(5));
+ };
+ assert_eq!(request["params"]["prompt"], "Verification code");
+ assert_eq!(request["params"]["title"], "Bastion MFA");
+ assert_eq!(request["params"]["default"], "000000");
+ assert_eq!(request["params"]["timeoutSecs"], 120);
+ assert_eq!(request["params"]["echo"], false);
+ assert!(request["params"].get("options").is_none());
+
+ assert!(client.deliver_response(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": request["id"],
+ "result": { "action": "submit", "value": "123456" }
+ })));
+ // Host -> plugin requests and unknown answers stay on the server path.
+ assert!(!client.deliver_response(&serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "connection/test" })));
+ assert!(!client.deliver_response(&serde_json::json!({ "jsonrpc": "2.0", "id": "plugin-999", "result": {} })));
+
+ let answer = caller.join().unwrap().unwrap();
+ assert_eq!(answer.submitted(), Some("123456"));
+ assert!(!answer.is_cancelled());
+ }
+
+ #[test]
+ fn host_client_surfaces_host_errors_cancels_and_timeouts() {
+ let (client, output) = recording_client();
+
+ let error_call = {
+ let client = client.clone();
+ thread::spawn(move || client.request_user_input(&UserInputPrompt::text("Account")))
+ };
+ let request = loop {
+ if let Some(request) = output.lines().into_iter().find(|line| line["method"] == HOST_REQUEST_USER_INPUT_METHOD) {
+ break request;
+ }
+ thread::sleep(Duration::from_millis(5));
+ };
+ assert!(client.deliver_response(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": request["id"],
+ "error": { "code": -32001, "message": "The DBX host cannot ask the user for input right now" }
+ })));
+ let error = error_call.join().unwrap().unwrap_err();
+ assert_eq!(error.code, -32001);
+ assert!(error.message.contains("cannot ask the user"));
+
+ // A cancel carries no value, so callers fail closed.
+ let cancel = UserInputAnswer { action: "cancel".to_string(), value: None };
+ assert_eq!(cancel.submitted(), None);
+ assert!(cancel.is_cancelled());
+ let timeout = UserInputAnswer { action: "timeout".to_string(), value: Some("ignored".to_string()) };
+ assert_eq!(timeout.submitted(), None);
+ assert!(timeout.is_timeout());
+
+ let timed_out = client
+ .request_with_timeout("host/requestUserInput", serde_json::json!({ "prompt": "x" }), Duration::from_millis(30))
+ .unwrap_err();
+ assert!(timed_out.message.contains("did not answer"), "{}", timed_out.message);
+ }
+
+ #[test]
+ fn user_input_prompt_builders_match_the_host_contract() {
+ assert_eq!(
+ serde_json::to_value(UserInputPrompt::secret("Code")).unwrap(),
+ serde_json::json!({ "prompt": "Code", "echo": false })
+ );
+ assert_eq!(
+ serde_json::to_value(UserInputPrompt::choice(
+ "Account",
+ vec![UserInputOption { value: "deploy".to_string(), label: "deploy".to_string() }]
+ ))
+ .unwrap(),
+ serde_json::json!({
+ "prompt": "Account",
+ "echo": true,
+ "options": [{ "value": "deploy", "label": "deploy" }]
+ })
+ );
+ // The convenience wrapper needs a running server to talk to.
+ HOST_CLIENT.lock().unwrap().take();
+ assert!(request_user_input(&UserInputPrompt::secret("Code")).is_err());
+ assert!(host_client().is_none());
+ }
}
fn io_error(error: io::Error) -> PluginError {
diff --git a/src-tauri/src/commands/ssh_prompt.rs b/src-tauri/src/commands/ssh_prompt.rs
index 9a9729248c..953935a928 100644
--- a/src-tauri/src/commands/ssh_prompt.rs
+++ b/src-tauri/src/commands/ssh_prompt.rs
@@ -263,9 +263,7 @@ mod tests {
port: 22,
key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()),
- previous_fingerprint: None,
- prompt: None,
- echo: false,
+ ..Default::default()
}
}