2 * @file HTTP(S) Router that treats the first directory in a URL's path as
9 const fs
= require('fs')
11 const dlog
= (msg
) => console
.log(msg
)
14 /** Regular expression for valid routes
15 * @var {Object.RegEx} validRoutes - matches valid route names
17 validRoutes
: /[a-zA-Z][a-zA-Z0-9\-_]*/,
19 /** Parameters set on bootup (startHttpServer)
20 * @var {string[2]} skelPage - html document split in twain for JS injection
21 * @var {string} clientJS - jerverscripps to inject in skelPage for clients
22 * @var {string} hostJS - jerverscripps for the hosts
23 * @var {string} httpdRoot - a normalized path for http-servable files
31 * @summary Synchronize Reading Multiple Files
32 * @desc reads an array of files into an object, whose keys are the
33 * input filenames, and values are the data read
34 * @arg {string[]} files - array of file names to read
35 * @arg {Object} [readOpts] - options to pass to fs.readFile()
37 syncReads
: (files
, readOpts
) => new Promise((resolve
,reject
) => {
38 dlog(`syncReads: ${files}`)
41 const read_cb
= (fileName
) => (err
, data
) => {
45 results
[fileName
] = data
46 if (++count
=== files
.length
)
49 if (readOpts
== undefined)
50 readOpts
= { encoding
: 'utf8' }
51 files
.forEach((file
) => fs
.readFile(file
, readOpts
, read_cb(file
)))
55 * @summary Main router listener
56 * @desc listens for http client requests and services routes/files
57 * @arg {http.ClientRequest} request
58 * @arg {http.ServerResponse} response
60 httpdListener: function (request
,response
) {
61 dlog(`Received request ${request.method} ${request.url}`)
62 const htArgv
= request
.url
.slice(1).split('?')
63 const routeName
= htArgv
[0].split('/')[0]
64 const route
= this.routes
[routeName
]
66 if (route
.host
== (request
.headers
['x-forwarded-for'] ||
67 request
.connection
.remoteAddress
))
68 this.serveHost(response
, route
, htArgv
)
70 this.serveClient(request
, response
, route
)
72 else if (this.validRoutes
.test(routeName
)) {
73 route
= this.createRoute(routeName
, this.httpsOpts
)
74 this.serveHost(response
, route
, htArgv
)
77 this.serveFile(response
, htArgv
[0])
82 * @summary Serve a route to an http client
83 * @desc routes may be bound to the filesystem, or to an outgoing host
84 * @arg {http.ClientRequest} request - request from the client
85 * @arg {http.ServerResponse} response - response object to use
86 * @arg {Object} route - route associated with client request
88 serveClient: function (request
, response
, route
) {
89 const type
= request
.headers
['x-strapp-type']
90 const pubKey
= request
.headers
['x-strapp-pubkey']
91 dlog(`Client ${type || 'HT'} request routed to ${route.name}`)
95 response
.writeHead(200, { 'Content-Type': 'text/html' })
96 response
.write(`${this.skelPage[0]}${this.clientJS}${this.skelPage[1]}`)
100 route
.pendingResponses
.addResponse(pubKey
, response
)
101 route
.socket
.send(`${type} ${pubKey}`)
104 case 'ice-candidate-request':
105 case 'ice-candidate-submission':
106 case 'client-sdp-offer':
109 route
.pendingResponses
.addResponse(pubKey
, response
)
110 request
.on('data', (chunk
) => data
+= chunk
)
111 request
.on('end', () => route
.socket
.send(`${pubKey} ${type} ${data}`))
114 response
.writeHead(401)
119 response
.writeHead(400)
125 * @summary Serve a route to an authorized http host
126 * @desc services host application to the client, establishing a socket
127 * @arg {http.ServerResponse} response - response object to use
128 * @arg {Object} route - the route that belongs to this host
129 * @arg {string[]} argv - vector of arguments sent to the host
131 serveHost: function (response
, route
, argv
) {
132 response
.writeHead(200, { 'Content-Type': 'text/html' })
133 response
.write(`${this.skelPage[0]}` +
134 `\tconst _strapp_port = ${route.port}\n` +
135 `\tconst _strapp_protocol = ` +
136 `${this.httpsOpts ? 'wss' : 'ws'}'\n` +
137 `${this.hostJS}\n${this.skelPage[1]}`)
142 * @summary Create a new route
143 * @desc makes a new route for the given route name
144 * @arg {string} routeName - name of the new route
145 * @arg {string} host - Origin address from the request that made this
146 * route (for security verification on the socket)
147 * @arg {Object} [httpsOpts] - key and cert for tls
148 * @returns {Object} a route object containing host, socket, and servers
150 createRoute: function (routeName
, host
, httpsOpts
) {
151 dlog(`Creating ${httpsOpts ? 'TLS ' : ''}route ${routeName} from ${host}`)
152 if (routeName
in this.routes
)
153 throw new Error(`route ${routeName} already exists`)
154 const httpd
= httpsOpts
155 ? require('https').createServer(httpsOpts
)
156 : require('http').createServer()
157 const wsd
= new require('ws').Server({
159 verifyClient
: (info
) => info
.origin
== host
&& (info
.secure
|| !httpsOpts
)
162 pendingResponses
: new Map([]),
169 route
.pendingResponses
.addResponse = function (key
, response
) {
170 let responses
= this.get(key
) || []
171 this.set(key
, responses
.push(response
))
173 wsd
.on('connection', (socket
) =>
174 socket
.on('message', (msg
) =>
175 this.hostMessage(msg
,route
)))
176 this.routes
[routeName
] = route
181 * @summary handle host message
182 * @desc receives a message from a host, handles the command (first character),
183 * and responds to either the host or the client, or both. Commands
184 * are whitespace separated strings.
186 * < clientKey payload [header]
187 * Route 'payload' to the client identified by 'clientKey'.
188 * The optional 'header' argument is a stringified JSON object,
189 * which will be written to the HTTP response header
190 * In case of multiple requests from a single client, the
191 * oldest request will be serviced on arrival of message
192 * ! errorMessage errorCode [offendingMessage]
193 * Notify host that an error has occured, providing a message
194 * and error code. 'offendingMessage', if present, is the
195 * message received from the remote that triggered the error.
196 * @arg {string} message - raw string from the host
197 * @arg {Object} route - the route over
199 hostMessage: function (message
, route
) {
200 const argv
= message
.split(' ')
201 const command
= argv
[0][0]
203 dlog(`Received host message from ${route.name}: ${command}`)
206 const response
= route
.pendingResponses
.get(argv
[0]).shift()
208 route
.socket
.send(`! "No pending responses for client ${argv[0]}" 0 `
210 else if (argv
.length
=== 2 || argv
.length
=== 3) {
211 const header
= argv
.length
=== 3 ? JSON
.parse(argv
[2]) : {}
212 if (!('Content-Type' in header
))
213 header
['Content-Type'] = 'application/octet-stream'
214 response
.writeHead(200, header
)
215 response
.write(argv
[1])
219 route
.socket
.send(`! "Insufficient arguments" 0 ${message}`)
222 if (argv
.length
=== 3)
223 argv
[0] += `\nIn message: ${argv[2]}`
224 console
.log(`Error[${route.host}|${argv[1]}]:${argv[0]}`)
230 * @summary Serve a file to an http client after a request
231 * @desc reads files from the system to be distributed to clients, and
232 * buffers recently accessed files
233 * @arg {http.ServerResponse} response - the response object to use
234 * @arg {string} filePath - location of the file on disk to service
236 serveFile: function (response
, filePath
) {
237 if (this.clientCanAccessFile(filePath
)) {
238 //TODO: Make a buffer to hold recently used files, and only read if we
239 // have to (don't forget to preserve mimetype)
240 fs
.readFile(filePath
, { encoding
: 'utf8' }, (err
, data
) => {
241 if (err
|| data
== undefined)
242 response
.writeHead(404)
244 response
.writeHead(200, {
245 'Content-Type': require('mime').lookup(filePath
)
253 response
.writeHead(403)
259 * @summary Test if client can access a file
260 * @return {Bool} true if the filePath is authorized
262 clientCanAccessFile
: (filePath
) => require('path')
263 .normalize(this.httpdRoot
+ filePath
)
264 .indexOf(this.httpdRoot
+ '/') === 0,
267 * @summary Start main HTTP server
268 * @desc starts up an HTTP or HTTPS server used for routing
269 * @arg {number|string} port - local system port to bind to
270 * @arg {string} skelFile - location of the skeleton HTML page to use
271 * @arg {string} clientJS - location of the client's JS distributable
272 * @arg {string} hostJS - location of the host's JS distributable
273 * @arg {string} [httpdRoot] - root path of http-accessible files, if not
274 * provided no files will be accessible
275 * @arg {Object} [tls] - if present, startHttpServer will start in tls
276 * mode. supported properties:
277 * 'certfile': certificate file location
278 * 'keyfile': key file location
280 startHttpServer: function (port
, skelFile
, clientJS
, hostJS
, httpdRoot
, tls
) {
282 throw new Error('httpd already running')
283 if (tls
== undefined)
284 this.httpd
= require('http').createServer(this.httpdListener
)
285 else if (!('key' in tls
) || !('cert' in tls
))
286 throw new Error('HTTPS requires a valid key and cert')
288 this.syncReads([tls
.keyfile
, tls
.certfile
]).then((results
) => {
289 Object
.defineProperty(this, 'httpsOpts', {
291 key
: results
[tls
.keyfile
],
292 cert
: results
[tls
.certfile
]
296 require('https').createServer(httpsOpts
, this.httpdListener
)
298 this.httpd
.listen(port
)
299 this.httpdRoot
= httpdRoot
? require('path').normalize(httpdRoot
):undefined
300 while (this.httpdRoot
[this.httpdRoot
.length
- 1] == require('path').sep
)
301 this.httpdRoot
= this.httpdRoot
.slice(0,-1)
302 this.skelPage
= fs
.readFileSync('./skel.html', { encoding
: 'utf8' })
303 .split('<!--STRAPP_SRC-->')
304 this.hostJS
= fs
.readFileSync(hostJS
)
305 this.clientJS
= fs
.readFileSync(clientJS
)
306 console
.log(`HTTP${(tls == undefined) ? 'S' : ''} ` +
307 `Server Started on port ${port}${this.httpdRoot ? ', serving' +
308 `files
from ${this.httpdRoot}
`:''}`)