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 else if (route
.host
== (request
.headers
['x-forwarded-for'] ||
133 request
.connection
.remoteAddress
))
134 this.serveHost(response
, route
, htArgv
)
136 this.serveClient(request
, response
, route
)
138 /* If it's a valid routename that doesn't exist, make this client a host */
139 else if (this.validRoutes
.test(routeName
)) {
140 route
= this.createRoute(routeName
, this.httpsOpts
)
141 this.serveHost(response
, route
, htArgv
)
143 /* Try servicing files if we have a root directory for it */
144 else if (this.httpdRoot
) {
145 let realPath
= require('path').join(this.httpdRoot
, htArgv
[0])
146 if (realPath
== this.httpdRoot
)
147 realPath
+= '/index.html'
148 if (realPath
.indexOf(`${this.httpdRoot}/`) == 0) {
149 const stat_cb
= (err
, stat
) => {
151 response
.writeHead(404)
155 else if (stat
.isDirectory()) {
156 realPath
+= '/index.html'
157 require('fs').lstat(realPath
, stat_cb
)
159 else if (stat
.isFile())
160 this.serveFile(response
, realPath
)
162 response
.writeHead(403)
166 require('fs').lstat(realPath
, stat_cb
)
169 response
.writeHead(400)
175 response
.writeHead(404)
181 * @summary Serves a binding to a client
182 * @desc Resolves a binding and serves a response to the client
183 * @arg {http.ServerResponse} response - the response to use
184 * @arg {Object} bind - the binding to serve the client
185 * @arg {string[]} argv - path and arguments for the bind
187 serveBind: function (response
, bind
, argv
) {
188 dlog(`Serving binding ${bind.path}/${argv[0]}`)
191 argv
[0] = 'index.html'
192 this.serveFile(response
, require('path').join(bind
.path
, argv
[0]))
195 this.serveFile(response
, bind
.path
)
199 * @summary Serve a route to an http client
200 * @desc routes may be bound to the filesystem, or to an outgoing host
201 * @arg {http.ClientRequest} request - request from the client
202 * @arg {http.ServerResponse} response - response object to use
203 * @arg {Object} route - route associated with client request
205 serveClient: function (request
, response
, route
) {
206 const type
= request
.headers
['x-strapp-type']
207 const pubKey
= request
.headers
['x-strapp-pubkey']
208 dlog(`Client ${type || 'HT'} request routed to ${route.name}`)
212 response
.writeHead(200, { 'Content-Type': 'text/html' })
213 response
.write(`${this.skelPage[0]}${this.clientJS}${this.skelPage[1]}`)
216 case 'ice-candidate-request':
217 case 'ice-candidate-submission':
218 case 'client-sdp-offer':
221 route
.pendingResponses
.addResponse(pubKey
, response
)
222 request
.on('data', (chunk
) => data
+= chunk
)
223 request
.on('end', () => route
.socket
.send(`${pubKey} ${type} ${data}`))
226 response
.writeHead(401)
231 response
.writeHead(400)
237 * @summary Serve a route to an authorized http host
238 * @desc services host application to the client, establishing a socket
239 * @arg {http.ServerResponse} response - response object to use
240 * @arg {Object} route - the route that belongs to this host
241 * @arg {string[]} argv - vector of arguments sent to the host
243 serveHost: function (response
, route
, argv
) {
244 response
.writeHead(200, { 'Content-Type': 'text/html' })
245 response
.write(`${this.skelPage[0]}` +
246 `\tconst _strapp_port = ${route.port}\n` +
247 `\tconst _strapp_protocol = ` +
248 `${this.httpsOpts ? 'wss' : 'ws'}'\n` +
249 `${this.hostJS}\n${this.skelPage[1]}`)
254 * @summary Create a new route
255 * @desc makes a new route for the given route name
256 * @arg {string} routeName - name of the new route
257 * @arg {string} host - Origin address from the request that made this
258 * route (for security verification on the socket)
259 * @arg {Object} [httpsOpts] - key and cert for tls
260 * @returns {Object} a route object containing host, socket, and servers
262 createRoute: function (routeName
, host
, httpsOpts
) {
263 dlog(`Creating ${httpsOpts ? 'TLS ' : ''}route ${routeName} from ${host}`)
264 if (routeName
in this.routes
)
265 throw new Error(`route ${routeName} already exists`)
266 const httpd
= httpsOpts
267 ? require('https').createServer(httpsOpts
)
268 : require('http').createServer()
270 pendingResponses
: new Map([]),
278 require('get-port')().then((port
) => {
280 route
.httpd
.listen(port
)
281 route
.wsd
= new require('ws').Server({
283 verifyClient
: (info
) =>
284 info
.origin
== host
&& (info
.secure
|| !httpsOpts
)
286 route
.wsd
.on('connection', (socket
) =>
287 socket
.on('message', (msg
) =>
288 this.hostMessage(msg
,route
)))
290 route
.pendingResponses
.addResponse = function (key
, response
) {
291 let responses
= this.get(key
) || []
292 this.set(key
, responses
.push(response
))
294 this.routes
[routeName
] = route
299 * @summary handle host message
300 * @desc receives a message from a host, handles the command (first character),
301 * and responds to either the host or the client, or both. Commands
302 * are whitespace separated strings.
304 * < clientKey payload [header]
305 * Route 'payload' to the client identified by 'clientKey'.
306 * The optional 'header' argument is a stringified JSON object,
307 * which will be written to the HTTP response header
308 * In case of multiple requests from a single client, the
309 * oldest request will be serviced on arrival of message
310 * ! errorMessage errorCode [offendingMessage]
311 * Notify host that an error has occured, providing a message
312 * and error code. 'offendingMessage', if present, is the
313 * message received from the remote that triggered the error.
314 * @arg {string} message - raw string from the host
315 * @arg {Object} route - the route over
317 hostMessage: function (message
, route
) {
318 const argv
= message
.split(' ')
319 const command
= argv
[0][0]
321 dlog(`Received host message from ${route.name}: ${command}`)
324 const response
= route
.pendingResponses
.get(argv
[0]).shift()
326 route
.socket
.send(`! "No pending responses for client ${argv[0]}" 0 `
328 else if (argv
.length
=== 2 || argv
.length
=== 3) {
329 const header
= argv
.length
=== 3 ? JSON
.parse(argv
[2]) : {}
330 if (!('Content-Type' in header
))
331 header
['Content-Type'] = 'application/octet-stream'
332 response
.writeHead(200, header
)
333 response
.write(argv
[1])
337 route
.socket
.send(`! "Insufficient arguments" 0 ${message}`)
340 if (argv
.length
=== 3)
341 argv
[0] += `\nIn message: ${argv[2]}`
342 console
.log(`Error[${route.host}|${argv[1]}]:${argv[0]}`)
348 * @summary Serve a file to an http client after a request
349 * @desc reads files from the system to be distributed to clients, and
350 * buffers recently accessed files
351 * @arg {http.ServerResponse} response - the response object to use
352 * @arg {string} filePath - relative location of the file
354 serveFile: function (response
, filePath
, rootPath
) {
355 //TODO: Make a buffer to hold recently used files, and only read if we
356 // have to (don't forget to preserve mimetype)
357 require('fs').readFile(filePath
, { encoding
: 'utf8' }, (err
, data
) => {
358 if (err
|| data
== undefined)
359 response
.writeHead(404)
361 response
.writeHead(200, {
362 'Content-Type': require('mime').lookup(filePath
)
371 * @summary Synchronize Reading Multiple Files
372 * @desc reads an array of files into an object, whose keys are the
373 * input filenames, and values are the data read
374 * @arg {string[]} files - array of file names to read
375 * @arg {Object} [readOpts] - options to pass to fs.readFile()
377 syncReads
: (files
, readOpts
) => new Promise((resolve
,reject
) => {
378 dlog(`syncReads: ${files}`)
381 const read_cb
= (fileName
) => (err
, data
) => {
385 results
[fileName
] = data
386 if (++count
=== files
.length
)
389 if (readOpts
== undefined)
390 readOpts
= { encoding
: 'utf8' }
391 files
.forEach((file
) =>
392 require('fs').readFile(file
, readOpts
, read_cb(file
)))