9d283f60b7c1a78a6e4b2f87bdb19e8c62c7dde7
2 * @file HTTP(S) Router that treats the first directory in a URL's path as
10 const dlog
= (msg
) => console
.log(msg
)
13 /** Regular expression for valid routes
14 * @prop {Object.RegEx} validRoutes - matches valid route names
16 validRoutes
: /[a-zA-Z][a-zA-Z0-9\-_]*/,
18 /** Parameters set on bootup (startHttpServer)
19 * @prop {string[2]} skelPage - html document split in twain for JS injection
20 * @prop {string} clientJS - jerverscripps to inject in skelPage for clients
21 * @prop {string} hostJS - jerverscripps for the hosts
22 * @prop {string} httpdRoot - a normalized path for http-servable files
23 * @prop {string} bindJail - jail bindings to this path
34 * @summary Start main HTTP server
35 * @desc starts up an HTTP or HTTPS server used for routing
36 * @arg {Object} conf - object containing configuration properties
37 * @prop {number|string} conf.port - local system port to bind to
38 * @prop {string} conf.skelFile - location of the skeleton HTML page
39 * @prop {string} conf.clientJS - client JS file
40 * @prop {string} conf.hostJS - host JS file
41 * @prop {string} [conf.httpdRoot] - root path of http-accessible files, if
42 * undefined no files are accessible
43 * @prop {Object} [conf.tls] - if present, startHttpServer will use tls
44 * @prop {string} [conf.tls.certFile] - tls certificate file
45 * @prop {string} [conf.tls.keyFile] - tls public key file
47 startHttpServer: function (conf
) {
49 throw new Error('httpd already running')
50 if (conf
.tls
== undefined)
51 this.httpd
= require('http').createServer(this.httpdListener
)
52 else if (!('keyFile' in conf
.tls
) || !('certFile' in conf
.tls
))
53 throw new Error('HTTPS requires a valid key and cert')
55 this.syncReads([conf
.tls
.keyFile
, conf
.tls
.certFile
]).then((results
) => {
56 Object
.defineProperty(this, 'httpsOpts', {
58 key
: results
[conf
.tls
.keyFile
],
59 cert
: results
[conf
.tls
.certFile
]
63 require('https').createServer(this.httpsOpts
, this.httpdListener
)
65 this.httpd
.listen(conf
.port
)
67 conf
.httpdRoot
? require('path').normalize(conf
.httpdRoot
) : undefined
68 while (this.httpdRoot
[this.httpdRoot
.length
- 1] == require('path').sep
)
69 this.httpdRoot
= this.httpdRoot
.slice(0,-1)
70 this.syncReads(conf
.skelFile
, conf
.clientJS
, conf
.hostJS
)
72 this.skelPage
= results
[conf
.skelFile
].split('<!--STRAPP_SRC-->')
73 this.clientJS
= results
[conf
.clientJS
]
74 this.hostJS
= results
[conf
.hostJS
]
79 console
.log(`HTTP${(conf.tls == undefined) ? 'S' : ''} ` +
80 `Server Started on port ${conf.port}${this.httpdRoot ?
81 `, serving files
from ${this.httpdRoot}
`:''}`)
85 * @summary Create a binding for the server
86 * @desc makes a new route which is bound to a file or a path. routes
87 * bound to files always serve that file, regardless of any
88 * additional path parameters provided by the URI
89 * @arg {string} routeName - the route to create
90 * @arg {string} path - the path to the file or directory to bind
92 createBind: function (routeName
, path
) {
93 dlog(`Binding ${routeName} to ${path}`)
94 if (routeName
in this.routes
)
95 throw new Error(`route ${routeName} already exists`)
96 path
= require('path').normalize(path
)
98 && path
.indexOf(`${this.bindJail}/`) !== 0
99 && this.bindJail
!= path
)
100 throw new Error(`${routeName}:${path} jailed to ${this.bindJail}`)
101 if (require('fs').existsSync(path
)) {
102 this.route
[routeName
] = {
105 dir
: require('fs').lstatSync(path
).isDirectory()
110 throw new Error(`${path} not found, ${routeName} not bound`)
115 * @desc listens for http client requests and services routes/files
116 * @arg {http.ClientRequest} request
117 * @arg {http.ServerResponse} response
119 httpdListener: function (request
,response
) {
120 dlog(`Received request ${request.method} ${request.url}`)
121 let htArgv
= request
.url
.slice(1).split('?')
122 const routeName
= htArgv
[0].split('/')[0]
123 const route
= this.routes
[routeName
]
124 /* If the route exists, check if we are a returning host or a new client */
127 htArgv
[0] = htArgv
[0].replace(`${routeName}`,'')
128 if (htArgv
[0][0] === '/')
129 htArgv
[0] = htArgv
[0].slice(1)
130 this.serveBind(response
, route
.bind
, htArgv
)
132 //TODO: auth better than this (ip spoofing is easy)
133 else if (route
.host
== (request
.headers
['x-forwarded-for'] ||
134 request
.connection
.remoteAddress
))
135 this.serveHost(response
, route
, htArgv
)
137 this.serveClient(request
, response
, route
)
139 /* If it's a valid routename that doesn't exist, make this client a host */
140 else if (this.validRoutes
.test(routeName
)) {
141 route
= this.createRoute(routeName
, this.httpsOpts
)
142 this.serveHost(response
, route
, htArgv
)
144 /* Try servicing files if we have a root directory for it */
145 else if (this.httpdRoot
) {
146 let realPath
= require('path').join(this.httpdRoot
, htArgv
[0])
147 if (realPath
== this.httpdRoot
)
148 realPath
+= '/index.html'
149 if (realPath
.indexOf(`${this.httpdRoot}/`) == 0) {
150 const stat_cb
= (err
, stat
) => {
152 response
.writeHead(404)
156 else if (stat
.isDirectory()) {
157 realPath
+= '/index.html'
158 require('fs').lstat(realPath
, stat_cb
)
160 else if (stat
.isFile())
161 this.serveFile(response
, realPath
)
163 response
.writeHead(403)
167 require('fs').lstat(realPath
, stat_cb
)
170 response
.writeHead(400)
176 response
.writeHead(404)
182 * @summary Serves a binding to a client
183 * @desc Resolves a binding and serves a response to the client
184 * @arg {http.ServerResponse} response - the response to use
185 * @arg {Object} bind - the binding to serve the client
186 * @arg {string[]} argv - path and arguments for the bind
188 serveBind: function (response
, bind
, argv
) {
189 dlog(`Serving binding ${bind.path}/${argv[0]}`)
192 argv
[0] = 'index.html'
193 this.serveFile(response
, require('path').join(bind
.path
, argv
[0]))
196 this.serveFile(response
, bind
.path
)
200 * @summary Serve a route to an http client
201 * @desc routes may be bound to the filesystem, or to an outgoing host
202 * @arg {http.ClientRequest} request - request from the client
203 * @arg {http.ServerResponse} response - response object to use
204 * @arg {Object} route - route associated with client request
206 serveClient: function (request
, response
, route
) {
207 const type
= request
.headers
['x-strapp-type']
208 const pubKey
= request
.headers
['x-strapp-pubkey']
209 dlog(`Client ${type || 'HT'} request routed to ${route.name}`)
213 response
.writeHead(200, { 'Content-Type': 'text/html' })
214 response
.write(`${this.skelPage[0]}${this.clientJS}${this.skelPage[1]}`)
217 case 'ice-candidate-request':
218 case 'ice-candidate-submission':
219 case 'client-sdp-offer':
222 route
.pendingResponses
.addResponse(pubKey
, response
)
223 request
.on('data', (chunk
) => data
+= chunk
)
224 request
.on('end', () => route
.socket
.send(`${pubKey} ${type} ${data}`))
227 response
.writeHead(401)
232 response
.writeHead(400)
238 * @summary Serve a route to an authorized http host
239 * @desc services host application to the client, establishing a socket
240 * @arg {http.ServerResponse} response - response object to use
241 * @arg {Object} route - the route that belongs to this host
242 * @arg {string[]} argv - vector of arguments sent to the host
244 serveHost: function (response
, route
, argv
) {
245 response
.writeHead(200, { 'Content-Type': 'text/html' })
246 response
.write(`${this.skelPage[0]}` +
247 `\tconst _strapp_port = ${route.port}\n` +
248 `\tconst _strapp_protocol = ` +
249 `${this.httpsOpts ? 'wss' : 'ws'}'\n` +
250 `${this.hostJS}\n${this.skelPage[1]}`)
255 * @summary Create a new route
256 * @desc makes a new route for the given route name
257 * @arg {string} routeName - name of the new route
258 * @arg {string} host - Origin address from the request that made this
259 * route (for security verification on the socket)
260 * @arg {Object} [httpsOpts] - key and cert for tls
261 * @returns {Object} a route object containing host, socket, and servers
263 createRoute: function (routeName
, host
, httpsOpts
) {
264 dlog(`Creating ${httpsOpts ? 'TLS ' : ''}route ${routeName} from ${host}`)
265 if (routeName
in this.routes
)
266 throw new Error(`route ${routeName} already exists`)
267 const httpd
= httpsOpts
268 ? require('https').createServer(httpsOpts
)
269 : require('http').createServer()
271 pendingResponses
: new Map([]),
279 require('get-port')().then((port
) => {
281 route
.httpd
.listen(port
)
282 route
.wsd
= new require('ws').Server({
284 verifyClient
: (info
) =>
285 info
.origin
== host
&& (info
.secure
|| !httpsOpts
)
287 route
.wsd
.on('connection', (socket
) =>
288 socket
.on('message', (msg
) =>
289 this.hostMessage(msg
,route
)))
291 route
.pendingResponses
.addResponse = function (key
, response
) {
292 let responses
= this.get(key
) || []
293 this.set(key
, responses
.push(response
))
295 this.routes
[routeName
] = route
300 * @summary handle host message
301 * @desc receives a message from a host, handles the command (first character),
302 * and responds to either the host or the client, or both. Commands
303 * are whitespace separated strings.
305 * < clientKey payload [header]
306 * Route 'payload' to the client identified by 'clientKey'.
307 * The optional 'header' argument is a stringified JSON object,
308 * which will be written to the HTTP response header
309 * In case of multiple requests from a single client, the
310 * oldest request will be serviced on arrival of message
311 * ! errorMessage errorCode [offendingMessage]
312 * Notify host that an error has occured, providing a message
313 * and error code. 'offendingMessage', if present, is the
314 * message received from the remote that triggered the error.
315 * @arg {string} message - raw string from the host
316 * @arg {Object} route - the route over
318 hostMessage: function (message
, route
) {
319 const argv
= message
.split(' ')
320 const command
= argv
[0][0]
322 dlog(`Received host message from ${route.name}: ${command}`)
325 const response
= route
.pendingResponses
.get(argv
[0]).shift()
327 route
.socket
.send(`! "No pending responses for client ${argv[0]}" 0 `
329 else if (argv
.length
=== 2 || argv
.length
=== 3) {
330 const header
= argv
.length
=== 3 ? JSON
.parse(argv
[2]) : {}
331 if (!('Content-Type' in header
))
332 header
['Content-Type'] = 'application/octet-stream'
333 response
.writeHead(200, header
)
334 response
.write(argv
[1])
338 route
.socket
.send(`! "Insufficient arguments" 0 ${message}`)
341 if (argv
.length
=== 3)
342 argv
[0] += `\nIn message: ${argv[2]}`
343 console
.log(`Error[${route.host}|${argv[1]}]:${argv[0]}`)
349 * @summary Serve a file to an http client after a request
350 * @desc reads files from the system to be distributed to clients, and
351 * buffers recently accessed files
352 * @arg {http.ServerResponse} response - the response object to use
353 * @arg {string} filePath - relative location of the file
355 serveFile: function (response
, filePath
, rootPath
) {
356 //TODO: Make a buffer to hold recently used files, and only read if we
357 // have to (don't forget to preserve mimetype)
358 require('fs').readFile(filePath
, { encoding
: 'utf8' }, (err
, data
) => {
359 if (err
|| data
== undefined)
360 response
.writeHead(404)
362 response
.writeHead(200, {
363 'Content-Type': require('mime').lookup(filePath
)
372 * @summary Synchronize Reading Multiple Files
373 * @desc reads an array of files into an object, whose keys are the
374 * input filenames, and values are the data read
375 * @arg {string[]} files - array of file names to read
376 * @arg {Object} [readOpts] - options to pass to fs.readFile()
378 syncReads
: (files
, readOpts
) => new Promise((resolve
,reject
) => {
379 dlog(`syncReads: ${files}`)
382 const read_cb
= (fileName
) => (err
, data
) => {
386 results
[fileName
] = data
387 if (++count
=== files
.length
)
390 if (readOpts
== undefined)
391 readOpts
= { encoding
: 'utf8' }
392 files
.forEach((file
) =>
393 require('fs').readFile(file
, readOpts
, read_cb(file
)))