feat(plugins): ask at first connect to a host the manifest does not list (net:ask) (#2417)

Plugins that declare net:ask can reach an HTTPS or loopback host their manifest does not list after the user allows it: Allow once, Always allow (remembered in the grant ledger, revocable in Settings › Plugins) or Deny. Unattended calls never prompt and are denied until the host is allowed. In remote development the dialog offers Allow for this session instead; the approval stays in memory on the server and ends with the connection, so no grant exists that the desktop cannot list or revoke.

Closes #2165

Co-authored-by: Inf1mum <[email protected]>
Цей коміт міститься в:
Vadim LazukтаInf1mum authored and GitHub committed 2026-11-10 12:31:45 +08:00
1 джерело bfe99c06e2
коміт 11594437b8
28 files changed
+894 -23

No files matched your search

+25 -1
Переглянути файл
@@ -49,6 +49,7 @@ import {
reloadPlugin,
setAllInstalledEnabled,
setPluginCapability,
revokePluginNetHost,
setPluginEnabled,
uninstallPlugin,
updateAllPlugins,
@@ -376,7 +377,7 @@ function ProgramPermission({ plugin, cap, disabled }: { plugin: PluginInfo; cap:
}
function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) {
if (plugin.capabilities.length === 0) {
if (plugin.capabilities.length === 0 && plugin.netHosts.length === 0) {
return (
<div className={styles.muted}>
<T>No special permissions.</T>
@@ -402,10 +403,33 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean })
/>
</CapabilityRow>
))}
{plugin.netHosts.map((host) => (
<NetHostRow key={host} plugin={plugin} host={host} disabled={busy || !confirmed} />
))}
</ul>
);
}
/** A host the user allowed through `net:ask` ("always"); removing it asks again next time. */
function NetHostRow({ plugin, host, disabled }: { plugin: PluginInfo; host: string; disabled: boolean }) {
return (
<li className={styles.capabilityItem}>
<div className={styles.capabilityHeader}>
<span className={styles.mono}>{`net:${host}`}</span>
<Badge tone={RISK_LABEL.medium.tone}>{RISK_LABEL.medium.label}</Badge>
</div>
<p className={styles.capabilityDescription}>
{tx("Allowed when the plugin asked at first use. Remove it to be asked again.")}
</p>
<div className={styles.programPermission}>
<Button disabled={disabled} onClick={() => void revokePluginNetHost(plugin.id, host)}>
{tx("Remove")}
</Button>
</div>
</li>
);
}
function Homepage({ value }: { value: string }) {
let isWebUrl = false;
try {
+139
Переглянути файл
@@ -10,6 +10,7 @@ import { useProject } from "@/platform/project";
import { pluginThemeRef, useContributedIconThemes } from "@/platform/themes";
import { ContextMenuHost, hideContextMenu } from "@/ui";
import { InputDialogsHost } from "@/workbench/inputDialogs";
import { MessagesHost } from "@/workbench/messages";
import {
onEndpointsChanged,
provideNotificationService,
@@ -74,6 +75,7 @@ function plugin(partial: Partial<PluginInfo> & Pick<PluginInfo, "id">): PluginIn
error: null,
hasCode: true,
capabilities: [],
netHosts: [],
contributions: [],
activation: [],
warnings: [],
@@ -640,6 +642,115 @@ describe("plugin prompts", () => {
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("2", null));
});
it("asks about a net:ask host with allow once, always allow and deny", async () => {
const user = userEvent.setup();
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
usePlugins.setState({ plugins: [plugin({ id: "p", name: "Relay" })] });
render(<MessagesHost />);
const ask = (promptId: string) =>
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId,
prompt: { kind: "netPermission", host: "api.example.com", sessionOnly: false },
});
});
ask("9");
expect(screen.getByText("Allow Relay to connect to api.example.com?")).toBeDefined();
expect(screen.getByText(/The host is not in the plugin's declared permissions\./)).toBeDefined();
expect(screen.getByRole("button", { name: "Deny" })).toHaveFocus();
await user.click(screen.getByRole("button", { name: "Always allow" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("9", ["always"]));
ask("10");
await user.click(await screen.findByRole("button", { name: "Allow once" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("10", ["once"]));
ask("11");
await user.click(await screen.findByRole("button", { name: "Deny" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("11", null));
});
it("offers session permission and deny for a remote net:ask prompt", async () => {
const user = userEvent.setup();
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
render(<MessagesHost />);
const ask = (promptId: string) =>
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId,
prompt: { kind: "netPermission", host: "api.example.com", sessionOnly: true },
});
});
ask("session-net");
expect(screen.queryByRole("button", { name: "Always allow" })).toBeNull();
expect(screen.queryByRole("button", { name: "Allow once" })).toBeNull();
expect(screen.getAllByRole("button")).toHaveLength(2);
expect(screen.getByText(/This allows api.example.com until the remote session ends\./)).toBeDefined();
expect(screen.queryByText(/revoke it any time/)).toBeNull();
expect(screen.getByRole("button", { name: "Deny" })).toHaveFocus();
await user.click(screen.getByRole("button", { name: "Allow for this session" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("session-net", ["session"]));
ask("denied-session-net");
await user.click(await screen.findByRole("button", { name: "Deny" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("denied-session-net", null));
});
it("refuses network prompts in a hidden window and closes them when hidden", async () => {
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
render(<MessagesHost />);
const visibility = vi.spyOn(document, "visibilityState", "get");
const ask = (promptId: string) =>
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId,
prompt: { kind: "netPermission", host: "api.example.com", sessionOnly: false },
});
});
try {
visibility.mockReturnValue("hidden");
ask("hidden");
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("hidden", null));
expect(screen.queryByRole("dialog")).toBeNull();
visibility.mockReturnValue("visible");
ask("visible");
expect(screen.getByRole("button", { name: "Deny" })).toHaveFocus();
visibility.mockReturnValue("hidden");
act(() => document.dispatchEvent(new Event("visibilitychange")));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("visible", null));
expect(screen.queryByRole("dialog")).toBeNull();
} finally {
visibility.mockRestore();
}
});
it("dismisses a network prompt without allowing the request", async () => {
const user = userEvent.setup();
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
render(<MessagesHost />);
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId: "dismissed-net",
prompt: { kind: "netPermission", host: "api.example.com", sessionOnly: false },
});
});
await user.keyboard("{Escape}");
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("dismissed-net", null));
});
it("asks multi-line text and confirms on Ctrl+Enter", async () => {
const user = userEvent.setup();
const answerPrompt = vi.fn().mockResolvedValue(undefined);
@@ -1232,6 +1343,34 @@ describe("marketplace", () => {
});
});
it.each(["api.example.com", "::1", "ask"])(
"revokes remembered host %s separately from capabilities",
async (host) => {
const user = userEvent.setup();
const base = createMemoryPluginsBackend([
plugin({
id: "p",
name: "P",
netHosts: [host, "relay.example.org"],
capabilities: [
{ id: "net:ask", risk: "medium", description: "Ask to connect", optional: true, granted: true },
],
}),
]);
const revokeNetHost = vi.fn((id: string, host: string) => base.revokeNetHost(id, host));
setPluginsBackend({ ...base, revokeNetHost });
render(<PluginsPage />);
await screen.findByText("net:relay.example.org");
expect(screen.getAllByText(`net:${host}`)).toHaveLength(host === "ask" ? 2 : 1);
expect(screen.getByText("net:relay.example.org")).toBeInTheDocument();
const rows = screen.getAllByRole("button", { name: "Remove" });
await user.click(rows[0]!);
await waitFor(() => expect(revokeNetHost).toHaveBeenCalledWith("p", host));
await waitFor(() => expect(screen.queryAllByText(`net:${host}`)).toHaveLength(host === "ask" ? 1 : 0));
expect(screen.getByText("net:relay.example.org")).toBeInTheDocument();
},
);
it("offers to roll back an update", async () => {
const base = createMemoryPluginsBackend([
plugin({ id: "p", name: "P", version: "2.0.0", previousVersion: "1.0.0" }),
+10
Переглянути файл
@@ -58,6 +58,7 @@ export interface PluginsBackend {
program(pluginId: string, program: string, scope: "global" | "project"): Promise<string>;
pickProgram(): Promise<string | null>;
setCapability(id: string, capability: string, granted: boolean): Promise<PluginInfo>;
revokeNetHost(id: string, host: string): Promise<PluginInfo>;
/** Validated assets (icon theme mapping and SVGs) whose id starts with `prefix`. */
assets(pluginId: string, prefix: string): Promise<[string, string][]>;
/** `language` / `file` / `view` activation events. */
@@ -216,6 +217,7 @@ export const tauriPluginsBackend: PluginsBackend = {
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
},
setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)),
revokeNetHost: (id, host) => call(commands.pluginRevokeNetHost(id, host)),
assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)),
activationEvent: async (kind, value) => {
await call(commands.pluginActivationEvent(kind, value));
@@ -420,6 +422,7 @@ function samplePlugins(): PluginInfo[] {
enabled: true,
error: null,
capabilities: [],
netHosts: [],
contributions: [],
activation: [],
warnings: [],
@@ -588,10 +591,17 @@ export function createMemoryPluginsBackend(
setCapability: async (id, capability, granted) => {
const p = find(id);
p.capabilities = p.capabilities.map((c) => (c.id === capability ? { ...c, granted } : c));
if (!granted && capability === "net:ask") p.netHosts = [];
if (!granted && p.capabilities.some((c) => c.id === capability && !c.optional)) p.status = "needsConsent";
emit({ type: "commandsChanged" });
return { ...p };
},
revokeNetHost: async (id, host) => {
const p = find(id);
p.netHosts = p.netHosts.filter((h) => h !== host);
emit({ type: "commandsChanged" });
return { ...p };
},
assets: async () => [],
activationEvent: async () => {},
catalog: async () => catalog.map((c) => ({ ...c })),
+5
Переглянути файл
@@ -39,6 +39,11 @@ export function capabilityDescription(cap: CapabilityInfo): string {
"Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing",
);
}
if (cap.id === "net:ask") {
return tx(
"Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones",
);
}
if (cap.id.startsWith("net.http:")) {
const host = cap.id.slice(9);
return tx`Connect to ${host} over unencrypted HTTP (from the machine the project is on)`;
+59
Переглянути файл
@@ -0,0 +1,59 @@
/**
* The host's own permission question (`net:ask`): a plugin with the
* capability reached an HTTPS host its manifest does not list. One dialog,
* one host: allow for this request, remember it, or refuse. Remembered
* local hosts appear in the plugin's permissions, where each can be revoked.
*/
import { tx } from "@/platform/i18n";
import { ask } from "@/workbench/messages";
import { usePlugins } from "./store";
/** Resolves with the host's answer key, or null when refused. */
export async function askNetPermission(
pluginId: string,
host: string,
sessionOnly: boolean,
signal: AbortSignal,
): Promise<string[] | null> {
if (document.visibilityState === "hidden") return null;
const controller = new AbortController();
const abort = () => controller.abort();
const visibilityChanged = () => {
if (document.visibilityState === "hidden") controller.abort();
};
signal.addEventListener("abort", abort);
document.addEventListener("visibilitychange", visibilityChanged);
if (signal.aborted) controller.abort();
const name = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.name ?? pluginId;
try {
const r = await ask({
title: tx`Allow ${name} to connect to ${host}?`,
body: [
tx("The host is not in the plugin's declared permissions."),
" ",
tx("This allows this exact host on any port; subdomains need separate permission."),
" ",
sessionOnly
? tx`This allows ${host} until the remote session ends.`
: tx`"Always allow" remembers ${host}; revoke it any time in the plugin's permissions.`,
],
buttons: sessionOnly
? [
{ id: "session", label: tx("Allow for this session") },
{ id: "deny", label: tx("Deny"), primary: true },
]
: [
{ id: "once", label: tx("Allow once") },
{ id: "always", label: tx("Always allow") },
{ id: "deny", label: tx("Deny"), primary: true },
],
cancel: false,
icon: "question",
signal: controller.signal,
});
return r.button === "session" || r.button === "once" || r.button === "always" ? [r.button] : null;
} finally {
signal.removeEventListener("abort", abort);
document.removeEventListener("visibilitychange", visibilityChanged);
}
}
+10 -3
Переглянути файл
@@ -45,6 +45,7 @@ import { confirm } from "@/workbench/messages";
import { removeTask, upsertTask, useTasks } from "@/workbench/tasks";
import { editorContext } from "./editorContext";
import { pluginsBackend } from "./backend";
import { askNetPermission } from "./netAsk";
import { usePluginT } from "./pluginText";
import { setPluginOutput } from "./views/outputStore";
import { PLUGIN_LOG_EDITOR_KIND } from "./views/logEditor";
@@ -408,13 +409,19 @@ async function askUser(prompt: Prompt, signal: AbortSignal): Promise<string[] |
return (await confirm({ title: prompt.title, message: prompt.message, ok: tx("OK"), signal, verbatim: true }))
? []
: null;
case "netPermission":
// The host's own question: answered before this (`answerPrompt`).
return null;
}
}
async function answerPrompt(promptId: string, prompt: Prompt) {
async function answerPrompt(promptId: string, prompt: Prompt, pluginId: string) {
const controller = new AbortController();
openPrompts.set(promptId, controller);
const answer = await askUser(prompt, controller.signal);
const answer =
prompt.kind === "netPermission"
? await askNetPermission(pluginId, prompt.host, prompt.sessionOnly, controller.signal)
: await askUser(prompt, controller.signal);
openPrompts.delete(promptId);
if (controller.signal.aborted) return;
await pluginsBackend()
@@ -599,7 +606,7 @@ export function handleRuntimeEvent(e: PluginEvent): boolean {
void openExternalUrl(e.url);
return true;
case "promptRequested":
void answerPrompt(e.promptId, e.prompt);
void answerPrompt(e.promptId, e.prompt, e.pluginId);
return true;
case "promptClosed":
openPrompts.get(e.promptId)?.abort();
+6
Переглянути файл
@@ -1,5 +1,6 @@
/** Installed plugins, their UI contributions, the selected plugin theme, and the operations on them. */
import { create } from "zustand";
import { tx } from "@/platform/i18n";
import type {
ActiveTheme,
CapabilityInfo,
@@ -191,6 +192,11 @@ export function setPluginCapability(id: string, capability: string, granted: boo
);
}
export function revokePluginNetHost(id: string, host: string): Promise<boolean> {
const name = nameOf(id);
return withBusy(id, tx`Could not revoke ${host} for ${name}`, () => pluginsBackend().revokeNetHost(id, host));
}
export async function refreshCatalog(): Promise<void> {
try {
usePlugins.setState({ catalog: await pluginsBackend().catalog(), catalogError: null });