Files
Netcatty/electron/main.cjs
T
LAPTOP-O016UC3M\Qi Chen afea784117 Adds FIDO2 security key support and key export workflow
Enables registration and management of FIDO2 hardware-backed SSH keys using WebAuthn, including a production HTTP server for secure context.

Introduces export-to-host functionality with script customization and host selection, improving workflow for attaching public keys to remote systems.

Refines UI interactions, adds context menus for keys, and improves toast notifications for consistent feedback.
2025-12-10 13:41:43 +08:00

1478 lines
47 KiB
JavaScript

// Make sure the helper processes do not get forced into Node-only mode.
// Presence of ELECTRON_RUN_AS_NODE (even "0") makes helpers parse Chromium
// switches as Node flags, leading to "bad option: --type=renderer".
if (process.env.ELECTRON_RUN_AS_NODE) {
delete process.env.ELECTRON_RUN_AS_NODE;
}
let electronModule;
try {
electronModule = require("node:electron");
} catch {
electronModule = require("electron");
}
console.log("electron module raw:", electronModule);
console.log("process.versions:", process.versions);
console.log("env ELECTRON_RUN_AS_NODE:", process.env.ELECTRON_RUN_AS_NODE);
const { app, BrowserWindow, nativeTheme, Menu } = electronModule || {};
if (!app || !BrowserWindow) {
throw new Error("Failed to load Electron runtime. Ensure the app is launched with the Electron binary.");
}
const path = require("node:path");
const os = require("node:os");
const fs = require("node:fs");
const net = require("node:net");
const http = require("node:http");
const pty = require("node-pty");
const SftpClient = require("ssh2-sftp-client");
const { Client: SSHClient } = require("ssh2");
// GPU: keep hardware acceleration enabled for smoother rendering
// (If you hit GPU issues, you can restore these switches.)
// app.commandLine.appendSwitch("disable-gpu");
// app.commandLine.appendSwitch("disable-software-rasterizer");
app.commandLine.appendSwitch("no-sandbox");
const devServerUrl = process.env.VITE_DEV_SERVER_URL;
const isDev = !!devServerUrl;
const preload = path.join(__dirname, "preload.cjs");
const isMac = process.platform === "darwin";
const appIcon = path.join(__dirname, "../public/icon.png");
// Production static file server (for WebAuthn secure context requirement)
let productionServer = null;
let productionServerUrl = null;
const MIME_TYPES = {
'.html': 'text/html',
'.js': 'application/javascript',
'.mjs': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.eot': 'application/vnd.ms-fontobject',
'.wasm': 'application/wasm',
};
// Start a local HTTP server for production to enable WebAuthn (requires secure context)
async function startProductionServer() {
const distPath = path.join(__dirname, "../dist");
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
let filePath = path.join(distPath, req.url === '/' ? 'index.html' : req.url);
// Security: prevent directory traversal
if (!filePath.startsWith(distPath)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
// Handle SPA routing - serve index.html for non-file routes
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
filePath = path.join(distPath, 'index.html');
}
const ext = path.extname(filePath).toLowerCase();
const mimeType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
// Fallback to index.html for SPA
fs.readFile(path.join(distPath, 'index.html'), (err2, data2) => {
if (err2) {
res.writeHead(404);
res.end('Not Found');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data2);
});
return;
}
res.writeHead(500);
res.end('Server Error');
return;
}
res.writeHead(200, { 'Content-Type': mimeType });
res.end(data);
});
});
// Find an available port starting from 17789
const tryPort = (port) => {
server.listen(port, '127.0.0.1', () => {
productionServer = server;
productionServerUrl = `http://127.0.0.1:${port}`;
console.log(`Production server started at ${productionServerUrl}`);
resolve(productionServerUrl);
}).on('error', (err) => {
if (err.code === 'EADDRINUSE') {
tryPort(port + 1);
} else {
reject(err);
}
});
};
tryPort(17789);
});
}
const sessions = new Map();
const sftpClients = new Map();
const keyRoot = path.join(os.homedir(), ".nebula-ssh", "keys");
// On Windows, node-pty with conpty needs full paths to executables
const findExecutable = (name) => {
if (process.platform !== "win32") return name;
const { execSync } = require("child_process");
try {
const result = execSync(`where.exe ${name}`, { encoding: "utf8" });
const firstLine = result.split(/\r?\n/)[0].trim();
if (firstLine && fs.existsSync(firstLine)) {
return firstLine;
}
} catch (err) {
console.warn(`Could not find ${name} via where.exe:`, err.message);
}
// Fallback to common locations
const commonPaths = [
path.join(process.env.SystemRoot || "C:\\Windows", "System32", "OpenSSH", `${name}.exe`),
path.join(process.env.ProgramFiles || "C:\\Program Files", "Git", "usr", "bin", `${name}.exe`),
path.join(process.env.ProgramFiles || "C:\\Program Files", "OpenSSH", `${name}.exe`),
];
for (const p of commonPaths) {
if (fs.existsSync(p)) return p;
}
return name; // Fall back to bare name
};
const ensureKeyDir = () => {
try {
fs.mkdirSync(keyRoot, { recursive: true, mode: 0o700 });
} catch (err) {
console.warn("Unable to ensure key cache dir", err);
}
};
const writeKeyToDisk = (keyId, privateKey) => {
if (!privateKey) return null;
ensureKeyDir();
const filename = `${keyId || "temp"}.pem`;
const target = path.join(keyRoot, filename);
const normalized = privateKey.endsWith("\n") ? privateKey : `${privateKey}\n`;
try {
fs.writeFileSync(target, normalized, { mode: 0o600 });
return target;
} catch (err) {
console.error("Failed to persist private key", err);
return null;
}
};
const registerSSHBridge = (win) => {
if (registerSSHBridge._registered) return;
registerSSHBridge._registered = true;
// Pure ssh2-based SSH session (no external ssh.exe required)
const start = (event, options) => {
return new Promise((resolve, reject) => {
const sessionId =
options.sessionId ||
`${Date.now()}-${Math.random().toString(16).slice(2)}`;
const conn = new SSHClient();
const cols = options.cols || 80;
const rows = options.rows || 24;
const connectOpts = {
host: options.hostname,
port: options.port || 22,
username: options.username || "root",
readyTimeout: 30000,
keepaliveInterval: 10000,
};
// Authentication: private key takes precedence
if (options.privateKey) {
connectOpts.privateKey = options.privateKey;
if (options.passphrase) {
connectOpts.passphrase = options.passphrase;
}
} else if (options.password) {
connectOpts.password = options.password;
}
// Agent forwarding
if (options.agentForwarding) {
connectOpts.agentForward = true;
if (process.platform === "win32") {
connectOpts.agent = "\\\\.\\pipe\\openssh-ssh-agent";
} else {
connectOpts.agent = process.env.SSH_AUTH_SOCK;
}
}
conn.on("ready", () => {
conn.shell(
{
term: "xterm-256color",
cols,
rows,
},
{
env: {
LANG: options.charset || "en_US.UTF-8",
COLORTERM: "truecolor",
},
},
(err, stream) => {
if (err) {
conn.end();
reject(err);
return;
}
const session = {
conn,
stream,
webContentsId: event.sender.id,
};
sessions.set(sessionId, session);
stream.on("data", (data) => {
const contents = BrowserWindow.fromWebContents(event.sender)?.webContents;
contents?.send("nebula:data", { sessionId, data: data.toString("utf8") });
});
stream.stderr?.on("data", (data) => {
const contents = BrowserWindow.fromWebContents(event.sender)?.webContents;
contents?.send("nebula:data", { sessionId, data: data.toString("utf8") });
});
stream.on("close", () => {
const contents = BrowserWindow.fromWebContents(event.sender)?.webContents;
contents?.send("nebula:exit", { sessionId, exitCode: 0 });
sessions.delete(sessionId);
conn.end();
});
// Run startup command if specified
if (options.startupCommand) {
setTimeout(() => {
stream.write(`${options.startupCommand}\n`);
}, 300);
}
resolve({ sessionId });
}
);
});
conn.on("error", (err) => {
console.error("SSH connection error:", err.message);
const contents = BrowserWindow.fromWebContents(event.sender)?.webContents;
contents?.send("nebula:exit", { sessionId, exitCode: 1, error: err.message });
sessions.delete(sessionId);
reject(err);
});
conn.on("close", () => {
const contents = BrowserWindow.fromWebContents(event.sender)?.webContents;
contents?.send("nebula:exit", { sessionId, exitCode: 0 });
sessions.delete(sessionId);
});
conn.connect(connectOpts);
});
};
const write = (_event, payload) => {
const session = sessions.get(payload.sessionId);
if (!session) return;
// SSH sessions use stream, local terminal uses proc
if (session.stream) {
session.stream.write(payload.data);
} else if (session.proc) {
session.proc.write(payload.data);
}
};
const resize = (_event, payload) => {
const session = sessions.get(payload.sessionId);
if (!session) return;
try {
if (session.stream) {
// SSH session - use setWindow
session.stream.setWindow(payload.rows, payload.cols, 0, 0);
} else if (session.proc) {
// Local terminal - use resize
session.proc.resize(payload.cols, payload.rows);
}
} catch (err) {
console.warn("Resize failed", err);
}
};
const close = (_event, payload) => {
const session = sessions.get(payload.sessionId);
if (!session) return;
try {
if (session.stream) {
session.stream.close();
session.conn?.end();
} else if (session.proc) {
session.proc.kill();
}
} catch (err) {
console.warn("Close failed", err);
}
sessions.delete(payload.sessionId);
};
electronModule.ipcMain.handle("nebula:start", start);
electronModule.ipcMain.handle("nebula:local:start", (event, payload) => {
const sessionId =
payload?.sessionId ||
`${Date.now()}-${Math.random().toString(16).slice(2)}`;
const defaultShell = process.platform === "win32"
? findExecutable("powershell") || "powershell.exe"
: process.env.SHELL || "/bin/bash";
const shell = payload?.shell || defaultShell;
const env = {
...process.env,
...(payload?.env || {}),
TERM: "xterm-256color",
COLORTERM: "truecolor",
};
const proc = pty.spawn(shell, [], {
cols: payload?.cols || 80,
rows: payload?.rows || 24,
env,
});
const session = {
proc,
webContentsId: event.sender.id,
};
sessions.set(sessionId, session);
proc.onData((data) => {
const contents = electronModule.webContents.fromId(session.webContentsId);
contents?.send("nebula:data", { sessionId, data });
});
proc.onExit((evt) => {
sessions.delete(sessionId);
const contents = electronModule.webContents.fromId(session.webContentsId);
contents?.send("nebula:exit", { sessionId, ...evt });
});
return { sessionId };
});
electronModule.ipcMain.on("nebula:write", write);
electronModule.ipcMain.on("nebula:resize", resize);
electronModule.ipcMain.on("nebula:close", close);
// One-off hidden exec (for probes like distro detection)
const execOnce = async (_event, payload) => {
return new Promise((resolve, reject) => {
const conn = new SSHClient();
let stdout = "";
let stderr = "";
let settled = false;
const timeoutMs = payload.timeout || 10000;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
conn.end();
reject(new Error("SSH exec timeout"));
}, timeoutMs);
conn
.on("ready", () => {
conn.exec(payload.command, (err, stream) => {
if (err) {
clearTimeout(timer);
settled = true;
conn.end();
return reject(err);
}
stream
.on("data", (data) => {
stdout += data.toString();
})
.stderr.on("data", (data) => {
stderr += data.toString();
})
.on("close", (code) => {
if (settled) return;
clearTimeout(timer);
settled = true;
conn.end();
resolve({ stdout, stderr, code });
});
});
})
.on("error", (err) => {
if (settled) return;
clearTimeout(timer);
settled = true;
reject(err);
})
.on("end", () => {
if (settled) return;
clearTimeout(timer);
settled = true;
resolve({ stdout, stderr, code: null });
});
conn.connect({
host: payload.hostname,
port: payload.port || 22,
username: payload.username,
password: payload.password,
privateKey: payload.privateKey,
readyTimeout: timeoutMs,
keepaliveInterval: 0,
});
});
};
electronModule.ipcMain.handle("nebula:ssh:exec", execOnce);
// SFTP handlers
const openSftp = async (_event, options) => {
const client = new SftpClient();
const connId = options.sessionId || `${Date.now()}-sftp-${Math.random().toString(16).slice(2)}`;
const connectOpts = {
host: options.hostname,
port: options.port || 22,
username: options.username || "root",
};
if (options.privateKey) {
connectOpts.privateKey = options.privateKey;
} else if (options.password) {
connectOpts.password = options.password;
}
await client.connect(connectOpts);
sftpClients.set(connId, client);
return { sftpId: connId };
};
const listSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
const list = await client.list(payload.path || ".");
return list.map((item) => ({
name: item.name,
type: item.type === "d" ? "directory" : "file",
size: `${item.size} bytes`,
lastModified: new Date(item.modifyTime || Date.now()).toISOString(),
}));
};
const readSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
const buffer = await client.get(payload.path);
return buffer.toString();
};
const writeSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
await client.put(Buffer.from(payload.content, "utf-8"), payload.path);
return true;
};
// Write binary data with progress callback
const writeSftpBinaryWithProgress = async (event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
const { sftpId, path: remotePath, content, transferId } = payload;
const buffer = Buffer.from(content);
const totalBytes = buffer.length;
let transferredBytes = 0;
let lastProgressTime = Date.now();
let lastTransferredBytes = 0;
// Create a readable stream from the buffer
const { Readable } = require("stream");
const readableStream = new Readable({
read() {
// Push data in chunks of 64KB for progress updates
const chunkSize = 65536;
if (transferredBytes < totalBytes) {
const end = Math.min(transferredBytes + chunkSize, totalBytes);
const chunk = buffer.slice(transferredBytes, end);
transferredBytes = end;
// Calculate speed
const now = Date.now();
const elapsed = (now - lastProgressTime) / 1000;
let speed = 0;
if (elapsed >= 0.1) {
speed = (transferredBytes - lastTransferredBytes) / elapsed;
lastProgressTime = now;
lastTransferredBytes = transferredBytes;
}
// Send progress update
const contents = electronModule.webContents.fromId(event.sender.id);
contents?.send("nebula:upload:progress", {
transferId,
transferred: transferredBytes,
totalBytes,
speed,
});
this.push(chunk);
} else {
this.push(null); // End of stream
}
}
});
try {
await client.put(readableStream, remotePath);
// Send completion
const contents = electronModule.webContents.fromId(event.sender.id);
contents?.send("nebula:upload:complete", { transferId });
return { success: true, transferId };
} catch (err) {
// Send error
const contents = electronModule.webContents.fromId(event.sender.id);
contents?.send("nebula:upload:error", { transferId, error: err.message });
throw err;
}
};
const closeSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) return;
try {
await client.end();
} catch (err) {
console.warn("SFTP close failed", err);
}
sftpClients.delete(payload.sftpId);
};
const mkdirSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
await client.mkdir(payload.path, true);
return true;
};
// Delete file or directory via SFTP
const deleteSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
// Check if it's a directory or file
const stat = await client.stat(payload.path);
if (stat.isDirectory) {
await client.rmdir(payload.path, true); // recursive delete
} else {
await client.delete(payload.path);
}
return true;
};
// Rename file or directory via SFTP
const renameSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
await client.rename(payload.oldPath, payload.newPath);
return true;
};
// Stat file via SFTP
const statSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
const stat = await client.stat(payload.path);
return {
name: path.basename(payload.path),
type: stat.isDirectory ? "directory" : stat.isSymbolicLink ? "symlink" : "file",
size: stat.size,
lastModified: stat.modifyTime,
permissions: stat.mode ? (stat.mode & 0o777).toString(8) : undefined,
};
};
// Change permissions via SFTP
const chmodSftp = async (_event, payload) => {
const client = sftpClients.get(payload.sftpId);
if (!client) throw new Error("SFTP session not found");
await client.chmod(payload.path, parseInt(payload.mode, 8));
return true;
};
// Local filesystem operations
const listLocalDir = async (_event, payload) => {
const dirPath = payload.path;
const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
const result = [];
for (const entry of entries) {
try {
const fullPath = path.join(dirPath, entry.name);
const stat = await fs.promises.stat(fullPath);
result.push({
name: entry.name,
type: entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "file",
size: `${stat.size} bytes`,
lastModified: stat.mtime.toISOString(),
});
} catch (err) {
// Skip files we can't stat (permission denied, etc.)
console.warn(`Could not stat ${entry.name}:`, err.message);
}
}
return result;
};
const readLocalFile = async (_event, payload) => {
const buffer = await fs.promises.readFile(payload.path);
return buffer;
};
const writeLocalFile = async (_event, payload) => {
await fs.promises.writeFile(payload.path, Buffer.from(payload.content));
return true;
};
const deleteLocalFile = async (_event, payload) => {
const stat = await fs.promises.stat(payload.path);
if (stat.isDirectory()) {
await fs.promises.rm(payload.path, { recursive: true, force: true });
} else {
await fs.promises.unlink(payload.path);
}
return true;
};
const renameLocalFile = async (_event, payload) => {
await fs.promises.rename(payload.oldPath, payload.newPath);
return true;
};
const mkdirLocal = async (_event, payload) => {
await fs.promises.mkdir(payload.path, { recursive: true });
return true;
};
const statLocal = async (_event, payload) => {
const stat = await fs.promises.stat(payload.path);
return {
name: path.basename(payload.path),
type: stat.isDirectory() ? "directory" : stat.isSymbolicLink() ? "symlink" : "file",
size: stat.size,
lastModified: stat.mtime.getTime(),
};
};
const getHomeDir = async () => {
return os.homedir();
};
// Read system known_hosts file
const readKnownHosts = async () => {
const homeDir = os.homedir();
const knownHostsPaths = [];
if (process.platform === "win32") {
// Windows: ~/.ssh/known_hosts
knownHostsPaths.push(path.join(homeDir, ".ssh", "known_hosts"));
// Also check OpenSSH system path
knownHostsPaths.push(path.join(process.env.PROGRAMDATA || "C:\\ProgramData", "ssh", "known_hosts"));
} else if (process.platform === "darwin") {
// macOS
knownHostsPaths.push(path.join(homeDir, ".ssh", "known_hosts"));
knownHostsPaths.push("/etc/ssh/ssh_known_hosts");
} else {
// Linux and others
knownHostsPaths.push(path.join(homeDir, ".ssh", "known_hosts"));
knownHostsPaths.push("/etc/ssh/ssh_known_hosts");
}
let combinedContent = "";
for (const knownHostsPath of knownHostsPaths) {
try {
if (fs.existsSync(knownHostsPath)) {
const content = fs.readFileSync(knownHostsPath, "utf8");
if (content.trim()) {
combinedContent += content + "\n";
}
}
} catch (err) {
console.warn(`Failed to read known_hosts from ${knownHostsPath}:`, err.message);
}
}
return combinedContent || null;
};
electronModule.ipcMain.handle("nebula:sftp:open", openSftp);
electronModule.ipcMain.handle("nebula:sftp:list", listSftp);
electronModule.ipcMain.handle("nebula:sftp:read", readSftp);
electronModule.ipcMain.handle("nebula:sftp:write", writeSftp);
electronModule.ipcMain.handle("nebula:sftp:writeBinaryWithProgress", writeSftpBinaryWithProgress);
electronModule.ipcMain.handle("nebula:sftp:close", closeSftp);
electronModule.ipcMain.handle("nebula:sftp:mkdir", mkdirSftp);
electronModule.ipcMain.handle("nebula:sftp:delete", deleteSftp);
electronModule.ipcMain.handle("nebula:sftp:rename", renameSftp);
electronModule.ipcMain.handle("nebula:sftp:stat", statSftp);
electronModule.ipcMain.handle("nebula:sftp:chmod", chmodSftp);
// Local filesystem handlers
electronModule.ipcMain.handle("nebula:local:list", listLocalDir);
electronModule.ipcMain.handle("nebula:local:read", readLocalFile);
electronModule.ipcMain.handle("nebula:local:write", writeLocalFile);
electronModule.ipcMain.handle("nebula:local:delete", deleteLocalFile);
electronModule.ipcMain.handle("nebula:local:rename", renameLocalFile);
electronModule.ipcMain.handle("nebula:local:mkdir", mkdirLocal);
electronModule.ipcMain.handle("nebula:local:stat", statLocal);
electronModule.ipcMain.handle("nebula:local:homedir", getHomeDir);
electronModule.ipcMain.handle("nebula:known-hosts:read", readKnownHosts);
// Streaming transfer with progress and cancellation support
const activeTransfers = new Map(); // transferId -> { cancelled: boolean, abortController?: AbortController }
const startTransfer = async (event, payload) => {
const { transferId, sourcePath, targetPath, sourceType, targetType, sourceSftpId, targetSftpId, totalBytes } = payload;
const sender = event.sender;
// Register transfer for cancellation
activeTransfers.set(transferId, { cancelled: false });
let lastTime = Date.now();
let lastTransferred = 0;
let speed = 0;
const sendProgress = (transferred, total) => {
if (activeTransfers.get(transferId)?.cancelled) return;
// Calculate speed
const now = Date.now();
const elapsed = now - lastTime;
if (elapsed >= 100) {
speed = Math.round((transferred - lastTransferred) / (elapsed / 1000));
lastTime = now;
lastTransferred = transferred;
}
sender.send("nebula:transfer:progress", { transferId, transferred, speed, totalBytes: total });
};
const sendComplete = () => {
activeTransfers.delete(transferId);
sender.send("nebula:transfer:complete", { transferId });
};
const sendError = (error) => {
activeTransfers.delete(transferId);
sender.send("nebula:transfer:error", { transferId, error: error.message || String(error) });
};
const isCancelled = () => activeTransfers.get(transferId)?.cancelled;
try {
let fileSize = totalBytes || 0;
// Get file size if not provided
if (!fileSize) {
if (sourceType === 'local') {
const stat = await fs.promises.stat(sourcePath);
fileSize = stat.size;
} else if (sourceType === 'sftp') {
const client = sftpClients.get(sourceSftpId);
if (!client) throw new Error("Source SFTP session not found");
const stat = await client.stat(sourcePath);
fileSize = stat.size;
}
}
// Send initial progress
sendProgress(0, fileSize);
// Handle different transfer scenarios
if (sourceType === 'local' && targetType === 'sftp') {
// Upload: Local -> SFTP (use fastPut with step callback)
const client = sftpClients.get(targetSftpId);
if (!client) throw new Error("Target SFTP session not found");
// Ensure remote directory exists
const dir = path.dirname(targetPath).replace(/\\/g, '/');
try { await client.mkdir(dir, true); } catch {}
await client.fastPut(sourcePath, targetPath, {
step: (totalTransferred, chunk, total) => {
if (isCancelled()) {
throw new Error('Transfer cancelled');
}
sendProgress(totalTransferred, total);
}
});
} else if (sourceType === 'sftp' && targetType === 'local') {
// Download: SFTP -> Local (use fastGet with step callback)
const client = sftpClients.get(sourceSftpId);
if (!client) throw new Error("Source SFTP session not found");
// Ensure local directory exists
const dir = path.dirname(targetPath);
await fs.promises.mkdir(dir, { recursive: true });
await client.fastGet(sourcePath, targetPath, {
step: (totalTransferred, chunk, total) => {
if (isCancelled()) {
throw new Error('Transfer cancelled');
}
sendProgress(totalTransferred, total);
}
});
} else if (sourceType === 'local' && targetType === 'local') {
// Local copy: use streams
const dir = path.dirname(targetPath);
await fs.promises.mkdir(dir, { recursive: true });
await new Promise((resolve, reject) => {
const readStream = fs.createReadStream(sourcePath);
const writeStream = fs.createWriteStream(targetPath);
let transferred = 0;
const transfer = activeTransfers.get(transferId);
if (transfer) {
transfer.readStream = readStream;
transfer.writeStream = writeStream;
}
readStream.on('data', (chunk) => {
if (isCancelled()) {
readStream.destroy();
writeStream.destroy();
reject(new Error('Transfer cancelled'));
return;
}
transferred += chunk.length;
sendProgress(transferred, fileSize);
});
readStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('finish', resolve);
readStream.pipe(writeStream);
});
} else if (sourceType === 'sftp' && targetType === 'sftp') {
// SFTP to SFTP: download to temp then upload
const tempPath = path.join(os.tmpdir(), `nebula-transfer-${transferId}`);
const sourceClient = sftpClients.get(sourceSftpId);
const targetClient = sftpClients.get(targetSftpId);
if (!sourceClient) throw new Error("Source SFTP session not found");
if (!targetClient) throw new Error("Target SFTP session not found");
// Download phase (0-50%)
await sourceClient.fastGet(sourcePath, tempPath, {
step: (totalTransferred, chunk, total) => {
if (isCancelled()) {
throw new Error('Transfer cancelled');
}
// Report as 0-50% of total
sendProgress(Math.floor(totalTransferred / 2), fileSize);
}
});
if (isCancelled()) {
try { await fs.promises.unlink(tempPath); } catch {}
throw new Error('Transfer cancelled');
}
// Upload phase (50-100%)
const dir = path.dirname(targetPath).replace(/\\/g, '/');
try { await targetClient.mkdir(dir, true); } catch {}
await targetClient.fastPut(tempPath, targetPath, {
step: (totalTransferred, chunk, total) => {
if (isCancelled()) {
throw new Error('Transfer cancelled');
}
// Report as 50-100% of total
sendProgress(Math.floor(fileSize / 2) + Math.floor(totalTransferred / 2), fileSize);
}
});
// Cleanup temp file
try { await fs.promises.unlink(tempPath); } catch {}
} else {
throw new Error("Invalid transfer configuration");
}
// Send final 100% progress
sendProgress(fileSize, fileSize);
sendComplete();
return { transferId, totalBytes: fileSize };
} catch (err) {
if (err.message === 'Transfer cancelled') {
activeTransfers.delete(transferId);
sender.send("nebula:transfer:cancelled", { transferId });
} else {
sendError(err);
}
return { transferId, error: err.message };
}
};
const cancelTransfer = async (_event, payload) => {
const { transferId } = payload;
const transfer = activeTransfers.get(transferId);
if (transfer) {
transfer.cancelled = true;
if (transfer.readStream) {
try { transfer.readStream.destroy(); } catch {}
}
if (transfer.writeStream) {
try { transfer.writeStream.destroy(); } catch {}
}
activeTransfers.delete(transferId);
}
return { success: true };
};
electronModule.ipcMain.handle("nebula:transfer:start", startTransfer);
electronModule.ipcMain.handle("nebula:transfer:cancel", cancelTransfer);
// ============================================
// PORT FORWARDING HANDLERS
// ============================================
// Store active port forwarding tunnels
const portForwardingTunnels = new Map();
// Start a port forwarding tunnel
const startPortForward = async (event, payload) => {
const {
tunnelId,
type, // 'local' | 'remote' | 'dynamic'
localPort,
bindAddress = '127.0.0.1',
remoteHost,
remotePort,
// SSH connection details
hostname,
port = 22,
username,
password,
privateKey,
} = payload;
return new Promise((resolve, reject) => {
const conn = new SSHClient();
const sender = event.sender;
const sendStatus = (status, error = null) => {
if (!sender.isDestroyed()) {
sender.send("nebula:portforward:status", { tunnelId, status, error });
}
};
const connectOpts = {
host: hostname,
port: port,
username: username || 'root',
readyTimeout: 30000,
keepaliveInterval: 10000,
};
if (privateKey) {
connectOpts.privateKey = privateKey;
} else if (password) {
connectOpts.password = password;
}
conn.on('ready', () => {
console.log(`[PortForward] SSH connection ready for tunnel ${tunnelId}`);
if (type === 'local') {
// LOCAL FORWARDING: Listen on local port, forward to remote
const server = net.createServer((socket) => {
conn.forwardOut(
bindAddress,
localPort,
remoteHost,
remotePort,
(err, stream) => {
if (err) {
console.error(`[PortForward] Forward error:`, err.message);
socket.end();
return;
}
socket.pipe(stream).pipe(socket);
socket.on('error', (e) => console.warn('[PortForward] Socket error:', e.message));
stream.on('error', (e) => console.warn('[PortForward] Stream error:', e.message));
}
);
});
server.on('error', (err) => {
console.error(`[PortForward] Server error:`, err.message);
sendStatus('error', err.message);
conn.end();
portForwardingTunnels.delete(tunnelId);
reject(err);
});
server.listen(localPort, bindAddress, () => {
console.log(`[PortForward] Local forwarding active: ${bindAddress}:${localPort} -> ${remoteHost}:${remotePort}`);
portForwardingTunnels.set(tunnelId, {
type: 'local',
conn,
server,
webContentsId: sender.id
});
sendStatus('active');
resolve({ tunnelId, success: true });
});
} else if (type === 'remote') {
// REMOTE FORWARDING: Listen on remote port, forward to local
conn.forwardIn(bindAddress, localPort, (err) => {
if (err) {
console.error(`[PortForward] Remote forward error:`, err.message);
sendStatus('error', err.message);
conn.end();
reject(err);
return;
}
console.log(`[PortForward] Remote forwarding active: remote ${bindAddress}:${localPort} -> local ${remoteHost}:${remotePort}`);
portForwardingTunnels.set(tunnelId, {
type: 'remote',
conn,
webContentsId: sender.id
});
sendStatus('active');
resolve({ tunnelId, success: true });
});
// Handle incoming connections from remote
conn.on('tcp connection', (info, accept, reject) => {
const stream = accept();
const socket = net.connect(remotePort, remoteHost || '127.0.0.1', () => {
stream.pipe(socket).pipe(stream);
});
socket.on('error', (e) => {
console.warn('[PortForward] Local socket error:', e.message);
stream.end();
});
stream.on('error', (e) => {
console.warn('[PortForward] Remote stream error:', e.message);
socket.end();
});
});
} else if (type === 'dynamic') {
// DYNAMIC FORWARDING (SOCKS5 Proxy)
const server = net.createServer((socket) => {
// Simple SOCKS5 handshake
socket.once('data', (data) => {
// SOCKS5 greeting: version, number of methods, methods
if (data[0] !== 0x05) {
socket.end();
return;
}
// Reply: version, no auth required
socket.write(Buffer.from([0x05, 0x00]));
// Wait for connection request
socket.once('data', (request) => {
if (request[0] !== 0x05 || request[1] !== 0x01) {
socket.write(Buffer.from([0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
socket.end();
return;
}
let targetHost, targetPort;
const addressType = request[3];
if (addressType === 0x01) {
// IPv4
targetHost = `${request[4]}.${request[5]}.${request[6]}.${request[7]}`;
targetPort = request.readUInt16BE(8);
} else if (addressType === 0x03) {
// Domain name
const domainLength = request[4];
targetHost = request.slice(5, 5 + domainLength).toString();
targetPort = request.readUInt16BE(5 + domainLength);
} else if (addressType === 0x04) {
// IPv6 - simplified handling
socket.write(Buffer.from([0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
socket.end();
return;
} else {
socket.write(Buffer.from([0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
socket.end();
return;
}
// Forward through SSH tunnel
conn.forwardOut(
bindAddress,
0, // Let the SSH server pick source port
targetHost,
targetPort,
(err, stream) => {
if (err) {
// Connection refused
socket.write(Buffer.from([0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
socket.end();
return;
}
// Success reply
const reply = Buffer.alloc(10);
reply[0] = 0x05; // version
reply[1] = 0x00; // success
reply[2] = 0x00; // reserved
reply[3] = 0x01; // IPv4
reply.writeUInt16BE(0, 8); // port
socket.write(reply);
// Pipe data
socket.pipe(stream).pipe(socket);
socket.on('error', () => stream.end());
stream.on('error', () => socket.end());
}
);
});
});
});
server.on('error', (err) => {
console.error(`[PortForward] SOCKS server error:`, err.message);
sendStatus('error', err.message);
conn.end();
portForwardingTunnels.delete(tunnelId);
reject(err);
});
server.listen(localPort, bindAddress, () => {
console.log(`[PortForward] Dynamic SOCKS5 proxy active on ${bindAddress}:${localPort}`);
portForwardingTunnels.set(tunnelId, {
type: 'dynamic',
conn,
server,
webContentsId: sender.id
});
sendStatus('active');
resolve({ tunnelId, success: true });
});
} else {
reject(new Error(`Unknown forwarding type: ${type}`));
}
});
conn.on('error', (err) => {
console.error(`[PortForward] SSH error:`, err.message);
sendStatus('error', err.message);
portForwardingTunnels.delete(tunnelId);
reject(err);
});
conn.on('close', () => {
console.log(`[PortForward] SSH connection closed for tunnel ${tunnelId}`);
const tunnel = portForwardingTunnels.get(tunnelId);
if (tunnel) {
if (tunnel.server) {
try { tunnel.server.close(); } catch {}
}
sendStatus('inactive');
portForwardingTunnels.delete(tunnelId);
}
});
sendStatus('connecting');
conn.connect(connectOpts);
});
};
// Stop a port forwarding tunnel
const stopPortForward = async (_event, payload) => {
const { tunnelId } = payload;
const tunnel = portForwardingTunnels.get(tunnelId);
if (!tunnel) {
return { tunnelId, success: false, error: 'Tunnel not found' };
}
try {
if (tunnel.server) {
tunnel.server.close();
}
if (tunnel.conn) {
tunnel.conn.end();
}
portForwardingTunnels.delete(tunnelId);
return { tunnelId, success: true };
} catch (err) {
return { tunnelId, success: false, error: err.message };
}
};
// Get status of all active tunnels
const getPortForwardStatus = async (_event, payload) => {
const { tunnelId } = payload;
const tunnel = portForwardingTunnels.get(tunnelId);
if (!tunnel) {
return { tunnelId, status: 'inactive' };
}
return { tunnelId, status: 'active', type: tunnel.type };
};
// List all active port forwards
const listPortForwards = async () => {
const list = [];
for (const [tunnelId, tunnel] of portForwardingTunnels) {
list.push({
tunnelId,
type: tunnel.type,
status: 'active',
});
}
return list;
};
electronModule.ipcMain.handle("nebula:portforward:start", startPortForward);
electronModule.ipcMain.handle("nebula:portforward:stop", stopPortForward);
electronModule.ipcMain.handle("nebula:portforward:status", getPortForwardStatus);
electronModule.ipcMain.handle("nebula:portforward:list", listPortForwards);
};
// Store reference to main window for theme updates
let mainWindow = null;
// Theme colors configuration
const THEME_COLORS = {
dark: {
background: "#0b1220",
titleBarColor: "#0b1220",
symbolColor: "#ffffff",
},
light: {
background: "#ffffff",
titleBarColor: "#f8fafc",
symbolColor: "#1e293b",
},
};
// Read initial theme from a simple approach - default to light
let currentTheme = "light";
async function createWindow() {
const themeConfig = THEME_COLORS[currentTheme];
const win = new BrowserWindow({
width: 1400,
height: 900,
backgroundColor: themeConfig.background,
icon: appIcon,
// macOS: use hiddenInset for native traffic lights
// Windows/Linux: use frameless window with custom controls
frame: isMac,
titleBarStyle: isMac ? "hiddenInset" : undefined,
trafficLightPosition: isMac ? { x: 12, y: 12 } : undefined,
webPreferences: {
preload,
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
},
});
mainWindow = win;
// Window control handlers (for custom title bar on Windows/Linux)
electronModule.ipcMain.handle("nebula:window:minimize", () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.minimize();
}
});
electronModule.ipcMain.handle("nebula:window:maximize", () => {
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
return false;
} else {
mainWindow.maximize();
return true;
}
}
return false;
});
electronModule.ipcMain.handle("nebula:window:close", () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.close();
}
});
electronModule.ipcMain.handle("nebula:window:isMaximized", () => {
if (mainWindow && !mainWindow.isDestroyed()) {
return mainWindow.isMaximized();
}
return false;
});
// Handle theme change requests from renderer
electronModule.ipcMain.handle("nebula:setTheme", (_event, theme) => {
currentTheme = theme;
nativeTheme.themeSource = theme;
const themeConfig = THEME_COLORS[theme] || THEME_COLORS.light;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.setBackgroundColor(themeConfig.background);
}
return true;
});
if (isDev) {
try {
await win.loadURL(devServerUrl);
win.webContents.openDevTools({ mode: "detach" });
registerSSHBridge(win);
return;
} catch (e) {
console.warn("Dev server not reachable, falling back to bundled dist.", e);
}
}
// In production, use local HTTP server for WebAuthn support (requires secure context)
// WebAuthn (Windows Hello, Touch ID, FIDO2) requires either HTTPS or localhost
try {
if (!productionServerUrl) {
await startProductionServer();
}
await win.loadURL(productionServerUrl);
} catch (e) {
console.warn("Failed to start production server, falling back to file://", e);
const indexPath = path.join(__dirname, "../dist/index.html");
await win.loadFile(indexPath);
}
registerSSHBridge(win);
}
app.whenReady().then(() => {
if (isMac && appIcon && app.dock?.setIcon) {
try {
app.dock.setIcon(appIcon);
} catch (err) {
console.warn("Failed to set dock icon", err);
}
}
// Set a minimal menu to prevent function keys from being intercepted
// This is especially important for F10 in htop and similar applications
const template = [
...(isMac
? [
{
label: app.name,
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
},
]
: []),
{
label: "Edit",
submenu: [
{ role: "undo" },
{ role: "redo" },
{ type: "separator" },
{ role: "cut" },
{ role: "copy" },
{ role: "paste" },
{ role: "selectAll" },
],
},
{
label: "View",
submenu: [
{ role: "reload" },
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn" },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
{
label: "Window",
submenu: [
{ role: "minimize" },
{ role: "zoom" },
...(isMac
? [{ type: "separator" }, { role: "front" }]
: [{ role: "close" }]),
],
},
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
// Cleanup production server
if (productionServer) {
productionServer.close();
productionServer = null;
productionServerUrl = null;
}
if (process.platform !== "darwin") app.quit();
});