All files index.js

9.91% Statements 11/111
0% Branches 0/34
0% Functions 0/27
10.09% Lines 11/109

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 3201x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
const Path = require('path');
const Hapi = require('@hapi/hapi');
const Inert = require('@hapi/inert');
const UtWss = require('ut-wss');
const jwt = require('jsonwebtoken');
const Boom = require('@hapi/boom');
const dgram = require('dgram');
const split2 = require('split2');
const _undefined = undefined;
const LRUCache = require('lru-cache');
 
module.exports = function({utPort}) {
    return class ConsolePort extends utPort {
        constructor() {
            super(...arguments);
            this.db = null;
            this.httpServer = null;
            this.socket = null;
            this.utWss = null;
            this.console = null;
            this.wsConsole = null;
            this.queue = [];
            this.browserConnected = false;
        }
 
        get defaults() {
            return {
                id: 'utPortConsole',
                type: 'console',
                exclusive: true,
                host: 'localhost',
                port: 30001,
                server: {
                    address: 'localhost',
                    port: 30001,
                    state: {
                        strictHeader: false
                    }
                },
                cookie: {
                    ttl: 100 * 60 * 1000,
                    encoding: 'none',
                    isSecure: true,
                    isHttpOnly: true,
                    clearInvalid: false,
                    strictHeader: true
                },
                ssoAuthUrl: 'not configured',
                jwt: {
                    cookieKey: 'ut5-cookie',
                    key: 'ut5-secret',
                    verifyOptions: {
                        ignoreExpiration: true,
                        algorithms: ['HS256']
                    },
                    signOptions: {
                        expiresIn: '1h',
                        algorithm: 'HS256'
                    }
                },
                cache: {
                    max: 100,
                    maxAge: 60 * 1000
                },
                maxLength: 16 * 1024
            };
        }
 
        async init() {
            const result = await super.init(...arguments);
            this.config.k8s = {
                ports: [{
                    name: 'http-ui',
                    service: {
                        clusterIP: 'None'
                    },
                    ingress: {
                        host: this.config.server.host
                    },
                    containerPort: this.config.server.port
                }, {
                    name: 'udp-log',
                    protocol: 'UDP',
                    service: {
                        clusterIP: 'None'
                    },
                    containerPort: this.config.port
                }]
            };
            return result;
        }
 
        readFromDB(criteria) {
            if (!this.db) {
                return;
            }
            const self = this;
            // this.console.emit('spinStart', '');
            this.db.createReadStream({
                keys: false,
                values: true,
                valueEncoding: 'json',
                gte: criteria.from + '0000',
                lte: criteria.to + '9999'
            }).on('data', function(log) {
                // self.console.emit(log.timestamp ? 'logMessage' : 'logJSON', log);
                // self.console.emit('logJSON', log);
                self.emit('logJSON', log);
            }).on('end', function() {
                // self.console.emit('spinStop', '');
            });
        }
 
        emit(type, msg) {
            if (this.browserConnected) {
                this.queue.push({type, msg});
                while (this.queue.length) {
                    this.utWss.publish({path: '/status'}, JSON.stringify(this.queue.shift()));
                }
            } else {
                if (this.queue.length >= 100) {
                    this.queue.shift();
                }
                this.queue.push({type, msg});
            }
        }
 
        async start() {
            await super.start(...arguments);
            const self = this;
            this.httpServer = new Hapi.Server(this.config.server);
            await this.httpServer.register(Inert);
            this.httpServer.route({
                method: 'GET',
                path: '/healthz',
                options: {
                    auth: false,
                    handler: (request, h) => ((this.isReady && 'ok') || h.response('service not available').code(503))
                }
            });
            this.httpServer.route({
                method: 'GET',
                path: '/{p*}',
                handler: {
                    directory: {
                        path: Path.join(__dirname, 'public'),
                        listing: false,
                        index: true
                    }
                }
            });
            this.httpServer.route({
                method: 'GET',
                path: '/sso/client',
                config: {auth: false},
                handler: {
                    file: Path.join(__dirname, 'public', 'sso.html')
                }
            });
            this.httpServer.route({
                method: 'GET',
                path: '/js/config.js',
                config: {auth: false},
                handler: (req, h) => {
                    const config = {
                        ssoAuthUrl: this.config.ssoAuthUrl,
                        xsrfToken: (req.state && req.state['xsrf-token'])
                    };
                    return h.response(`var config = ${JSON.stringify(config)}`);
                }
            });
            this.httpServer.route({
                method: 'POST',
                path: '/sso/client',
                config: {auth: false},
                handler: (req, reply) => {
                    const cookieConf = Object.assign({}, this.config.cookie, {path: '/'});
                    if (req.payload && req.payload.cookie && req.payload.cookie.name && req.payload.cookie.value) {
                        jwt.verify(req.payload.cookie.value, this.config.jwt.key, Object.assign({}, this.config.jwt.verifyOptions, {ignoreExpiration: false}), (err, decoded) => {
                            if (err) {
                                reply(Boom.unauthorized());
                            } else {
                                reply('OK')
                                    .state(
                                        req.payload.cookie.name,
                                        req.payload.cookie.value,
                                        cookieConf
                                    )
                                    .state(
                                        'xsrf-token',
                                        decoded.xsrfToken,
                                        cookieConf
                                    );
                            }
                        });
                    } else {
                        reply(Boom.unauthorized());
                    }
                }
            });
            this.httpServer.route({
                method: 'POST',
                path: '/upload-logs',
                config: {
                    payload: {
                        maxBytes: 209715200,
                        output: 'stream',
                        parse: true
                    },
                    handler: function(request, reply) {
                        request.payload.files.pipe(split2(JSON.parse)).on('data', function(log) {
                            self.emit('logJSON', log);
                        });
                        return reply('');
                    }
                }
            });
 
            this.httpServer.route({
                method: 'POST',
                path: '/query-logs',
                handler: function(request, reply) {
                    self.readFromDB(request.payload);
                    return reply('');
                }
            });
 
            this.cache = new LRUCache(this.config.cache);
 
            const logError = (error, data) => this.emit('logJSON', {
                error: {
                    message: error.message,
                    type: 'split2.error'
                },
                name: this.config.id,
                context: 'console port',
                service: this.bus.config.service,
                level: 'error',
                $meta: {
                    mtid: 'error',
                    method: 'split2.write'
                },
                msg: data && data.substr && data.substr(0, 256)
            });
 
            const createStream = (id, rinfo) => {
                const result = split2(/\n/, JSON.parse, {maxLength: this.config.maxLength});
                this.cache.set(id, result);
                result.on('data', msg => this.emit('logJSON', msg));
                result.mapper = msg => {
                    try {
                        return JSON.parse(msg);
                    } catch (error) {
                        logError(error, msg);
                        result.destroy();
                        return null;
                    }
                };
                result.on('error', error => {
                    logError(error, result._last);
                    result.destroy();
                });
                result.on('close', () => {
                    this.cache.del(id);
                    this.socket.send(JSON.stringify({method: 'uuid'}), rinfo.port, rinfo.address); // notify sender to generate new stream id
                });
                return result;
            };
            this.socket = dgram.createSocket('udp4');
            this.socket.on('message', (msg, rinfo) => {
                const id = msg.slice(0, 16).toString('hex');
                const stream = this.cache.get(id) || createStream(id, rinfo);
                stream.write(msg.slice(16));
            });
            this.socket.on('close', () => {
                this.cache.reset();
            });
            this.socket.bind({
                address: this.config.address,
                port: this.config.port,
                exclusive: this.config.exclusive
            });
 
            this.utWss = new UtWss({log: this.log}, this.config);
            this.utWss.on('connection', () => {
                self.browserConnected = true;
                self.emit('logJSON', '');
            });
            this.utWss.registerPath('/status');
            this.utWss.start(this.httpServer.listener);
 
            this.httpServer.start(function() {
                self.log.info && self.log.info({
                    $meta: {
                        mtid: 'event',
                        method: 'port.started'
                    },
                    msg: 'go to: ' + self.httpServer.info.uri + ' to access the debug console'
                });
            });
        }
 
        async stop() {
            // cleanup
            this.socket && this.socket.close();
            this.httpServer && this.httpServer.stop();
            if (this.db && this.db.close) {
                this.db.close();
                this.db = _undefined;
            }
            this.httpServer = _undefined;
            this.socket = _undefined;
            this.console = _undefined;
            this.queue = _undefined;
            this.browserConnected = _undefined;
            return super.stop(...arguments);
        }
    };
};