DockTerm / app /server.js
clone3's picture
Update app/server.js
c32ab8c verified
const fs = require('fs');
const path = require('path');
const http = require('http');
const SSHClient = require('ssh2').Client;
const socketIO = require('socket.io');
// Create HTTP server
const server = http.createServer(onRequest);
// Attach Socket.IO to the server
const io = socketIO(server);
// Load static files into memory
let staticFiles = {};
let basePath = path.join(require.resolve('xterm'), '..');
staticFiles['/xterm.css'] = fs.readFileSync(path.join(basePath, '../css/xterm.css'));
staticFiles['/xterm.js'] = fs.readFileSync(path.join(basePath, 'xterm.js'));
basePath = path.join(require.resolve('xterm-addon-fit'), '..');
staticFiles['/xterm-addon-fit.js'] = fs.readFileSync(path.join(basePath, 'xterm-addon-fit.js'));
staticFiles['/'] = fs.readFileSync('index.html');
// Handle static file serving
function onRequest(req, res) {
let file;
if (req.method === 'GET' && (file = staticFiles[req.url])) {
res.writeHead(200, {
'Content-Type': 'text/' + (/css$/.test(req.url) ? 'css' : (/js$/.test(req.url) ? 'javascript' : 'html'))
});
return res.end(file);
}
res.writeHead(404);
res.end();
}
// Setup WebSocket connection
io.on('connection', (socket) => {
const conn = new SSHClient();
// Debug logging
conn.on('debug', (msg) => {
console.log('DEBUG:', msg);
});
// On SSH connection ready
conn.on('ready', () => {
socket.emit('data', '\r\n*** SSH CONNECTION ESTABLISHED ***\r\n');
// Start shell session
conn.shell((err, stream) => {
if (err) {
return socket.emit('data', '\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
}
// When data is received from the client, write to the stream
socket.on('data', (data) => {
stream.write(data);
});
// Send data back to the client when received from the SSH session
stream.on('data', (d) => {
socket.emit('data', d.toString('binary'));
}).on('close', () => {
conn.end();
});
});
})
.on('close', () => {
socket.emit('data', '\r\n*** SSH CONNECTION CLOSED ***\r\n');
})
.on('error', (err) => {
console.error('SSH Connection Error:', err);
socket.emit('data', '\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
})
.connect({
host: process.env.REMOTE_HOST,
port: 22,
username: process.env.REMOTE_USERNAME,
password: process.env.REMOTE_PASSWORD,
readyTimeout: 60000,
debug: (msg) => console.log('DEBUG:', msg) // Enable debug logging
});
});
// Start the server
const port = 8000;
console.log('Listening on port', port);
server.listen(port);