forked from asg017/churro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
58 lines (53 loc) · 1.53 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const port = process.env.PORT || 8888;
const io = require("socket.io")(port);
const os = require("os");
const pty = require("node-pty");
const socketioJwt = require("socketio-jwt");
require("dotenv").config();
const secret = process.env.SECRET;
if (!secret) {
console.error(`ERROR: Please provide a string SECRET env var in .env`);
io.close();
return;
}
console.log(`socket.io server on port ${port}`);
const shell = os.platform() === "win32" ? "powershell.exe" : "bash";
const ptyProcesses = new Map();
io.on(
"connection",
socketioJwt.authorize({
secret: process.env.SECRET,
timeout: 2000
})
)
.on("authenticated", function(socket) {
const { decoded_token } = socket;
const { data } = decoded_token;
console.log("Authentication! ", decoded_token);
socket.emit("profile", decoded_token);
let ptyProcess = ptyProcesses.get(data);
if (ptyProcess == null) {
ptyProcess = pty.spawn(shell, [], {
name: `xterm-color${data}`,
cols: 80,
rows: 35,
cwd: process.env.HOME,
env: process.env
});
ptyProcesses.set(data, ptyProcess);
}
ptyProcess.resize(80, 35);
ptyProcess.write('echo "Connected to a client! "\r');
socket.on("sendData", data => {
ptyProcess.write(data);
});
socket.on("resize", ({ rows = 35, cols = 80 }) => {
ptyProcess.resize(cols, rows);
});
ptyProcess.on("data", data => {
socket.emit("data", data);
});
})
.on("unauthorized", err => {
console.error("Unauthorized access", err);
});