v1.7.0 #318

Merged
LukeGus merged 138 commits from dev-1.7.0 into main 2025-10-01 20:40:10 +00:00
15 changed files with 467 additions and 535 deletions
Showing only changes of commit 63e776f183 - Show all commits
+8 -8
View File
@@ -3,10 +3,10 @@ const path = require("path");
const fs = require("fs"); const fs = require("fs");
const os = require("os"); const os = require("os");
app.commandLine.appendSwitch('--ignore-certificate-errors'); app.commandLine.appendSwitch("--ignore-certificate-errors");
app.commandLine.appendSwitch('--ignore-ssl-errors'); app.commandLine.appendSwitch("--ignore-ssl-errors");
app.commandLine.appendSwitch('--ignore-certificate-errors-spki-list'); app.commandLine.appendSwitch("--ignore-certificate-errors-spki-list");
app.commandLine.appendSwitch('--enable-features=NetworkService'); app.commandLine.appendSwitch("--enable-features=NetworkService");
gemini-code-assist[bot] commented 2025-10-01 20:38:41 +00:00 (Migrated from github.com)
Review

medium

Globally ignoring all certificate and SSL errors is a significant security risk. This makes the application vulnerable to Man-in-the-Middle (MITM) attacks, as it will trust any certificate, including malicious ones. While this might be intended for connecting to self-hosted instances with self-signed certificates, it should not be enabled by default for all connections. Consider making this a user-configurable setting that is disabled by default, and perhaps apply it more granularly only to user-defined server connections rather than globally.

![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg) Globally ignoring all certificate and SSL errors is a significant security risk. This makes the application vulnerable to Man-in-the-Middle (MITM) attacks, as it will trust any certificate, including malicious ones. While this might be intended for connecting to self-hosted instances with self-signed certificates, it should not be enabled by default for all connections. Consider making this a user-configurable setting that is disabled by default, and perhaps apply it more granularly only to user-defined server connections rather than globally.
let mainWindow = null; let mainWindow = null;
@@ -141,9 +141,9 @@ async function fetchGitHubAPI(endpoint, cacheKey) {
requestOptions.rejectUnauthorized = false; requestOptions.rejectUnauthorized = false;
requestOptions.agent = new https.Agent({ requestOptions.agent = new https.Agent({
rejectUnauthorized: false, rejectUnauthorized: false,
secureProtocol: 'TLSv1_2_method', secureProtocol: "TLSv1_2_method",
checkServerIdentity: () => undefined, checkServerIdentity: () => undefined,
ciphers: 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH', ciphers: "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH",
honorCipherOrder: true, honorCipherOrder: true,
}); });
} }
1
@@ -315,9 +315,9 @@ ipcMain.handle("test-server-connection", async (event, serverUrl) => {
requestOptions.rejectUnauthorized = false; requestOptions.rejectUnauthorized = false;
requestOptions.agent = new https.Agent({ requestOptions.agent = new https.Agent({
rejectUnauthorized: false, rejectUnauthorized: false,
secureProtocol: 'TLSv1_2_method', secureProtocol: "TLSv1_2_method",
checkServerIdentity: () => undefined, checkServerIdentity: () => undefined,
ciphers: 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH', ciphers: "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH",
honorCipherOrder: true, honorCipherOrder: true,
}); });
} }
+1 -1
View File
@@ -245,7 +245,7 @@ app.get("/version", authenticateJWT, async (req, res) => {
} catch { } catch {
return null; return null;
} }
} },
]; ];
for (const getVersion of versionSources) { for (const getVersion of versionSources) {
1
+55 -152
View File
@@ -1128,93 +1128,79 @@ async function deploySSHKeyToHost(
conn.on("ready", async () => { conn.on("ready", async () => {
clearTimeout(connectionTimeout); clearTimeout(connectionTimeout);
authLogger.info("SSH connection established for key deployment", {
host: hostConfig.ip,
username: hostConfig.username,
authType: hostConfig.authType,
});
try { try {
authLogger.info("Ensuring .ssh directory exists", { host: hostConfig.ip });
await new Promise<void>((resolveCmd, rejectCmd) => { await new Promise<void>((resolveCmd, rejectCmd) => {
const cmdTimeout = setTimeout(() => { const cmdTimeout = setTimeout(() => {
rejectCmd(new Error("mkdir command timeout")); rejectCmd(new Error("mkdir command timeout"));
}, 10000); // Reduced to 10 seconds }, 10000);
// Use a more robust command that handles existing directories conn.exec(
conn.exec("test -d ~/.ssh || mkdir -p ~/.ssh; chmod 700 ~/.ssh", (err, stream) => { "test -d ~/.ssh || mkdir -p ~/.ssh; chmod 700 ~/.ssh",
(err, stream) => {
if (err) { if (err) {
clearTimeout(cmdTimeout); clearTimeout(cmdTimeout);
authLogger.error("mkdir command error", { host: hostConfig.ip, error: err.message });
return rejectCmd(err); return rejectCmd(err);
} }
stream.on("close", (code) => { stream.on("close", (code) => {
clearTimeout(cmdTimeout); clearTimeout(cmdTimeout);
authLogger.info("mkdir command completed", { host: hostConfig.ip, code });
if (code === 0) { if (code === 0) {
resolveCmd(); resolveCmd();
} else { } else {
rejectCmd(new Error(`mkdir command failed with code ${code}`)); rejectCmd(
new Error(`mkdir command failed with code ${code}`),
);
} }
}); });
stream.on("data", (data) => { stream.on("data", (data) => {});
authLogger.info("mkdir command output", { host: hostConfig.ip, output: data.toString() }); },
}); );
});
}); });
const keyExists = await new Promise<boolean>( const keyExists = await new Promise<boolean>(
(resolveCheck, rejectCheck) => { (resolveCheck, rejectCheck) => {
const checkTimeout = setTimeout(() => { const checkTimeout = setTimeout(() => {
rejectCheck(new Error("Key check timeout")); rejectCheck(new Error("Key check timeout"));
}, 5000); // Reduced to 5 seconds }, 5000);
// Parse public key - handle both JSON and plain text formats
let actualPublicKey = publicKey; let actualPublicKey = publicKey;
try { try {
// Try to parse as JSON first
const parsed = JSON.parse(publicKey); const parsed = JSON.parse(publicKey);
if (parsed.data) { if (parsed.data) {
actualPublicKey = parsed.data; actualPublicKey = parsed.data;
authLogger.info("Parsed public key from JSON format", { host: hostConfig.ip });
}
} catch (e) {
// Not JSON, use as-is
authLogger.info("Using public key as plain text", { host: hostConfig.ip });
} }
} catch (e) {}
// Validate public key format
const keyParts = actualPublicKey.trim().split(" "); const keyParts = actualPublicKey.trim().split(" ");
if (keyParts.length < 2) { if (keyParts.length < 2) {
clearTimeout(checkTimeout); clearTimeout(checkTimeout);
authLogger.error("Invalid public key format", { host: hostConfig.ip, publicKey: actualPublicKey.substring(0, 50) + "..." }); return rejectCheck(
return rejectCheck(new Error("Invalid public key format - must contain at least 2 parts")); new Error(
"Invalid public key format - must contain at least 2 parts",
),
);
} }
const keyPattern = keyParts[1]; const keyPattern = keyParts[1];
authLogger.info("Checking for existing key", { host: hostConfig.ip, keyPattern: keyPattern.substring(0, 20) + "..." });
// Use a simpler approach - just check if the file exists and has content
conn.exec( conn.exec(
`if [ -f ~/.ssh/authorized_keys ]; then grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?; else echo 1; fi`, `if [ -f ~/.ssh/authorized_keys ]; then grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?; else echo 1; fi`,
(err, stream) => { (err, stream) => {
if (err) { if (err) {
clearTimeout(checkTimeout); clearTimeout(checkTimeout);
authLogger.error("Key check error", { host: hostConfig.ip, error: err.message });
return rejectCheck(err); return rejectCheck(err);
} }
let output = ''; let output = "";
stream.on('data', (data) => { stream.on("data", (data) => {
output += data.toString(); output += data.toString();
}); });
stream.on("close", (code) => { stream.on("close", (code) => {
clearTimeout(checkTimeout); clearTimeout(checkTimeout);
const exists = output.trim() === '0'; const exists = output.trim() === "0";
authLogger.info("Key check completed", { host: hostConfig.ip, code, output: output.trim(), exists });
resolveCheck(exists); resolveCheck(exists);
}); });
}, },
@@ -1228,40 +1214,33 @@ async function deploySSHKeyToHost(
return; return;
} }
authLogger.info("Adding SSH key to authorized_keys", { host: hostConfig.ip });
await new Promise<void>((resolveAdd, rejectAdd) => { await new Promise<void>((resolveAdd, rejectAdd) => {
const addTimeout = setTimeout(() => { const addTimeout = setTimeout(() => {
rejectAdd(new Error("Key add timeout")); rejectAdd(new Error("Key add timeout"));
}, 10000); // Reduced to 10 seconds }, 10000);
// Parse public key - handle both JSON and plain text formats
let actualPublicKey = publicKey; let actualPublicKey = publicKey;
try { try {
// Try to parse as JSON first
const parsed = JSON.parse(publicKey); const parsed = JSON.parse(publicKey);
if (parsed.data) { if (parsed.data) {
actualPublicKey = parsed.data; actualPublicKey = parsed.data;
} }
} catch (e) { } catch (e) {}
// Not JSON, use as-is
}
// Use printf instead of echo for more reliable key addition const escapedKey = actualPublicKey
const escapedKey = actualPublicKey.replace(/\\/g, '\\\\').replace(/'/g, "'\\''"); .replace(/\\/g, "\\\\")
authLogger.info("Adding key to authorized_keys", { host: hostConfig.ip, keyLength: actualPublicKey.length }); .replace(/'/g, "'\\''");
conn.exec( conn.exec(
`printf '%s\\n' '${escapedKey}' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`, `printf '%s\\n' '${escapedKey}' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
(err, stream) => { (err, stream) => {
if (err) { if (err) {
clearTimeout(addTimeout); clearTimeout(addTimeout);
authLogger.error("Key add error", { host: hostConfig.ip, error: err.message });
return rejectAdd(err); return rejectAdd(err);
} }
stream.on("close", (code) => { stream.on("close", (code) => {
clearTimeout(addTimeout); clearTimeout(addTimeout);
authLogger.info("Key add completed", { host: hostConfig.ip, code });
if (code === 0) { if (code === 0) {
resolveAdd(); resolveAdd();
} else { } else {
@@ -1270,39 +1249,32 @@ async function deploySSHKeyToHost(
); );
} }
}); });
stream.on("data", (data) => {
authLogger.info("Key add output", { host: hostConfig.ip, output: data.toString() });
});
}, },
); );
}); });
authLogger.info("Verifying key deployment", { host: hostConfig.ip });
const verifySuccess = await new Promise<boolean>( const verifySuccess = await new Promise<boolean>(
(resolveVerify, rejectVerify) => { (resolveVerify, rejectVerify) => {
const verifyTimeout = setTimeout(() => { const verifyTimeout = setTimeout(() => {
rejectVerify(new Error("Key verification timeout")); rejectVerify(new Error("Key verification timeout"));
}, 5000); // Reduced to 5 seconds }, 5000);
// Parse public key - handle both JSON and plain text formats
let actualPublicKey = publicKey; let actualPublicKey = publicKey;
try { try {
// Try to parse as JSON first
const parsed = JSON.parse(publicKey); const parsed = JSON.parse(publicKey);
if (parsed.data) { if (parsed.data) {
actualPublicKey = parsed.data; actualPublicKey = parsed.data;
} }
} catch (e) { } catch (e) {}
// Not JSON, use as-is
}
// Use the same key pattern extraction as above
const keyParts = actualPublicKey.trim().split(" "); const keyParts = actualPublicKey.trim().split(" ");
if (keyParts.length < 2) { if (keyParts.length < 2) {
clearTimeout(verifyTimeout); clearTimeout(verifyTimeout);
authLogger.error("Invalid public key format for verification", { host: hostConfig.ip, publicKey: actualPublicKey.substring(0, 50) + "..." }); return rejectVerify(
return rejectVerify(new Error("Invalid public key format - must contain at least 2 parts")); new Error(
"Invalid public key format - must contain at least 2 parts",
),
);
} }
const keyPattern = keyParts[1]; const keyPattern = keyParts[1];
@@ -1311,19 +1283,17 @@ async function deploySSHKeyToHost(
(err, stream) => { (err, stream) => {
if (err) { if (err) {
clearTimeout(verifyTimeout); clearTimeout(verifyTimeout);
authLogger.error("Key verification error", { host: hostConfig.ip, error: err.message });
return rejectVerify(err); return rejectVerify(err);
} }
let output = ''; let output = "";
stream.on('data', (data) => { stream.on("data", (data) => {
output += data.toString(); output += data.toString();
}); });
stream.on("close", (code) => { stream.on("close", (code) => {
clearTimeout(verifyTimeout); clearTimeout(verifyTimeout);
const verified = output.trim() === '0'; const verified = output.trim() === "0";
authLogger.info("Key verification completed", { host: hostConfig.ip, code, output: output.trim(), verified });
resolveVerify(verified); resolveVerify(verified);
}); });
}, },
@@ -1354,27 +1324,28 @@ async function deploySSHKeyToHost(
clearTimeout(connectionTimeout); clearTimeout(connectionTimeout);
let errorMessage = err.message; let errorMessage = err.message;
// Log detailed error information for debugging if (
authLogger.error("SSH connection failed during key deployment", { err.message.includes("All configured authentication methods failed")
host: hostConfig.ip, ) {
username: hostConfig.username, errorMessage =
authType: hostConfig.authType, "Authentication failed. Please check your credentials and ensure the SSH service is running.";
hasPassword: !!hostConfig.password, } else if (
hasPrivateKey: !!hostConfig.privateKey, err.message.includes("ENOTFOUND") ||
error: err.message, err.message.includes("ENOENT")
errorCode: (err as any).code, ) {
});
if (err.message.includes("All configured authentication methods failed")) {
errorMessage = "Authentication failed. Please check your credentials and ensure the SSH service is running.";
} else if (err.message.includes("ENOTFOUND") || err.message.includes("ENOENT")) {
errorMessage = "Could not resolve hostname or connect to server."; errorMessage = "Could not resolve hostname or connect to server.";
} else if (err.message.includes("ECONNREFUSED")) { } else if (err.message.includes("ECONNREFUSED")) {
errorMessage = "Connection refused. The server may not be running or the port may be incorrect."; errorMessage =
"Connection refused. The server may not be running or the port may be incorrect.";
} else if (err.message.includes("ETIMEDOUT")) { } else if (err.message.includes("ETIMEDOUT")) {
errorMessage = "Connection timed out. Check your network connection and server availability."; errorMessage =
} else if (err.message.includes("authentication failed") || err.message.includes("Permission denied")) { "Connection timed out. Check your network connection and server availability.";
errorMessage = "Authentication failed. Please check your username and password/key."; } else if (
err.message.includes("authentication failed") ||
err.message.includes("Permission denied")
) {
errorMessage =
"Authentication failed. Please check your username and password/key.";
} }
resolve({ success: false, error: errorMessage }); resolve({ success: false, error: errorMessage });
@@ -1462,24 +1433,9 @@ async function deploySSHKeyToHost(
return; return;
} }
// Log connection attempt
authLogger.info("Attempting SSH connection for key deployment", {
host: connectionConfig.host,
port: connectionConfig.port,
username: connectionConfig.username,
authType: hostConfig.authType,
hasPassword: !!connectionConfig.password,
hasPrivateKey: !!connectionConfig.privateKey,
hasPassphrase: !!connectionConfig.passphrase,
});
conn.connect(connectionConfig); conn.connect(connectionConfig);
} catch (error) { } catch (error) {
clearTimeout(connectionTimeout); clearTimeout(connectionTimeout);
authLogger.error("Failed to initiate SSH connection", {
host: hostConfig.ip,
error: error instanceof Error ? error.message : "Unknown error",
});
resolve({ resolve({
success: false, success: false,
error: error instanceof Error ? error.message : "Connection failed", error: error instanceof Error ? error.message : "Connection failed",
@@ -1547,11 +1503,7 @@ router.post(
}); });
} }
const targetHost = await SimpleDBOps.select( const targetHost = await SimpleDBOps.select(
db db.select().from(sshData).where(eq(sshData.id, targetHostId)).limit(1),
.select()
.from(sshData)
.where(eq(sshData.id, targetHostId))
.limit(1),
"ssh_data", "ssh_data",
userId, userId,
); );
@@ -1575,25 +1527,9 @@ router.post(
keyPassword: hostData.keyPassword, keyPassword: hostData.keyPassword,
}; };
authLogger.info("Host configuration for SSH key deployment", {
hostId: targetHostId,
ip: hostConfig.ip,
port: hostConfig.port,
username: hostConfig.username,
authType: hostConfig.authType,
hasPassword: !!hostConfig.password,
hasPrivateKey: !!hostConfig.privateKey,
hasKeyPassword: !!hostConfig.keyPassword,
passwordLength: hostConfig.password ? hostConfig.password.length : 0,
});
if (hostData.authType === "credential" && hostData.credentialId) { if (hostData.authType === "credential" && hostData.credentialId) {
const userId = (req as any).userId; const userId = (req as any).userId;
if (!userId) { if (!userId) {
authLogger.error("Missing userId for credential resolution", {
hostId: targetHostId,
credentialId: hostData.credentialId,
});
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
error: "Authentication required for credential resolution", error: "Authentication required for credential resolution",
@@ -1624,32 +1560,13 @@ router.post(
hostConfig.privateKey = cred.privateKey || cred.key; hostConfig.privateKey = cred.privateKey || cred.key;
hostConfig.keyPassword = cred.keyPassword; hostConfig.keyPassword = cred.keyPassword;
} }
authLogger.info("Resolved host credentials for SSH key deployment", {
hostId: targetHostId,
credentialId: hostData.credentialId,
authType: hostConfig.authType,
username: hostConfig.username,
hasPassword: !!hostConfig.password,
hasPrivateKey: !!hostConfig.privateKey,
hasKeyPassword: !!hostConfig.keyPassword,
});
} else { } else {
authLogger.error("Host credential not found", {
hostId: targetHostId,
credentialId: hostData.credentialId,
});
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
error: "Host credential not found", error: "Host credential not found",
}); });
} }
} catch (error) { } catch (error) {
authLogger.error("Failed to resolve host credentials", {
hostId: targetHostId,
credentialId: hostData.credentialId,
error: error instanceof Error ? error.message : "Unknown error",
});
return res.status(500).json({ return res.status(500).json({
success: false, success: false,
error: "Failed to resolve host credentials", error: "Failed to resolve host credentials",
@@ -1664,31 +1581,17 @@ router.post(
); );
if (deployResult.success) { if (deployResult.success) {
authLogger.success(`SSH key deployed successfully`, {
credentialId,
targetHostId,
operation: "deploy_ssh_key",
});
res.json({ res.json({
success: true, success: true,
message: deployResult.message || "SSH key deployed successfully", message: deployResult.message || "SSH key deployed successfully",
}); });
} else { } else {
authLogger.error(`SSH key deployment failed`, {
credentialId,
targetHostId,
error: deployResult.error,
operation: "deploy_ssh_key",
});
res.status(500).json({ res.status(500).json({
success: false, success: false,
error: deployResult.error || "Deployment failed", error: deployResult.error || "Deployment failed",
}); });
} }
} catch (error) { } catch (error) {
authLogger.error("Failed to deploy SSH key", error);
res.status(500).json({ res.status(500).json({
success: false, success: false,
error: error:
+4 -2
View File
@@ -926,7 +926,9 @@ router.post("/login", async (req, res) => {
username: userRecord.username, username: userRecord.username,
}; };
const isElectron = req.headers['x-electron-app'] === 'true' || req.headers['X-Electron-App'] === 'true'; const isElectron =
req.headers["x-electron-app"] === "true" ||
req.headers["X-Electron-App"] === "true";
if (isElectron) { if (isElectron) {
response.token = token; response.token = token;
@@ -1507,7 +1509,7 @@ router.post("/totp/verify-login", async (req, res) => {
success: true, success: true,
is_admin: !!userRecord.is_admin, is_admin: !!userRecord.is_admin,
username: userRecord.username, username: userRecord.username,
token: req.headers['x-electron-app'] === 'true' ? token : undefined, token: req.headers["x-electron-app"] === "true" ? token : undefined,
}); });
} catch (err) { } catch (err) {
authLogger.error("TOTP verification failed", err); authLogger.error("TOTP verification failed", err);
+16 -23
View File
@@ -9,7 +9,6 @@ import { fileLogger } from "../utils/logger.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js"; import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { AuthManager } from "../utils/auth-manager.js"; import { AuthManager } from "../utils/auth-manager.js";
function isExecutableFile(permissions: string, fileName: string): boolean { function isExecutableFile(permissions: string, fileName: string): boolean {
const hasExecutePermission = const hasExecutePermission =
permissions[3] === "x" || permissions[6] === "x" || permissions[9] === "x"; permissions[3] === "x" || permissions[6] === "x" || permissions[9] === "x";
@@ -88,8 +87,6 @@ app.use(express.raw({ limit: "5gb", type: "application/octet-stream" }));
const authManager = AuthManager.getInstance(); const authManager = AuthManager.getInstance();
app.use(authManager.createAuthMiddleware()); app.use(authManager.createAuthMiddleware());
interface SSHSession { interface SSHSession {
client: SSHClient; client: SSHClient;
isConnected: boolean; isConnected: boolean;
@@ -144,7 +141,6 @@ function getMimeType(fileName: string): string {
return mimeTypes[ext || ""] || "application/octet-stream"; return mimeTypes[ext || ""] || "application/octet-stream";
} }
app.post("/ssh/file_manager/ssh/connect", async (req, res) => { app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
const { const {
sessionId, sessionId,
1
@@ -279,9 +275,17 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
}, },
}; };
if (resolvedCredentials.authType === "password" && resolvedCredentials.password && resolvedCredentials.password.trim()) { if (
resolvedCredentials.authType === "password" &&
resolvedCredentials.password &&
resolvedCredentials.password.trim()
) {
config.password = resolvedCredentials.password; config.password = resolvedCredentials.password;
} else if (resolvedCredentials.authType === "key" && resolvedCredentials.sshKey && resolvedCredentials.sshKey.trim()) { } else if (
resolvedCredentials.authType === "key" &&
resolvedCredentials.sshKey &&
resolvedCredentials.sshKey.trim()
) {
try { try {
if ( if (
!resolvedCredentials.sshKey.includes("-----BEGIN") || !resolvedCredentials.sshKey.includes("-----BEGIN") ||
@@ -309,14 +313,17 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
return res.status(400).json({ error: "Invalid SSH key format" }); return res.status(400).json({ error: "Invalid SSH key format" });
} }
} else { } else {
fileLogger.warn("No valid authentication method provided for file manager", { fileLogger.warn(
"No valid authentication method provided for file manager",
{
operation: "file_connect", operation: "file_connect",
sessionId, sessionId,
hostId, hostId,
authType: resolvedCredentials.authType, authType: resolvedCredentials.authType,
hasPassword: !!resolvedCredentials.password, hasPassword: !!resolvedCredentials.password,
hasKey: !!resolvedCredentials.sshKey, hasKey: !!resolvedCredentials.sshKey,
}); },
);
return res return res
.status(400) .status(400)
.json({ error: "Either password or SSH key must be provided" }); .json({ error: "Either password or SSH key must be provided" });
@@ -359,14 +366,12 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
client.connect(config); client.connect(config);
}); });
app.post("/ssh/file_manager/ssh/disconnect", (req, res) => { app.post("/ssh/file_manager/ssh/disconnect", (req, res) => {
const { sessionId } = req.body; const { sessionId } = req.body;
cleanupSession(sessionId); cleanupSession(sessionId);
res.json({ status: "success", message: "SSH connection disconnected" }); res.json({ status: "success", message: "SSH connection disconnected" });
}); });
app.get("/ssh/file_manager/ssh/status", (req, res) => { app.get("/ssh/file_manager/ssh/status", (req, res) => {
const sessionId = req.query.sessionId as string; const sessionId = req.query.sessionId as string;
const isConnected = !!sshSessions[sessionId]?.isConnected; const isConnected = !!sshSessions[sessionId]?.isConnected;
@@ -400,7 +405,6 @@ app.post("/ssh/file_manager/ssh/keepalive", (req, res) => {
}); });
}); });
app.get("/ssh/file_manager/ssh/listFiles", (req, res) => { app.get("/ssh/file_manager/ssh/listFiles", (req, res) => {
const sessionId = req.query.sessionId as string; const sessionId = req.query.sessionId as string;
const sshConn = sshSessions[sessionId]; const sshConn = sshSessions[sessionId];
@@ -499,7 +503,6 @@ app.get("/ssh/file_manager/ssh/listFiles", (req, res) => {
}); });
}); });
app.get("/ssh/file_manager/ssh/identifySymlink", (req, res) => { app.get("/ssh/file_manager/ssh/identifySymlink", (req, res) => {
const sessionId = req.query.sessionId as string; const sessionId = req.query.sessionId as string;
const sshConn = sshSessions[sessionId]; const sshConn = sshSessions[sessionId];
@@ -567,7 +570,6 @@ app.get("/ssh/file_manager/ssh/identifySymlink", (req, res) => {
}); });
}); });
app.get("/ssh/file_manager/ssh/readFile", (req, res) => { app.get("/ssh/file_manager/ssh/readFile", (req, res) => {
const sessionId = req.query.sessionId as string; const sessionId = req.query.sessionId as string;
const sshConn = sshSessions[sessionId]; const sshConn = sshSessions[sessionId];
@@ -690,7 +692,6 @@ app.get("/ssh/file_manager/ssh/readFile", (req, res) => {
); );
}); });
app.post("/ssh/file_manager/ssh/writeFile", async (req, res) => { app.post("/ssh/file_manager/ssh/writeFile", async (req, res) => {
const { sessionId, path: filePath, content, hostId, userId } = req.body; const { sessionId, path: filePath, content, hostId, userId } = req.body;
const sshConn = sshSessions[sessionId]; const sshConn = sshSessions[sessionId];
@@ -878,7 +879,6 @@ app.post("/ssh/file_manager/ssh/writeFile", async (req, res) => {
trySFTP(); trySFTP();
}); });
app.post("/ssh/file_manager/ssh/uploadFile", async (req, res) => { app.post("/ssh/file_manager/ssh/uploadFile", async (req, res) => {
const { const {
sessionId, sessionId,
@@ -1175,7 +1175,6 @@ app.post("/ssh/file_manager/ssh/uploadFile", async (req, res) => {
trySFTP(); trySFTP();
}); });
app.post("/ssh/file_manager/ssh/createFile", async (req, res) => { app.post("/ssh/file_manager/ssh/createFile", async (req, res) => {
const { const {
sessionId, sessionId,
@@ -1284,7 +1283,6 @@ app.post("/ssh/file_manager/ssh/createFile", async (req, res) => {
}); });
}); });
app.post("/ssh/file_manager/ssh/createFolder", async (req, res) => { app.post("/ssh/file_manager/ssh/createFolder", async (req, res) => {
const { sessionId, path: folderPath, folderName, hostId, userId } = req.body; const { sessionId, path: folderPath, folderName, hostId, userId } = req.body;
const sshConn = sshSessions[sessionId]; const sshConn = sshSessions[sessionId];
@@ -1721,7 +1719,6 @@ app.put("/ssh/file_manager/ssh/moveItem", async (req, res) => {
}); });
}); });
app.post("/ssh/file_manager/ssh/downloadFile", async (req, res) => { app.post("/ssh/file_manager/ssh/downloadFile", async (req, res) => {
const { sessionId, path: filePath, hostId, userId } = req.body; const { sessionId, path: filePath, hostId, userId } = req.body;
@@ -1823,7 +1820,6 @@ app.post("/ssh/file_manager/ssh/downloadFile", async (req, res) => {
}); });
}); });
app.post("/ssh/file_manager/ssh/copyItem", async (req, res) => { app.post("/ssh/file_manager/ssh/copyItem", async (req, res) => {
const { sessionId, sourcePath, targetDir, hostId, userId } = req.body; const { sessionId, sourcePath, targetDir, hostId, userId } = req.body;
@@ -2085,7 +2081,6 @@ app.post("/ssh/file_manager/ssh/executeFile", async (req, res) => {
}); });
}); });
process.on("SIGINT", () => { process.on("SIGINT", () => {
Object.keys(sshSessions).forEach(cleanupSession); Object.keys(sshSessions).forEach(cleanupSession);
process.exit(0); process.exit(0);
@@ -2096,10 +2091,8 @@ process.on("SIGTERM", () => {
process.exit(0); process.exit(0);
}); });
const PORT = 30004; const PORT = 30004;
try { try {
const server = app.listen(PORT, async () => { const server = app.listen(PORT, async () => {
try { try {
@@ -2111,7 +2104,7 @@ try {
} }
}); });
server.on('error', (err) => { server.on("error", (err) => {
fileLogger.error("File Manager server error", err, { fileLogger.error("File Manager server error", err, {
operation: "file_manager_server_error", operation: "file_manager_server_error",
port: PORT, port: PORT,
+8 -2
View File
@@ -588,9 +588,15 @@ wss.on("connection", async (ws: WebSocket, req) => {
compress: ["none", "zlib@openssh.com", "zlib"], compress: ["none", "zlib@openssh.com", "zlib"],
}, },
}; };
if (resolvedCredentials.authType === "password" && resolvedCredentials.password) { if (
resolvedCredentials.authType === "password" &&
resolvedCredentials.password
) {
connectConfig.password = resolvedCredentials.password; connectConfig.password = resolvedCredentials.password;
} else if (resolvedCredentials.authType === "key" && resolvedCredentials.key) { } else if (
resolvedCredentials.authType === "key" &&
resolvedCredentials.key
) {
try { try {
if ( if (
!resolvedCredentials.key.includes("-----BEGIN") || !resolvedCredentials.key.includes("-----BEGIN") ||
+10 -4
View File
@@ -30,7 +30,9 @@ import { systemLogger, versionLogger } from "./utils/logger.js";
() => { () => {
try { try {
const packageJsonPath = path.join(process.cwd(), "package.json"); const packageJsonPath = path.join(process.cwd(), "package.json");
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")); const packageJson = JSON.parse(
readFileSync(packageJsonPath, "utf-8"),
);
return packageJson.version; return packageJson.version;
} catch { } catch {
return null; return null;
@@ -43,7 +45,9 @@ import { systemLogger, versionLogger } from "./utils/logger.js";
path.dirname(__filename), path.dirname(__filename),
"../../../package.json", "../../../package.json",
); );
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")); const packageJson = JSON.parse(
readFileSync(packageJsonPath, "utf-8"),
);
return packageJson.version; return packageJson.version;
} catch { } catch {
return null; return null;
@@ -52,12 +56,14 @@ import { systemLogger, versionLogger } from "./utils/logger.js";
() => { () => {
try { try {
const packageJsonPath = path.join("/app", "package.json"); const packageJsonPath = path.join("/app", "package.json");
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")); const packageJson = JSON.parse(
readFileSync(packageJsonPath, "utf-8"),
);
return packageJson.version; return packageJson.version;
} catch { } catch {
return null; return null;
} }
} },
]; ];
for (const getVersion of versionSources) { for (const getVersion of versionSources) {
+13 -5
View File
@@ -12,7 +12,11 @@ const Toaster = ({ ...props }: ToasterProps) => {
const now = Date.now(); const now = Date.now();
const lastToast = lastToastRef.current; const lastToast = lastToastRef.current;
if (lastToast && lastToast.text === message && (now - lastToast.timestamp) < 1000) { if (
lastToast &&
lastToast.text === message &&
now - lastToast.timestamp < 1000
) {
return; return;
} }
@@ -21,10 +25,14 @@ const Toaster = ({ ...props }: ToasterProps) => {
}; };
Object.assign(toast, { Object.assign(toast, {
success: (message: string, options?: any) => rateLimitedToast(message, { ...options, type: 'success' }), success: (message: string, options?: any) =>
error: (message: string, options?: any) => rateLimitedToast(message, { ...options, type: 'error' }), rateLimitedToast(message, { ...options, type: "success" }),
warning: (message: string, options?: any) => rateLimitedToast(message, { ...options, type: 'warning' }), error: (message: string, options?: any) =>
info: (message: string, options?: any) => rateLimitedToast(message, { ...options, type: 'info' }), rateLimitedToast(message, { ...options, type: "error" }),
warning: (message: string, options?: any) =>
rateLimitedToast(message, { ...options, type: "warning" }),
info: (message: string, options?: any) =>
rateLimitedToast(message, { ...options, type: "info" }),
message: rateLimitedToast, message: rateLimitedToast,
}); });
+1 -4
View File
@@ -24,10 +24,7 @@ interface VersionAlertProps {
onDownload?: () => void; onDownload?: () => void;
} }
export function VersionAlert({ export function VersionAlert({ updateInfo, onDownload }: VersionAlertProps) {
updateInfo,
onDownload,
}: VersionAlertProps) {
const { t } = useTranslation(); const { t } = useTranslation();
if (!updateInfo.success) { if (!updateInfo.success) {
+7 -10
View File
@@ -11,7 +11,11 @@ interface VersionCheckModalProps {
isAuthenticated?: boolean; isAuthenticated?: boolean;
} }
export function VersionCheckModal({ onDismiss, onContinue, isAuthenticated = false }: VersionCheckModalProps) { export function VersionCheckModal({
onDismiss,
onContinue,
isAuthenticated = false,
}: VersionCheckModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [versionInfo, setVersionInfo] = useState<any>(null); const [versionInfo, setVersionInfo] = useState<any>(null);
const [versionChecking, setVersionChecking] = useState(false); const [versionChecking, setVersionChecking] = useState(false);
@@ -93,7 +97,6 @@ export function VersionCheckModal({ onDismiss, onContinue, isAuthenticated = fal
); );
} }
if (!versionInfo || versionDismissed) { if (!versionInfo || versionDismissed) {
return ( return (
<div className="fixed inset-0 flex items-center justify-center z-50"> <div className="fixed inset-0 flex items-center justify-center z-50">
@@ -131,10 +134,7 @@ export function VersionCheckModal({ onDismiss, onContinue, isAuthenticated = fal
)} )}
<div className="flex gap-2"> <div className="flex gap-2">
<Button <Button onClick={handleContinue} className="flex-1 h-10">
onClick={handleContinue}
className="flex-1 h-10"
>
{t("common.continue")} {t("common.continue")}
</Button> </Button>
</div> </div>
@@ -177,10 +177,7 @@ export function VersionCheckModal({ onDismiss, onContinue, isAuthenticated = fal
</div> </div>
<div className="flex gap-2"> <div className="flex gap-2">
<Button <Button onClick={handleContinue} className="flex-1 h-10">
onClick={handleContinue}
className="flex-1 h-10"
>
{t("common.continue")} {t("common.continue")}
</Button> </Button>
</div> </div>
@@ -107,7 +107,10 @@ export function CredentialsManager({
setHostSearchQuery(""); setHostSearchQuery("");
setSelectedHostId(""); setSelectedHostId("");
setTimeout(() => { setTimeout(() => {
if (document.activeElement && (document.activeElement as HTMLElement).blur) { if (
document.activeElement &&
(document.activeElement as HTMLElement).blur
) {
(document.activeElement as HTMLElement).blur(); (document.activeElement as HTMLElement).blur();
} }
}, 50); }, 50);
+10 -3
View File
@@ -222,7 +222,8 @@ export function HomepageAuth({
setTotpCode(""); setTotpCode("");
setTotpTempToken(""); setTotpTempToken("");
} catch (err: any) { } catch (err: any) {
const errorMessage = err?.response?.data?.error || err?.message || t("errors.unknownError"); const errorMessage =
err?.response?.data?.error || err?.message || t("errors.unknownError");
toast.error(errorMessage); toast.error(errorMessage);
setInternalLoggedIn(false); setInternalLoggedIn(false);
setLoggedIn(false); setLoggedIn(false);
@@ -370,7 +371,10 @@ export function HomepageAuth({
setTotpTempToken(""); setTotpTempToken("");
toast.success(t("messages.loginSuccess")); toast.success(t("messages.loginSuccess"));
} catch (err: any) { } catch (err: any) {
const errorMessage = err?.response?.data?.error || err?.message || t("errors.invalidTotpCode"); const errorMessage =
err?.response?.data?.error ||
err?.message ||
t("errors.invalidTotpCode");
toast.error(errorMessage); toast.error(errorMessage);
} finally { } finally {
setTotpLoading(false); setTotpLoading(false);
@@ -390,7 +394,10 @@ export function HomepageAuth({
window.location.replace(authUrl); window.location.replace(authUrl);
} catch (err: any) { } catch (err: any) {
const errorMessage = err?.response?.data?.error || err?.message || t("errors.failedOidcLogin"); const errorMessage =
err?.response?.data?.error ||
err?.message ||
t("errors.failedOidcLogin");
toast.error(errorMessage); toast.error(errorMessage);
setOidcLoading(false); setOidcLoading(false);
} }
+10 -3
View File
@@ -204,7 +204,8 @@ export function HomepageAuth({
setTotpCode(""); setTotpCode("");
setTotpTempToken(""); setTotpTempToken("");
} catch (err: any) { } catch (err: any) {
const errorMessage = err?.response?.data?.error || err?.message || t("errors.unknownError"); const errorMessage =
err?.response?.data?.error || err?.message || t("errors.unknownError");
toast.error(errorMessage); toast.error(errorMessage);
setInternalLoggedIn(false); setInternalLoggedIn(false);
setLoggedIn(false); setLoggedIn(false);
@@ -346,7 +347,10 @@ export function HomepageAuth({
setTotpTempToken(""); setTotpTempToken("");
toast.success(t("messages.loginSuccess")); toast.success(t("messages.loginSuccess"));
} catch (err: any) { } catch (err: any) {
const errorMessage = err?.response?.data?.error || err?.message || t("errors.invalidTotpCode"); const errorMessage =
err?.response?.data?.error ||
err?.message ||
t("errors.invalidTotpCode");
toast.error(errorMessage); toast.error(errorMessage);
} finally { } finally {
setTotpLoading(false); setTotpLoading(false);
@@ -366,7 +370,10 @@ export function HomepageAuth({
window.location.replace(authUrl); window.location.replace(authUrl);
} catch (err: any) { } catch (err: any) {
const errorMessage = err?.response?.data?.error || err?.message || t("errors.failedOidcLogin"); const errorMessage =
err?.response?.data?.error ||
err?.message ||
t("errors.failedOidcLogin");
toast.error(errorMessage); toast.error(errorMessage);
setOidcLoading(false); setOidcLoading(false);
} }
+13 -10
View File
@@ -463,14 +463,19 @@ export let statsApi: AxiosInstance;
export let authApi: AxiosInstance; export let authApi: AxiosInstance;
if (isElectron()) { if (isElectron()) {
getServerConfig().then((config) => { getServerConfig()
.then((config) => {
if (config?.serverUrl) { if (config?.serverUrl) {
configuredServerUrl = config.serverUrl; configuredServerUrl = config.serverUrl;
(window as any).configuredServerUrl = configuredServerUrl; (window as any).configuredServerUrl = configuredServerUrl;
} }
initializeApiInstances(); initializeApiInstances();
}).catch((error) => { })
console.error("Failed to load server config, initializing with default:", error); .catch((error) => {
console.error(
"Failed to load server config, initializing with default:",
error,
);
initializeApiInstances(); initializeApiInstances();
}); });
} else { } else {
@@ -536,14 +541,12 @@ function handleApiError(error: unknown, operation: string): never {
errorContext, errorContext,
); );
const isLoginEndpoint = url?.includes('/users/login'); const isLoginEndpoint = url?.includes("/users/login");
const errorMessage = isLoginEndpoint ? message : "Authentication required. Please log in again."; const errorMessage = isLoginEndpoint
? message
: "Authentication required. Please log in again.";
throw new ApiError( throw new ApiError(errorMessage, 401, "AUTH_REQUIRED");
errorMessage,
401,
"AUTH_REQUIRED",
);
} else if (status === 403) { } else if (status === 403) {
authLogger.warn(`Access denied: ${method} ${url}`, errorContext); authLogger.warn(`Access denied: ${method} ${url}`, errorContext);
throw new ApiError( throw new ApiError(