fix(plugins): run only safe actions from keys a plugin web view passes on (#3763)

A plugin web view forwards shortcuts its page did not handle to the IDE keymap by posting a message, which page script could do at any time and so run any bound action without the ide.commands grant. A forwarded key now counts only while the frame has focus right after user activation, never starts a chord or a double Shift, and without ide.commands runs only an allowlist of navigation, save and settings actions.

Co-authored-by: rohitdanda <10144914+rohitdanda@users.noreply.github.com>
This commit is contained in:
rohitkumardanda
2026-11-16 23:50:51 +08:00
committed by GitHub
co-authored by rohitdanda
parent 3c624ccb22
commit ec76dcde7f
4 changed files with 380 additions and 7 deletions
@@ -0,0 +1,144 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import type { PluginInfo } from "@/bindings";
import { registerAction } from "@/platform/actions";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { usePlugins } from "../store";
import { FRAME_TAG } from "../views/frame";
import { WebView } from "../views/WebView";
let uninstall = () => {};
afterEach(() => {
uninstall();
setPluginsBackend(null);
usePlugins.setState({ plugins: [] });
useKeymap.setState({ overrides: {} });
Reflect.deleteProperty(navigator, "userActivation");
vi.restoreAllMocks();
});
/** What a browser reports after the user's own input in the frame (`isActive`), or long after it. */
function reportUserActivation(isActive: boolean) {
Object.defineProperty(navigator, "userActivation", { configurable: true, value: { isActive } });
}
async function mount(capabilities: { id: string; granted: boolean }[]) {
setPluginsBackend({ ...createMemoryPluginsBackend([]), webPageUrl: async () => "about:blank" });
usePlugins.setState({
plugins: [{ id: "evil.view", hasCode: false, enabled: true, capabilities } as unknown as PluginInfo],
});
const view = render(<WebView pluginId="evil.view" view="v" label="V" />);
const frame = await waitFor(() => {
const found = view.container.querySelector("iframe");
expect(found).not.toBeNull();
return found!;
});
return frame;
}
/** What page script in the frame can post at any time, with no user gesture. */
function pass(frame: HTMLIFrameElement, key: KeyboardEventInit) {
window.dispatchEvent(new MessageEvent("message", { data: { tag: FRAME_TAG, key }, source: frame.contentWindow }));
}
const SAVE = { key: "s", code: "KeyS", metaKey: true };
const RUN = { key: "F10", code: "F10", shiftKey: true };
function bind() {
const save = vi.fn();
const run = vi.fn();
registerAction({ id: "file.save", title: "Save", run: save });
registerAction({ id: "t.runSelected", title: "Run 'app'", run });
useKeymap.setState({ overrides: { "file.save": ["Meta+S"], "t.runSelected": ["Shift+F10"] } });
uninstall = installKeyboardDispatcher(window);
return { save, run };
}
const flush = async () => {
await Promise.resolve();
await Promise.resolve();
};
describe("keys a plugin web view passes on", () => {
it("run nothing while the user is not in the frame", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
const { save, run } = bind();
const frame = await mount([]);
pass(frame, SAVE);
pass(frame, RUN);
await flush();
expect(save).not.toHaveBeenCalled();
expect(run).not.toHaveBeenCalled();
});
it("run nothing while the window has no focus", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(false);
const { save } = bind();
const frame = await mount([]);
frame.focus();
pass(frame, SAVE);
await flush();
expect(save).not.toHaveBeenCalled();
});
it("run a safe action, and only a safe one, for a plugin without ide.commands", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
const { save, run } = bind();
const frame = await mount([{ id: "clipboard", granted: true }]);
frame.focus();
expect(document.activeElement).toBe(frame);
pass(frame, SAVE);
pass(frame, RUN);
await flush();
expect(save).toHaveBeenCalledOnce();
expect(run).not.toHaveBeenCalled();
});
it("run any bound action for a plugin granted ide.commands, but still only while the user is in the frame", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
const { run } = bind();
const frame = await mount([{ id: "ide.commands", granted: true }]);
pass(frame, RUN);
await flush();
expect(run).not.toHaveBeenCalled();
frame.focus();
pass(frame, RUN);
await flush();
expect(run).toHaveBeenCalledOnce();
});
it("run nothing when the user has not touched the frame lately, even if the page took the focus", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
reportUserActivation(false);
const { save } = bind();
const frame = await mount([]);
// The page can call focus() on itself; it cannot give itself user activation.
frame.focus();
expect(document.activeElement).toBe(frame);
pass(frame, SAVE);
await flush();
expect(save).not.toHaveBeenCalled();
});
it("run a safe action right after the user pressed a key in the frame", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
reportUserActivation(true);
const { save } = bind();
const frame = await mount([]);
frame.focus();
pass(frame, SAVE);
await flush();
expect(save).toHaveBeenCalledOnce();
});
it("do not run any bound action for a plugin whose ide.commands is declared but not granted", async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
const { run } = bind();
const frame = await mount([{ id: "ide.commands", granted: false }]);
frame.focus();
pass(frame, RUN);
await flush();
expect(run).not.toHaveBeenCalled();
});
});
+14 -3
View File
@@ -18,6 +18,7 @@
*/
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
import { tx } from "@/platform/i18n";
import { dispatchForwardedKey } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
import { EmptyState, Spinner } from "@/ui";
@@ -223,6 +224,11 @@ export function WebView({
useOwnToolWindowHeader(headless);
const hasCode = plugin?.hasCode ?? false;
const clipboard = plugin?.capabilities.some((c) => c.id === "clipboard" && c.granted) ?? false;
const anyAction = plugin?.capabilities.some((c) => c.id === "ide.commands" && c.granted) ?? false;
const anyActionRef = useRef(anyAction);
useEffect(() => {
anyActionRef.current = anyAction;
}, [anyAction]);
const frame = useRef<HTMLIFrameElement>(null);
const post = useCallback((message: object, transfer: Transferable[] = []) => {
@@ -413,12 +419,17 @@ export function WebView({
} | null;
if (m?.tag !== FRAME_TAG) return;
if (m.key && typeof m.key === "object") {
// A shortcut the page didn't handle: as if pressed on the frame, for the IDE's keymap.
// A shortcut the page didn't handle: as if pressed on the frame, for the IDE's keymap. The
// page can post one at any time and can take the focus, but it cannot fake the user's own
// input, so it counts only right after the user pressed a key or clicked in the frame.
const host = frame.current.ownerDocument;
const activation = host.defaultView?.navigator.userActivation;
if (host.activeElement !== frame.current || !host.hasFocus() || (activation && !activation.isActive)) return;
const k = m.key as KeyboardEventInit;
const init: KeyboardEventInit = { bubbles: true, cancelable: true };
const init: KeyboardEventInit = {};
for (const f of ["key", "code"] as const) if (typeof k[f] === "string") init[f] = k[f];
for (const f of ["metaKey", "ctrlKey", "altKey", "shiftKey", "repeat"] as const) init[f] = k[f] === true;
frame.current.dispatchEvent(new KeyboardEvent("keydown", init));
dispatchForwardedKey(frame.current, init, anyActionRef.current);
} else if (typeof m.call === "number" && typeof m.op === "string") {
const id = m.call;
run(m.op, (m.args ?? {}) as Record<string, unknown>).then(
+130
View File
@@ -1,6 +1,9 @@
import { readdirSync, readFileSync } from "node:fs";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
dispatchForwardedKey,
effectiveBindings,
FORWARDABLE_ACTIONS,
formatBinding,
installKeyboardDispatcher,
isAltGrTyping,
@@ -88,6 +91,117 @@ describe("keymap", () => {
expect(chord).toHaveBeenCalledOnce();
});
it("runs only safe actions from keys a plugin frame without ide.commands passes on", async () => {
const run = vi.fn();
const save = vi.fn();
const findAction = vi.fn();
registerAction({ id: "run.runSelected", title: "run", run });
registerAction({ id: "file.save", title: "save", run: save });
registerAction({ id: "navigate.findAction", title: "find action", run: findAction });
useKeymap.setState({
overrides: {
"run.runSelected": ["Shift+F10"],
"file.save": ["Meta+S"],
"navigate.findAction": ["Meta+Shift+A"],
},
});
uninstall = installKeyboardDispatcher(window);
const frame = document.body.appendChild(document.createElement("iframe"));
dispatchForwardedKey(frame, { key: "F10", code: "F10", shiftKey: true });
dispatchForwardedKey(frame, { key: "s", code: "KeyS", metaKey: true });
dispatchForwardedKey(frame, { key: "A", code: "KeyA", metaKey: true, shiftKey: true });
await Promise.resolve();
expect(run).not.toHaveBeenCalled();
expect(save).toHaveBeenCalledOnce();
expect(findAction).toHaveBeenCalledOnce();
// The same key pressed by the user still runs it.
frame.dispatchEvent(new KeyboardEvent("keydown", { key: "F10", code: "F10", shiftKey: true, bubbles: true }));
await Promise.resolve();
expect(run).toHaveBeenCalledOnce();
frame.remove();
});
it("runs any bound action from keys a plugin frame passes on when the plugin may run IDE actions", async () => {
const run = vi.fn();
registerAction({ id: "run.runSelected", title: "run", run });
useKeymap.setState({ overrides: { "run.runSelected": ["Shift+F10"] } });
uninstall = installKeyboardDispatcher(window);
const frame = document.body.appendChild(document.createElement("iframe"));
dispatchForwardedKey(frame, { key: "F10", code: "F10", shiftKey: true }, true);
await Promise.resolve();
expect(run).toHaveBeenCalledOnce();
frame.remove();
});
it.each([
"view.toggleTheme",
"view.quickSwitchScheme",
"view.toggleStatusBarWidget",
"view.zoomIn",
"window.new",
"window.mergeAllWindows",
"window.closeOtherTabs",
"window.toggleFullScreen",
"navigate.toggleBookmark",
"navigate.toggleBookmark3",
"navigate.toggleBookmarkWithMnemonic",
"toolwindow.terminal",
"toolwindow.closeContent",
])("does not run %s from a key a plugin frame without ide.commands passes on", async (id) => {
expect(FORWARDABLE_ACTIONS.has(id)).toBe(false);
const run = vi.fn();
const dispose = registerAction({ id, title: id, run });
useKeymap.setState({ overrides: { [id]: ["Meta+Alt+Shift+F12"] } });
uninstall = installKeyboardDispatcher(window);
const frame = document.body.appendChild(document.createElement("iframe"));
try {
dispatchForwardedKey(frame, { key: "F12", code: "F12", metaKey: true, altKey: true, shiftKey: true });
await Promise.resolve();
expect(run).not.toHaveBeenCalled();
} finally {
frame.remove();
dispose();
}
});
it("lets passed-on keys run only actions the app registers, by exact id", () => {
const root = import.meta.dirname.replace(/[\\/]platform$/, "");
const sources: string[] = [];
const walk = (dir: string) => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = `${dir}/${entry.name}`;
if (entry.isDirectory()) {
if (entry.name !== "__tests__" && path !== `${root}/platform/keymaps`) walk(path);
} else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
if (!path.endsWith("/platform/keymap.ts") && !path.endsWith("/bindings.ts")) sources.push(path);
}
}
};
walk(root);
const text = sources.map((p) => readFileSync(p, "utf8")).join("\n");
// Ids registered from a template, e.g. `navigate.gotoBookmark${d}`; a bare `prefix.${…}` proves nothing.
const templated = [...text.matchAll(/`([a-z]+\.[A-Za-z]+)\$\{/g)].map((m) => m[1]!);
const unregistered = [...FORWARDABLE_ACTIONS].filter(
(id) =>
!text.includes(`"${id}"`) && !templated.some((prefix) => new RegExp(`^${prefix}[A-Za-z0-9]+$`).test(id)),
);
expect(sources.length).toBeGreaterThan(100);
expect(unregistered).toEqual([]);
});
it("does not let a key a plugin frame passes on start a chord the user then finishes", async () => {
const chord = vi.fn();
registerAction({ id: "t.chord", title: "chord", run: chord });
useKeymap.setState({ overrides: { "t.chord": ["Meta+K Meta+C"] } });
uninstall = installKeyboardDispatcher(window);
const frame = document.body.appendChild(document.createElement("iframe"));
dispatchForwardedKey(frame, { key: "k", code: "KeyK", metaKey: true });
window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", code: "KeyC", metaKey: true, bubbles: true }));
await Promise.resolve();
expect(chord).not.toHaveBeenCalled();
frame.remove();
});
it("respects when clauses", async () => {
const run = vi.fn();
registerAction({ id: "t.gated", title: "gated", when: "never", run });
@@ -274,6 +388,22 @@ describe("keymap", () => {
expect(run).not.toHaveBeenCalled();
});
it("ignores a double Shift whose key presses a plugin frame without ide.commands passes on", async () => {
const { run, at, shift } = setup();
const frame = document.body.appendChild(document.createElement("iframe"));
const press = (ms: number) => {
at(ms);
dispatchForwardedKey(frame, { key: "Shift", code: "ShiftLeft", shiftKey: true });
};
press(1000);
shift("keyup", 1050);
press(1200);
shift("keyup", 1250);
await Promise.resolve();
expect(run).not.toHaveBeenCalled();
frame.remove();
});
it("ignores Shift tapped right after typing", () => {
const { run, tap, at } = setup();
at(990);
+92 -4
View File
@@ -496,6 +496,92 @@ export function dispatchMouseShortcut(e: MouseEvent, prepare?: (id: string) => b
return false;
}
/**
* Actions a shortcut passed on by a plugin's frame may run (`dispatchForwardedKey`) when the plugin
* does not hold `ide.commands`: saving, closing the editor tab, settings, and those that only move
* the caret or focus, or show a popup or tool window. The frame's page may send any key at any time,
* so nothing that runs, changes or sends something is listed: not themes, schemes, zoom or
* bookmarks, nor opening, merging or closing windows and tabs, nor the terminal (showing it starts
* a shell). Exact ids, never prefixes; a test checks that each one is still registered.
*/
export const FORWARDABLE_ACTIONS: ReadonlySet<string> = new Set([
"file.save",
"file.settings",
"editor.closeTab",
"navigate.back",
"navigate.forward",
"navigate.lastEditLocation",
"navigate.nextEditLocation",
"navigate.gotoLine",
"navigate.gotoClass",
"navigate.gotoFile",
"navigate.gotoSymbol",
"navigate.searchEverywhere",
"navigate.findAction",
"navigate.searchText",
"navigate.recentFiles",
"navigate.recentLocations",
"navigate.switcher",
"navigate.switcherBack",
"navigate.fileStructure",
"navigate.navigationBar",
"navigate.selectIn",
"navigate.selectInProjectView",
"navigate.showFilePath",
"navigate.showBookmarks",
...Array.from({ length: 10 }, (_, d) => `navigate.gotoBookmark${d}`),
"navigate.declaration",
"navigate.typeDeclaration",
"navigate.implementation",
"navigate.superMethod",
"navigate.callHierarchy",
"navigate.typeHierarchy",
"navigate.nextError",
"navigate.prevError",
"navigate.nextMethod",
"navigate.previousMethod",
"navigate.nextOccurrence",
"navigate.prevOccurrence",
"navigate.nextHighlightedUsage",
"navigate.prevHighlightedUsage",
"toolwindow.project",
"toolwindow.structure",
"toolwindow.problems",
"toolwindow.find",
"toolwindow.bookmarks",
"toolwindow.git",
"toolwindow.commit",
"toolwindow.run",
"toolwindow.debug",
"toolwindow.hideActive",
"toolwindow.hideAll",
"toolwindow.jumpToLast",
"toolwindow.focusEditor",
"toolwindow.maximize",
"toolwindow.resizeUp",
"toolwindow.resizeDown",
"toolwindow.resizeLeft",
"toolwindow.resizeRight",
"window.next",
"window.previous",
"window.nextTab",
"window.previousTab",
]);
const restrictedKeys = new WeakSet<Event>();
/**
* Dispatches on `target` a shortcut that a plugin's sandboxed frame says was pressed in it and left
* alone, for the keymap. The page can post one at any time, so unless the plugin may run any IDE
* action (`anyAction`: it holds `ide.commands`), the keymap runs only `FORWARDABLE_ACTIONS` from it,
* and it neither starts nor finishes a chord and takes no part in a double-modifier gesture.
*/
export function dispatchForwardedKey(target: EventTarget, init: KeyboardEventInit, anyAction = false): void {
const e = new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true });
if (!anyAction) restrictedKeys.add(e);
target.dispatchEvent(e);
}
/**
* Installs the global keydown dispatcher (capture phase, so IDE shortcuts win
* over CodeMirror defaults). Returns an uninstall function. `now` is the clock
@@ -561,9 +647,11 @@ export function installKeyboardDispatcher(
resetTap();
return;
}
const restricted = restrictedKeys.has(e);
if (restricted) reset();
const modifier = KEY_MODIFIER[e.key];
if (modifier) return onModifierDown(e, modifier);
if (runHeldGesture(e)) return reset();
if (modifier) return restricted ? undefined : onModifierDown(e, modifier);
if (!restricted && runHeldGesture(e)) return reset();
resetTap();
otherKeyAt = e.key === "Escape" || e.key === "Tab" ? -Infinity : now();
if (isImeKey(e)) return;
@@ -616,7 +704,7 @@ export function installKeyboardDispatcher(
}
for (const id of [...preferred, ...fallback]) {
const action = getAction(id);
if (action && isActionKeyEnabled(action, ctx)) {
if (action && isActionKeyEnabled(action, ctx) && (!restricted || FORWARDABLE_ACTIONS.has(id))) {
e.preventDefault();
e.stopPropagation();
reset();
@@ -624,7 +712,7 @@ export function installKeyboardDispatcher(
return;
}
}
if (bindings.some(([b]) => b.startsWith(seq + " "))) {
if (!restricted && bindings.some(([b]) => b.startsWith(seq + " "))) {
e.preventDefault();
e.stopPropagation();
pending.push(stroke);