diff --git a/src/backend/ssh/file-manager.ts b/src/backend/ssh/file-manager.ts index 2e5ade28..0860a472 100644 --- a/src/backend/ssh/file-manager.ts +++ b/src/backend/ssh/file-manager.ts @@ -315,6 +315,7 @@ interface SSHSession { lastActive: number; timeout?: NodeJS.Timeout; activeOperations: number; + sudoPassword?: string; } interface PendingTOTPSession { @@ -337,6 +338,45 @@ interface PendingTOTPSession { const sshSessions: Record = {}; const pendingTOTPSessions: Record = {}; +function execWithSudo( + client: SSHClient, + command: string, + sudoPassword: string, +): Promise<{ stdout: string; stderr: string; code: number }> { + return new Promise((resolve) => { + const escapedPassword = sudoPassword.replace(/'/g, "'\"'\"'"); + const sudoCommand = `echo '${escapedPassword}' | sudo -S ${command} 2>&1`; + + client.exec(sudoCommand, (err, stream) => { + if (err) { + resolve({ stdout: "", stderr: err.message, code: 1 }); + return; + } + + let stdout = ""; + let stderr = ""; + + stream.on("data", (chunk: Buffer) => { + stdout += chunk.toString(); + }); + + stream.stderr.on("data", (chunk: Buffer) => { + stderr += chunk.toString(); + }); + + stream.on("close", (code: number) => { + // Filter out sudo password prompt from output + stdout = stdout.replace(/\[sudo\] password for .+?:\s*/g, ""); + resolve({ stdout, stderr, code: code || 0 }); + }); + + stream.on("error", (streamErr: Error) => { + resolve({ stdout, stderr: streamErr.message, code: 1 }); + }); + }); + }); +} + function cleanupSession(sessionId: string) { const session = sshSessions[sessionId]; if (session) { @@ -1205,6 +1245,42 @@ app.post("/ssh/file_manager/ssh/disconnect", (req, res) => { res.json({ status: "success", message: "SSH connection disconnected" }); }); +/** + * @openapi + * /ssh/file_manager/sudo-password: + * post: + * summary: Set sudo password for session + * description: Stores sudo password temporarily in session for elevated operations. + * tags: + * - File Manager + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * properties: + * sessionId: + * type: string + * password: + * type: string + * responses: + * 200: + * description: Sudo password set successfully. + * 400: + * description: Invalid session. + */ +app.post("/ssh/file_manager/sudo-password", (req, res) => { + const { sessionId, password } = req.body; + const session = sshSessions[sessionId]; + if (!session || !session.isConnected) { + return res.status(400).json({ error: "Invalid or disconnected session" }); + } + session.sudoPassword = password; + session.lastActive = Date.now(); + res.json({ status: "success", message: "Sudo password set" }); +}); + /** * @openapi * /ssh/file_manager/ssh/status: @@ -2657,86 +2733,106 @@ app.delete("/ssh/file_manager/ssh/deleteItem", async (req, res) => { const escapedPath = itemPath.replace(/'/g, "'\"'\"'"); const deleteCommand = isDirectory - ? `rm -rf '${escapedPath}' && echo "SUCCESS" && exit 0` - : `rm -f '${escapedPath}' && echo "SUCCESS" && exit 0`; + ? `rm -rf '${escapedPath}'` + : `rm -f '${escapedPath}'`; - sshConn.client.exec(deleteCommand, (err, stream) => { - if (err) { - fileLogger.error("SSH deleteItem error:", err); - if (!res.headersSent) { - return res.status(500).json({ error: err.message }); - } - return; - } - - let outputData = ""; - let errorData = ""; - - stream.on("data", (chunk: Buffer) => { - outputData += chunk.toString(); - }); - - stream.stderr.on("data", (chunk: Buffer) => { - errorData += chunk.toString(); - - if (chunk.toString().includes("Permission denied")) { - fileLogger.error(`Permission denied deleting: ${itemPath}`); - if (!res.headersSent) { - return res.status(403).json({ - error: `Permission denied: Cannot delete ${itemPath}. Check file permissions.`, - }); - } - return; - } - }); - - stream.on("close", (code) => { - if (outputData.includes("SUCCESS")) { - if (!res.headersSent) { - res.json({ - message: "Item deleted successfully", - path: itemPath, - toast: { - type: "success", - message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`, - }, - }); - } - return; - } - - if (code !== 0) { - fileLogger.error( - `SSH deleteItem command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`, - ); - if (!res.headersSent) { - return res.status(500).json({ - error: `Command failed: ${errorData}`, - toast: { type: "error", message: `Delete failed: ${errorData}` }, - }); - } - return; - } - - if (!res.headersSent) { - res.json({ - message: "Item deleted successfully", - path: itemPath, - toast: { - type: "success", - message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`, + const executeDelete = (useSudo: boolean): Promise => { + return new Promise((resolve) => { + if (useSudo && sshConn.sudoPassword) { + execWithSudo(sshConn.client, deleteCommand, sshConn.sudoPassword).then( + (result) => { + if ( + result.code === 0 || + (!result.stderr.includes("Permission denied") && + !result.stdout.includes("Permission denied")) + ) { + res.json({ + message: "Item deleted successfully", + path: itemPath, + toast: { + type: "success", + message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`, + }, + }); + } else { + res.status(500).json({ + error: `Delete failed: ${result.stderr || result.stdout}`, + }); + } + resolve(); }, - }); + ); + return; } - }); - stream.on("error", (streamErr) => { - fileLogger.error("SSH deleteItem stream error:", streamErr); - if (!res.headersSent) { - res.status(500).json({ error: `Stream error: ${streamErr.message}` }); - } + sshConn.client.exec( + `${deleteCommand} && echo "SUCCESS"`, + (err, stream) => { + if (err) { + fileLogger.error("SSH deleteItem error:", err); + res.status(500).json({ error: err.message }); + resolve(); + return; + } + + let outputData = ""; + let errorData = ""; + let permissionDenied = false; + + stream.on("data", (chunk: Buffer) => { + outputData += chunk.toString(); + }); + + stream.stderr.on("data", (chunk: Buffer) => { + errorData += chunk.toString(); + if (chunk.toString().includes("Permission denied")) { + permissionDenied = true; + } + }); + + stream.on("close", (code) => { + if (permissionDenied) { + if (sshConn.sudoPassword) { + executeDelete(true).then(resolve); + return; + } + fileLogger.error(`Permission denied deleting: ${itemPath}`); + res.status(403).json({ + error: `Permission denied: Cannot delete ${itemPath}.`, + needsSudo: true, + }); + resolve(); + return; + } + + if (outputData.includes("SUCCESS") || code === 0) { + res.json({ + message: "Item deleted successfully", + path: itemPath, + toast: { + type: "success", + message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`, + }, + }); + } else { + res.status(500).json({ + error: `Command failed: ${errorData}`, + }); + } + resolve(); + }); + + stream.on("error", (streamErr) => { + fileLogger.error("SSH deleteItem stream error:", streamErr); + res.status(500).json({ error: `Stream error: ${streamErr.message}` }); + resolve(); + }); + }, + ); }); - }); + }; + + await executeDelete(false); }); /** diff --git a/src/locales/en.json b/src/locales/en.json index dea8a24d..b334426c 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -1376,6 +1376,11 @@ "itemDeletedSuccessfully": "{{type}} deleted successfully", "itemsDeletedSuccessfully": "{{count}} items deleted successfully", "failedToDeleteItems": "Failed to delete items", + "sudoPasswordRequired": "Administrator Password Required", + "enterSudoPassword": "Enter sudo password to continue this operation", + "sudoPassword": "Sudo password", + "sudoOperationFailed": "Sudo operation failed", + "deleteOperation": "Delete files/folders", "dragFilesToUpload": "Drop files here to upload", "emptyFolder": "This folder is empty", "itemCount": "{{count}} items", diff --git a/src/ui/desktop/apps/features/file-manager/FileManager.tsx b/src/ui/desktop/apps/features/file-manager/FileManager.tsx index 1a25c73e..145c3bf0 100644 --- a/src/ui/desktop/apps/features/file-manager/FileManager.tsx +++ b/src/ui/desktop/apps/features/file-manager/FileManager.tsx @@ -21,6 +21,7 @@ import { TOTPDialog } from "@/ui/desktop/navigation/TOTPDialog.tsx"; import { SSHAuthDialog } from "@/ui/desktop/navigation/SSHAuthDialog.tsx"; import { PermissionsDialog } from "./components/PermissionsDialog.tsx"; import { CompressDialog } from "./components/CompressDialog.tsx"; +import { SudoPasswordDialog } from "./SudoPasswordDialog.tsx"; import { Upload, FolderPlus, @@ -57,6 +58,7 @@ import { changeSSHPermissions, extractSSHArchive, compressSSHFiles, + setSudoPassword, } from "@/ui/main-axios.ts"; import type { SidebarItem } from "./FileManagerSidebar.tsx"; @@ -163,6 +165,12 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) { [], ); + const [sudoDialogOpen, setSudoDialogOpen] = useState(false); + const [pendingSudoOperation, setPendingSudoOperation] = useState<{ + type: "delete"; + files: FileItem[]; + } | null>(null); + const { selectedFiles, clearSelection, setSelection } = useFileSelection(); const { dragHandlers } = useDragAndDrop({ @@ -720,9 +728,18 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) { handleRefreshDirectory(); clearSelection(); } catch (error: unknown) { + const axiosError = error as { + response?: { data?: { needsSudo?: boolean; error?: string } }; + message?: string; + }; + if (axiosError.response?.data?.needsSudo) { + setPendingSudoOperation({ type: "delete", files }); + setSudoDialogOpen(true); + return; + } if ( - error.message?.includes("connection") || - error.message?.includes("established") + axiosError.message?.includes("connection") || + axiosError.message?.includes("established") ) { toast.error( `SSH connection failed. Please check your connection to ${currentHost?.name} (${currentHost?.ip}:${currentHost?.port})`, @@ -737,6 +754,41 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) { ); } + async function handleSudoPasswordSubmit(password: string) { + if (!sshSessionId || !pendingSudoOperation) return; + + try { + await setSudoPassword(sshSessionId, password); + setSudoDialogOpen(false); + + if (pendingSudoOperation.type === "delete") { + for (const file of pendingSudoOperation.files) { + await deleteSSHItem( + sshSessionId, + file.path, + file.type === "directory", + currentHost?.id, + currentHost?.userId?.toString(), + ); + } + toast.success( + t("fileManager.itemsDeletedSuccessfully", { + count: pendingSudoOperation.files.length, + }), + ); + handleRefreshDirectory(); + clearSelection(); + } + + setPendingSudoOperation(null); + } catch (error: unknown) { + const axiosError = error as { message?: string }; + toast.error( + axiosError.message || t("fileManager.sudoOperationFailed"), + ); + } + } + function handleCreateNewFolder() { const defaultName = generateUniqueName( t("fileManager.newFolderDefault"), @@ -2173,6 +2225,20 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) { }} onSave={handleSavePermissions} /> + + { + setSudoDialogOpen(open); + if (!open) setPendingSudoOperation(null); + }} + onSubmit={handleSudoPasswordSubmit} + operation={ + pendingSudoOperation?.type === "delete" + ? t("fileManager.deleteOperation") + : undefined + } + /> ); } diff --git a/src/ui/desktop/apps/features/file-manager/SudoPasswordDialog.tsx b/src/ui/desktop/apps/features/file-manager/SudoPasswordDialog.tsx new file mode 100644 index 00000000..469d367e --- /dev/null +++ b/src/ui/desktop/apps/features/file-manager/SudoPasswordDialog.tsx @@ -0,0 +1,98 @@ +import React, { useState, useEffect } from "react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog.tsx"; +import { Button } from "@/components/ui/button.tsx"; +import { PasswordInput } from "@/components/ui/password-input.tsx"; +import { useTranslation } from "react-i18next"; +import { ShieldAlert } from "lucide-react"; + +interface SudoPasswordDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + onSubmit: (password: string) => void; + operation?: string; +} + +export function SudoPasswordDialog({ + open, + onOpenChange, + onSubmit, + operation, +}: SudoPasswordDialogProps) { + const { t } = useTranslation(); + const [password, setPassword] = useState(""); + const [loading, setLoading] = useState(false); + + useEffect(() => { + if (!open) { + setPassword(""); + setLoading(false); + } + }, [open]); + + const handleSubmit = async (e?: React.FormEvent) => { + if (e) { + e.preventDefault(); + } + + if (!password.trim()) { + return; + } + + setLoading(true); + onSubmit(password); + }; + + return ( + + +
+ + + + {t("fileManager.sudoPasswordRequired")} + + + {t("fileManager.enterSudoPassword")} + {operation && ( + + {operation} + + )} + + + +
+ setPassword(e.target.value)} + placeholder={t("fileManager.sudoPassword")} + autoFocus + disabled={loading} + /> +
+ + + + + +
+
+
+ ); +} diff --git a/src/ui/main-axios.ts b/src/ui/main-axios.ts index 0e322433..b7c0b7ba 100644 --- a/src/ui/main-axios.ts +++ b/src/ui/main-axios.ts @@ -1641,6 +1641,20 @@ export async function deleteSSHItem( } } +export async function setSudoPassword( + sessionId: string, + password: string, +): Promise { + try { + await fileManagerApi.post("/sudo-password", { + sessionId, + password, + }); + } catch (error) { + handleApiError(error, "set sudo password"); + } +} + export async function copySSHItem( sessionId: string, sourcePath: string,