-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (65 loc) · 1.78 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const express = require('express')
const minimist = require('minimist')
const expressws = require('express-ws')
const pty = require('pty.js')
const cookieparser = require('cookie-parser')
const crypto = require('crypto')
// parse command line options
const options = {
port: '8080',
vm: 'sandbox',
}
Object.assign(options, minimist(process.argv.slice(2)))
const app = express()
const _ = expressws(app)
app.use(cookieParser())
app.use(express.static('static'))
app.ws('/terminal', (ws, req) => {
console.log('spawning client...')
const vm = pty.spawn(
'docker',
// ['run', '-it', 'project5_sandbox'],
['attach', options.vm],
{
name: 'screen-256color',
cols: 80,
rows: 30
}
)
ws.on('message', msg => {
msg = JSON.parse(msg)
switch (msg.type) {
case 'keys':
vm.stdin.write(msg.data)
break
case 'resize':
vm.resize(msg.cols, msg.rows)
break
case 'quit':
vm.terminate()
break;
}
})
let trytowrite = data => {
try {
ws.send(data)
} catch (e) {
console.log('terminating vm due to exception')
vm.kill()
}
}
vm.stdout.on('data', trytowrite)
vm.stderr.on('data', trytowrite)
vm.on('exit', () => {
console.log('terminated client')
ws.terminate()
})
})
app.get('/api/login', (req, res) => {
if ('pw' in req.query && req.query.pw === 'foobar') {
res.json({success: true})
return
}
res.json({success: false})
})
app.listen(options.port, () => console.log(`listening on ${options.port}, serving out vm ${options.vm}`))