mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 19:07:17 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98a80206ac | ||
|
|
48674bdcf3 | ||
|
|
5db00a6eb4 | ||
|
|
d5eacb8584 | ||
|
|
5be716942a | ||
|
|
ac959b3b9e | ||
|
|
9d0c171af8 | ||
|
|
8a684983ba |
No files matched your search
@@ -485,6 +485,9 @@ export const enVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'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',
|
||||
|
||||
@@ -485,6 +485,9 @@ export const esVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'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',
|
||||
|
||||
@@ -528,6 +528,9 @@ export const ruVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Копировать путь к файлу',
|
||||
'sftp.context.insertPathToTerminal': 'Вставить путь в терминал',
|
||||
'sftp.context.cdInTerminal': 'Открыть в терминале (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'Невозможно вставить путь, пока курсор терминала находится внутри незакрытых кавычек или экранирования',
|
||||
'sftp.context.openWithDefault': 'Открыть в системном приложении',
|
||||
'sftp.context.openWith': 'Открыть с помощью...',
|
||||
'sftp.context.edit': 'Редактировать',
|
||||
|
||||
@@ -95,6 +95,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'history.clearAll.dialog.confirm': '全部清空',
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': '复制文件路径',
|
||||
'sftp.context.insertPathToTerminal': '插入路径到终端',
|
||||
'sftp.context.cdInTerminal': '在终端中打开 (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': '终端光标位于未闭合的引号或转义符内,无法安全插入路径',
|
||||
'sftp.context.openWith': '打开方式...',
|
||||
'sftp.context.edit': '编辑',
|
||||
'sftp.opener.title': '打开方式',
|
||||
|
||||
@@ -95,6 +95,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'history.clearAll.dialog.confirm': '全部清空',
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': '複製檔案路徑',
|
||||
'sftp.context.insertPathToTerminal': '插入路徑到終端機',
|
||||
'sftp.context.cdInTerminal': '在終端機中開啟 (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': '終端機游標位於未閉合的引號或跳脫字元內,無法安全插入路徑',
|
||||
'sftp.context.openWith': '開啟方式...',
|
||||
'sftp.context.edit': '編輯',
|
||||
'sftp.opener.title': '開啟方式',
|
||||
|
||||
@@ -77,11 +77,22 @@ import {
|
||||
resolveLocateSftpPathInTerminalAction,
|
||||
resolveLocateSftpPathSessionId,
|
||||
} from "../domain/sftpLocatePathInTerminal";
|
||||
import {
|
||||
canSendSftpPathToTerminal,
|
||||
isTerminalContinuationPrompt,
|
||||
isTerminalDraftContextSafeForCd,
|
||||
isTerminalDraftContextSafeForPathInsertion,
|
||||
resolveCdSftpPathInTerminalAction,
|
||||
resolveInsertSftpPathInTerminalAction,
|
||||
} from "../domain/sftpTerminalPath";
|
||||
import { sftpRequiresDedicatedLogin } from "../domain/sftpDedicatedLogin";
|
||||
import { classifyDistroId } from "../domain/host";
|
||||
import { classifyDistroId, resolveHostOs } 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 {
|
||||
@@ -1815,6 +1826,36 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
|
||||
]);
|
||||
|
||||
const canLocatePathInTerminal = canLocateSftpPathInTerminal(locatePathInTerminalContext);
|
||||
const canSendPathToTerminal = canSendSftpPathToTerminal(locatePathInTerminalContext);
|
||||
|
||||
const buildLiveTerminalPathContext = useCallback(() => {
|
||||
const connection = sftpRef.current.leftPane.connection;
|
||||
const locateSessionId = resolveLocateSftpPathSessionId({
|
||||
activeSessionId,
|
||||
focusedSessionId,
|
||||
});
|
||||
const session = sessions.find((candidate) => candidate.id === locateSessionId) ?? null;
|
||||
const host = displayHost ?? activeHost;
|
||||
const isNetworkDevice = host?.deviceType === "network"
|
||||
|| classifyDistroId(host?.distro) === "network-device";
|
||||
return {
|
||||
sessionId: locateSessionId,
|
||||
sessionStatus: session?.status,
|
||||
sessionHostId: session?.hostId,
|
||||
sftpHostId: connection?.hostId,
|
||||
sftpIsLocal: Boolean(connection?.isLocal),
|
||||
protocol: session?.protocol ?? host?.protocol,
|
||||
shellType: session?.shellType,
|
||||
hostOs: host ? resolveHostOs(host) : undefined,
|
||||
isNetworkDevice,
|
||||
sessionHostname: session?.hostname,
|
||||
sessionUsername: session?.username,
|
||||
sessionPort: session?.port,
|
||||
sftpHostname: host?.hostname,
|
||||
sftpUsername: host?.username,
|
||||
sftpPort: host?.port,
|
||||
};
|
||||
}, [activeHost, activeSessionId, displayHost, focusedSessionId, sessions, sftpRef]);
|
||||
|
||||
const handleLocatePathInTerminal = useCallback(() => {
|
||||
const connection = sftpRef.current.leftPane.connection;
|
||||
@@ -1864,6 +1905,61 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
|
||||
terminalBackend,
|
||||
]);
|
||||
|
||||
const handleInsertPathToTerminal = useCallback((targetPath: string) => {
|
||||
const context = buildLiveTerminalPathContext();
|
||||
if (!canSendSftpPathToTerminal(context) || !context.sessionId) return;
|
||||
// Never insert paths into a password/sudo prompt.
|
||||
if (isTerminalSensitiveInputActive(context.sessionId)) return;
|
||||
// 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(context.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(context.sessionId);
|
||||
if (!draftContext || isTerminalContinuationPrompt(draftContext.promptText)) {
|
||||
toast.warning(t("sftp.terminal.insertBlockedUnsafeQuote"), "SFTP");
|
||||
return;
|
||||
}
|
||||
const action = resolveInsertSftpPathInTerminalAction({
|
||||
...context,
|
||||
promptText: draftContext.promptText,
|
||||
path: targetPath,
|
||||
});
|
||||
if (!action) return;
|
||||
if (
|
||||
!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, t, terminalBackend]);
|
||||
|
||||
const handleCdInTerminal = useCallback((targetPath: string) => {
|
||||
const context = buildLiveTerminalPathContext();
|
||||
if (!canSendSftpPathToTerminal(context) || !context.sessionId) return;
|
||||
// Never inject cd into a password/sudo prompt.
|
||||
if (isTerminalSensitiveInputActive(context.sessionId)) return;
|
||||
// Only submit cd at an idle shell prompt -- never append into typed input or a TUI.
|
||||
if (!isTerminalReadyForCommandInjection(context.sessionId)) return;
|
||||
// Reject continuation prompts (e.g. PS2 `>`, `dquote>`) where the shell is
|
||||
// still reading an unterminated quote or compound command.
|
||||
const draftContext = getTerminalPromptDraftContext(context.sessionId);
|
||||
if (!draftContext || !isTerminalDraftContextSafeForCd(draftContext)) return;
|
||||
const action = resolveCdSftpPathInTerminalAction({
|
||||
...context,
|
||||
promptText: draftContext.promptText,
|
||||
path: targetPath,
|
||||
});
|
||||
if (!action) return;
|
||||
terminalBackend.writeToSession(action.sessionId, action.data, { automated: true });
|
||||
scheduleDeferredTerminalFocus(onRequestTerminalFocus);
|
||||
}, [buildLiveTerminalPathContext, onRequestTerminalFocus, terminalBackend]);
|
||||
|
||||
const MAX_VISIBLE_TRANSFERS = 5;
|
||||
const visibleTransfers = useMemo(() => {
|
||||
const connection = sftp.leftPane.connection;
|
||||
@@ -2023,6 +2119,8 @@ const SftpSidePanelInteractiveBody: React.FC<SftpSidePanelInteractiveBodyProps>
|
||||
onToggleShowHiddenFiles={() => handleToggleHiddenFiles(pane.id)}
|
||||
onGoToTerminalCwd={onGetTerminalCwd ? handleGoToTerminalCwd : undefined}
|
||||
onLocatePathInTerminal={canLocatePathInTerminal ? handleLocatePathInTerminal : undefined}
|
||||
onInsertPathToTerminal={canSendPathToTerminal ? handleInsertPathToTerminal : undefined}
|
||||
onCdInTerminal={canSendPathToTerminal ? handleCdInTerminal : undefined}
|
||||
followTerminalCwd={canFollowTerminalCwd ? effectiveFollowTerminalCwd : undefined}
|
||||
onToggleFollowTerminalCwd={canFollowTerminalCwd ? handleToggleFollowTerminalCwd : undefined}
|
||||
/>
|
||||
|
||||
+32
-17
@@ -179,7 +179,7 @@ import {
|
||||
isIdleShellReadyForCommandInjection,
|
||||
isShellPromptReadyForInsertion,
|
||||
} from "../domain/terminalCommandInjectionReady";
|
||||
import { detectPrompt } from "./terminal/autocomplete/promptDetector";
|
||||
import { detectPrompt, getPromptLineTextAfterCursor } from "./terminal/autocomplete/promptDetector";
|
||||
import type { SensitiveInputActiveRef } from "./terminal/autocomplete/terminalAutocompletePrompt";
|
||||
import {
|
||||
applyUserCursorPreference,
|
||||
@@ -632,22 +632,37 @@ 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,
|
||||
afterCursorInputLength: getPromptLineTextAfterCursor(term).trim().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);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { AppWindow, Archive, ArrowDown, ArrowRight, ArrowUp, ChevronDown, ClipboardCopy, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderPlus, Loader2, Pencil, RefreshCw, Shield, Trash2, Unplug, Upload } from "lucide-react";
|
||||
import { AppWindow, Archive, ArrowDown, ArrowRight, ArrowUp, ChevronDown, ClipboardCopy, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderPlus, Loader2, Pencil, RefreshCw, Shield, Terminal, TerminalSquare, Trash2, Unplug, Upload } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
ContextMenu,
|
||||
@@ -73,6 +73,8 @@ interface SftpPaneFileListProps {
|
||||
onEditPermissions?: (entry: SftpFileEntry) => void;
|
||||
onUploadExternalFileList?: (fileList: FileList, targetPath?: string) => Promise<void> | void;
|
||||
onUploadExternalFolder?: (targetPath?: string) => Promise<void> | void;
|
||||
onInsertPathToTerminal?: (path: string) => void;
|
||||
onCdInTerminal?: (dirPath: string) => void;
|
||||
// Whether this pane is rendering a local filesystem. Upload menu items only
|
||||
// make sense for remote (SFTP) panes, so they are suppressed when isLocal.
|
||||
isLocal?: boolean;
|
||||
@@ -165,6 +167,8 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
onEditPermissions,
|
||||
onUploadExternalFileList,
|
||||
onUploadExternalFolder,
|
||||
onInsertPathToTerminal,
|
||||
onCdInTerminal,
|
||||
isLocal = false,
|
||||
openRenameDialog,
|
||||
openDeleteConfirm,
|
||||
@@ -431,6 +435,26 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
<ClipboardCopy size={14} className="mr-2" />{" "}
|
||||
{t("sftp.context.copyPath")}
|
||||
</ContextMenuItem>
|
||||
{onInsertPathToTerminal && (
|
||||
<ContextMenuItem
|
||||
onClick={() => {
|
||||
onInsertPathToTerminal(joinPath(pane.connection.currentPath, entry.name));
|
||||
}}
|
||||
>
|
||||
<TerminalSquare size={14} className="mr-2" />{" "}
|
||||
{t("sftp.context.insertPathToTerminal")}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onCdInTerminal && isNavigableDirectory(entry) && (
|
||||
<ContextMenuItem
|
||||
onClick={() => {
|
||||
onCdInTerminal(joinPath(pane.connection.currentPath, entry.name));
|
||||
}}
|
||||
>
|
||||
<Terminal size={14} className="mr-2" />{" "}
|
||||
{t("sftp.context.cdInTerminal")}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuSeparator />
|
||||
{(() => {
|
||||
const sourceParent = getParentPath(joinPath(pane.connection?.currentPath ?? "", entry.name));
|
||||
@@ -539,6 +563,8 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
onRefresh,
|
||||
onUploadExternalFileList,
|
||||
onUploadExternalFolder,
|
||||
onInsertPathToTerminal,
|
||||
onCdInTerminal,
|
||||
uploadEnabled,
|
||||
folderUploadEnabled,
|
||||
openDeleteConfirm,
|
||||
@@ -802,6 +828,14 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
<Upload size={14} className="mr-2" />{t("sftp.context.uploadFolder")}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onCdInTerminal && pane.connection?.currentPath && (
|
||||
<>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onClick={() => onCdInTerminal(pane.connection.currentPath)}>
|
||||
<Terminal size={14} className="mr-2" />{t("sftp.context.cdInTerminal")}
|
||||
</ContextMenuItem>
|
||||
</>
|
||||
)}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
|
||||
|
||||
@@ -65,6 +65,8 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
|
||||
onUploadExternalFiles,
|
||||
onUploadExternalFileList,
|
||||
onUploadExternalFolder,
|
||||
onInsertPathToTerminal,
|
||||
onCdInTerminal,
|
||||
sorting,
|
||||
reloadRequest,
|
||||
}) => {
|
||||
@@ -933,6 +935,8 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
|
||||
executeMoveAction,
|
||||
triggerUploadPicker,
|
||||
onUploadExternalFolder,
|
||||
onInsertPathToTerminal,
|
||||
onCdInTerminal,
|
||||
uploadEnabled,
|
||||
folderUploadEnabled,
|
||||
setMoveTargetPaths,
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface SftpPaneTreeViewProps {
|
||||
onUploadExternalFiles?: (dataTransfer: DataTransfer, targetPath?: string) => Promise<void>;
|
||||
onUploadExternalFileList?: (fileList: FileList, targetPath?: string) => Promise<void>;
|
||||
onUploadExternalFolder?: (targetPath?: string) => Promise<void>;
|
||||
onInsertPathToTerminal?: (path: string) => void;
|
||||
onCdInTerminal?: (dirPath: string) => void;
|
||||
sorting: UseSftpPaneSortingResult;
|
||||
reloadRequest: { token: number; paths?: string[]; full?: boolean };
|
||||
}
|
||||
@@ -83,6 +83,8 @@ interface SftpPaneViewProps {
|
||||
onToggleShowHiddenFiles?: () => void;
|
||||
onGoToTerminalCwd?: () => void;
|
||||
onLocatePathInTerminal?: () => void;
|
||||
onInsertPathToTerminal?: (path: string) => void;
|
||||
onCdInTerminal?: (dirPath: string) => void;
|
||||
followTerminalCwd?: boolean;
|
||||
onToggleFollowTerminalCwd?: () => void;
|
||||
/** When true, treat this pane as always active (used by SftpSidePanel which manages visibility itself) */
|
||||
@@ -100,6 +102,8 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
onToggleShowHiddenFiles,
|
||||
onGoToTerminalCwd,
|
||||
onLocatePathInTerminal,
|
||||
onInsertPathToTerminal,
|
||||
onCdInTerminal,
|
||||
followTerminalCwd,
|
||||
onToggleFollowTerminalCwd,
|
||||
forceActive,
|
||||
@@ -663,6 +667,8 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
onUploadExternalFiles={handleUploadExternalFiles}
|
||||
onUploadExternalFileList={handleUploadExternalFileList}
|
||||
onUploadExternalFolder={handleUploadExternalFolder}
|
||||
onInsertPathToTerminal={onInsertPathToTerminal}
|
||||
onCdInTerminal={onCdInTerminal}
|
||||
sorting={sortingControls}
|
||||
reloadRequest={treeReloadRequest}
|
||||
/>
|
||||
@@ -713,6 +719,8 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
onEditPermissions={callbacks.onEditPermissions}
|
||||
onUploadExternalFileList={handleUploadExternalFileList}
|
||||
onUploadExternalFolder={handleUploadExternalFolder}
|
||||
onInsertPathToTerminal={onInsertPathToTerminal}
|
||||
onCdInTerminal={onCdInTerminal}
|
||||
isLocal={!!pane.connection?.isLocal}
|
||||
openRenameDialog={openRenameDialog}
|
||||
openDeleteConfirm={openDeleteConfirm}
|
||||
@@ -804,6 +812,8 @@ const sftpPaneViewAreEqual = (
|
||||
if (prev.onToggleFollowTerminalCwd !== next.onToggleFollowTerminalCwd) return false;
|
||||
if (prev.onGoToTerminalCwd !== next.onGoToTerminalCwd) return false;
|
||||
if (prev.onLocatePathInTerminal !== next.onLocatePathInTerminal) return false;
|
||||
if (prev.onInsertPathToTerminal !== next.onInsertPathToTerminal) return false;
|
||||
if (prev.onCdInTerminal !== next.onCdInTerminal) return false;
|
||||
if (prev.onToggleShowHiddenFiles !== next.onToggleShowHiddenFiles) return false;
|
||||
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test, { after } from "node:test";
|
||||
import React from "react";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { createEmptyPane } from "../../application/state/sftp/types";
|
||||
import type { SftpFileEntry } from "../../types";
|
||||
import { ContextMenuContent } from "../ui/context-menu";
|
||||
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 { detectPrompt, getPromptLineTextAfterCursor } from "../terminal/autocomplete/promptDetector";
|
||||
import { isIdleShellReadyForCommandInjection } from "../../domain/terminalCommandInjectionReady";
|
||||
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";
|
||||
import zhCN from "../../application/i18n/locales/zh-CN";
|
||||
import zhTW from "../../application/i18n/locales/zh-TW";
|
||||
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
after(() => { environment.IS_REACT_ACT_ENVIRONMENT = previous; });
|
||||
|
||||
type MenuItem = React.ReactElement<{ children?: React.ReactNode; onClick?: () => void }>;
|
||||
|
||||
function collectMenuItems(node: React.ReactNode, out: MenuItem[] = []): MenuItem[] {
|
||||
React.Children.forEach(node, (child) => {
|
||||
if (!React.isValidElement<{ children?: React.ReactNode; onClick?: () => void }>(child)) return;
|
||||
if (typeof child.props.onClick === "function") {
|
||||
out.push(child);
|
||||
}
|
||||
if (child.props.children) {
|
||||
collectMenuItems(child.props.children, out);
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function findMenuAction(children: React.ReactNode, key: string): MenuItem | undefined {
|
||||
return collectMenuItems(children).find((item) =>
|
||||
React.Children.toArray(item.props.children).includes(key),
|
||||
);
|
||||
}
|
||||
|
||||
const folder: SftpFileEntry = {
|
||||
name: "docker app",
|
||||
type: "directory",
|
||||
size: 0,
|
||||
sizeFormatted: "0 B",
|
||||
lastModified: 0,
|
||||
lastModifiedFormatted: "",
|
||||
};
|
||||
const file: SftpFileEntry = {
|
||||
name: "docker-compose.yml",
|
||||
type: "file",
|
||||
size: 128,
|
||||
sizeFormatted: "128 B",
|
||||
lastModified: 0,
|
||||
lastModifiedFormatted: "",
|
||||
};
|
||||
|
||||
test("list context menu exposes insert-path for files/folders and cd for folders and background only when paired", async (t) => {
|
||||
const dom = installDomEnvironment();
|
||||
const noop = () => {};
|
||||
const inserted: string[] = [];
|
||||
const cdTargets: string[] = [];
|
||||
|
||||
let props: React.ComponentProps<typeof SftpPaneFileList> = {
|
||||
t: (key) => key,
|
||||
pane: {
|
||||
...createEmptyPane("pane-terminal-path"),
|
||||
connection: {
|
||||
id: "conn",
|
||||
hostId: "host",
|
||||
hostLabel: "Host",
|
||||
isLocal: false,
|
||||
status: "connected",
|
||||
currentPath: "/srv/site",
|
||||
},
|
||||
selectedFiles: new Set<string>(),
|
||||
files: [folder, file],
|
||||
},
|
||||
side: "left",
|
||||
isPaneFocused: true,
|
||||
sorting: {
|
||||
sortField: "name",
|
||||
sortOrder: "asc",
|
||||
directoriesFirst: true,
|
||||
columnWidths: { name: 50, modified: 24, size: 7, type: 9, owner: 10 },
|
||||
visibleColumns: { name: true, modified: true, size: true, type: true, owner: true },
|
||||
handleSort: noop,
|
||||
handleResizeStart: noop,
|
||||
toggleColumnVisibility: noop,
|
||||
toggleDirectoriesFirst: noop,
|
||||
},
|
||||
fileListRef: { current: null },
|
||||
handleFileListScroll: noop,
|
||||
shouldVirtualize: false,
|
||||
totalHeight: 0,
|
||||
sortedDisplayFiles: [folder, file],
|
||||
isDragOverPane: false,
|
||||
draggedFiles: null,
|
||||
onRefresh: noop,
|
||||
onNavigateTo: noop,
|
||||
onClearSelection: noop,
|
||||
setShowNewFolderDialog: noop,
|
||||
setShowNewFileDialog: noop,
|
||||
getNextUntitledName: () => "",
|
||||
setNewFileName: noop,
|
||||
setFileNameError: noop,
|
||||
dragOverEntry: null,
|
||||
handleRowSelect: noop,
|
||||
handleRowOpen: noop,
|
||||
handleFileDragStart: noop,
|
||||
onDragEnd: noop,
|
||||
handleEntryDragOver: noop,
|
||||
handleRowDragLeave: noop,
|
||||
handleEntryDrop: noop,
|
||||
onCopyToOtherPane: noop,
|
||||
onMoveEntriesToPath: async () => {},
|
||||
openRenameDialog: noop,
|
||||
openDeleteConfirm: noop,
|
||||
onInsertPathToTerminal: (path) => { inserted.push(path); },
|
||||
onCdInTerminal: (dirPath) => { cdTargets.push(dirPath); },
|
||||
rowHeight: 28,
|
||||
visibleRows: [],
|
||||
};
|
||||
|
||||
const render = () => React.createElement(TooltipProvider, null, React.createElement(SftpPaneFileList, props));
|
||||
let renderer!: ReactTestRenderer;
|
||||
await act(async () => { renderer = create(render()); });
|
||||
t.after(async () => {
|
||||
await act(async () => { renderer.unmount(); });
|
||||
dom.cleanup();
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
});
|
||||
|
||||
const menus = () => renderer.root.findAllByType(ContextMenuContent);
|
||||
const insertActions = () => menus()
|
||||
.map((menu) => findMenuAction(menu.props.children, "sftp.context.insertPathToTerminal"))
|
||||
.filter((item): item is MenuItem => Boolean(item));
|
||||
const cdActions = () => menus()
|
||||
.map((menu) => findMenuAction(menu.props.children, "sftp.context.cdInTerminal"))
|
||||
.filter((item): item is MenuItem => Boolean(item));
|
||||
|
||||
// Folder row + file row both have Insert path into terminal.
|
||||
assert.equal(insertActions().length, 2);
|
||||
insertActions()[0].props.onClick?.();
|
||||
insertActions()[1].props.onClick?.();
|
||||
assert.deepEqual(inserted, ["/srv/site/docker app", "/srv/site/docker-compose.yml"]);
|
||||
|
||||
// Folder row + empty background menu have Open in terminal (cd); file row does not.
|
||||
assert.equal(cdActions().length, 2);
|
||||
cdActions()[0].props.onClick?.();
|
||||
cdActions()[1].props.onClick?.();
|
||||
assert.deepEqual(cdTargets, ["/srv/site/docker app", "/srv/site"]);
|
||||
|
||||
// When unpaired (callbacks omitted), both context actions disappear cleanly.
|
||||
props = { ...props, onInsertPathToTerminal: undefined, onCdInTerminal: undefined };
|
||||
await act(async () => { renderer.update(render()); });
|
||||
assert.equal(insertActions().length, 0);
|
||||
assert.equal(cdActions().length, 0);
|
||||
});
|
||||
|
||||
test("tree context menu shows insert-path on files/folders, cd on folders only, and hides on parent entry or unpaired pane", async (t) => {
|
||||
const inserted: string[] = [];
|
||||
const cdTargets: string[] = [];
|
||||
const emptyRef = { current: undefined };
|
||||
|
||||
let props: Parameters<typeof useSftpPaneTreeContextMenu>[0] = {
|
||||
contextTarget: { entry: folder, entryPath: "/srv/site/docker app" },
|
||||
pane: { connection: { id: "conn", isLocal: false } },
|
||||
tRef: { current: (key: string) => key },
|
||||
onOpenFileWithSystemDefaultRef: emptyRef,
|
||||
onOpenFileWithRef: emptyRef,
|
||||
onEditFileRef: emptyRef,
|
||||
onDownloadFileRef: emptyRef,
|
||||
onExtractArchiveRef: emptyRef,
|
||||
onEditPermissionsRef: emptyRef,
|
||||
onDuplicateEntriesRef: emptyRef,
|
||||
onCreateArchiveRef: emptyRef,
|
||||
onInsertPathToTerminal: (path: string) => { inserted.push(path); },
|
||||
onCdInTerminal: (dirPath: string) => { cdTargets.push(dirPath); },
|
||||
getActionPaths: (path: string) => [path],
|
||||
};
|
||||
|
||||
let menu: React.ReactNode;
|
||||
function Probe() {
|
||||
menu = useSftpPaneTreeContextMenu(props);
|
||||
return null;
|
||||
}
|
||||
|
||||
let renderer!: ReactTestRenderer;
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
t.after(async () => { await act(async () => { renderer.unmount(); }); });
|
||||
|
||||
const getAction = (key: string) =>
|
||||
findMenuAction((menu as React.ReactElement<{ children: React.ReactNode }>).props.children, key);
|
||||
|
||||
// Directory node: both insert and cd.
|
||||
const dirInsert = getAction("sftp.context.insertPathToTerminal");
|
||||
const dirCd = getAction("sftp.context.cdInTerminal");
|
||||
assert.ok(dirInsert);
|
||||
assert.ok(dirCd);
|
||||
dirInsert!.props.onClick?.();
|
||||
dirCd!.props.onClick?.();
|
||||
assert.deepEqual(inserted, ["/srv/site/docker app"]);
|
||||
assert.deepEqual(cdTargets, ["/srv/site/docker app"]);
|
||||
|
||||
// File node: insert only, no cd.
|
||||
props = { ...props, contextTarget: { entry: file, entryPath: "/srv/site/docker-compose.yml" } };
|
||||
await act(async () => { renderer.update(React.createElement(Probe)); });
|
||||
const fileInsert = getAction("sftp.context.insertPathToTerminal");
|
||||
assert.ok(fileInsert);
|
||||
assert.equal(getAction("sftp.context.cdInTerminal"), undefined);
|
||||
fileInsert!.props.onClick?.();
|
||||
assert.deepEqual(inserted, ["/srv/site/docker app", "/srv/site/docker-compose.yml"]);
|
||||
|
||||
// Synthetic parent ".." entry: neither insert nor cd.
|
||||
props = { ...props, contextTarget: { entry: { ...folder, name: ".." }, entryPath: "/srv" } };
|
||||
await act(async () => { renderer.update(React.createElement(Probe)); });
|
||||
assert.equal(getAction("sftp.context.insertPathToTerminal"), undefined);
|
||||
assert.equal(getAction("sftp.context.cdInTerminal"), undefined);
|
||||
|
||||
// Unpaired pane: neither insert nor cd.
|
||||
props = {
|
||||
...props,
|
||||
contextTarget: { entry: folder, entryPath: "/srv/site/docker app" },
|
||||
onInsertPathToTerminal: undefined,
|
||||
onCdInTerminal: undefined,
|
||||
};
|
||||
await act(async () => { renderer.update(React.createElement(Probe)); });
|
||||
assert.equal(getAction("sftp.context.insertPathToTerminal"), undefined);
|
||||
assert.equal(getAction("sftp.context.cdInTerminal"), undefined);
|
||||
});
|
||||
|
||||
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\(context\.sessionId\)[\s\S]*?isTerminalReadyForCommandInjection\(context\.sessionId, \{ allowDraft: true \}\)[\s\S]*?getTerminalPromptDraftContext\(context\.sessionId\)[\s\S]*?resolveInsertSftpPathInTerminalAction\(\{[\s\S]*?promptText: draftContext\.promptText[\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,
|
||||
/const handleCdInTerminal = useCallback\([\s\S]*?isTerminalSensitiveInputActive\(context\.sessionId\)[\s\S]*?isTerminalReadyForCommandInjection\(context\.sessionId\)[\s\S]*?getTerminalPromptDraftContext\(context\.sessionId\)[\s\S]*?isTerminalDraftContextSafeForCd\(draftContext\)[\s\S]*?resolveCdSftpPathInTerminalAction\(\{[\s\S]*?promptText: draftContext\.promptText[\s\S]*?terminalBackend\.writeToSession\(action\.sessionId, action\.data, \{ automated: true \}\)[\s\S]*?scheduleDeferredTerminalFocus\(onRequestTerminalFocus\)/,
|
||||
);
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/onInsertPathToTerminal=\{canSendPathToTerminal \? handleInsertPathToTerminal : undefined\}/,
|
||||
);
|
||||
assert.match(
|
||||
sidePanelSource,
|
||||
/onCdInTerminal=\{canSendPathToTerminal \? handleCdInTerminal : undefined\}/,
|
||||
);
|
||||
assert.match(
|
||||
terminalSource,
|
||||
/registerTerminalCommandInjectionReadyReader\(\s*sessionId,[\s\S]*?afterCursorInputLength: getPromptLineTextAfterCursor\(term\)\.trim\(\)\.length,[\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("after-cursor text after Ctrl+A on recalled history blocks idle cd injection (including wrapped lines)", () => {
|
||||
const makeTerm = (rows: Array<{ text: string; isWrapped?: boolean }>, cursorY: number, cursorX: number) => ({
|
||||
cols: 80,
|
||||
buffer: {
|
||||
active: {
|
||||
baseY: 0,
|
||||
cursorY,
|
||||
cursorX,
|
||||
length: rows.length,
|
||||
getLine: (row: number) => {
|
||||
const entry = rows[row];
|
||||
if (!entry) return undefined;
|
||||
return {
|
||||
isWrapped: Boolean(entry.isWrapped),
|
||||
translateToString: () => entry.text,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Recalled `$ rm -rf /tmp/foo` then pressed Ctrl+A (cursor right after `$ `).
|
||||
const recalledTerm = makeTerm([{ text: "$ rm -rf /tmp/foo " }], 0, 2);
|
||||
const recalledPrompt = detectPrompt(recalledTerm as never);
|
||||
assert.equal(recalledPrompt.isAtPrompt, true);
|
||||
assert.equal(recalledPrompt.userInput, "");
|
||||
const recalledAfter = getPromptLineTextAfterCursor(recalledTerm as never).trim();
|
||||
assert.equal(recalledAfter, "rm -rf /tmp/foo");
|
||||
assert.equal(
|
||||
isIdleShellReadyForCommandInjection({
|
||||
sensitiveInputActive: false,
|
||||
hasLiveTerminal: true,
|
||||
alternateScreenActive: false,
|
||||
isAtPrompt: recalledPrompt.isAtPrompt,
|
||||
userInputLength: recalledPrompt.userInput.length,
|
||||
pendingTypedInputLength: 0,
|
||||
afterCursorInputLength: recalledAfter.length,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
|
||||
// Wrapped command where remainder sits on the wrapped continuation row.
|
||||
const wrappedTerm = makeTerm(
|
||||
[
|
||||
{ text: "$ " },
|
||||
{ text: "rm -rf /tmp/foo", isWrapped: true },
|
||||
],
|
||||
0,
|
||||
2,
|
||||
);
|
||||
const wrappedAfter = getPromptLineTextAfterCursor(wrappedTerm as never).trim();
|
||||
assert.equal(wrappedAfter, "rm -rf /tmp/foo");
|
||||
assert.equal(
|
||||
isIdleShellReadyForCommandInjection({
|
||||
sensitiveInputActive: false,
|
||||
hasLiveTerminal: true,
|
||||
alternateScreenActive: false,
|
||||
isAtPrompt: true,
|
||||
userInputLength: 0,
|
||||
pendingTypedInputLength: 0,
|
||||
afterCursorInputLength: wrappedAfter.length,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
|
||||
// Clean idle prompt with only padding spaces after cursor stays ready.
|
||||
const idleTerm = makeTerm(
|
||||
[
|
||||
{ text: "$ " },
|
||||
{ text: "unrelated next line", isWrapped: false },
|
||||
],
|
||||
0,
|
||||
2,
|
||||
);
|
||||
const idlePrompt = detectPrompt(idleTerm as never);
|
||||
const idleAfter = getPromptLineTextAfterCursor(idleTerm as never).trim();
|
||||
assert.equal(idleAfter, "");
|
||||
assert.equal(
|
||||
isIdleShellReadyForCommandInjection({
|
||||
sensitiveInputActive: false,
|
||||
hasLiveTerminal: true,
|
||||
alternateScreenActive: false,
|
||||
isAtPrompt: idlePrompt.isAtPrompt,
|
||||
userInputLength: idlePrompt.userInput.length,
|
||||
pendingTypedInputLength: 0,
|
||||
afterCursorInputLength: idleAfter.length,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("right-aligned shell prompt decorations (e.g. zsh RPROMPT) do not block idle readiness while space-padded recalled commands still do", () => {
|
||||
const makeCellTerm = (
|
||||
cols: number,
|
||||
line: string,
|
||||
cursorX: number,
|
||||
unwrittenRange?: { start: number; end: number },
|
||||
) => ({
|
||||
cols,
|
||||
buffer: {
|
||||
active: {
|
||||
baseY: 0,
|
||||
cursorY: 0,
|
||||
cursorX,
|
||||
length: 1,
|
||||
getLine: (row: number) =>
|
||||
row === 0
|
||||
? {
|
||||
isWrapped: false,
|
||||
translateToString: () => line,
|
||||
getCell: (x: number) => {
|
||||
if (unwrittenRange && x >= unwrittenRange.start && x < unwrittenRange.end) {
|
||||
return { getCode: () => 0, getChars: () => "" };
|
||||
}
|
||||
const ch = line[x] ?? "";
|
||||
return {
|
||||
getCode: () => (ch ? ch.codePointAt(0) ?? 0 : 0),
|
||||
getChars: () => ch,
|
||||
};
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Zsh RPROMPT clock with default ZLE_RPROMPT_INDENT=1 (`$ ` + 69 unwritten cells + `12:34:56 ` = 80 cols).
|
||||
const rpromptClock = "$ " + " ".repeat(69) + "12:34:56 ";
|
||||
const rpromptTerm = makeCellTerm(80, rpromptClock, 2, { start: 2, end: 71 });
|
||||
const rprompt = detectPrompt(rpromptTerm as never);
|
||||
assert.equal(rprompt.isAtPrompt, true);
|
||||
assert.equal(rprompt.userInput, "");
|
||||
const rpromptAfter = getPromptLineTextAfterCursor(rpromptTerm as never).trim();
|
||||
assert.equal(rpromptAfter, "");
|
||||
assert.equal(
|
||||
isIdleShellReadyForCommandInjection({
|
||||
sensitiveInputActive: false,
|
||||
hasLiveTerminal: true,
|
||||
alternateScreenActive: false,
|
||||
isAtPrompt: rprompt.isAtPrompt,
|
||||
userInputLength: rprompt.userInput.length,
|
||||
pendingTypedInputLength: 0,
|
||||
afterCursorInputLength: rpromptAfter.length,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
// Flush-right multi-segment RPROMPT (ZLE_RPROMPT_INDENT=0) with cursor-jumped gap.
|
||||
const flushRight = "user@host:~$ " + " ".repeat(53) + "main 12:34:56";
|
||||
assert.equal(
|
||||
getPromptLineTextAfterCursor(makeCellTerm(80, flushRight, 13, { start: 13, end: 66 }) as never).trim(),
|
||||
"",
|
||||
);
|
||||
|
||||
// Recalled command in a 40-col Bash terminal with written leading spaces reaching the right margin
|
||||
// MUST remain blocked (literal 0x20 space cells, not unwritten cursor-jump cells).
|
||||
const recalledRightAligned = "$ " + " ".repeat(17) + "true; printf INJECTED";
|
||||
assert.equal(recalledRightAligned.length, 40);
|
||||
assert.ok(
|
||||
getPromptLineTextAfterCursor(makeCellTerm(40, recalledRightAligned, 2) as never).trim().length > 0,
|
||||
);
|
||||
|
||||
// Recalled command at cursor with RPROMPT still present MUST remain blocked.
|
||||
const recalledWithRprompt = "$ rm -rf /tmp/foo" + " ".repeat(54) + "12:34:56 ";
|
||||
assert.ok(
|
||||
getPromptLineTextAfterCursor(makeCellTerm(80, recalledWithRprompt, 2, { start: 17, end: 71 }) as never).trim().length > 0,
|
||||
);
|
||||
|
||||
// Recalled command with leading spaces + RPROMPT MUST remain blocked.
|
||||
const spacedRecalledWithRprompt = "$ rm -rf /tmp/foo" + " ".repeat(52) + "12:34:56 ";
|
||||
assert.ok(
|
||||
getPromptLineTextAfterCursor(makeCellTerm(80, spacedRecalledWithRprompt, 2, { start: 19, end: 71 }) as never).trim().length > 0,
|
||||
);
|
||||
|
||||
// Rows without getCell metadata conservatively retain right-aligned suffixes as editable text.
|
||||
const noCellMetadataTerm = {
|
||||
cols: 80,
|
||||
buffer: {
|
||||
active: {
|
||||
baseY: 0,
|
||||
cursorY: 0,
|
||||
cursorX: 2,
|
||||
length: 1,
|
||||
getLine: (row: number) => (row === 0 ? { isWrapped: false, translateToString: () => rpromptClock } : undefined),
|
||||
},
|
||||
},
|
||||
};
|
||||
assert.ok(getPromptLineTextAfterCursor(noCellMetadataTerm as never).trim().length > 0);
|
||||
});
|
||||
|
||||
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)) {
|
||||
for (const key of keys) {
|
||||
assert.ok(messages[key]?.trim(), `${locale} missing ${key}`);
|
||||
if (locale !== "en") {
|
||||
assert.notEqual(messages[key], en[key], `${locale} left ${key} untranslated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo } from 'react';
|
||||
import { AppWindow, Archive, ArrowRight, ArrowUp, ClipboardCopy, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderInput, FolderPlus, Pencil, RefreshCw, Shield, Trash2, Upload } from 'lucide-react';
|
||||
import { AppWindow, Archive, ArrowRight, ArrowUp, ClipboardCopy, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderInput, FolderPlus, Pencil, RefreshCw, Shield, Terminal, TerminalSquare, Trash2, Upload } from 'lucide-react';
|
||||
import { ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from '../ui/context-menu';
|
||||
import { getParentPath } from '../../application/state/sftp/utils';
|
||||
import { isKnownBinaryFile } from '../../lib/sftpFileUtils';
|
||||
@@ -16,7 +16,7 @@ export const isSftpTreeParentEntry = (entry: { name: string }): boolean => entry
|
||||
export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps) {
|
||||
const {
|
||||
contextTarget, pane, toggleExpand, stableOnOpenEntry, stableOnRefresh, getActionPaths, toTransferSources,
|
||||
executeMoveAction, triggerUploadPicker, onUploadExternalFolder, uploadEnabled, folderUploadEnabled,
|
||||
executeMoveAction, triggerUploadPicker, onUploadExternalFolder, onInsertPathToTerminal, onCdInTerminal, uploadEnabled, folderUploadEnabled,
|
||||
setMoveTargetPaths, setMoveToPath, setMoveToError, setMoveToSuggestions, setMoveToSuggestionIndex,
|
||||
setIsMoving, setShowMoveToDialog, tRef, onCopyToOtherPaneRef, onDuplicateEntriesRef, onNavigateToRef, onOpenFileWithSystemDefaultRef, onOpenFileWithRef,
|
||||
onEditFileRef, onDownloadFileRef, onExtractArchiveRef, onCreateArchiveRef, onEditPermissionsRef, openDeleteConfirmRef, openRenameDialogRef,
|
||||
@@ -127,6 +127,16 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
<ContextMenuItem onClick={() => navigator.clipboard.writeText(entryPath)}>
|
||||
<ClipboardCopy size={14} className="mr-2" />{tRef.current('sftp.context.copyPath')}
|
||||
</ContextMenuItem>
|
||||
{onInsertPathToTerminal && !isParentEntry && (
|
||||
<ContextMenuItem onClick={() => onInsertPathToTerminal(entryPath)}>
|
||||
<TerminalSquare size={14} className="mr-2" />{tRef.current('sftp.context.insertPathToTerminal')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onCdInTerminal && isDir && !isParentEntry && (
|
||||
<ContextMenuItem onClick={() => onCdInTerminal(entryPath)}>
|
||||
<Terminal size={14} className="mr-2" />{tRef.current('sftp.context.cdInTerminal')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuSeparator />
|
||||
{(() => {
|
||||
const sourceParent = getParentPath(entryPath);
|
||||
@@ -211,6 +221,8 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
uploadEnabled,
|
||||
folderUploadEnabled,
|
||||
onUploadExternalFolder,
|
||||
onInsertPathToTerminal,
|
||||
onCdInTerminal,
|
||||
onCopyToOtherPaneRef,
|
||||
onDuplicateEntriesRef,
|
||||
onDownloadFileRef,
|
||||
|
||||
@@ -877,3 +877,25 @@ test("password, passphrase, PIN, and secret prompts stay uncompletable (#3622)",
|
||||
assert.equal(resolveAutocompleteQueryInput(result.prompt, "use", true), null, line);
|
||||
}
|
||||
});
|
||||
|
||||
test("detectPrompt recognizes standard root-directory shell prompts ending in :/$ (#1982)", () => {
|
||||
for (const [line, expectedPrompt, expectedInput] of [
|
||||
["ubuntu@prod:/$ ", "ubuntu@prod:/$ ", ""],
|
||||
['ubuntu@prod:/$ echo "unclosed', "ubuntu@prod:/$ ", 'echo "unclosed'],
|
||||
["(venv) ubuntu@prod:/$ ls", "(venv) ubuntu@prod:/$ ", "ls"],
|
||||
["alpine:/$ ", "alpine:/$ ", ""],
|
||||
["/$ ", "/$ ", ""],
|
||||
["ubuntu@box:~$ echo user@host:/$ ", "ubuntu@box:~$ ", "echo user@host:/$ "],
|
||||
] as const) {
|
||||
const result = detectPrompt(createFakeTerm(line, line.length) as never);
|
||||
assert.equal(result.isAtPrompt, true, line);
|
||||
assert.equal(result.promptText, expectedPrompt, line);
|
||||
assert.equal(result.userInput, expectedInput, line);
|
||||
}
|
||||
|
||||
for (const nonPrompt of ["echo foo/$ ", "https://example.com/$ "]) {
|
||||
const result = detectPrompt(createFakeTerm(nonPrompt, nonPrompt.length) as never);
|
||||
assert.equal(result.isAtPrompt, false, nonPrompt);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import type { Terminal as XTerm } from "@xterm/xterm";
|
||||
import { isSensitiveTerminalChallenge } from "../../../domain/terminalPromptSecurity";
|
||||
import { sliceStringByCellColumns } from "./terminalStringCellWidth";
|
||||
import { sliceStringByCellColumns, stringCellWidth } from "./terminalStringCellWidth";
|
||||
import { COMMON_SHELL_COMMANDS, NON_PROMPT_PATTERNS, PROMPT_CHARS } from "./promptDetectorPatterns";
|
||||
|
||||
export interface PromptDetectionResult {
|
||||
@@ -680,6 +680,114 @@ export function detectPrompt(term: XTerm): PromptDetectionResult {
|
||||
return NO_PROMPT;
|
||||
}
|
||||
|
||||
type CellInspectableBufferLine = {
|
||||
getCell?: (x: number) => {
|
||||
getCode?: () => number;
|
||||
getChars?: () => string;
|
||||
} | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* True when single-row text after the cursor is confirmed by xterm cell
|
||||
* metadata to be a cursor-jumped right-aligned shell prompt decoration (e.g.
|
||||
* zsh `RPROMPT`, fish `fish_right_prompt`, Powerlevel10k, Starship) rather than
|
||||
* editable command text left behind after `Ctrl+A`.
|
||||
*
|
||||
* Shells draw right prompts by erasing to end-of-line (`EL`) and jumping to the
|
||||
* right margin (`CUF`/`CHA`), leaving unwritten null cells (`code === 0`,
|
||||
* `chars === ""`) in the gap starting at `cursorX`. By contrast, recalled or
|
||||
* typed commands with leading spaces write literal ASCII space characters
|
||||
* (`code === 32`, `chars === " "`) starting at `cursorX`, so checking the cell
|
||||
* buffer prevents space-padded commands near the right margin from ever being
|
||||
* misclassified as non-editable decorations. Rows without `getCell` metadata
|
||||
* are conservatively treated as editable text.
|
||||
*/
|
||||
function isRightPromptDecorationAfterCursor(
|
||||
line: CellInspectableBufferLine,
|
||||
rowAfter: string,
|
||||
cursorX: number,
|
||||
cols: number,
|
||||
term: XTerm,
|
||||
): boolean {
|
||||
if (typeof line.getCell !== "function") return false;
|
||||
if (!Number.isFinite(cols) || cols <= 0) return false;
|
||||
const trimmedRight = rowAfter.trimEnd();
|
||||
if (!trimmedRight) return false;
|
||||
|
||||
const leadingSpaces = trimmedRight.length - trimmedRight.trimStart().length;
|
||||
if (leadingSpaces < 2) return false;
|
||||
|
||||
const endCol = cursorX + stringCellWidth(trimmedRight, term);
|
||||
if (endCol < cols - 2) return false;
|
||||
|
||||
// Confirm the padding gap starting at cursorX consists of unwritten null
|
||||
// cells left by cursor-forward jumps (not literal 0x20 space characters
|
||||
// written by a recalled command). Allow at most 1 written leading space at
|
||||
// the end of the gap in case the RPROMPT text itself starts with a space.
|
||||
let unwrittenGapCells = 0;
|
||||
for (let offset = 0; offset < leadingSpaces; offset += 1) {
|
||||
const cell = line.getCell(cursorX + offset);
|
||||
if (!cell || typeof cell.getCode !== "function") return false;
|
||||
const isUnwritten = cell.getCode() === 0 && (!cell.getChars || cell.getChars() === "");
|
||||
if (!isUnwritten) break;
|
||||
unwrittenGapCells += 1;
|
||||
}
|
||||
if (unwrittenGapCells < 2 || unwrittenGapCells < leadingSpaces - 1) return false;
|
||||
|
||||
// Reject lines where editable text sits near the cursor before a wider gap
|
||||
// leading into the right prompt.
|
||||
const body = trimmedRight.trimStart();
|
||||
let maxInternalSpaceRun = 0;
|
||||
let currentSpaceRun = 0;
|
||||
for (let i = 0; i < body.length; i += 1) {
|
||||
if (body[i] === " ") {
|
||||
currentSpaceRun += 1;
|
||||
if (currentSpaceRun > maxInternalSpaceRun) {
|
||||
maxInternalSpaceRun = currentSpaceRun;
|
||||
}
|
||||
} else {
|
||||
currentSpaceRun = 0;
|
||||
}
|
||||
}
|
||||
if (maxInternalSpaceRun >= unwrittenGapCells) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract editable text on the active logical line to the right of the cursor,
|
||||
* including any wrapped continuation rows belonging to the same line, while
|
||||
* ignoring cell-confirmed right-aligned prompt decorations (e.g. zsh `RPROMPT`)
|
||||
* on an unwrapped row.
|
||||
*/
|
||||
export function getPromptLineTextAfterCursor(term: XTerm): string {
|
||||
const buffer = term.buffer.active;
|
||||
const cursorY = buffer.cursorY + buffer.baseY;
|
||||
const cursorX = Math.max(0, buffer.cursorX);
|
||||
const line = buffer.getLine(cursorY);
|
||||
if (!line) return "";
|
||||
|
||||
const rowAfter = sliceStringByCellColumns(line.translateToString(false), cursorX, undefined, term);
|
||||
let wrappedAfter = "";
|
||||
const maxRow = typeof buffer.length === "number" ? buffer.length : Number.POSITIVE_INFINITY;
|
||||
for (let row = cursorY + 1; row < maxRow; row += 1) {
|
||||
const nextLine = buffer.getLine(row);
|
||||
if (!nextLine || !nextLine.isWrapped) break;
|
||||
wrappedAfter += nextLine.translateToString(false);
|
||||
}
|
||||
|
||||
if (wrappedAfter.trim().length > 0) {
|
||||
return rowAfter + wrappedAfter;
|
||||
}
|
||||
if (rowAfter.trim().length === 0) {
|
||||
return "";
|
||||
}
|
||||
if (isRightPromptDecorationAfterCursor(line, rowAfter, cursorX, term.cols, term)) {
|
||||
return "";
|
||||
}
|
||||
return rowAfter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a character lives in the Unicode Private Use Area (U+E000–U+F8FF).
|
||||
* Powerline separators (U+E0B0..) and Nerd Font icons (U+E200.., U+F000..) all
|
||||
@@ -801,22 +909,21 @@ function findPromptBoundary(lineText: string): number {
|
||||
// A prompt $ is typically preceded by: space, ), ], digit, username chars, or is at position 0.
|
||||
// A variable $ is typically inside a command: echo $HOME, export PATH=$PATH:...
|
||||
//
|
||||
// Heuristic: if the $ is preceded by a letter/digit/underscore without a space before it
|
||||
// (i.e., it's part of a token like "echo" or "=$PATH"), it's likely a variable.
|
||||
// Standard Linux/BSD prompts also end with `:/$ ` when the shell's cwd is `/`
|
||||
// (e.g. `ubuntu@server:/$ `, `(venv) user@host:/$ `, `host:/$ `, `/$ `).
|
||||
const prefixBeforeDollar = lineText.slice(0, i);
|
||||
const prev = i > 0 ? lineText[i - 1] : "";
|
||||
const isRootOrSlashPathPrompt =
|
||||
prev === "/" &&
|
||||
!prefixBeforeDollar.includes("://") &&
|
||||
(prefixBeforeDollar === "/" ||
|
||||
/(?:^|\s)[\w.@-]+:\/(?:[^\s]*\/)?$/.test(prefixBeforeDollar));
|
||||
|
||||
if (i > 0) {
|
||||
const prev = lineText[i - 1];
|
||||
// If preceded by = or / or another non-separator, it's a variable reference
|
||||
if (prev === "=" || prev === "/" || prev === ":") continue;
|
||||
// If preceded by a letter and there's no space between, it could be $HOME-style
|
||||
// But actually: "user@host:~$ " has letter before $. So check if there's
|
||||
// a valid prompt pattern before the $.
|
||||
// If preceded by = or : or a non-prompt /, it's likely a variable reference
|
||||
if (prev === "=" || prev === ":" || (prev === "/" && !isRootOrSlashPathPrompt)) continue;
|
||||
}
|
||||
|
||||
// Check what follows: if after "$ " there's more content with $ in variable positions
|
||||
// Actually the simplest reliable check: if the character after the space is alphanumeric
|
||||
// or $ or (, this is likely the START of a command (i.e., this $ IS the prompt ending).
|
||||
// That's always true for a prompt. So the $ check is really about false positives mid-line.
|
||||
//
|
||||
// Better heuristic: if we haven't seen a space before this $ (meaning the $ is inside
|
||||
// the first token), it's likely a prompt. If we've already passed spaces (meaning
|
||||
// we're past the first "word"), a $ is more likely a variable.
|
||||
@@ -827,10 +934,10 @@ function findPromptBoundary(lineText: string): number {
|
||||
// If there was a space before this $, it might be mid-command (like "echo $HOME")
|
||||
// Only accept if the $ is reasonably close to common prompt patterns
|
||||
if (seenSpaceBeforeDollar) {
|
||||
// Check if this looks like a bracketed prompt ending: "]$ " or ")$ "
|
||||
// Check if this looks like a bracketed or host:path prompt ending: "]$ ", ")$ ", "user@host:/$ "
|
||||
if (i > 0 && (lineText[i - 1] === "]" || lineText[i - 1] === ")" ||
|
||||
lineText[i - 1] === " " || lineText[i - 1] === "~")) {
|
||||
// Likely a prompt ending like [user@host ~]$
|
||||
lineText[i - 1] === " " || lineText[i - 1] === "~" || isRootOrSlashPathPrompt)) {
|
||||
// Likely a prompt ending like [user@host ~]$ or (venv) user@host:/$
|
||||
} else {
|
||||
continue; // Skip — likely a variable reference mid-command
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
canSendSftpPathToTerminal,
|
||||
formatSftpCdCommand,
|
||||
formatSftpPathForTerminalInsert,
|
||||
hasUnsafeTerminalControlChars,
|
||||
isShellDraftSafeForPathInsertion,
|
||||
isTerminalContinuationPrompt,
|
||||
isTerminalDraftContextSafeForCd,
|
||||
isTerminalDraftContextSafeForPathInsertion,
|
||||
quoteSftpPathForShell,
|
||||
resolveCdSftpPathInTerminalAction,
|
||||
resolveInsertSftpPathInTerminalAction,
|
||||
resolveSftpTerminalShellKind,
|
||||
type SftpTerminalShellKind,
|
||||
} from "./sftpTerminalPath.ts";
|
||||
|
||||
const baseRemote = {
|
||||
sessionId: "sess-1",
|
||||
sessionStatus: "connected" as const,
|
||||
sessionHostId: "host-1",
|
||||
sftpHostId: "host-1",
|
||||
sftpIsLocal: false,
|
||||
protocol: "ssh" as const,
|
||||
shellType: "posix" as const,
|
||||
isNetworkDevice: false,
|
||||
};
|
||||
|
||||
test("resolveSftpTerminalShellKind maps shellType, live prompt, and host OS to quoting dialect", () => {
|
||||
assert.equal(resolveSftpTerminalShellKind("posix"), "posix");
|
||||
assert.equal(resolveSftpTerminalShellKind("fish"), "fish");
|
||||
assert.equal(resolveSftpTerminalShellKind("powershell"), "powershell");
|
||||
assert.equal(resolveSftpTerminalShellKind("cmd"), "cmd");
|
||||
assert.equal(resolveSftpTerminalShellKind("unknown"), "unix-portable");
|
||||
assert.equal(resolveSftpTerminalShellKind(undefined), "unix-portable");
|
||||
assert.equal(resolveSftpTerminalShellKind(null), "unix-portable");
|
||||
|
||||
// Remote SSH without shellType infers PowerShell/CMD from live prompt text.
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { promptText: "PS C:\\Users\\alice> ", hostOs: "windows" }),
|
||||
"powershell",
|
||||
);
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { promptText: "(venv) PS /home/alice> ", hostOs: "linux" }),
|
||||
"powershell",
|
||||
);
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { promptText: "C:\\Users\\alice>", hostOs: "windows" }),
|
||||
"cmd",
|
||||
);
|
||||
|
||||
// Unknown Windows host or Windows path must never silently fall back to POSIX.
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { hostOs: "windows" }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { promptText: "custom> ", hostOs: "windows" }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { path: "/C:/Users/alice/file.txt" }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSftpTerminalShellKind(undefined, { path: "C:\\Users\\alice\\file.txt" }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("formatSftpPathForTerminalInsert quotes POSIX paths safely with trailing space", () => {
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/etc/nginx/nginx.conf", "posix"),
|
||||
"/etc/nginx/nginx.conf ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/srv/my app/docker-compose.yml", "posix"),
|
||||
"'/srv/my app/docker-compose.yml' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/srv/it's/file.txt", "posix"),
|
||||
"'/srv/it'\\''s/file.txt' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/$(whoami).txt", "posix"),
|
||||
"'/tmp/$(whoami).txt' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/`id`/a;rm -rf /.txt", "posix"),
|
||||
"'/tmp/`id`/a;rm -rf /.txt' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/a\"$HOME/file*.log", "posix"),
|
||||
"'/tmp/a\"$HOME/file*.log' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/srv/dir ", "posix"),
|
||||
"'/srv/dir ' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("-rf", "posix"),
|
||||
"'-rf' ",
|
||||
);
|
||||
});
|
||||
|
||||
test("formatSftpPathForTerminalInsert escapes backslashes and quotes for fish", () => {
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/srv/simple.txt", "fish"),
|
||||
"/srv/simple.txt ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/srv/a\\b's (id).txt", "fish"),
|
||||
"'/srv/a\\\\b\\'s (id).txt' ",
|
||||
);
|
||||
});
|
||||
|
||||
test("formatSftpPathForTerminalInsert quotes PowerShell paths including smart quotes", () => {
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\Users\\alice\\file.txt", "powershell"),
|
||||
"C:\\Users\\alice\\file.txt ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\Program Files\\My App\\run.ps1", "powershell"),
|
||||
"'C:\\Program Files\\My App\\run.ps1' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\Users\\O'Brien\\$(calc).txt", "powershell"),
|
||||
"'C:\\Users\\O''Brien\\$(calc).txt' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\tmp\\`n;calc.exe", "powershell"),
|
||||
"'C:\\tmp\\`n;calc.exe' ",
|
||||
);
|
||||
// PowerShell treats U+2018..U+201B as single-quote delimiters.
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\tmp\\a\u2019;calc", "powershell"),
|
||||
"'C:\\tmp\\a\u2019\u2019;calc' ",
|
||||
);
|
||||
});
|
||||
|
||||
test("formatSftpPathForTerminalInsert handles CMD paths and blocks unquotable characters", () => {
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\Users\\alice\\file.txt", "cmd"),
|
||||
"C:\\Users\\alice\\file.txt ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("C:\\Program Files\\app & calc.txt", "cmd"),
|
||||
"\"C:\\Program Files\\app & calc.txt\" ",
|
||||
);
|
||||
// Double quote, %, and ! cannot be safely escaped in interactive cmd.exe.
|
||||
assert.equal(formatSftpPathForTerminalInsert("C:\\tmp\\a\" & calc", "cmd"), null);
|
||||
assert.equal(formatSftpPathForTerminalInsert("C:\\tmp\\%COMSPEC%", "cmd"), null);
|
||||
assert.equal(formatSftpPathForTerminalInsert("C:\\tmp\\!PATH!", "cmd"), null);
|
||||
});
|
||||
|
||||
test("control characters and line separators are rejected across all shells", () => {
|
||||
const payloads = [
|
||||
"/tmp/evil\nrm -rf /",
|
||||
"/tmp/evil\rrm -rf /",
|
||||
"/tmp/evil\r\nwhoami",
|
||||
"/tmp/evil\x00file",
|
||||
"/tmp/evil\tfile",
|
||||
"/tmp/evil\x03file",
|
||||
"/tmp/evil\x1b[31mfile",
|
||||
"/tmp/evil\x7ffile",
|
||||
"/tmp/evil\x85file",
|
||||
"/tmp/evil\x9b31mfile",
|
||||
"/tmp/evil\u2028file",
|
||||
"/tmp/evil\u2029file",
|
||||
];
|
||||
const shells: SftpTerminalShellKind[] = ["posix", "fish", "powershell", "cmd"];
|
||||
|
||||
for (const payload of payloads) {
|
||||
assert.equal(hasUnsafeTerminalControlChars(payload), true, JSON.stringify(payload));
|
||||
for (const shell of shells) {
|
||||
assert.equal(quoteSftpPathForShell(payload, shell), null, `${shell}: ${JSON.stringify(payload)}`);
|
||||
assert.equal(formatSftpPathForTerminalInsert(payload, shell), null, `${shell}: ${JSON.stringify(payload)}`);
|
||||
assert.equal(formatSftpCdCommand(payload, shell), null, `${shell}: ${JSON.stringify(payload)}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const blank of ["", " ", null, undefined]) {
|
||||
assert.equal(formatSftpPathForTerminalInsert(blank, "posix"), null);
|
||||
assert.equal(formatSftpCdCommand(blank, "posix"), null);
|
||||
}
|
||||
});
|
||||
|
||||
test("formatSftpCdCommand builds safe cd commands for POSIX, fish, PowerShell, and CMD", () => {
|
||||
assert.equal(formatSftpCdCommand("/srv/app", "posix"), "cd -- '/srv/app'");
|
||||
assert.equal(formatSftpCdCommand("/srv/my 'app' $(id)", "posix"), "cd -- '/srv/my '\\''app'\\'' $(id)'");
|
||||
assert.equal(formatSftpCdCommand("~", "posix"), "cd -- ~");
|
||||
assert.equal(formatSftpCdCommand("~/my docs", "posix"), "cd -- ~/'my docs'");
|
||||
assert.equal(formatSftpCdCommand("relative/dir", "posix"), null);
|
||||
assert.equal(formatSftpCdCommand("C:\\Users\\alice", "posix"), null);
|
||||
|
||||
assert.equal(formatSftpCdCommand("/srv/a\\b'c", "fish"), "cd -- '/srv/a\\\\b\\'c'");
|
||||
assert.equal(formatSftpCdCommand("~/a'b", "fish"), "cd -- ~/'a\\'b'");
|
||||
|
||||
assert.equal(
|
||||
formatSftpCdCommand("C:\\Users\\O'Brien\\[prod]", "powershell"),
|
||||
"cd -LiteralPath 'C:\\Users\\O''Brien\\[prod]'",
|
||||
);
|
||||
assert.equal(formatSftpCdCommand("~", "powershell"), "cd ~");
|
||||
assert.equal(
|
||||
formatSftpCdCommand("\\\\server\\share\\dir", "powershell"),
|
||||
"cd -LiteralPath '\\\\server\\share\\dir'",
|
||||
);
|
||||
assert.equal(formatSftpCdCommand("relative\\dir", "powershell"), null);
|
||||
|
||||
assert.equal(formatSftpCdCommand("C:\\Program Files\\app", "cmd"), "cd /d \"C:\\Program Files\\app\"");
|
||||
assert.equal(formatSftpCdCommand("D:\\", "cmd"), "cd /d \"D:\\\"");
|
||||
assert.equal(formatSftpCdCommand("/srv/app", "cmd"), null);
|
||||
assert.equal(formatSftpCdCommand("C:\\tmp\\%USERNAME%", "cmd"), null);
|
||||
assert.equal(formatSftpCdCommand("C:\\tmp\\a\" & calc", "cmd"), null);
|
||||
});
|
||||
|
||||
test("canSendSftpPathToTerminal enforces connected, same-endpoint, non-network-device pairing", () => {
|
||||
assert.equal(canSendSftpPathToTerminal(baseRemote), true);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, protocol: "mosh" }), true);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, protocol: "et" }), true);
|
||||
|
||||
// Local SFTP paired with local terminal (including Windows PowerShell & CMD).
|
||||
assert.equal(
|
||||
canSendSftpPathToTerminal({
|
||||
sessionId: "local-1",
|
||||
sessionStatus: "connected",
|
||||
sftpIsLocal: true,
|
||||
protocol: "local",
|
||||
shellType: "powershell",
|
||||
isNetworkDevice: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
canSendSftpPathToTerminal({
|
||||
sessionId: "local-2",
|
||||
sessionStatus: "connected",
|
||||
sftpIsLocal: true,
|
||||
protocol: "local",
|
||||
shellType: "cmd",
|
||||
isNetworkDevice: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
// Rejected cases
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, sessionId: null }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, sessionStatus: "disconnected" }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, sessionStatus: "connecting" }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, isNetworkDevice: true }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, protocol: "telnet" }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, protocol: "serial" }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, sftpHostId: "host-2" }), false);
|
||||
assert.equal(canSendSftpPathToTerminal({ ...baseRemote, sftpIsLocal: true, protocol: "ssh" }), false);
|
||||
assert.equal(
|
||||
canSendSftpPathToTerminal({
|
||||
...baseRemote,
|
||||
sessionHostname: "a.example.test",
|
||||
sftpHostname: "b.example.test",
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveInsertSftpPathInTerminalAction and resolveCdSftpPathInTerminalAction build PTY payloads", () => {
|
||||
assert.deepEqual(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
...baseRemote,
|
||||
path: "/srv/app/my file.yml",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: "'/srv/app/my file.yml' ",
|
||||
shellKind: "posix",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
resolveCdSftpPathInTerminalAction({
|
||||
...baseRemote,
|
||||
path: "/srv/app dir",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: "cd -- '/srv/app dir'\r",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
sessionId: "win-1",
|
||||
sessionStatus: "connected",
|
||||
sftpIsLocal: true,
|
||||
protocol: "local",
|
||||
shellType: "powershell",
|
||||
path: "C:\\Program Files\\app.exe",
|
||||
}),
|
||||
{
|
||||
sessionId: "win-1",
|
||||
data: "'C:\\Program Files\\app.exe' ",
|
||||
shellKind: "powershell",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
resolveCdSftpPathInTerminalAction({
|
||||
sessionId: "win-2",
|
||||
sessionStatus: "connected",
|
||||
sftpIsLocal: true,
|
||||
protocol: "local",
|
||||
shellType: "cmd",
|
||||
path: "D:\\work dir",
|
||||
}),
|
||||
{
|
||||
sessionId: "win-2",
|
||||
data: "cd /d \"D:\\work dir\"\r",
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
...baseRemote,
|
||||
path: "/srv/evil\nid",
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCdSftpPathInTerminalAction({
|
||||
...baseRemote,
|
||||
path: "/srv/evil\nid",
|
||||
}),
|
||||
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);
|
||||
|
||||
// Trailing unescaped `$` would fuse with an inserted `'...'` into ANSI-C `$'...'`,
|
||||
// turning `/tmp/\'; printf INJECTED; #` into an unquoted breakout.
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $$", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(echo $", "posix"), false);
|
||||
assert.equal(
|
||||
isTerminalDraftContextSafeForPathInsertion({
|
||||
promptText: "user@host:~$ ",
|
||||
userInput: "echo $",
|
||||
pendingTypedInput: "echo $",
|
||||
shellKind: "posix",
|
||||
}),
|
||||
false,
|
||||
);
|
||||
// Escaped `$` or `$VAR` (not immediately preceding the inserted quote) stays safe.
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo \\$", "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $HOME", "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $HOME ", "posix"), true);
|
||||
});
|
||||
|
||||
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);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $", "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 @", "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,
|
||||
);
|
||||
});
|
||||
|
||||
test("isShellDraftSafeForPathInsertion rejects POSIX arithmetic, parameter expansion, array subscripts, and let contexts", () => {
|
||||
// Arithmetic expansion $(( ... )) and arithmetic command (( ... ))
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $((", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(( 1 + ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion('echo "$((', "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(( (1 + 2) + ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("(( ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("for (( i=0; ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(( $(echo ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(( 'a))' + ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(( 1 + 2 )) ", "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(( (1 + 2) + 3 )) ", "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion('echo "$((1 + 2))" ', "posix"), true);
|
||||
|
||||
// Legacy $[...] arithmetic
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $[", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion('echo "$[', "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $[1 + 2] ", "posix"), true);
|
||||
|
||||
// Parameter expansions and array subscripts
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo ${a[", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion('echo "${a[', "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo ${var:-", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("a[", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("unset arr[", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("declare -i x[", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("cp ${DIR}/", "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion('echo "${a[0]}" ', "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("a[0]=", "posix"), true);
|
||||
|
||||
// `let` arithmetic builtin and `[[` arithmetic comparison operators
|
||||
assert.equal(isShellDraftSafeForPathInsertion("let ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo ok; let ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $(let ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion('echo "foo; let " ', "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("[[ 1 -eq ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("[[ $x -gt ", "posix"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("[[ -f ", "posix"), true);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("[[ 1 -eq 1 ]] && ls ", "posix"), true);
|
||||
});
|
||||
|
||||
test("isTerminalDraftContextSafeForCd rejects continuation prompts and non-empty drafts", () => {
|
||||
assert.equal(
|
||||
isTerminalDraftContextSafeForCd({
|
||||
promptText: "user@host:~$ ",
|
||||
userInput: "",
|
||||
pendingTypedInput: "",
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isTerminalDraftContextSafeForCd({
|
||||
promptText: "root@host:/# ",
|
||||
userInput: "",
|
||||
pendingTypedInput: "",
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
// Continuation prompts must be rejected even when draft input is empty
|
||||
for (const promptText of [
|
||||
"dquote> ",
|
||||
"quote> ",
|
||||
"> ",
|
||||
">> ",
|
||||
"heredoc> ",
|
||||
"dquote cmdsubst> ",
|
||||
"pipe dquote> ",
|
||||
"More? ",
|
||||
]) {
|
||||
assert.equal(
|
||||
isTerminalDraftContextSafeForCd({
|
||||
promptText,
|
||||
userInput: "",
|
||||
pendingTypedInput: "",
|
||||
}),
|
||||
false,
|
||||
`expected continuation prompt ${JSON.stringify(promptText)} to block auto-cd`,
|
||||
);
|
||||
}
|
||||
|
||||
// Non-empty draft input or un-echoed typed input must block auto-cd
|
||||
assert.equal(
|
||||
isTerminalDraftContextSafeForCd({
|
||||
promptText: "user@host:~$ ",
|
||||
userInput: "ls ",
|
||||
pendingTypedInput: "",
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isTerminalDraftContextSafeForCd({
|
||||
promptText: "user@host:~$ ",
|
||||
userInput: "",
|
||||
pendingTypedInput: "rm -rf",
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("unix-portable dialect quotes backslashes and quotes identically for POSIX and fish and intersects draft safety", () => {
|
||||
// Consecutive and trailing backslashes are emitted outside single quotes so
|
||||
// both POSIX shells (sh/bash/zsh) and fish decode the exact same literal path.
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/a\\b", "unix-portable"),
|
||||
"'/tmp/a'\\\\'b' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/a\\\\b", "unix-portable"),
|
||||
"'/tmp/a'\\\\\\\\'b' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/a\\", "unix-portable"),
|
||||
"'/tmp/a'\\\\ ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpPathForTerminalInsert("/tmp/a\\'b", "unix-portable"),
|
||||
"'/tmp/a'\\\\\\''b' ",
|
||||
);
|
||||
assert.equal(
|
||||
formatSftpCdCommand("/tmp/a\\\\b", "unix-portable"),
|
||||
"cd -- '/tmp/a'\\\\\\\\'b'",
|
||||
);
|
||||
|
||||
// Draft validation under unix-portable rejects BOTH POSIX-unsafe arithmetic
|
||||
// AND fish-unsafe escaped single quotes (`'foo\'` is unclosed in fish).
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo $((", "unix-portable"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("echo 'foo\\'", "unix-portable"), false);
|
||||
assert.equal(isShellDraftSafeForPathInsertion("cat ", "unix-portable"), true);
|
||||
});
|
||||
|
||||
test("remote SSH sessions with unset shellType resolve PowerShell/CMD from prompt, normalize /C:/ paths, and reject unknown Windows shells", () => {
|
||||
const remoteNoShellType = { ...baseRemote, shellType: undefined };
|
||||
|
||||
// Remote Unix SSH uses unix-portable dialect for backslash paths.
|
||||
assert.deepEqual(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "linux",
|
||||
promptText: "user@host ~> ",
|
||||
path: "/tmp/a\\\\b",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: "'/tmp/a'\\\\\\\\'b' ",
|
||||
shellKind: "unix-portable",
|
||||
},
|
||||
);
|
||||
|
||||
// Remote Windows OpenSSH running PowerShell normalizes /C:/... paths.
|
||||
assert.deepEqual(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "windows",
|
||||
promptText: "PS C:\\Users\\alice> ",
|
||||
path: "/C:/Users/alice/my file.txt",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: "'C:\\Users\\alice\\my file.txt' ",
|
||||
shellKind: "powershell",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
resolveCdSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "windows",
|
||||
promptText: "PS C:\\Users\\alice> ",
|
||||
path: "/C:/Users/alice/my dir",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: "cd -LiteralPath 'C:\\Users\\alice\\my dir'\r",
|
||||
},
|
||||
);
|
||||
|
||||
// Remote Windows OpenSSH running cmd.exe normalizes /C:/... paths.
|
||||
assert.deepEqual(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "windows",
|
||||
promptText: "C:\\Users\\alice>",
|
||||
path: "/C:/Users/alice/my file.txt",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: '"C:\\Users\\alice\\my file.txt" ',
|
||||
shellKind: "cmd",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
resolveCdSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "windows",
|
||||
promptText: "C:\\Users\\alice>",
|
||||
path: "/C:/Users/alice/my dir",
|
||||
}),
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
data: 'cd /d "C:\\Users\\alice\\my dir"\r',
|
||||
},
|
||||
);
|
||||
|
||||
// Remote Windows SSH with unknown shell dialect refuses instead of emitting POSIX syntax.
|
||||
assert.equal(
|
||||
resolveInsertSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "windows",
|
||||
promptText: "custom> ",
|
||||
path: "/C:/Users/alice/my file.txt",
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCdSftpPathInTerminalAction({
|
||||
...remoteNoShellType,
|
||||
hostOs: "windows",
|
||||
promptText: "custom> ",
|
||||
path: "/C:/Users/alice/my dir",
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,968 @@
|
||||
export type SftpTerminalShellKind = "posix" | "fish" | "unix-portable" | "powershell" | "cmd";
|
||||
|
||||
export type SftpTerminalPathContext = {
|
||||
sessionId?: string | null;
|
||||
sessionStatus?: string | null;
|
||||
sessionHostId?: string | null;
|
||||
sftpHostId?: string | null;
|
||||
sftpIsLocal?: boolean;
|
||||
protocol?: string | null;
|
||||
shellType?: string | null;
|
||||
hostOs?: string | null;
|
||||
promptText?: string | null;
|
||||
isNetworkDevice?: boolean;
|
||||
sessionHostname?: string | null;
|
||||
sessionUsername?: string | null;
|
||||
sessionPort?: number | null;
|
||||
sftpHostname?: string | null;
|
||||
sftpUsername?: string | null;
|
||||
sftpPort?: number | null;
|
||||
};
|
||||
|
||||
const POSIX_SAFE_UNQUOTED_RE = /^[A-Za-z0-9._/@:+][A-Za-z0-9._/@:+-]*$/;
|
||||
const WINDOWS_SAFE_UNQUOTED_RE = /^[A-Za-z0-9._\\/:+][A-Za-z0-9._\\/:+-]*$/;
|
||||
const WINDOWS_DRIVE_PATH_RE = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_OPENSSH_DRIVE_PATH_RE = /^\/[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_RE = /^\\\\[^\\]+\\[^\\]+/;
|
||||
// PowerShell prompt (e.g. `PS C:\Users\alice> `, `PS /home/alice> `, `(venv) PS C:\> `).
|
||||
const POWERSHELL_PROMPT_RE = /^(?:\([^)]+\)\s+)*PS\s+(?:[A-Za-z]:[\\/]|\\\\|\/|~|\S+[^>]*)\s*>\s*$/;
|
||||
// cmd.exe prompt (e.g. `C:\Users\alice>`, `D:\work>`).
|
||||
const CMD_PROMPT_RE = /^[A-Za-z]:\\[^>]*>\s*$/;
|
||||
// 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_WORD =
|
||||
"(?:[a-z]*quote|heredoc|cmdsubst|pipe|for|if|while|until|case|select|then|else|elif|cursh|subsh|brace|math|array|param|function|repeat|foreach|eval|and|or)";
|
||||
const CONTINUATION_PROMPT_RE = new RegExp(
|
||||
`^(?:(?:${CONTINUATION_PROMPT_WORD}(?:\\s+${CONTINUATION_PROMPT_WORD})*)?>|>>?|More\\?)\\s*$`,
|
||||
"i",
|
||||
);
|
||||
|
||||
/**
|
||||
* True when a string contains control bytes (C0, DEL, C1) or Unicode line
|
||||
* separators that an interactive PTY, readline, or shell could interpret as
|
||||
* keystrokes or command terminators even inside quotes.
|
||||
*/
|
||||
export function hasUnsafeTerminalControlChars(value: string): boolean {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
const code = value.charCodeAt(i);
|
||||
if (
|
||||
code <= 0x1f
|
||||
|| (code >= 0x7f && code <= 0x9f)
|
||||
|| code === 0x2028
|
||||
|| code === 0x2029
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isWindowsStylePath(path?: string | null): boolean {
|
||||
const trimmed = path?.trim() ?? "";
|
||||
if (!trimmed) return false;
|
||||
return WINDOWS_DRIVE_PATH_RE.test(trimmed)
|
||||
|| WINDOWS_OPENSSH_DRIVE_PATH_RE.test(trimmed)
|
||||
|| WINDOWS_UNC_PATH_RE.test(trimmed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize Windows OpenSSH SFTP drive paths (e.g. `/C:/Users/alice`) into
|
||||
* native drive-letter paths (`C:\Users\alice`) for PowerShell and cmd.exe.
|
||||
*/
|
||||
function normalizeWindowsShellPath(
|
||||
path: string,
|
||||
shellKind: "powershell" | "cmd",
|
||||
): string {
|
||||
if (WINDOWS_OPENSSH_DRIVE_PATH_RE.test(path)) {
|
||||
return path.slice(1).replace(/\//g, "\\");
|
||||
}
|
||||
if (shellKind === "cmd" && WINDOWS_DRIVE_PATH_RE.test(path)) {
|
||||
return path.replace(/\//g, "\\");
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a terminal session's shellType, live prompt text, host OS, and path
|
||||
* shape to a concrete quoting dialect.
|
||||
*
|
||||
* When `shellType` is unset on a remote session:
|
||||
* - Recognizes PowerShell (`PS ...>`) and CMD (`C:\...>`) from the live prompt.
|
||||
* - Refuses (`null`) on Windows hosts or Windows drive/UNC paths when the
|
||||
* active Windows shell dialect cannot be identified, avoiding incompatible
|
||||
* POSIX quoting.
|
||||
* - Uses `"unix-portable"` on non-Windows hosts so quoting works identically
|
||||
* across POSIX shells (sh/bash/zsh/dash/ksh) and fish, even for paths
|
||||
* containing backslashes.
|
||||
*/
|
||||
export function resolveSftpTerminalShellKind(
|
||||
shellType?: string | null,
|
||||
options?: {
|
||||
promptText?: string | null;
|
||||
hostOs?: string | null;
|
||||
path?: string | null;
|
||||
},
|
||||
): SftpTerminalShellKind | null {
|
||||
if (
|
||||
shellType === "posix"
|
||||
|| shellType === "fish"
|
||||
|| shellType === "powershell"
|
||||
|| shellType === "cmd"
|
||||
) {
|
||||
return shellType;
|
||||
}
|
||||
|
||||
const prompt = options?.promptText?.trim() ?? "";
|
||||
if (prompt) {
|
||||
if (POWERSHELL_PROMPT_RE.test(prompt)) return "powershell";
|
||||
if (CMD_PROMPT_RE.test(prompt)) return "cmd";
|
||||
}
|
||||
|
||||
const isWindowsHost = options?.hostOs?.trim().toLowerCase() === "windows";
|
||||
if (isWindowsHost || isWindowsStylePath(options?.path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return "unix-portable";
|
||||
}
|
||||
|
||||
function quotePosixSingle(value: string): string {
|
||||
return `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
|
||||
function quoteFishSingle(value: string): string {
|
||||
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a path so it evaluates to the exact same literal string in both POSIX
|
||||
* shells (sh/bash/zsh/dash/ksh) and fish. Single quotes keep `$`, `` ` ``, `"`,
|
||||
* spaces, and globs literal, while `'` and `\` are emitted outside single
|
||||
* quotes as `\'` and `\\`, which both POSIX and fish unescape identically.
|
||||
*/
|
||||
function quoteUnixPortable(value: string): string {
|
||||
let out = "";
|
||||
let buf = "";
|
||||
const flush = () => {
|
||||
if (buf.length > 0) {
|
||||
out += `'${buf}'`;
|
||||
buf = "";
|
||||
}
|
||||
};
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
const ch = value[i];
|
||||
if (ch === "'") {
|
||||
flush();
|
||||
out += "\\'";
|
||||
} else if (ch === "\\") {
|
||||
flush();
|
||||
out += "\\\\";
|
||||
} else {
|
||||
buf += ch;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return out || "''";
|
||||
}
|
||||
|
||||
function quoteUnixPath(
|
||||
value: string,
|
||||
shellKind: "posix" | "fish" | "unix-portable",
|
||||
): string {
|
||||
if (shellKind === "fish") return quoteFishSingle(value);
|
||||
if (shellKind === "unix-portable") return quoteUnixPortable(value);
|
||||
return quotePosixSingle(value);
|
||||
}
|
||||
|
||||
function quotePowerShellSingle(value: string): string {
|
||||
return `'${value.replace(POWERSHELL_SINGLE_QUOTE_RE, "$&$&")}'`;
|
||||
}
|
||||
|
||||
function isPosixCdPathEligible(path: string): boolean {
|
||||
const trimmed = path.trim();
|
||||
if (!trimmed) return false;
|
||||
if (WINDOWS_DRIVE_PATH_RE.test(trimmed) || WINDOWS_OPENSSH_DRIVE_PATH_RE.test(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
return trimmed.startsWith("/") || trimmed === "~" || trimmed.startsWith("~/");
|
||||
}
|
||||
|
||||
function isPowerShellCdPathEligible(path: string): boolean {
|
||||
const trimmed = path.trim();
|
||||
if (!trimmed) return false;
|
||||
return WINDOWS_DRIVE_PATH_RE.test(trimmed)
|
||||
|| WINDOWS_UNC_PATH_RE.test(trimmed)
|
||||
|| trimmed.startsWith("/")
|
||||
|| trimmed === "~"
|
||||
|| trimmed.startsWith("~/")
|
||||
|| trimmed.startsWith("~\\");
|
||||
}
|
||||
|
||||
function isCmdCdPathEligible(path: string): boolean {
|
||||
const trimmed = path.trim();
|
||||
if (!trimmed) return false;
|
||||
return WINDOWS_DRIVE_PATH_RE.test(trimmed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a filesystem path for safe insertion into an interactive shell line.
|
||||
* Returns null if the path is blank, contains control characters, or contains
|
||||
* shell-unquotable expansion characters (e.g. `"`, `%`, `!` in interactive cmd.exe).
|
||||
*/
|
||||
export function quoteSftpPathForShell(
|
||||
path: string | null | undefined,
|
||||
shellKind: SftpTerminalShellKind = "posix",
|
||||
): string | null {
|
||||
if (!path || !path.trim()) return null;
|
||||
if (hasUnsafeTerminalControlChars(path)) return null;
|
||||
|
||||
if (shellKind === "powershell") {
|
||||
const normalized = normalizeWindowsShellPath(path, "powershell");
|
||||
if (WINDOWS_SAFE_UNQUOTED_RE.test(normalized)) return normalized;
|
||||
return quotePowerShellSingle(normalized);
|
||||
}
|
||||
|
||||
if (shellKind === "cmd") {
|
||||
const normalized = normalizeWindowsShellPath(path, "cmd");
|
||||
// Interactive cmd.exe expands %VAR% and delayed !VAR! inside double quotes,
|
||||
// and double quotes cannot be safely escaped without risking command breakout.
|
||||
if (normalized.includes('"') || normalized.includes("%") || normalized.includes("!")) return null;
|
||||
if (WINDOWS_SAFE_UNQUOTED_RE.test(normalized)) return normalized;
|
||||
return `"${normalized}"`;
|
||||
}
|
||||
|
||||
if (POSIX_SAFE_UNQUOTED_RE.test(path)) return path;
|
||||
return quoteUnixPath(path, shellKind);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format an SFTP file or directory path for inserting at the cursor in an
|
||||
* interactive terminal (quoted as needed, followed by a trailing space, no CR/LF).
|
||||
*/
|
||||
export function formatSftpPathForTerminalInsert(
|
||||
path: string | null | undefined,
|
||||
shellKind: SftpTerminalShellKind = "posix",
|
||||
): string | null {
|
||||
const quoted = quoteSftpPathForShell(path, shellKind);
|
||||
if (!quoted) return null;
|
||||
return `${quoted} `;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a safe interactive `cd` command (without trailing CR) for the target shell.
|
||||
*/
|
||||
export function formatSftpCdCommand(
|
||||
dirPath: string | null | undefined,
|
||||
shellKind: SftpTerminalShellKind = "posix",
|
||||
): string | null {
|
||||
if (!dirPath || !dirPath.trim()) return null;
|
||||
if (hasUnsafeTerminalControlChars(dirPath)) return null;
|
||||
|
||||
if (shellKind === "powershell") {
|
||||
const normalized = normalizeWindowsShellPath(dirPath, "powershell");
|
||||
if (!isPowerShellCdPathEligible(normalized)) return null;
|
||||
if (normalized === "~") return "cd ~";
|
||||
return `cd -LiteralPath ${quotePowerShellSingle(normalized)}`;
|
||||
}
|
||||
|
||||
if (shellKind === "cmd") {
|
||||
const normalized = normalizeWindowsShellPath(dirPath, "cmd");
|
||||
if (!isCmdCdPathEligible(normalized)) return null;
|
||||
if (normalized.includes('"') || normalized.includes("%") || normalized.includes("!")) return null;
|
||||
return `cd /d "${normalized}"`;
|
||||
}
|
||||
|
||||
if (!isPosixCdPathEligible(dirPath)) return null;
|
||||
if (dirPath === "~") return "cd -- ~";
|
||||
if (dirPath.startsWith("~/")) {
|
||||
const suffix = dirPath.slice(2);
|
||||
if (!suffix) return "cd -- ~";
|
||||
const quotedSuffix = quoteUnixPath(suffix, shellKind);
|
||||
return `cd -- ~/${quotedSuffix}`;
|
||||
}
|
||||
const quotedDir = quoteUnixPath(dirPath, shellKind);
|
||||
return `cd -- ${quotedDir}`;
|
||||
}
|
||||
|
||||
function remoteEndpointsMatch(options: SftpTerminalPathContext): boolean {
|
||||
if (!options.sessionHostname || !options.sftpHostname) return true;
|
||||
return options.sessionHostname === options.sftpHostname
|
||||
&& (options.sessionPort ?? 22) === (options.sftpPort ?? 22)
|
||||
&& (options.sessionUsername || "root") === (options.sftpUsername || "root");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an SFTP side panel is paired with a connected terminal session on the
|
||||
* same host/endpoint where paths may be inserted or `cd`'d into.
|
||||
*/
|
||||
export function canSendSftpPathToTerminal(
|
||||
options: SftpTerminalPathContext,
|
||||
): boolean {
|
||||
if (!options.sessionId || options.sessionStatus !== "connected") return false;
|
||||
if (options.isNetworkDevice) return false;
|
||||
|
||||
const protocol = options.protocol ?? "ssh";
|
||||
if (protocol === "telnet" || protocol === "serial") return false;
|
||||
|
||||
if (options.sftpIsLocal) {
|
||||
return protocol === "local";
|
||||
}
|
||||
|
||||
if (!options.sftpHostId || !options.sessionHostId) return false;
|
||||
if (options.sftpHostId !== options.sessionHostId) return false;
|
||||
if (!remoteEndpointsMatch(options)) return false;
|
||||
|
||||
return protocol === "ssh"
|
||||
|| protocol === "mosh"
|
||||
|| protocol === "et"
|
||||
|| protocol === "local";
|
||||
}
|
||||
|
||||
const POSIX_IDENTIFIER_CHAR_RE = /[A-Za-z0-9_]/;
|
||||
const POSIX_LET_COMMAND_RE = /^\s*let(?:\s+|$)/;
|
||||
const POSIX_DOUBLE_BRACKET_ARITH_OP_RE = /(?:^|\s)-(?:eq|ne|lt|le|gt|ge)\s+\S*$/;
|
||||
|
||||
function isPosixDraftSafeForPathInsertion(draft: string): boolean {
|
||||
type Frame =
|
||||
| { kind: "single" }
|
||||
| { kind: "ansiSingle" }
|
||||
| { kind: "double" }
|
||||
| { kind: "backtick" }
|
||||
| { kind: "cmdsubst"; parenDepth: number; segmentStart: number }
|
||||
| { kind: "arith"; parenDepth: number }
|
||||
| { kind: "arithBracket"; bracketDepth: number }
|
||||
| { kind: "param" }
|
||||
| { kind: "subscript"; bracketDepth: number }
|
||||
| { kind: "doubleBracket"; startIdx: number };
|
||||
|
||||
const stack: Frame[] = [];
|
||||
let rootSegmentStart = 0;
|
||||
|
||||
for (let i = 0; i < draft.length; i += 1) {
|
||||
const ch = draft[i];
|
||||
const top = stack[stack.length - 1];
|
||||
|
||||
if (top?.kind === "single") {
|
||||
if (ch === "'") stack.pop();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "ansiSingle") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") stack.pop();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "double") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(" && draft[i + 2] === "(") {
|
||||
stack.push({ kind: "arith", parenDepth: 0 });
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(") {
|
||||
stack.push({ kind: "cmdsubst", parenDepth: 0, segmentStart: i + 2 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "[") {
|
||||
stack.push({ kind: "arithBracket", bracketDepth: 0 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "{") {
|
||||
stack.push({ kind: "param" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
stack.push({ kind: "backtick" });
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') stack.pop();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "backtick") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") stack.pop();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "arith") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(" && draft[i + 2] === "(") {
|
||||
stack.push({ kind: "arith", parenDepth: 0 });
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(") {
|
||||
stack.push({ kind: "cmdsubst", parenDepth: 0, segmentStart: i + 2 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "[") {
|
||||
stack.push({ kind: "arithBracket", bracketDepth: 0 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "{") {
|
||||
stack.push({ kind: "param" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "'") {
|
||||
stack.push({ kind: "ansiSingle" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
stack.push({ kind: "single" });
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
stack.push({ kind: "double" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
stack.push({ kind: "backtick" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "(") {
|
||||
top.parenDepth += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === ")") {
|
||||
if (top.parenDepth > 0) {
|
||||
top.parenDepth -= 1;
|
||||
continue;
|
||||
}
|
||||
if (draft[i + 1] === ")") {
|
||||
stack.pop();
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "arithBracket") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "'") {
|
||||
stack.push({ kind: "ansiSingle" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
stack.push({ kind: "single" });
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
stack.push({ kind: "double" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
stack.push({ kind: "backtick" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "[") {
|
||||
top.bracketDepth += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "]") {
|
||||
if (top.bracketDepth > 0) {
|
||||
top.bracketDepth -= 1;
|
||||
} else {
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "param") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "'") {
|
||||
stack.push({ kind: "ansiSingle" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(" && draft[i + 2] === "(") {
|
||||
stack.push({ kind: "arith", parenDepth: 0 });
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(") {
|
||||
stack.push({ kind: "cmdsubst", parenDepth: 0, segmentStart: i + 2 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "[") {
|
||||
stack.push({ kind: "arithBracket", bracketDepth: 0 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "{") {
|
||||
stack.push({ kind: "param" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
stack.push({ kind: "single" });
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
stack.push({ kind: "double" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
stack.push({ kind: "backtick" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "}") {
|
||||
stack.pop();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (top?.kind === "subscript") {
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "'") {
|
||||
stack.push({ kind: "ansiSingle" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(" && draft[i + 2] === "(") {
|
||||
stack.push({ kind: "arith", parenDepth: 0 });
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(") {
|
||||
stack.push({ kind: "cmdsubst", parenDepth: 0, segmentStart: i + 2 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "[") {
|
||||
stack.push({ kind: "arithBracket", bracketDepth: 0 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "{") {
|
||||
stack.push({ kind: "param" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
stack.push({ kind: "single" });
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
stack.push({ kind: "double" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
stack.push({ kind: "backtick" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "[") {
|
||||
top.bracketDepth += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "]") {
|
||||
if (top.bracketDepth > 0) {
|
||||
top.bracketDepth -= 1;
|
||||
} else {
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Outside quotes (top === undefined, "cmdsubst", or "doubleBracket")
|
||||
if (ch === "\\") {
|
||||
if (i + 1 >= draft.length) return false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && i === draft.length - 1) {
|
||||
// A trailing unescaped `$` would fuse with an inserted `'...'` into
|
||||
// POSIX/Bash/Zsh ANSI-C `$'...'`, where `\'` escapes quotes.
|
||||
return false;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "'") {
|
||||
stack.push({ kind: "ansiSingle" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(" && draft[i + 2] === "(") {
|
||||
stack.push({ kind: "arith", parenDepth: 0 });
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "(") {
|
||||
stack.push({ kind: "cmdsubst", parenDepth: 0, segmentStart: i + 2 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "[") {
|
||||
stack.push({ kind: "arithBracket", bracketDepth: 0 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$" && draft[i + 1] === "{") {
|
||||
stack.push({ kind: "param" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "(" && draft[i + 1] === "(") {
|
||||
stack.push({ kind: "arith", parenDepth: 0 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
ch === "["
|
||||
&& draft[i + 1] === "["
|
||||
&& (i === 0 || /[\s;|&(\n]/.test(draft[i - 1]))
|
||||
&& (i + 2 >= draft.length || /\s/.test(draft[i + 2]))
|
||||
) {
|
||||
stack.push({ kind: "doubleBracket", startIdx: i + 2 });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
top?.kind === "doubleBracket"
|
||||
&& ch === "]"
|
||||
&& draft[i + 1] === "]"
|
||||
) {
|
||||
stack.pop();
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "[" && i > 0 && POSIX_IDENTIFIER_CHAR_RE.test(draft[i - 1])) {
|
||||
// Array element subscript (e.g. `a[`, `unset arr[`, `declare a[`) is
|
||||
// evaluated in arithmetic context by Bash/Zsh where single quotes do not
|
||||
// suppress `$(...)` expansion.
|
||||
stack.push({ kind: "subscript", bracketDepth: 0 });
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
stack.push({ kind: "single" });
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
stack.push({ kind: "double" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
stack.push({ kind: "backtick" });
|
||||
continue;
|
||||
}
|
||||
if (ch === "(" && top?.kind === "cmdsubst") {
|
||||
top.parenDepth += 1;
|
||||
top.segmentStart = i + 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === ")" && top?.kind === "cmdsubst") {
|
||||
if (top.parenDepth > 0) {
|
||||
top.parenDepth -= 1;
|
||||
} else {
|
||||
stack.pop();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch === ";" || ch === "|" || ch === "&" || ch === "\n" || ch === "(") {
|
||||
if (top?.kind === "cmdsubst") {
|
||||
top.segmentStart = i + 1;
|
||||
} else if (top === undefined) {
|
||||
rootSegmentStart = i + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reject if any enclosing frame is an arithmetic, parameter-expansion, or
|
||||
// array-subscript context (even when nested inside `$(...)`, whose output
|
||||
// would still be re-evaluated by the enclosing arithmetic expression).
|
||||
if (
|
||||
stack.some(
|
||||
(frame) =>
|
||||
frame.kind === "arith"
|
||||
|| frame.kind === "arithBracket"
|
||||
|| frame.kind === "param"
|
||||
|| frame.kind === "subscript",
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const top = stack[stack.length - 1];
|
||||
if (top?.kind === "doubleBracket") {
|
||||
const tail = draft.slice(top.startIdx);
|
||||
if (POSIX_DOUBLE_BRACKET_ARITH_OP_RE.test(tail)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (top !== undefined && top.kind !== "cmdsubst") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Bash/Zsh `let` evaluates all arguments as arithmetic expressions.
|
||||
const segmentStart = top?.kind === "cmdsubst" ? top.segmentStart : rootSegmentStart;
|
||||
const activeSegment = draft.slice(segmentStart);
|
||||
if (POSIX_LET_COMMAND_RE.test(activeSegment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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 === "$" && i === draft.length - 1) return false;
|
||||
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 === "@" && i === draft.length - 1) {
|
||||
// A trailing `@` would fuse with an inserted `'...'` into a PowerShell here-string (`@'`).
|
||||
return false;
|
||||
}
|
||||
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 === "unix-portable") {
|
||||
return isPosixDraftSafeForPathInsertion(draft) && 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)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the live terminal prompt + draft text before automatically
|
||||
* submitting a `cd` command. Rejects secondary/continuation prompts (such as
|
||||
* PS2 `>` or `dquote>`) where the shell is still reading an unterminated quote
|
||||
* or compound command, as well as any non-empty draft input.
|
||||
*/
|
||||
export function isTerminalDraftContextSafeForCd(options: {
|
||||
promptText?: string;
|
||||
userInput: string;
|
||||
pendingTypedInput?: string;
|
||||
}): boolean {
|
||||
if (options.promptText && isTerminalContinuationPrompt(options.promptText)) {
|
||||
return false;
|
||||
}
|
||||
if (options.userInput.trim().length > 0) return false;
|
||||
if ((options.pendingTypedInput ?? "").trim().length > 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 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; shellKind: SftpTerminalShellKind } | null {
|
||||
if (!canSendSftpPathToTerminal(options) || !options.sessionId) return null;
|
||||
const shellKind = resolveSftpTerminalShellKind(options.shellType, {
|
||||
promptText: options.promptText,
|
||||
hostOs: options.hostOs,
|
||||
path: options.path,
|
||||
});
|
||||
if (!shellKind) return null;
|
||||
const data = formatSftpPathForTerminalInsert(options.path, shellKind);
|
||||
if (!data) return null;
|
||||
return { sessionId: options.sessionId, data, shellKind };
|
||||
}
|
||||
|
||||
/** Build the PTY write payload for changing directory in the paired terminal. */
|
||||
export function resolveCdSftpPathInTerminalAction(
|
||||
options: SftpTerminalPathContext & { path?: string | null },
|
||||
): { sessionId: string; data: string } | null {
|
||||
if (!canSendSftpPathToTerminal(options) || !options.sessionId) return null;
|
||||
const shellKind = resolveSftpTerminalShellKind(options.shellType, {
|
||||
promptText: options.promptText,
|
||||
hostOs: options.hostOs,
|
||||
path: options.path,
|
||||
});
|
||||
if (!shellKind) return null;
|
||||
const command = formatSftpCdCommand(options.path, shellKind);
|
||||
if (!command) return null;
|
||||
return { sessionId: options.sessionId, data: `${command}\r` };
|
||||
}
|
||||
@@ -45,6 +45,10 @@ test("rejects sensitive prompts, alt-screen TUIs, partial input, and missing ter
|
||||
isIdleShellReadyForCommandInjection({ ...ready, pendingTypedInputLength: 2 }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isIdleShellReadyForCommandInjection({ ...ready, afterCursorInputLength: 14 }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isIdleShellReadyForCommandInjection({ ...ready, hasLiveTerminal: false }),
|
||||
false,
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface ShellPromptReadiness {
|
||||
isAtPrompt: boolean;
|
||||
userInputLength: number;
|
||||
pendingTypedInputLength?: number;
|
||||
afterCursorInputLength?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -27,5 +28,6 @@ export function isIdleShellReadyForCommandInjection(options: ShellPromptReadines
|
||||
if (!isShellPromptReadyForInsertion(options)) return false;
|
||||
if (options.userInputLength > 0) return false;
|
||||
if ((options.pendingTypedInputLength ?? 0) > 0) return false;
|
||||
if ((options.afterCursorInputLength ?? 0) > 0) return false;
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user