cor-base-service
Version:
Library build upon COR web services. Handles authN/authZ, standarizes logging and error messages
79 lines (78 loc) • 3.35 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.attachTestWebSocketServer = exports.attachWebSocketServer = void 0;
const ws_1 = require("ws");
const errors_1 = require("./errors");
const ws_2 = require("./auth/ws");
const utils_1 = require("./auth/utils");
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const sendErrorAndDestory = (socket, error, options) => {
options.logger.error({ error }, "Error on the upgrade signal");
socket.write(`HTTP/1.1 ${error.status} ${error.message}\r\n\r\n`);
socket.destroy();
};
const attachWebSocketServer = (server, options, router) => {
const wss = new ws_1.WebSocketServer({ noServer: true });
server.on("upgrade", async (req, socket, head) => {
const location = new URL(req.url, `http://${req.headers.host}`);
const path = location.pathname;
const matchRoute = router.find(route => route.path === path);
if (matchRoute) {
/* If authenticated */
let token;
if (options.config.server.auth.enabled) {
try {
token = await (0, ws_2.socketAuthentication)(req, options.config, options.logger);
}
catch (error) {
sendErrorAndDestory(socket, error, options);
return;
}
}
else {
const oid = location.searchParams.get("oid");
if (!oid) {
const err = { status: 400, message: "Missing user id" };
sendErrorAndDestory(socket, err, options);
return;
}
token = { oid };
}
/* Upgrade the conncetion */
wss.handleUpgrade(req, socket, head, (ws, req) => {
matchRoute.handler(wss, req, ws, token);
wss.emit("connection", ws, req, token);
});
}
else {
sendErrorAndDestory(socket, (0, errors_1.NotFoundError)(), options);
}
});
};
exports.attachWebSocketServer = attachWebSocketServer;
const attachTestWebSocketServer = (server, options, router) => {
const wss = new ws_1.WebSocketServer({ noServer: true });
server.on("upgrade", async (req, socket, head) => {
const location = new URL(req.url, `http://${req.headers.host}`);
const path = location.pathname;
const matchRoute = router.find(route => route.path === path);
if (matchRoute) {
/* This is for testing so auth or no auth we upgrade with the decoded token */
let token;
const encoded = (0, utils_1.getTokenFromWebSocket)(req, options.logger);
token = jsonwebtoken_1.default.decode(encoded);
/* Upgrade the conncetion */
wss.handleUpgrade(req, socket, head, (ws, req) => {
matchRoute.handler(wss, req, ws, token);
wss.emit("connection", ws, req, token);
});
}
else {
sendErrorAndDestory(socket, (0, errors_1.NotFoundError)(), options);
}
});
};
exports.attachTestWebSocketServer = attachTestWebSocketServer;