-
Notifications
You must be signed in to change notification settings - Fork 12
/
webrepl.js
239 lines (225 loc) · 9.28 KB
/
webrepl.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright (c) 2011 Michael Mattozzi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var SimpleStream = require('./SimpleStream');
var repl = require('repl');
var http = require('http');
var fs = require('fs');
var util = require('util');
var ReplHttpServer = function ReplHttpServer(prompt, stream, replServer, options) {
this.running = false;
this.prompt = prompt;
this.stream = stream;
this.replServer = replServer;
this.webdir = __dirname;
if (options !== undefined) {
if (options.username !== undefined) {
this.username = options.username;
}
if (options.username !== undefined) {
this.password = options.password;
}
if (options.hostname !== undefined) {
this.hostname = options.hostname;
}
}
};
ReplHttpServer.prototype.start = function(port) {
var self = this;
if (this.username !== undefined && this.password !== undefined) {
// Set up server that requires http digest authentication
var configuredUsername = this.username;
var configuredPassword = this.password;
var auth = require('http-auth');
var crypto = require('crypto');
var digest = auth.digest({ realm: "webrepl" },
function (username, callback) { // Expecting md5(username:realm:password) in callback.
if (username === configuredUsername) {
var md5hash = crypto.createHash('md5');
callback(md5hash.update(configuredUsername + ":webrepl:" + configuredPassword).digest("hex"));
} else {
callback();
}
}
);
self.server = http.createServer(digest, function(req, res) {
self.route(req, res);
});
self.server.listen(port, this.hostname);
} else {
// No auth required
self.server = http.createServer(function(req, res) { self.route(req, res); });
self.server.on('error', function() { /* Ignore Errors */ });
self.server.listen(port, this.hostname);
}
return self;
};
ReplHttpServer.prototype.route = function(req, res) {
var stream = this.stream;
var replServer = this.replServer;
req.on('error', function() { /* Ignore Errors */ });
res.on('error', function() { /* Ignore Errors */ });
var match = null;
if (req.url.match(/^\/repl/)) {
if (req.method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
var resBody = '';
while (stream.messages.length > 0) {
var msg = stream.messages.shift();
if (! msg.match("^" + this.prompt)) {
resBody += msg;
}
}
res.end(resBody);
} else if (req.method === 'POST') {
var allData = "";
req.on('data', function(data) {
allData += data;
});
req.on('end', function() {
allData += "\n";
if (stream.emit('data', allData)) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end();
} else {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end();
}
});
}
} else if ((match = req.url.match(/^\/context\/([a-zA-Z_$][0-9a-zA-Z_$\.]*)$/))) {
try {
var variableName = match[1];
var obj = eval('replServer.context.' + variableName);
if (!obj) {
res.writeHeader(404);
res.end();
} else {
if (req.method == 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(obj));
} else if (req.method == 'PUT') {
var allData = "";
req.on('data', function(data) {
allData += data;
});
req.on('end', function() {
console.log("Saving " + allData + " to " + variableName);
eval('replServer.context.' + variableName + ' = ' + allData);
var modifiedObj = eval('replServer.context.' + variableName);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(modifiedObj));
});
}
}
} catch (err) {
console.log("Error resolving context request: " + err.toString());
res.writeHeader(500);
res.end();
}
} else if ((match = req.url.match(/^\/complete\/(.*)/))) {
if (match[1].length > 0) {
// This is written to accomodate both versions of the complete method
// in node.js. Older versions of node (0.4) return the completions from
// the function. Newer versions (0.6+) take a callback to handle the
// completions.
var completionsOld = this.replServer.complete(match[1], function(o, completions) {
var cObj = { "completions": completions[0] };
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(cObj));
});
if (completionsOld !== undefined) {
var cObj = { "completions": completionsOld[0] };
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(cObj));
}
} else {
res.writeHead(500, {'Content-Type': 'application/json'});
res.end();
}
} else if (req.url.match(/^\/info/)) {
var name = (process.argv.length > 1 ? process.argv[1] : process.argv[0]);
var info = { 'pid': process.pid, 'name': name };
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(info));
} else if (req.url.match(/^\/clear/) && req.method === 'POST') {
var rli = this.replServer.rli;
if (this.replServer.bufferedCommand && this.replServer.bufferedCommand.length > 0) {
rli.write('\n');
this.replServer.bufferedCommand = '';
this.replServer.displayPrompt();
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end();
} else {
match = req.url.match(/\/(.*)/);
if (match) {
var file = match[1];
if (file === '') { file = 'index.html'; }
file = this.webdir + '/' + file;
this.serveFile(file, res);
}
}
};
ReplHttpServer.prototype.serveFile = function(file, response) {
function contentType(file) {
if (file.match(/.js$/)) {
return "application/x-javascript";
} else if (file.match(/.html$/)) {
return "text/html";
} else if (file.match(/.css$/)) {
return "text/css";
}
return "text/plain";
}
fs.stat(file, function(err, stat) {
if (err) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Cannot find file: " + file);
response.end();
return;
}
fs.readFile(file, "binary", function (err, data) {
if (err) {
response.writeHead(500, {"Content-Type": contentType(file) });
response.write("Error opening file " + file + ": " + err);
} else {
response.writeHead(200, { 'Content-Type': contentType(file), 'Content-Length': data.length });
response.write(data, "binary");
}
response.end();
});
});
};
/**
* Starts a repl served via a web console.
* @param {Integer} port Port to serve web console
* @param {Object} options Set username, password, and hostname options
* @return Return the REPLServer. Context can be set on this variable.
*/
var start = function(port, options) {
var stream = new SimpleStream();
var prompt = 'node> ';
var rs = repl.start({ prompt: prompt, input: stream, output: stream});
var replHttpServer = new ReplHttpServer(prompt, stream, rs, options);
replHttpServer.start(port);
return rs;
};
var exports = { 'start' : start };
module.exports = exports;