var process = require('process');
// Hacks to get ssh2 working in browser
process.binding = function () { return {} };
process.version = '1.0.0';
var Client = require('ssh2/lib/client');
var ws = require('websocket-stream');
var xterm = require('xterm');
var fit = require('xterm/lib/addons/fit/fit');
var conn = new Client();
var term = new xterm();
var chan;
var wndopts = { term: 'xterm' };
window.term = term;
// Store current size for initialization
term.on('resize', function (rev) {
wndopts.rows = rev.rows;
wndopts.cols = rev.cols;
});
term.on('title', function (title) {
document.title = title;
});
conn.on('ready', function() {
console.log('Client :: ready');
chan = conn.shell(wndopts, function(err, stream) {
if (err) throw err;
stream.on('close', function() {
console.log('Stream :: close');
conn.end();
}).on('data', function(data) {
term.write(data.toString());
}).stderr.on('data', function(data) {
term.write(data.toString());
});
term.on('key', function (key, kev) {
stream.write(key);
});
term.on('resize', function (rev) {
stream.setWindow(rev.rows, rev.cols, 480, 640);
});
});
}).on('error', function (err) {
term.write(err.toString());
}).on('close', function () {
term.write('\r\nConnection lost.\r\n');
});
var user = '', pass = '';
function read_pass (key, kev) {
for (var i in key) {
var c = key[i];
switch (c.charCodeAt(0)) {
case 127:
pass = user.substring(0, user.length - 1);
break;
case 13:
term.off('key', read_pass);
term.write('\r\n');
conn.connect({
sock: ws('ws://localhost:8022', ['binary']),
username: user,
password: pass
});
default:
pass += c;
}
}
}
function read_user(key, kev) {
for (var i in key) {
var c = key[i];
switch (c.charCodeAt(0)) {
case 127:
user = user.substring(0, user.length - 1);
term.write('\033[D \033[D');
break;
case 13:
term.off('key', read_user);
term.write('\r\nPassword: ');
term.on('key', read_pass);
break;
default:
user += c;
term.write(c);
}
}
}
term.write('Login as: ');
term.on('key', read_user);
term.open(document.getElementById('#terminal'));
term.fit();
window.onresize = term.fit.bind(term);