fix(sftp): guard terminal path insertion against unclosed quote contexts

This commit is contained in:
bincxz committed 2026-11-23 19:44:14 +08:00
1 parent 8a684983ba
commit 9d0c171af8
11 files changed
+508 -23

No files matched your search

+1
View File
@@ -487,6 +487,7 @@ export const enVaultMessages: Messages = {
'sftp.context.copyPath': 'Copy file path',
'sftp.context.insertPathToTerminal': 'Insert path into terminal',
'sftp.context.cdInTerminal': 'Open in terminal (cd)',
'sftp.terminal.insertBlockedUnsafeQuote': 'Cannot insert path while the terminal cursor is inside an unclosed quote or escape',
'sftp.context.openWithDefault': 'Open with system default',
'sftp.context.openWith': 'Open with...',
'sftp.context.edit': 'Edit',
+1
View File
@@ -487,6 +487,7 @@ export const esVaultMessages: Messages = {
'sftp.context.copyPath': 'Copiar ruta del archivo',
'sftp.context.insertPathToTerminal': 'Insertar ruta en la terminal',
'sftp.context.cdInTerminal': 'Abrir en la terminal (cd)',
'sftp.terminal.insertBlockedUnsafeQuote': 'No se puede insertar la ruta mientras el cursor de la terminal esté dentro de una comilla o secuencia de escape sin cerrar',
'sftp.context.openWithDefault': 'Abrir con la aplicación predeterminada del sistema',
'sftp.context.openWith': 'Abrir con...',
'sftp.context.edit': 'Editar',
+1
View File
@@ -530,6 +530,7 @@ export const ruVaultMessages: Messages = {
'sftp.context.copyPath': 'Копировать путь к файлу',
'sftp.context.insertPathToTerminal': 'Вставить путь в терминал',
'sftp.context.cdInTerminal': 'Открыть в терминале (cd)',
'sftp.terminal.insertBlockedUnsafeQuote': 'Невозможно вставить путь, пока курсор терминала находится внутри незакрытых кавычек или экранирования',
'sftp.context.openWithDefault': 'Открыть в системном приложении',
'sftp.context.openWith': 'Открыть с помощью...',
'sftp.context.edit': 'Редактировать',
@@ -97,6 +97,7 @@ export const zhCNTerminalMessages: Messages = {
'sftp.context.copyPath': '复制文件路径',
'sftp.context.insertPathToTerminal': '插入路径到终端',
'sftp.context.cdInTerminal': '在终端中打开 (cd)',
'sftp.terminal.insertBlockedUnsafeQuote': '终端光标位于未闭合的引号或转义符内,无法安全插入路径',
'sftp.context.openWith': '打开方式...',
'sftp.context.edit': '编辑',
'sftp.opener.title': '打开方式',
@@ -97,6 +97,7 @@ export const zhTWTerminalMessages: Messages = {
'sftp.context.copyPath': '複製檔案路徑',
'sftp.context.insertPathToTerminal': '插入路徑到終端機',
'sftp.context.cdInTerminal': '在終端機中開啟 (cd)',
'sftp.terminal.insertBlockedUnsafeQuote': '終端機游標位於未閉合的引號或跳脫字元內,無法安全插入路徑',
'sftp.context.openWith': '開啟方式...',
'sftp.context.edit': '編輯',
'sftp.opener.title': '開啟方式',
+19 -2
View File
@@ -79,6 +79,7 @@ import {
} from "../domain/sftpLocatePathInTerminal";
import {
canSendSftpPathToTerminal,
isTerminalDraftContextSafeForPathInsertion,
resolveCdSftpPathInTerminalAction,
resolveInsertSftpPathInTerminalAction,
} from "../domain/sftpTerminalPath";
@@ -86,7 +87,10 @@ import { sftpRequiresDedicatedLogin } from "../domain/sftpDedicatedLogin";
import { classifyDistroId } from "../domain/host";
import { useTerminalBackend } from "../application/state/useTerminalBackend";
import { isTerminalSensitiveInputActive } from "./terminal/runtime/terminalSensitiveInputRegistry";
import { isTerminalReadyForCommandInjection } from "./terminal/runtime/terminalCommandInjectionReadyRegistry";
import {
getTerminalPromptDraftContext,
isTerminalReadyForCommandInjection,
} from "./terminal/runtime/terminalCommandInjectionReadyRegistry";
import { getNextSftpToolbarDisplayPath } from "./sftp/SftpPaneToolbar";
import { scheduleDeferredTerminalFocus } from "./systemManager/tmuxActionFocus";
import {
@@ -1909,9 +1913,22 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
// Allow inserting at a prompt that already has a typed command draft (e.g. `vim `),
// while still blocking alternate-screen TUIs and non-prompt states.
if (!isTerminalReadyForCommandInjection(action.sessionId, { allowDraft: true })) return;
// Refuse insertion if the cursor is inside an unclosed quote, backtick,
// trailing escape, or continuation prompt where standalone quoting is unsafe.
const draftContext = getTerminalPromptDraftContext(action.sessionId);
if (
!draftContext
|| !isTerminalDraftContextSafeForPathInsertion({
...draftContext,
shellKind: action.shellKind,
})
) {
toast.warning(t("sftp.terminal.insertBlockedUnsafeQuote"), "SFTP");
return;
}
terminalBackend.writeToSession(action.sessionId, action.data, { automated: true });
scheduleDeferredTerminalFocus(onRequestTerminalFocus);
}, [buildLiveTerminalPathContext, onRequestTerminalFocus, terminalBackend]);
}, [buildLiveTerminalPathContext, onRequestTerminalFocus, t, terminalBackend]);
const handleCdInTerminal = useCallback((targetPath: string) => {
const action = resolveCdSftpPathInTerminalAction({
+30 -16
View File
@@ -632,22 +632,36 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const onTerminalDataCaptureRef = useRef(onTerminalDataCapture);
const onSessionExitRef = useRef(onSessionExit);
const commandBufferRef = useRef<string>("");
useEffect(() => registerTerminalCommandInjectionReadyReader(sessionId, (options) => {
const term = termRef.current;
if (!term) return false;
const prompt = detectPrompt(term);
const readiness = {
sensitiveInputActive: passwordPromptActiveRef.current,
hasLiveTerminal: true,
alternateScreenActive: isTerminalAlternateScreenActive(term),
isAtPrompt: prompt.isAtPrompt,
userInputLength: prompt.userInput.length,
pendingTypedInputLength: commandBufferRef.current.length,
};
return options?.allowDraft
? isShellPromptReadyForInsertion(readiness)
: isIdleShellReadyForCommandInjection(readiness);
}), [sessionId]);
useEffect(() => registerTerminalCommandInjectionReadyReader(
sessionId,
(options) => {
const term = termRef.current;
if (!term) return false;
const prompt = detectPrompt(term);
const readiness = {
sensitiveInputActive: passwordPromptActiveRef.current,
hasLiveTerminal: true,
alternateScreenActive: isTerminalAlternateScreenActive(term),
isAtPrompt: prompt.isAtPrompt,
userInputLength: prompt.userInput.length,
pendingTypedInputLength: commandBufferRef.current.length,
};
return options?.allowDraft
? isShellPromptReadyForInsertion(readiness)
: isIdleShellReadyForCommandInjection(readiness);
},
() => {
const term = termRef.current;
if (!term) return null;
const prompt = detectPrompt(term);
if (!prompt.isAtPrompt) return null;
return {
promptText: prompt.promptText,
userInput: prompt.userInput,
pendingTypedInput: commandBufferRef.current,
};
},
), [sessionId]);
const promptLineBreakStateRef = useRef<PromptLineBreakState>(createPromptLineBreakState());
const [hasMouseTracking, setHasMouseTracking] = useState(false);
const mouseTrackingRef = useRef(false);
+50 -3
View File
@@ -10,6 +10,12 @@ import { TooltipProvider } from "../ui/tooltip";
import { installDomEnvironment } from "../test-support/renderReactDom";
import { SftpPaneFileList } from "./SftpPaneFileList";
import { useSftpPaneTreeContextMenu } from "./useSftpPaneTreeContextMenu";
import {
getTerminalPromptDraftContext,
isTerminalReadyForCommandInjection,
registerTerminalCommandInjectionReadyReader,
} from "../terminal/runtime/terminalCommandInjectionReadyRegistry";
import { isTerminalDraftContextSafeForPathInsertion } from "../../domain/sftpTerminalPath";
import en from "../../application/i18n/locales/en";
import es from "../../application/i18n/locales/es";
import ru from "../../application/i18n/locales/ru";
@@ -237,10 +243,11 @@ test("tree context menu shows insert-path on files/folders, cd on folders only,
test("SftpSidePanel guards terminal path insertion and cd writes and SftpPaneView compares handlers in memo", () => {
const sidePanelSource = readFileSync(new URL("../SftpSidePanel.tsx", import.meta.url), "utf8");
const paneViewSource = readFileSync(new URL("./SftpPaneView.tsx", import.meta.url), "utf8");
const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
assert.match(
sidePanelSource,
/const handleInsertPathToTerminal = useCallback\([\s\S]*?isTerminalSensitiveInputActive\(action\.sessionId\)[\s\S]*?isTerminalReadyForCommandInjection\(action\.sessionId, \{ allowDraft: true \}\)[\s\S]*?terminalBackend\.writeToSession\(action\.sessionId, action\.data, \{ automated: true \}\)[\s\S]*?scheduleDeferredTerminalFocus\(onRequestTerminalFocus\)/,
/const handleInsertPathToTerminal = useCallback\([\s\S]*?isTerminalSensitiveInputActive\(action\.sessionId\)[\s\S]*?isTerminalReadyForCommandInjection\(action\.sessionId, \{ allowDraft: true \}\)[\s\S]*?getTerminalPromptDraftContext\(action\.sessionId\)[\s\S]*?isTerminalDraftContextSafeForPathInsertion\(\{[\s\S]*?shellKind: action\.shellKind[\s\S]*?toast\.warning\(t\("sftp\.terminal\.insertBlockedUnsafeQuote"\), "SFTP"\)[\s\S]*?terminalBackend\.writeToSession\(action\.sessionId, action\.data, \{ automated: true \}\)[\s\S]*?scheduleDeferredTerminalFocus\(onRequestTerminalFocus\)/,
);
assert.match(
sidePanelSource,
@@ -254,12 +261,52 @@ test("SftpSidePanel guards terminal path insertion and cd writes and SftpPaneVie
sidePanelSource,
/onCdInTerminal=\{canSendPathToTerminal \? handleCdInTerminal : undefined\}/,
);
assert.match(
terminalSource,
/registerTerminalCommandInjectionReadyReader\(\s*sessionId,[\s\S]*?promptText: prompt\.promptText,\s*userInput: prompt\.userInput,\s*pendingTypedInput: commandBufferRef\.current,/,
);
assert.match(paneViewSource, /if \(prev\.onInsertPathToTerminal !== next\.onInsertPathToTerminal\) return false;/);
assert.match(paneViewSource, /if \(prev\.onCdInTerminal !== next\.onCdInTerminal\) return false;/);
});
test("all 5 locales define translated labels for SFTP terminal path context menu items", () => {
const keys = ["sftp.context.insertPathToTerminal", "sftp.context.cdInTerminal"] as const;
test("prompt draft reader blocks insertion when cursor is inside an open double quote and cleans up on unregister", () => {
const sessionId = "sftp-insert-draft-test";
let draft = { promptText: "user@host:~$ ", userInput: "cat \"", pendingTypedInput: "cat \"" };
const unregister = registerTerminalCommandInjectionReadyReader(
sessionId,
(options) => Boolean(options?.allowDraft),
() => draft,
);
try {
assert.equal(isTerminalReadyForCommandInjection(sessionId, { allowDraft: true }), true);
const unsafeContext = getTerminalPromptDraftContext(sessionId);
assert.ok(unsafeContext);
assert.equal(
isTerminalDraftContextSafeForPathInsertion({ ...unsafeContext!, shellKind: "posix" }),
false,
);
draft = { promptText: "user@host:~$ ", userInput: "cat ", pendingTypedInput: "cat " };
const safeContext = getTerminalPromptDraftContext(sessionId);
assert.ok(safeContext);
assert.equal(
isTerminalDraftContextSafeForPathInsertion({ ...safeContext!, shellKind: "posix" }),
true,
);
} finally {
unregister();
}
assert.equal(getTerminalPromptDraftContext(sessionId), null);
});
test("all 5 locales define translated labels for SFTP terminal path context menu items and unsafe-quote feedback", () => {
const keys = [
"sftp.context.insertPathToTerminal",
"sftp.context.cdInTerminal",
"sftp.terminal.insertBlockedUnsafeQuote",
] as const;
const locales = { en, es, ru, "zh-CN": zhCN, "zh-TW": zhTW };
for (const [locale, messages] of Object.entries(locales)) {
@@ -3,20 +3,40 @@ export interface TerminalCommandInjectionReadyOptions {
allowDraft?: boolean;
}
export interface TerminalPromptDraftContext {
promptText: string;
userInput: string;
pendingTypedInput: string;
}
const commandInjectionReadyReaders = new Map<
string,
(options?: TerminalCommandInjectionReadyOptions) => boolean
>();
const promptDraftReaders = new Map<
string,
() => TerminalPromptDraftContext | null
>();
export function registerTerminalCommandInjectionReadyReader(
sessionId: string,
reader: (options?: TerminalCommandInjectionReadyOptions) => boolean,
draftReader?: () => TerminalPromptDraftContext | null,
): () => void {
commandInjectionReadyReaders.set(sessionId, reader);
if (draftReader) {
promptDraftReaders.set(sessionId, draftReader);
} else {
promptDraftReaders.delete(sessionId);
}
return () => {
if (commandInjectionReadyReaders.get(sessionId) === reader) {
commandInjectionReadyReaders.delete(sessionId);
}
if (draftReader && promptDraftReaders.get(sessionId) === draftReader) {
promptDraftReaders.delete(sessionId);
}
};
}
@@ -27,3 +47,10 @@ export function isTerminalReadyForCommandInjection(
): boolean {
return commandInjectionReadyReaders.get(sessionId)?.(options) === true;
}
/** Return the current prompt and draft text up to the cursor for a live terminal. */
export function getTerminalPromptDraftContext(
sessionId: string,
): TerminalPromptDraftContext | null {
return promptDraftReaders.get(sessionId)?.() ?? null;
}
+118
View File
@@ -6,6 +6,9 @@ import {
formatSftpCdCommand,
formatSftpPathForTerminalInsert,
hasUnsafeTerminalControlChars,
isShellDraftSafeForPathInsertion,
isTerminalContinuationPrompt,
isTerminalDraftContextSafeForPathInsertion,
quoteSftpPathForShell,
resolveCdSftpPathInTerminalAction,
resolveInsertSftpPathInTerminalAction,
@@ -237,6 +240,7 @@ test("resolveInsertSftpPathInTerminalAction and resolveCdSftpPathInTerminalActio
{
sessionId: "sess-1",
data: "'/srv/app/my file.yml' ",
shellKind: "posix",
},
);
assert.deepEqual(
@@ -261,6 +265,7 @@ test("resolveInsertSftpPathInTerminalAction and resolveCdSftpPathInTerminalActio
{
sessionId: "win-1",
data: "'C:\\Program Files\\app.exe' ",
shellKind: "powershell",
},
);
assert.deepEqual(
@@ -292,3 +297,116 @@ test("resolveInsertSftpPathInTerminalAction and resolveCdSftpPathInTerminalActio
null,
);
});
test("isShellDraftSafeForPathInsertion blocks unclosed quotes, backticks, and trailing escapes in POSIX", () => {
// Normal safe drafts
assert.equal(isShellDraftSafeForPathInsertion("", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("vim -R ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat \"hello\" ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat 'hello' ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat \"a \\\" b\" ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat \"a \\\\\"", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat \\\" ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("cat \\\\", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo 'a\\' ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo $(cat ", "posix"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo \"$(cat \"a\")\" ", "posix"), true);
// Unsafe quoting contexts (e.g. cat " + /tmp/$(id) would execute id inside double quotes)
assert.equal(isShellDraftSafeForPathInsertion("cat \"", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat \"/tmp/", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat \"a \\\"", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat '", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat '/tmp/", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("printf $'hello\\'", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("echo `cat ", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("echo \"$(cat \"", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("echo \"$(cat \"a\")", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat \\", "posix"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat \\\\\\", "posix"), false);
});
test("isShellDraftSafeForPathInsertion handles fish, PowerShell, and CMD quoting rules", () => {
// Fish escapes \' inside single quotes
assert.equal(isShellDraftSafeForPathInsertion("cat ", "fish"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo 'a\\'b' ", "fish"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo 'a\\'", "fish"), false);
assert.equal(isShellDraftSafeForPathInsertion("echo \"a", "fish"), false);
assert.equal(isShellDraftSafeForPathInsertion("cat \\", "fish"), false);
// PowerShell single/double quotes, doubled quotes, curly quotes, backtick escapes
assert.equal(isShellDraftSafeForPathInsertion("Get-Content ", "powershell"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo 'O''Brien' ", "powershell"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo \"a`\"b\" ", "powershell"), true);
assert.equal(isShellDraftSafeForPathInsertion("echo ``", "powershell"), true);
assert.equal(isShellDraftSafeForPathInsertion("Get-Content \"", "powershell"), false);
assert.equal(isShellDraftSafeForPathInsertion("Get-Content '", "powershell"), false);
assert.equal(isShellDraftSafeForPathInsertion("Get-Content 'O''Brien", "powershell"), false);
assert.equal(isShellDraftSafeForPathInsertion("Get-Content \u2019", "powershell"), false);
assert.equal(isShellDraftSafeForPathInsertion("Get-Content \u201C", "powershell"), false);
assert.equal(isShellDraftSafeForPathInsertion("Get-Content `", "powershell"), false);
assert.equal(isShellDraftSafeForPathInsertion("echo \"$(cat \"", "powershell"), false);
// CMD double quotes and caret escapes
assert.equal(isShellDraftSafeForPathInsertion("type ", "cmd"), true);
assert.equal(isShellDraftSafeForPathInsertion("type \"a\" ", "cmd"), true);
assert.equal(isShellDraftSafeForPathInsertion("type ^^", "cmd"), true);
assert.equal(isShellDraftSafeForPathInsertion("type \"", "cmd"), false);
assert.equal(isShellDraftSafeForPathInsertion("type ^", "cmd"), false);
});
test("isTerminalDraftContextSafeForPathInsertion rejects continuation prompts and un-echoed open quotes", () => {
assert.equal(isTerminalContinuationPrompt("> "), true);
assert.equal(isTerminalContinuationPrompt(">> "), true);
assert.equal(isTerminalContinuationPrompt("dquote> "), true);
assert.equal(isTerminalContinuationPrompt("quote> "), true);
assert.equal(isTerminalContinuationPrompt("heredoc> "), true);
assert.equal(isTerminalContinuationPrompt("user@host:~$ "), false);
assert.equal(isTerminalContinuationPrompt("C:\\Users\\alice>"), false);
assert.equal(isTerminalContinuationPrompt("PS C:\\Users\\alice> "), false);
// Continuation prompt blocks even when current line draft is empty
assert.equal(
isTerminalDraftContextSafeForPathInsertion({
promptText: "dquote> ",
userInput: "",
pendingTypedInput: "",
shellKind: "posix",
}),
false,
);
// Typed-ahead open double quote over high-latency SSH (not yet echoed on screen)
assert.equal(
isTerminalDraftContextSafeForPathInsertion({
promptText: "user@host:~$ ",
userInput: "cat ",
pendingTypedInput: "cat \"",
shellKind: "posix",
}),
false,
);
// Recalled history with closing quote already echoed on screen stays safe
assert.equal(
isTerminalDraftContextSafeForPathInsertion({
promptText: "user@host:~$ ",
userInput: "echo \"hi\" ",
pendingTypedInput: "\" ",
shellKind: "posix",
}),
true,
);
// Normal echoed draft is safe
assert.equal(
isTerminalDraftContextSafeForPathInsertion({
promptText: "user@host:~$ ",
userInput: "cat ",
pendingTypedInput: "cat ",
shellKind: "posix",
}),
true,
);
});
+259 -2
View File
@@ -23,6 +23,10 @@ const WINDOWS_DRIVE_PATH_RE = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_RE = /^\\\\[^\\]+\\[^\\]+/;
// PowerShell treats curly single quotes (U+2018..U+201B) as string delimiters.
const POWERSHELL_SINGLE_QUOTE_RE = /['\u2018\u2019\u201A\u201B]/g;
const POWERSHELL_SINGLE_QUOTE_CHARS = new Set(["'", "\u2018", "\u2019", "\u201A", "\u201B"]);
const POWERSHELL_DOUBLE_QUOTE_CHARS = new Set(['"', "\u201C", "\u201D", "\u201E"]);
const CONTINUATION_PROMPT_RE =
/^(?:(?:[a-z]*quote|heredoc|cmdsubst|pipe|for|if|while|until|case|select|then|else|elif|cursh|subsh|brace|math|array|param)?>|>>?)\s*$/i;
/**
* True when a string contains control bytes (C0, DEL, C1) or Unicode line
@@ -200,15 +204,268 @@ export function canSendSftpPathToTerminal(
|| protocol === "local";
}
function isPosixDraftSafeForPathInsertion(draft: string): boolean {
type Context = "single" | "ansiSingle" | "double" | "backtick" | "cmdsubst";
const stack: Context[] = [];
for (let i = 0; i < draft.length; i += 1) {
const ch = draft[i];
const top = stack[stack.length - 1];
if (top === "single") {
if (ch === "'") stack.pop();
continue;
}
if (top === "ansiSingle") {
if (ch === "\\") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === "'") stack.pop();
continue;
}
if (top === "double") {
if (ch === "\\") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === "$" && draft[i + 1] === "(") {
stack.push("cmdsubst");
i += 1;
continue;
}
if (ch === "`") {
stack.push("backtick");
continue;
}
if (ch === '"') stack.pop();
continue;
}
if (top === "backtick") {
if (ch === "\\") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === "`") stack.pop();
continue;
}
// Outside quotes (top === undefined or top === "cmdsubst")
if (ch === "\\") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === "$" && draft[i + 1] === "'") {
stack.push("ansiSingle");
i += 1;
continue;
}
if (ch === "$" && draft[i + 1] === "(") {
stack.push("cmdsubst");
i += 1;
continue;
}
if (ch === "'") {
stack.push("single");
continue;
}
if (ch === '"') {
stack.push("double");
continue;
}
if (ch === "`") {
stack.push("backtick");
continue;
}
if (ch === ")" && top === "cmdsubst") {
stack.pop();
}
}
const top = stack[stack.length - 1];
return top === undefined || top === "cmdsubst";
}
function isFishDraftSafeForPathInsertion(draft: string): boolean {
let mode: "none" | "single" | "double" = "none";
for (let i = 0; i < draft.length; i += 1) {
const ch = draft[i];
if (ch === "\\") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (mode === "none") {
if (ch === "'") mode = "single";
else if (ch === '"') mode = "double";
} else if (mode === "single") {
if (ch === "'") mode = "none";
} else if (ch === '"') {
mode = "none";
}
}
return mode === "none";
}
function isPowerShellDraftSafeForPathInsertion(draft: string): boolean {
type Context = "single" | "double" | "cmdsubst";
const stack: Context[] = [];
for (let i = 0; i < draft.length; i += 1) {
const ch = draft[i];
const top = stack[stack.length - 1];
if (top === "single") {
if (POWERSHELL_SINGLE_QUOTE_CHARS.has(ch)) {
if (i + 1 < draft.length && POWERSHELL_SINGLE_QUOTE_CHARS.has(draft[i + 1])) {
i += 1;
} else {
stack.pop();
}
}
continue;
}
if (top === "double") {
if (ch === "`") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === "$" && draft[i + 1] === "(") {
stack.push("cmdsubst");
i += 1;
continue;
}
if (POWERSHELL_DOUBLE_QUOTE_CHARS.has(ch)) {
if (i + 1 < draft.length && POWERSHELL_DOUBLE_QUOTE_CHARS.has(draft[i + 1])) {
i += 1;
} else {
stack.pop();
}
}
continue;
}
// Outside quotes (top === undefined or top === "cmdsubst")
if (ch === "`") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === "$" && draft[i + 1] === "(") {
stack.push("cmdsubst");
i += 1;
continue;
}
if (POWERSHELL_SINGLE_QUOTE_CHARS.has(ch)) {
stack.push("single");
continue;
}
if (POWERSHELL_DOUBLE_QUOTE_CHARS.has(ch)) {
stack.push("double");
continue;
}
if (ch === ")" && top === "cmdsubst") {
stack.pop();
}
}
const top = stack[stack.length - 1];
return top === undefined || top === "cmdsubst";
}
function isCmdDraftSafeForPathInsertion(draft: string): boolean {
let inDouble = false;
for (let i = 0; i < draft.length; i += 1) {
const ch = draft[i];
if (!inDouble) {
if (ch === "^") {
if (i + 1 >= draft.length) return false;
i += 1;
continue;
}
if (ch === '"') inDouble = true;
} else if (ch === '"') {
inDouble = false;
}
}
return !inDouble;
}
/**
* True when the command draft before the cursor is outside any open quote,
* backtick substitution, or trailing escape character, so inserting a
* standalone shell-quoted path cannot break out of or interpolate inside quotes.
*/
export function isShellDraftSafeForPathInsertion(
draft: string,
shellKind: SftpTerminalShellKind = "posix",
): boolean {
if (!draft) return true;
if (shellKind === "fish") return isFishDraftSafeForPathInsertion(draft);
if (shellKind === "powershell") return isPowerShellDraftSafeForPathInsertion(draft);
if (shellKind === "cmd") return isCmdDraftSafeForPathInsertion(draft);
return isPosixDraftSafeForPathInsertion(draft);
}
/** True when a shell prompt is a secondary/continuation prompt (e.g. PS2 `>`, `dquote>`). */
export function isTerminalContinuationPrompt(promptText: string): boolean {
return CONTINUATION_PROMPT_RE.test(promptText.trim());
}
/**
* Validate the live terminal prompt + draft text (combining screen prefix up to
* the cursor and any un-echoed typed buffer) before inserting a quoted path.
*/
export function isTerminalDraftContextSafeForPathInsertion(options: {
promptText?: string;
userInput: string;
pendingTypedInput?: string;
shellKind?: SftpTerminalShellKind;
}): boolean {
if (options.promptText && isTerminalContinuationPrompt(options.promptText)) {
return false;
}
const shellKind = options.shellKind ?? "posix";
const userInput = options.userInput;
const pending = options.pendingTypedInput ?? "";
if (!pending) {
return isShellDraftSafeForPathInsertion(userInput, shellKind);
}
if (userInput.endsWith(pending)) {
return isShellDraftSafeForPathInsertion(userInput, shellKind);
}
if (pending.startsWith(userInput)) {
return isShellDraftSafeForPathInsertion(pending, shellKind);
}
return (
isShellDraftSafeForPathInsertion(userInput, shellKind)
&& isShellDraftSafeForPathInsertion(pending, shellKind)
);
}
/** Build the PTY write payload for inserting a quoted path into the paired terminal. */
export function resolveInsertSftpPathInTerminalAction(
options: SftpTerminalPathContext & { path?: string | null },
): { sessionId: string; data: string } | null {
): { sessionId: string; data: string; shellKind: SftpTerminalShellKind } | null {
if (!canSendSftpPathToTerminal(options) || !options.sessionId) return null;
const shellKind = resolveSftpTerminalShellKind(options.shellType);
const data = formatSftpPathForTerminalInsert(options.path, shellKind);
if (!data) return null;
return { sessionId: options.sessionId, data };
return { sessionId: options.sessionId, data, shellKind };
}
/** Build the PTY write payload for changing directory in the paired terminal. */