Socket
Socket
Sign inDemoInstall

@furystack/rest-service

Package Overview
Dependencies
Maintainers
1
Versions
170
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@furystack/rest-service - npm Package Compare versions

Comparing version 2.1.7 to 2.1.8

253

dist/api-manager.js

@@ -15,138 +15,135 @@ "use strict";

const http_user_context_1 = require("./http-user-context");
let ApiManager = /** @class */ (() => {
let ApiManager = class ApiManager {
constructor(serverManager) {
this.serverManager = serverManager;
this.apis = new Map();
}
dispose() {
this.apis.clear();
}
getSuportedMethods(api) {
return Object.keys(api);
}
compileApi(api, root) {
const compiledApi = {};
this.getSuportedMethods(api).forEach((method) => {
const endpoint = {};
Object.entries(api[method]).forEach(([path, action]) => {
const fullPath = `/${utils_1.PathHelper.joinPaths(root, path)}`;
const regex = path_to_regexp_1.pathToRegexp(fullPath);
endpoint[path] = { regex, action, fullPath };
});
compiledApi[method] = endpoint;
let ApiManager = class ApiManager {
constructor(serverManager) {
this.serverManager = serverManager;
this.apis = new Map();
}
dispose() {
this.apis.clear();
}
getSuportedMethods(api) {
return Object.keys(api);
}
compileApi(api, root) {
const compiledApi = {};
this.getSuportedMethods(api).forEach((method) => {
const endpoint = {};
Object.entries(api[method]).forEach(([path, action]) => {
const fullPath = `/${utils_1.PathHelper.joinPaths(root, path)}`;
const regex = path_to_regexp_1.pathToRegexp(fullPath);
endpoint[path] = { regex, action, fullPath };
});
return compiledApi;
}
async addApi({ api, hostName, port, root, cors, injector, deserializeQueryParams, }) {
const supportedMethods = this.getSuportedMethods(api);
const rootApiPath = utils_1.PathHelper.normalize(root);
const server = await this.serverManager.getOrCreate({ hostName, port });
const compiledApi = this.compileApi(api, root);
server.apis.push({
shouldExec: (msg) => {
var _a;
return this.shouldExecRequest({
...msg,
method: (_a = msg.req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
rootApiPath,
supportedMethods,
url: utils_1.PathHelper.normalize(msg.req.url || ''),
});
},
onRequest: (msg) => this.onMessage({
compiledApi[method] = endpoint;
});
return compiledApi;
}
async addApi({ api, hostName, port, root, cors, injector, deserializeQueryParams, }) {
const supportedMethods = this.getSuportedMethods(api);
const rootApiPath = utils_1.PathHelper.normalize(root);
const server = await this.serverManager.getOrCreate({ hostName, port });
const compiledApi = this.compileApi(api, root);
server.apis.push({
shouldExec: (msg) => {
var _a;
return this.shouldExecRequest({
...msg,
compiledApi,
method: (_a = msg.req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
rootApiPath,
port,
supportedMethods,
cors,
injector,
hostName,
deserializeQueryParams,
}),
});
url: utils_1.PathHelper.normalize(msg.req.url || ''),
});
},
onRequest: (msg) => this.onMessage({
...msg,
compiledApi,
rootApiPath,
port,
supportedMethods,
cors,
injector,
hostName,
deserializeQueryParams,
}),
});
}
shouldExecRequest(options) {
return options.method &&
options.url &&
(options.supportedMethods.includes(options.method) || options.method === 'OPTIONS') &&
utils_1.PathHelper.normalize(options.url).startsWith(options.rootApiPath)
? true
: false;
}
getActionFromEndpoint(compiledEndpoint, fullUrl, method) {
return (Object.values(compiledEndpoint[method]).find((route) => route.regex.test(fullUrl.pathname)) ||
undefined);
}
async executeAction({ injector, req, res, fullUrl, action, regex, fullPath, deserializeQueryParams, }) {
await utils_1.usingAsync(injector.createChild(), async (i) => {
const utils = i.getInstance(utils_2.Utils);
const httpUserContext = i.getInstance(http_user_context_1.HttpUserContext);
i.setExplicitInstance({
getCurrentUser: () => httpUserContext.getCurrentUser(req),
isAuthorized: (...roles) => httpUserContext.isAuthorized(req, ...roles),
isAuthenticated: () => httpUserContext.isAuthenticated(req),
}, core_1.IdentityContext);
try {
const actionResult = await action({
request: req,
response: res,
injector: i,
getBody: () => utils.readPostBody(req),
getQuery: () => {
return [...fullUrl.searchParams.keys()].reduce((last, current) => {
const currentValue = fullUrl.searchParams.get(current);
last[current] = deserializeQueryParams ? deserializeQueryParams(currentValue) : currentValue;
return last;
}, {});
},
getUrlParams: () => {
if (!req.url || !regex) {
throw new Error('Error parsing request parameters. Missing URL or RegExp.');
}
const matcher = path_to_regexp_1.match(fullPath, { decode: decodeURIComponent });
const { params } = matcher(fullUrl.pathname);
return params;
},
});
res.sendActionResult(actionResult);
}
catch (error) {
const errorActionResult = await error_action_1.ErrorAction({
request: req,
response: res,
injector: i,
getBody: async () => error,
});
res.sendActionResult(errorActionResult);
}
return;
});
}
async onMessage(options) {
var _a;
const fullUrl = new URL(utils_1.PathHelper.joinPaths('http://', `${options.hostName || server_manager_1.ServerManager.DEFAULT_HOST}:${options.port}`, options.req.url));
options.cors && options.injector.getInstance(utils_2.Utils).addCorsHeaders(options.cors, options.req, options.res);
if (options.req.method === 'OPTIONS') {
options.res.writeHead(200);
options.res.end();
return;
}
shouldExecRequest(options) {
return options.method &&
options.url &&
(options.supportedMethods.includes(options.method) || options.method === 'OPTIONS') &&
utils_1.PathHelper.normalize(options.url).startsWith(options.rootApiPath)
? true
: false;
const action = this.getActionFromEndpoint(options.compiledApi, fullUrl, (_a = options.req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase());
if (action) {
await this.executeAction({ ...options, ...action, fullUrl });
}
getActionFromEndpoint(compiledEndpoint, fullUrl, method) {
return (Object.values(compiledEndpoint[method]).find((route) => route.regex.test(fullUrl.pathname)) ||
undefined);
else {
options.res.sendActionResult(await not_found_action_1.NotFoundAction({ injector: options.injector, request: options.req, response: options.res }));
}
async executeAction({ injector, req, res, fullUrl, action, regex, fullPath, deserializeQueryParams, }) {
await utils_1.usingAsync(injector.createChild(), async (i) => {
const utils = i.getInstance(utils_2.Utils);
const httpUserContext = i.getInstance(http_user_context_1.HttpUserContext);
i.setExplicitInstance({
getCurrentUser: () => httpUserContext.getCurrentUser(req),
isAuthorized: (...roles) => httpUserContext.isAuthorized(req, ...roles),
isAuthenticated: () => httpUserContext.isAuthenticated(req),
}, core_1.IdentityContext);
try {
const actionResult = await action({
request: req,
response: res,
injector: i,
getBody: () => utils.readPostBody(req),
getQuery: () => {
return [...fullUrl.searchParams.keys()].reduce((last, current) => {
const currentValue = fullUrl.searchParams.get(current);
last[current] = deserializeQueryParams ? deserializeQueryParams(currentValue) : currentValue;
return last;
}, {});
},
getUrlParams: () => {
if (!req.url || !regex) {
throw new Error('Error parsing request parameters. Missing URL or RegExp.');
}
const matcher = path_to_regexp_1.match(fullPath, { decode: decodeURIComponent });
const { params } = matcher(fullUrl.pathname);
return params;
},
});
res.sendActionResult(actionResult);
}
catch (error) {
const errorActionResult = await error_action_1.ErrorAction({
request: req,
response: res,
injector: i,
getBody: async () => error,
});
res.sendActionResult(errorActionResult);
}
return;
});
}
async onMessage(options) {
var _a;
const fullUrl = new URL(utils_1.PathHelper.joinPaths('http://', `${options.hostName || server_manager_1.ServerManager.DEFAULT_HOST}:${options.port}`, options.req.url));
options.cors && options.injector.getInstance(utils_2.Utils).addCorsHeaders(options.cors, options.req, options.res);
if (options.req.method === 'OPTIONS') {
options.res.writeHead(200);
options.res.end();
return;
}
const action = this.getActionFromEndpoint(options.compiledApi, fullUrl, (_a = options.req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase());
if (action) {
await this.executeAction({ ...options, ...action, fullUrl });
}
else {
options.res.sendActionResult(await not_found_action_1.NotFoundAction({ injector: options.injector, request: options.req, response: options.res }));
}
}
};
ApiManager = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'singleton' }),
tslib_1.__metadata("design:paramtypes", [server_manager_1.ServerManager])
], ApiManager);
return ApiManager;
})();
}
};
ApiManager = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'singleton' }),
tslib_1.__metadata("design:paramtypes", [server_manager_1.ServerManager])
], ApiManager);
exports.ApiManager = ApiManager;
//# sourceMappingURL=api-manager.js.map

@@ -12,19 +12,16 @@ "use strict";

*/
let HttpAuthenticationSettings = /** @class */ (() => {
let HttpAuthenticationSettings = class HttpAuthenticationSettings {
constructor() {
this.model = core_1.User;
this.getUserStore = (sm) => sm.getStoreFor(core_1.User);
this.getSessionStore = (sm) => sm.getStoreFor(default_session_1.DefaultSession);
this.cookieName = 'fss';
this.hashMethod = (plain) => hash_js_1.sha256().update(plain).digest('hex');
this.enableBasicAuth = true;
}
};
HttpAuthenticationSettings = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'singleton' })
], HttpAuthenticationSettings);
return HttpAuthenticationSettings;
})();
let HttpAuthenticationSettings = class HttpAuthenticationSettings {
constructor() {
this.model = core_1.User;
this.getUserStore = (sm) => sm.getStoreFor(core_1.User);
this.getSessionStore = (sm) => sm.getStoreFor(default_session_1.DefaultSession);
this.cookieName = 'fss';
this.hashMethod = (plain) => hash_js_1.sha256().update(plain).digest('hex');
this.enableBasicAuth = true;
}
};
HttpAuthenticationSettings = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'singleton' })
], HttpAuthenticationSettings);
exports.HttpAuthenticationSettings = HttpAuthenticationSettings;
//# sourceMappingURL=http-authentication-settings.js.map

@@ -12,126 +12,140 @@ "use strict";

*/
let HttpUserContext = /** @class */ (() => {
let HttpUserContext = class HttpUserContext {
constructor(injector, authentication, storeManager) {
this.authentication = authentication;
this.users = authentication.getUserStore(storeManager);
this.sessions = authentication.getSessionStore(storeManager);
this.logger = injector.logger.withScope(`@furystack/rest-service/${this.constructor.name}`);
let HttpUserContext = class HttpUserContext {
constructor(injector, authentication, storeManager) {
this.authentication = authentication;
this.users = authentication.getUserStore(storeManager);
this.sessions = authentication.getSessionStore(storeManager);
this.logger = injector.logger.withScope(`@furystack/rest-service/${this.constructor.name}`);
}
/**
* @param request The request to be authenticated
* @returns if the current user is authenticated
*/
async isAuthenticated(request) {
try {
const currentUser = await this.getCurrentUser(request);
return currentUser !== null;
}
/**
* @param request The request to be authenticated
* @returns if the current user is authenticated
*/
async isAuthenticated(request) {
try {
const currentUser = await this.getCurrentUser(request);
return currentUser !== null;
}
catch (error) {
catch (error) {
return false;
}
}
/**
* Returns if the current user can be authorized with ALL of the specified roles
*
* @param request The request to be authenticated
* @param roles The list of roles to authorize
*
* @returns a boolean value that indicates if the user is authenticated
*/
async isAuthorized(request, ...roles) {
const currentUser = await this.getCurrentUser(request);
for (const role of roles) {
if (!currentUser || !currentUser.roles.some((c) => c === role)) {
return false;
}
}
/**
* Returns if the current user can be authorized with ALL of the specified roles
*
* @param request The request to be authenticated
* @param roles The list of roles to authorize
*
* @returns a boolean value that indicates if the user is authenticated
*/
async isAuthorized(request, ...roles) {
const currentUser = await this.getCurrentUser(request);
for (const role of roles) {
if (!currentUser || !currentUser.roles.some((c) => c === role)) {
return false;
}
return true;
}
/**
* Checks if the system contains a user with the provided name and password, throws an error otherwise
*
* @param userName The username
* @param password The password
* @returns the authenticated User
*/
async authenticateUser(userName, password) {
const match = (password &&
password.length &&
(await this.users.find({
filter: {
username: { $eq: userName },
password: { $eq: this.authentication.hashMethod(password) },
},
}))) ||
[];
if (match.length === 1) {
const { password: pw, ...user } = match[0];
return user;
}
throw Error('Failed to authenticate.');
}
async getCurrentUser(request) {
if (!this.user) {
this.user = await this.authenticateRequest(request);
return this.user;
}
return this.user;
}
getSessionIdFromRequest(request) {
if (request.headers.cookie) {
const cookies = request.headers.cookie
.toString()
.split(';')
.filter((val) => val.length > 0)
.map((val) => {
const [name, value] = val.split('=');
return { name: name.trim(), value: value.trim() };
});
const sessionCookie = cookies.find((c) => c.name === this.authentication.cookieName);
if (sessionCookie) {
return sessionCookie.value;
}
return true;
}
/**
* Checks if the system contains a user with the provided name and password, throws an error otherwise
*
* @param userName The username
* @param password The password
* @returns the authenticated User
*/
async authenticateUser(userName, password) {
const match = (password &&
password.length &&
(await this.users.find({
return null;
}
async authenticateRequest(request) {
// Basic auth
if (this.authentication.enableBasicAuth && request.headers.authorization) {
const authData = Buffer.from(request.headers.authorization.toString().split(' ')[1], 'base64');
const [userName, password] = authData.toString().split(':');
return await this.authenticateUser(userName, password);
}
// Cookie auth
const sessionId = this.getSessionIdFromRequest(request);
if (sessionId) {
const [session] = await this.sessions.find({ filter: { sessionId: { $eq: sessionId } }, top: 2 });
if (session) {
const userResult = await this.users.find({
filter: {
username: { $eq: userName },
password: { $eq: this.authentication.hashMethod(password) },
username: { $eq: session.username },
},
}))) ||
[];
if (match.length === 1) {
const { password: pw, ...user } = match[0];
return user;
}
throw Error('Failed to authenticate.');
}
async getCurrentUser(request) {
if (!this.user) {
this.user = await this.authenticateRequest(request);
return this.user;
}
return this.user;
}
getSessionIdFromRequest(request) {
if (request.headers.cookie) {
const cookies = request.headers.cookie
.toString()
.split(';')
.filter((val) => val.length > 0)
.map((val) => {
const [name, value] = val.split('=');
return { name: name.trim(), value: value.trim() };
});
const sessionCookie = cookies.find((c) => c.name === this.authentication.cookieName);
if (sessionCookie) {
return sessionCookie.value;
if (userResult.length === 1) {
const { password, ...user } = userResult[0];
return user;
}
throw Error('Inconsistent session result');
}
return null;
}
async authenticateRequest(request) {
// Basic auth
if (this.authentication.enableBasicAuth && request.headers.authorization) {
const authData = Buffer.from(request.headers.authorization.toString().split(' ')[1], 'base64');
const [userName, password] = authData.toString().split(':');
return await this.authenticateUser(userName, password);
}
// Cookie auth
const sessionId = this.getSessionIdFromRequest(request);
if (sessionId) {
const [session] = await this.sessions.find({ filter: { sessionId: { $eq: sessionId } }, top: 2 });
if (session) {
const userResult = await this.users.find({
filter: {
username: { $eq: session.username },
},
});
if (userResult.length === 1) {
const { password, ...user } = userResult[0];
return user;
}
throw Error('Inconsistent session result');
}
}
throw Error('Failed to authenticate request');
}
/**
* Creates and sets up a cookie-based session for the provided user
*
* @param user The user to create a session for
* @param serverResponse A serverResponse to set the cookie
* @returns the current User
*/
async cookieLogin(user, serverResponse) {
const sessionId = uuid_1.v1();
await this.sessions.add({ sessionId, username: user.username });
serverResponse.setHeader('Set-Cookie', `${this.authentication.cookieName}=${sessionId}; Path=/; HttpOnly`);
throw Error('Failed to authenticate request');
}
/**
* Creates and sets up a cookie-based session for the provided user
*
* @param user The user to create a session for
* @param serverResponse A serverResponse to set the cookie
* @returns the current User
*/
async cookieLogin(user, serverResponse) {
const sessionId = uuid_1.v1();
await this.sessions.add({ sessionId, username: user.username });
serverResponse.setHeader('Set-Cookie', `${this.authentication.cookieName}=${sessionId}; Path=/; HttpOnly`);
this.logger.information({
message: `User '${user.username}' logged in.`,
data: {
user,
sessionId,
},
});
return user;
}
async cookieLogout(request, response) {
const sessionId = this.getSessionIdFromRequest(request);
if (sessionId) {
const user = await this.authenticateRequest(request);
await this.sessions.remove(sessionId);
response.setHeader('Set-Cookie', `${this.authentication.cookieName}=; Path=/; HttpOnly`);
this.logger.information({
message: `User '${user.username}' logged in.`,
message: `User '${user.username}' has been logged out.`,
data: {

@@ -142,29 +156,12 @@ user,

});
return user;
}
async cookieLogout(request, response) {
const sessionId = this.getSessionIdFromRequest(request);
if (sessionId) {
const user = await this.authenticateRequest(request);
await this.sessions.remove(sessionId);
response.setHeader('Set-Cookie', `${this.authentication.cookieName}=; Path=/; HttpOnly`);
this.logger.information({
message: `User '${user.username}' has been logged out.`,
data: {
user,
sessionId,
},
});
}
}
};
HttpUserContext = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'scoped' }),
tslib_1.__metadata("design:paramtypes", [inject_1.Injector,
http_authentication_settings_1.HttpAuthenticationSettings,
core_1.StoreManager])
], HttpUserContext);
return HttpUserContext;
})();
}
};
HttpUserContext = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'scoped' }),
tslib_1.__metadata("design:paramtypes", [inject_1.Injector,
http_authentication_settings_1.HttpAuthenticationSettings,
core_1.StoreManager])
], HttpUserContext);
exports.HttpUserContext = HttpUserContext;
//# sourceMappingURL=http-user-context.js.map
"use strict";
var ServerManager_1;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -8,72 +9,68 @@ exports.ServerManager = void 0;

const semaphore_async_await_1 = tslib_1.__importDefault(require("semaphore-async-await"));
let ServerManager = /** @class */ (() => {
var ServerManager_1;
let ServerManager = ServerManager_1 = class ServerManager {
constructor(injector) {
this.servers = new Map();
this.openedSockets = new Set();
this.listenLock = new semaphore_async_await_1.default(1);
this.getHostUrl = (options) => `http://${options.hostName || ServerManager_1.DEFAULT_HOST}:${options.port}`;
this.onConnection = (socket) => {
this.openedSockets.add(socket);
socket.once('close', () => this.openedSockets.delete(socket));
};
this.logger = injector.logger.withScope('@furystack/rest-service/server-manager');
}
async dispose() {
let ServerManager = ServerManager_1 = class ServerManager {
constructor(injector) {
this.servers = new Map();
this.openedSockets = new Set();
this.listenLock = new semaphore_async_await_1.default(1);
this.getHostUrl = (options) => `http://${options.hostName || ServerManager_1.DEFAULT_HOST}:${options.port}`;
this.onConnection = (socket) => {
this.openedSockets.add(socket);
socket.once('close', () => this.openedSockets.delete(socket));
};
this.logger = injector.logger.withScope('@furystack/rest-service/server-manager');
}
async dispose() {
await this.listenLock.acquire();
this.openedSockets.forEach((s) => s.destroy());
await Promise.allSettled([...this.servers.values()].map((s) => new Promise((resolve, reject) => {
s.server.close((err) => (err ? reject(err) : resolve()));
s.server.off('connection', this.onConnection);
})));
this.servers.clear();
this.listenLock.release();
}
async getOrCreate(options) {
const url = this.getHostUrl(options);
if (!this.servers.has(url)) {
await this.listenLock.acquire();
this.openedSockets.forEach((s) => s.destroy());
await Promise.allSettled([...this.servers.values()].map((s) => new Promise((resolve, reject) => {
s.server.close((err) => (err ? reject(err) : resolve()));
s.server.off('connection', this.onConnection);
})));
this.servers.clear();
this.listenLock.release();
}
async getOrCreate(options) {
const url = this.getHostUrl(options);
if (!this.servers.has(url)) {
await this.listenLock.acquire();
if (!this.servers.has(url)) {
try {
await new Promise((resolve, reject) => {
const apis = [];
const server = http_1.createServer((req, res) => {
const apiMatch = apis.find((api) => api.shouldExec({ req, res }));
if (apiMatch) {
apiMatch.onRequest({ req, res });
}
else {
res.destroy();
}
});
server.on('connection', this.onConnection);
server
.listen(options.port, options.hostName)
.on('listening', () => resolve())
.on('error', (err) => reject(err));
this.servers.set(url, { server, apis });
try {
await new Promise((resolve, reject) => {
const apis = [];
const server = http_1.createServer((req, res) => {
const apiMatch = apis.find((api) => api.shouldExec({ req, res }));
if (apiMatch) {
apiMatch.onRequest({ req, res });
}
else {
res.destroy();
}
});
}
catch (error) {
this.logger.error({
message: `There was an error during server creation at ${url}`,
data: { error, url, options },
});
throw error;
}
server.on('connection', this.onConnection);
server
.listen(options.port, options.hostName)
.on('listening', () => resolve())
.on('error', (err) => reject(err));
this.servers.set(url, { server, apis });
});
}
this.listenLock.release();
catch (error) {
this.logger.error({
message: `There was an error during server creation at ${url}`,
data: { error, url, options },
});
throw error;
}
}
return this.servers.get(url);
this.listenLock.release();
}
};
ServerManager.DEFAULT_HOST = 'localhost';
ServerManager = ServerManager_1 = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'singleton' }),
tslib_1.__metadata("design:paramtypes", [inject_1.Injector])
], ServerManager);
return ServerManager;
})();
return this.servers.get(url);
}
};
ServerManager.DEFAULT_HOST = 'localhost';
ServerManager = ServerManager_1 = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'singleton' }),
tslib_1.__metadata("design:paramtypes", [inject_1.Injector])
], ServerManager);
exports.ServerManager = ServerManager;
//# sourceMappingURL=server-manager.js.map

@@ -9,58 +9,55 @@ "use strict";

*/
let Utils = /** @class */ (() => {
let Utils = class Utils {
/**
* Reads the post's body and returns a promise with a parsed value
*
* @param incomingMessage The incoming message instance
* @returns the parsed object from the post body
*/
async readPostBody(incomingMessage) {
let body = '';
await new Promise((resolve, reject) => {
incomingMessage.on('readable', () => {
const data = incomingMessage.read();
if (data) {
body += data;
}
});
incomingMessage.on('end', () => {
resolve();
});
incomingMessage.on('error', (err) => {
reject(err);
});
let Utils = class Utils {
/**
* Reads the post's body and returns a promise with a parsed value
*
* @param incomingMessage The incoming message instance
* @returns the parsed object from the post body
*/
async readPostBody(incomingMessage) {
let body = '';
await new Promise((resolve, reject) => {
incomingMessage.on('readable', () => {
const data = incomingMessage.read();
if (data) {
body += data;
}
});
return JSON.parse(body);
}
/**
* Adds the specified CORS headers to the response
*
* @param options The CORS Options object
* @param incomingMessage The incoming message instance
* @param serverResponse The outgoing response instance
*/
addCorsHeaders(options, incomingMessage, serverResponse) {
if (incomingMessage.headers &&
incomingMessage.headers.origin !== incomingMessage.headers.host &&
options.origins.some((origin) => origin === incomingMessage.headers.origin)) {
serverResponse.setHeader('Access-Control-Allow-Origin', incomingMessage.headers.origin);
if (options.credentials) {
serverResponse.setHeader('Access-Control-Allow-Credentials', 'true');
}
if (options.headers && options.headers.length) {
serverResponse.setHeader('Access-Control-Allow-Headers', options.headers.join(', '));
}
if (options.methods && options.methods.length) {
serverResponse.setHeader('Access-Control-Allow-Methods', options.methods.join(', '));
}
incomingMessage.on('end', () => {
resolve();
});
incomingMessage.on('error', (err) => {
reject(err);
});
});
return JSON.parse(body);
}
/**
* Adds the specified CORS headers to the response
*
* @param options The CORS Options object
* @param incomingMessage The incoming message instance
* @param serverResponse The outgoing response instance
*/
addCorsHeaders(options, incomingMessage, serverResponse) {
if (incomingMessage.headers &&
incomingMessage.headers.origin !== incomingMessage.headers.host &&
options.origins.some((origin) => origin === incomingMessage.headers.origin)) {
serverResponse.setHeader('Access-Control-Allow-Origin', incomingMessage.headers.origin);
if (options.credentials) {
serverResponse.setHeader('Access-Control-Allow-Credentials', 'true');
}
if (options.headers && options.headers.length) {
serverResponse.setHeader('Access-Control-Allow-Headers', options.headers.join(', '));
}
if (options.methods && options.methods.length) {
serverResponse.setHeader('Access-Control-Allow-Methods', options.methods.join(', '));
}
}
};
Utils = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'transient' })
], Utils);
return Utils;
})();
}
};
Utils = tslib_1.__decorate([
inject_1.Injectable({ lifetime: 'transient' })
], Utils);
exports.Utils = Utils;
//# sourceMappingURL=utils.js.map
{
"name": "@furystack/rest-service",
"version": "2.1.7",
"version": "2.1.8",
"description": "Repository implementation for FuryStack",

@@ -34,7 +34,7 @@ "main": "dist/index.js",

"dependencies": {
"@furystack/core": "^9.1.2",
"@furystack/inject": "^4.0.31",
"@furystack/logging": "^2.0.38",
"@furystack/rest": "^1.1.15",
"@furystack/utils": "^1.2.1",
"@furystack/core": "^9.1.3",
"@furystack/inject": "^4.0.32",
"@furystack/logging": "^2.0.39",
"@furystack/rest": "^1.1.16",
"@furystack/utils": "^1.2.2",
"hash.js": "^1.1.7",

@@ -47,3 +47,3 @@ "path-to-regexp": "^6.1.0",

"devDependencies": {
"@types/jest": "^25.2.1",
"@types/jest": "^26.0.0",
"@types/node": "^14.0.4",

@@ -54,3 +54,3 @@ "@types/uuid": "^8.0.0",

"typings": "./dist/index.d.ts",
"gitHead": "d84807f44d6224349d3355818b5c38d19ea1a44e"
"gitHead": "a9ce562cb2fcdb7c5c417f83df3386e00e1c2d95"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc