@universis/janitor 1.9.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -0
- package/dist/index.d.ts +46 -5
- package/dist/index.esm.js +444 -154
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +445 -153
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
- package/public/schemas/v1/rate-limit-service.json +4 -4
- package/public/schemas/v1/speed-limit-service.json +4 -4
- package/src/AppRateLimitService.d.ts +5 -0
- package/src/AppRateLimitService.js +21 -0
- package/src/AppSpeedLimitService.d.ts +5 -0
- package/src/AppSpeedLimitService.js +21 -0
- package/src/RateLimitService.d.ts +20 -1
- package/src/RateLimitService.js +201 -70
- package/src/SpeedLimitService.d.ts +20 -2
- package/src/SpeedLimitService.js +207 -83
- package/src/index.d.ts +2 -0
- package/src/index.js +2 -0
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/RateLimitService.js","../src/SpeedLimitService.js","../src/RedisClientStore.js","../src/ScopeAccessConfiguration.js","../src/validateScope.js","../src/OAuth2ClientService.js","../src/RemoteAddressValidator.js"],"sourcesContent":["import { ApplicationService, TraceUtils } from '@themost/common';\nimport { rateLimit } from 'express-rate-limit';\nimport express from 'express';\nimport path from 'path';\n\nexport class RateLimitService extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication} app \n */\n constructor(app) {\n super(app);\n app.serviceRouter.subscribe(serviceRouter => {\n if (serviceRouter == null) {\n return;\n }\n try {\n const addRouter = express.Router();\n let serviceConfiguration = app.getConfiguration().getSourceAt('settings/universis/janitor/rateLimit') || {\n profiles: [],\n paths: []\n };\n if (serviceConfiguration.extends) {\n // get additional configuration\n const configurationPath = app.getConfiguration().getConfigurationPath();\n const extendsPath = path.resolve(configurationPath, serviceConfiguration.extends);\n TraceUtils.log(`@universis/janitor#RateLimitService will try to extend service configuration from ${extendsPath}`);\n serviceConfiguration = require(extendsPath);\n }\n const pathsArray = serviceConfiguration.paths || [];\n const profilesArray = serviceConfiguration.profiles || [];\n // create maps\n const paths = new Map(pathsArray);\n const profiles = new Map(profilesArray);\n if (paths.size === 0) {\n TraceUtils.warn('@universis/janitor#RateLimitService is being started but the collection of paths is empty.');\n }\n // get proxy address forwarding option\n let proxyAddressForwarding = app.getConfiguration().getSourceAt('settings/universis/api/proxyAddressForwarding');\n if (typeof proxyAddressForwarding !== 'boolean') {\n proxyAddressForwarding = false;\n }\n paths.forEach((value, path) => {\n let profile;\n // get profile\n if (value.profile) {\n profile = profiles.get(value.profile);\n } else {\n // or options defined inline\n profile = value\n }\n if (profile != null) {\n const rateLimitOptions = Object.assign({\n windowMs: 5 * 60 * 1000, // 5 minutes\n limit: 50, // 50 requests\n legacyHeaders: true // send headers\n }, profile, {\n keyGenerator: (req) => {\n let remoteAddress;\n if (proxyAddressForwarding) {\n // get proxy headers or remote address\n remoteAddress = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n } else {\n // get remote address\n remoteAddress = (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n }\n return `${path}:${remoteAddress}`;\n }\n });\n if (typeof rateLimitOptions.store === 'string') {\n // load store\n const store = rateLimitOptions.store.split('#');\n let StoreClass;\n if (store.length === 2) {\n const storeModule = require(store[0]);\n if (Object.prototype.hasOwnProperty.call(storeModule, store[1])) {\n StoreClass = storeModule[store[1]];\n rateLimitOptions.store = new StoreClass(this, rateLimitOptions);\n } else {\n throw new Error(`${store} cannot be found or is inaccessible`);\n }\n } else {\n StoreClass = require(store[0]);\n // create store\n rateLimitOptions.store = new StoreClass(this, rateLimitOptions);\n }\n }\n addRouter.use(path, rateLimit(rateLimitOptions));\n }\n });\n if (addRouter.stack.length) {\n serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);\n }\n } catch (err) {\n TraceUtils.error('An error occurred while validating rate limit configuration.');\n TraceUtils.error(err);\n TraceUtils.warn('Rate limit service is inactive due to an error occured while loading configuration.')\n }\n });\n }\n\n}","import { ApplicationService, TraceUtils } from '@themost/common';\nimport slowDown from 'express-slow-down';\nimport express from 'express';\nimport path from 'path';\n\nexport class SpeedLimitService extends ApplicationService {\n constructor(app) {\n super(app);\n\n app.serviceRouter.subscribe(serviceRouter => {\n if (serviceRouter == null) {\n return;\n }\n try {\n const addRouter = express.Router();\n let serviceConfiguration = app.getConfiguration().getSourceAt('settings/universis/janitor/speedLimit') || {\n profiles: [],\n paths: []\n };\n if (serviceConfiguration.extends) {\n // get additional configuration\n const configurationPath = app.getConfiguration().getConfigurationPath();\n const extendsPath = path.resolve(configurationPath, serviceConfiguration.extends);\n TraceUtils.log(`@universis/janitor#SpeedLimitService will try to extend service configuration from ${extendsPath}`);\n serviceConfiguration = require(extendsPath);\n }\n const pathsArray = serviceConfiguration.paths || [];\n const profilesArray = serviceConfiguration.profiles || [];\n // create maps\n const paths = new Map(pathsArray);\n const profiles = new Map(profilesArray);\n if (paths.size === 0) {\n TraceUtils.warn('@universis/janitor#SpeedLimitService is being started but the collection of paths is empty.');\n }\n // get proxy address forwarding option\n let proxyAddressForwarding = app.getConfiguration().getSourceAt('settings/universis/api/proxyAddressForwarding');\n if (typeof proxyAddressForwarding !== 'boolean') {\n proxyAddressForwarding = false;\n }\n paths.forEach((value, path) => {\n let profile;\n // get profile\n if (value.profile) {\n profile = profiles.get(value.profile);\n } else {\n // or options defined inline\n profile = value\n }\n if (profile != null) {\n const slowDownOptions = Object.assign({\n windowMs: 5 * 60 * 1000, // 5 minutes\n delayAfter: 20, // 20 requests\n delayMs: 500, // 500 ms\n maxDelayMs: 10000 // 10 seconds\n }, profile, {\n keyGenerator: (req) => {\n let remoteAddress;\n if (proxyAddressForwarding) {\n // get proxy headers or remote address\n remoteAddress = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n } else {\n // get remote address\n remoteAddress = (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n }\n return `${path}:${remoteAddress}`;\n }\n });\n if (Array.isArray(slowDownOptions.randomDelayMs)) {\n slowDownOptions.delayMs = () => {\n const delayMs = Math.floor(Math.random() * (slowDownOptions.randomDelayMs[1] - slowDownOptions.randomDelayMs[0] + 1) + slowDownOptions.randomDelayMs[0]);\n return delayMs;\n }\n }\n if (Array.isArray(slowDownOptions.randomMaxDelayMs)) {\n slowDownOptions.maxDelayMs = () => {\n const maxDelayMs = Math.floor(Math.random() * (slowDownOptions.randomMaxDelayMs[1] - slowDownOptions.randomMaxDelayMs[0] + 1) + slowDownOptions.randomMaxDelayMs[0]);\n return maxDelayMs;\n }\n }\n if (typeof slowDownOptions.store === 'string') {\n // load store\n const store = slowDownOptions.store.split('#');\n let StoreClass;\n if (store.length === 2) {\n const storeModule = require(store[0]);\n if (Object.prototype.hasOwnProperty.call(storeModule, store[1])) {\n StoreClass = storeModule[store[1]];\n slowDownOptions.store = new StoreClass(this, slowDownOptions);\n } else {\n throw new Error(`${store} cannot be found or is inaccessible`);\n }\n } else {\n StoreClass = require(store[0]);\n // create store\n slowDownOptions.store = new StoreClass(this, slowDownOptions);\n }\n }\n addRouter.use(path, slowDown(slowDownOptions));\n }\n });\n if (addRouter.stack.length) {\n serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);\n }\n } catch (err) {\n TraceUtils.error('An error occurred while validating speed limit configuration.');\n TraceUtils.error(err);\n TraceUtils.warn('Speed limit service is inactive due to an error occured while loading configuration.')\n }\n });\n }\n\n}","import { TraceUtils } from '@themost/common';\nimport { RedisStore } from 'rate-limit-redis';\nimport { Redis } from 'ioredis';\nimport '@themost/promise-sequence';\n\nlet superLoadIncrementScript;\nlet superLoadGetScript;\n\nfunction noLoadGetScript() {\n //\n}\n\nfunction noLoadIncrementScript() {\n //\n}\n\nif (RedisStore.prototype.loadIncrementScript.name === 'loadIncrementScript') {\n // get super method for future use\n superLoadIncrementScript = RedisStore.prototype.loadIncrementScript;\n RedisStore.prototype.loadIncrementScript = noLoadIncrementScript;\n}\n\nif (RedisStore.prototype.loadGetScript.name === 'loadGetScript') {\n // get super method\n superLoadGetScript = RedisStore.prototype.loadGetScript;\n RedisStore.prototype.loadGetScript = noLoadGetScript;\n}\n\nclass RedisClientStore extends RedisStore {\n\n /**\n * @type {import('redis').RedisClientType}\n */\n client;\n\n /**\n * \n * @param {import('@themost/common').ApplicationService} service\n * @param {{windowMs: number}} options\n */\n constructor(service, options) {\n super({\n /**\n * @param {...string} args\n * @returns {Promise<*>}\n */\n sendCommand: function () {\n const args = Array.from(arguments);\n const [command] = args.splice(0, 1);\n const self = this;\n if (command === 'SCRIPT') {\n const connectOptions = service.getApplication().getConfiguration().getSourceAt('settings/redis/options') || {\n host: '127.0.0.1',\n port: 6379\n };\n const client = new Redis(connectOptions);\n return client.call(command, args).catch((error) => {\n if (error instanceof TypeError && error.message === 'Invalid argument type') {\n TraceUtils.warn('RedisClientStore: Invalid argument type: ' + JSON.stringify(args));\n }\n return Promise.reject(error);\n }).finally(() => {\n if (client.isOpen) {\n client.disconnect().catch((errDisconnect) => {\n TraceUtils.error(errDisconnect);\n });\n }\n });\n }\n if (self.client == null) {\n const connectOptions = service.getApplication().getConfiguration().getSourceAt('settings/redis/options') || {\n host: '127.0.0.1',\n port: 6379\n };\n self.client = new Redis(connectOptions);\n }\n if (self.client.isOpen) {\n return self.client.call(command, args).catch((error) => {\n if (error instanceof TypeError && error.message === 'Invalid argument type') {\n TraceUtils.warn('RedisClientStore: Invalid argument type: ' + JSON.stringify(args));\n }\n return Promise.reject(error);\n });\n }\n // send load script commands once\n return (() => {\n if (self.incrementScriptSha == null) {\n return this.postInit();\n }\n return Promise.resolve();\n })().then(() => {\n // send command \n args[0] = self.incrementScriptSha;\n return self.client.call(command, args).catch((error) => {\n if (error instanceof TypeError && error.message === 'Invalid argument type') {\n TraceUtils.warn('RedisClientStore: Invalid argument type: ' + JSON.stringify(args));\n }\n return Promise.reject(error);\n });\n });\n }\n });\n this.init(options);\n TraceUtils.debug('RedisClientStore: Starting up and loading increment and get scripts.');\n void this.postInit().then(() => {\n TraceUtils.debug('RedisClientStore: Successfully loaded increment and get scripts.');\n }).catch((err) => {\n TraceUtils.error('RedisClientStore: Failed to load increment and get scripts.');\n TraceUtils.error(err);\n });\n }\n async postInit() {\n const [incrementScriptSha, getScriptSha] = await Promise.sequence([\n () => superLoadIncrementScript.call(this),\n () => superLoadGetScript.call(this)\n ]);\n this.incrementScriptSha = incrementScriptSha;\n this.getScriptSha = getScriptSha;\n }\n\n}\n\nexport {\n RedisClientStore\n}","\nimport {ConfigurationStrategy, Args, ApplicationService} from '@themost/common';\nimport path from 'path';\nimport url from 'url';\n\nconst HTTP_METHOD_REGEXP = /^\\b(POST|PUT|PATCH|DELETE)\\b$/i;\n\nclass ScopeString {\n constructor(str) {\n this.value = str;\n }\n toString() {\n return this.value;\n }\n /**\n * Splits a comma-separated or space-separated scope string e.g. \"profile email\" or \"profile,email\"\n *\n * Important note: https://www.rfc-editor.org/rfc/rfc6749#section-3.3 defines the regular expression of access token scopes\n * which is a space separated string. Several OAuth2 servers use a comma-separated list instead.\n *\n * The operation will try to use both implementations by excluding comma ',' from access token regular expressions\n * @returns {Array<string>}\n */\n split() {\n // the default regular expression includes comma /([\\x21\\x23-\\x5B\\x5D-\\x7E]+)/g\n // the modified regular expression excludes comma /x2C /([\\x21\\x23-\\x2B\\x2D-\\x5B\\x5D-\\x7E]+)/g\n const re = /([\\x21\\x23-\\x2B\\x2D-\\x5B\\x5D-\\x7E]+)/g\n const results = [];\n let match = re.exec(this.value);\n while(match !== null) {\n results.push(match[0]);\n match = re.exec(this.value);\n }\n return results;\n }\n}\n\nclass ScopeAccessConfiguration extends ConfigurationStrategy {\n /**\n * @param {import('@themost/common').ConfigurationBase} configuration\n */\n constructor(configuration) {\n super(configuration);\n let elements = [];\n // define property\n Object.defineProperty(this, 'elements', {\n get: () => {\n return elements;\n },\n enumerable: true\n });\n }\n\n /**\n * @param {Request} req\n * @returns Promise<ScopeAccessConfigurationElement>\n */\n verify(req) {\n return new Promise((resolve, reject) => {\n try {\n // validate request context\n Args.notNull(req.context,'Context');\n // validate request context user\n Args.notNull(req.context.user,'User');\n if (req.context.user.authenticationScope && req.context.user.authenticationScope.length>0) {\n // get original url\n let reqUrl = url.parse(req.originalUrl).pathname;\n // get user context scopes as array e.g, ['students', 'students:read']\n let reqScopes = new ScopeString(req.context.user.authenticationScope).split();\n // get user access based on HTTP method e.g. GET -> read access\n let reqAccess = HTTP_METHOD_REGEXP.test(req.method) ? 'write' : 'read';\n // first phase: find element by resource and scope\n let result = this.elements.find(x => {\n // filter element by access level\n return new RegExp( \"^\" + x.resource, 'i').test(reqUrl)\n // and scopes\n && x.scope.find(y => {\n // search user scopes (validate wildcard scope)\n return y === \"*\" || reqScopes.indexOf(y)>=0;\n });\n });\n // second phase: check access level\n if (result == null) {\n return resolve();\n }\n // if access is missing or access is not an array\n if (Array.isArray(result.access) === false) {\n // the requested access is not allowed because the access is not defined\n return resolve();\n }\n // if the requested access is not in the access array\n if (result.access.indexOf(reqAccess) < 0) {\n // the requested access is not allowed because the access levels do not match\n return resolve();\n }\n // otherwise, return result\n return resolve(result);\n }\n return resolve();\n }\n catch(err) {\n return reject(err);\n }\n\n });\n }\n\n}\n\n/**\n * @class\n */\nclass DefaultScopeAccessConfiguration extends ScopeAccessConfiguration {\n /**\n * @param {import('@themost/common').ConfigurationBase} configuration\n */\n constructor(configuration) {\n super(configuration);\n let defaults = [];\n // load scope access from configuration resource\n try {\n /**\n * @type {Array<ScopeAccessConfigurationElement>}\n */\n defaults = require(path.resolve(configuration.getConfigurationPath(), 'scope.access.json'));\n }\n catch(err) {\n // if an error occurred other than module not found (there are no default access policies)\n if (err.code !== 'MODULE_NOT_FOUND') {\n // throw error\n throw err;\n }\n // otherwise continue\n }\n this.elements.push.apply(this.elements, defaults);\n }\n}\n\nclass EnableScopeAccessConfiguration extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase} app \n */\n constructor(app) {\n super(app);\n // register scope access configuration\n app.getConfiguration().useStrategy(ScopeAccessConfiguration, DefaultScopeAccessConfiguration);\n }\n}\n\n\n/**\n * @class\n */\nclass ExtendScopeAccessConfiguration extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase} app\n */\n constructor(app) {\n super(app);\n // Get the additional scope access extensions from the configuration\n const scopeAccessExtensions = app.getConfiguration().settings.universis?.janitor?.scopeAccess.imports;\n if (app && app.container && scopeAccessExtensions != null) {\n app.container.subscribe((container) => {\n if (container) {\n const scopeAccess = app.getConfiguration().getStrategy(function ScopeAccessConfiguration() { });\n if (scopeAccess != null) {\n for (const scopeAccessExtension of scopeAccessExtensions) {\n try {\n const elements = require(path.resolve(app.getConfiguration().getConfigurationPath(), scopeAccessExtension));\n if (elements) {\n // add extra scope access elements\n scopeAccess.elements.unshift(...elements);\n }\n }\n catch(err) {\n // if an error occurred other than module not found (there are no default access policies)\n if (err.code !== 'MODULE_NOT_FOUND') {\n // throw error\n throw err;\n }\n }\n }\n }\n }\n });\n }\n }\n}\n\nexport {\n ScopeString,\n ScopeAccessConfiguration,\n DefaultScopeAccessConfiguration,\n EnableScopeAccessConfiguration,\n ExtendScopeAccessConfiguration\n}\n","import { ScopeAccessConfiguration } from './ScopeAccessConfiguration';\nimport {HttpForbiddenError} from '@themost/common';\n\nfunction validateScope() {\n return (req, res, next) => {\n /**\n * @type {ScopeAccessConfiguration}\n */\n let scopeAccessConfiguration = req.context.getApplication().getConfiguration().getStrategy(ScopeAccessConfiguration);\n if (typeof scopeAccessConfiguration === 'undefined') {\n return next(new Error('Invalid application configuration. Scope access configuration strategy is missing or is in accessible.'));\n }\n scopeAccessConfiguration.verify(req).then(value => {\n if (value) {\n return next();\n }\n return next(new HttpForbiddenError('Access denied due to authorization scopes.'))\n }).catch(reason => {\n return next(reason);\n });\n };\n}\n\nexport {\n validateScope\n}\n","import {Request} from 'superagent'\nimport {URL} from 'url';\nimport {ApplicationService, DataError, HttpError} from '@themost/common';\n\nfunction responseHander(resolve, reject) {\n return function (err, response) {\n if (err) {\n /**\n * @type {import('superagent').Response}\n */\n const response = err.response\n if (response && response.headers['content-type'] === 'application/json') {\n // get body\n const clientError = response.body;\n const error = new HttpError(response.status);\n return reject(Object.assign(error, {\n clientError\n }));\n }\n return reject(err);\n }\n if (response.status === 204 && response.headers['content-type'] === 'application/json') {\n return resolve(null);\n }\n return resolve(response.body);\n };\n}\n\n/**\n * @class\n */\nclass OAuth2ClientService extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication} app\n */\n constructor(app) {\n super(app);\n /**\n * @name OAuth2ClientService#settings\n * @type {{server_uri:string,token_uri?:string}}\n */\n Object.defineProperty(this, 'settings', {\n writable: false,\n value: app.getConfiguration().getSourceAt('settings/auth'),\n enumerable: false,\n configurable: false\n });\n }\n\n /**\n * Gets keycloak server root\n * @returns {string}\n */\n getServer() {\n return this.settings.server_uri;\n }\n\n /**\n * Gets keycloak server root\n * @returns {string}\n */\n getAdminRoot() {\n return this.settings.admin_uri;\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * Gets user's profile by calling OAuth2 server profile endpoint\n * @param {ExpressDataContext} context\n * @param {string} token\n */\n getUserInfo(token) {\n return new Promise((resolve, reject) => {\n const userinfo_uri = this.settings.userinfo_uri ? new URL(this.settings.userinfo_uri, this.getServer()) : new URL('me', this.getServer());\n return new Request('GET', userinfo_uri)\n .set({\n 'Authorization': `Bearer ${token}`,\n 'Accept': 'application/json'\n })\n .query({\n 'access_token':token\n }).end(responseHander(resolve, reject));\n });\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * Gets the token info of the current context\n * @param {ExpressDataContext} context\n */\n getContextTokenInfo(context) {\n if (context.user == null) {\n return Promise.reject(new Error('Context user may not be null'));\n }\n if (context.user.authenticationType !== 'Bearer') {\n return Promise.reject(new Error('Invalid context authentication type'));\n }\n if (context.user.authenticationToken == null) {\n return Promise.reject(new Error('Context authentication data may not be null'));\n }\n return this.getTokenInfo(context, context.user.authenticationToken);\n }\n /**\n * Gets token info by calling OAuth2 server endpoint\n * @param {ExpressDataContext} _context\n * @param {string} token\n */\n getTokenInfo(_context, token) {\n return new Promise((resolve, reject) => {\n const introspection_uri = this.settings.introspection_uri ? new URL(this.settings.introspection_uri, this.getServer()) : new URL('tokeninfo', this.getServer());\n return new Request('POST', introspection_uri)\n .auth(this.settings.client_id, this.settings.client_secret)\n .set('Accept', 'application/json')\n .type('form')\n .send({\n 'token_type_hint': 'access_token',\n 'token': token,\n }).end(responseHander(resolve, reject));\n });\n }\n\n /**\n * @param {AuthorizeUser} authorizeUser\n */\n authorize(authorizeUser) {\n const tokenURL = this.settings.token_uri ? new URL(this.settings.token_uri) : new URL('authorize', this.getServer());\n return new Promise((resolve, reject)=> {\n return new Request('POST', tokenURL)\n .type('form')\n .send(authorizeUser).end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Gets a user by name\n * @param {*} user_id \n * @param {AdminMethodOptions} options \n */\n getUserById(user_id, options) {\n return new Promise((resolve, reject) => {\n return new Request('GET', new URL(`users/${user_id}`, this.getAdminRoot()))\n .set('Authorization', `Bearer ${options.access_token}`)\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Gets a user by name\n * @param {string} username \n * @param {AdminMethodOptions} options \n */\n getUser(username, options) {\n return new Promise((resolve, reject)=> {\n return new Request('GET', new URL('users', this.getAdminRoot()))\n .set('Authorization', `Bearer ${options.access_token}`)\n .query({\n '$filter': `name eq '${username}'`\n })\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Gets a user by email address\n * @param {string} email \n * @param {AdminMethodOptions} options \n */\n getUserByEmail(email, options) {\n return new Promise((resolve, reject)=> {\n return new Request('GET', new URL('users', this.getAdminRoot()))\n .set('Authorization', `Bearer ${options.access_token}`)\n .query({\n '$filter': `alternateName eq '${email}'`\n })\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Updates an existing user\n * @param {*} user \n * @param {AdminMethodOptions} options \n */\n updateUser(user, options) {\n return new Promise((resolve, reject)=> {\n if (user.id == null) {\n return reject(new DataError('E_IDENTIFIER', 'User may not be empty at this context.', null, 'User', 'id'));\n }\n const request = new Request('PUT', new URL(`users/${user.id}`, this.getAdminRoot()));\n return request.set('Authorization', `Bearer ${options.access_token}`)\n .set('Content-Type', 'application/json')\n .send(user)\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Creates a new user\n * @param {*} user \n * @param {AdminMethodOptions} options \n */\n createUser(user, options) {\n return new Promise((resolve, reject)=> {\n const request = new Request('POST', new URL('users', this.getAdminRoot()));\n return request.set('Authorization', `Bearer ${options.access_token}`)\n .set('Content-Type', 'application/json')\n .send(Object.assign({}, user, {\n $state: 1 // for create\n }))\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Deletes a user\n * @param {{id: any}} user \n * @param {AdminMethodOptions} options \n */\n deleteUser(user, options) {\n return new Promise((resolve, reject)=> {\n if (user.id == null) {\n return reject(new DataError('E_IDENTIFIER', 'User may not be empty at this context.', null, 'User', 'id'));\n }\n const request = new Request('DELETE', new URL(`users/${user.id}`, this.getAdminRoot()));\n return request.set('Authorization', `Bearer ${options.access_token}`)\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * @param {boolean=} force \n * @returns {*}\n */\n getWellKnownConfiguration(force) {\n if (force) {\n this.well_known_configuration = null;\n }\n if (this.well_known_configuration) {\n return Promise.resolve(this.well_known_configuration);\n }\n return new Promise((resolve, reject) => {\n const well_known_configuration_uri = this.settings.well_known_configuration_uri ? new URL(this.settings.well_known_configuration_uri, this.getServer()) : new URL('.well-known/openid-configuration', this.getServer());\n return new Request('GET', well_known_configuration_uri)\n .end(responseHander(resolve, reject));\n }).then((configuration) => {\n this.well_known_configuration = configuration;\n return configuration;\n });\n }\n}\n\nexport {\n OAuth2ClientService\n}\n\n","import { ApplicationService, HttpForbiddenError, TraceUtils } from '@themost/common';\nimport express from 'express';\nimport jwt from 'jsonwebtoken';\n\nclass HttpRemoteAddrForbiddenError extends HttpForbiddenError {\n constructor() {\n super('Access is denied due to remote address conflict. The client network has been changed or cannot be determined.');\n this.statusCode = 403.6;\n }\n \n}\n\nclass RemoteAddressValidator extends ApplicationService {\n constructor(app) {\n super(app);\n\n // get proxy address forwarding option\n let proxyAddressForwarding = app.getConfiguration().getSourceAt('settings/universis/api/proxyAddressForwarding');\n if (typeof proxyAddressForwarding !== 'boolean') {\n proxyAddressForwarding = false;\n }\n this.proxyAddressForwarding = proxyAddressForwarding;\n // get token claim name\n this.claim = app.getConfiguration().getSourceAt('settings/universis/janitor/remoteAddress/claim') || 'remoteAddress';\n\n app.serviceRouter.subscribe((serviceRouter) => {\n if (serviceRouter == null) {\n return;\n }\n const addRouter = express.Router();\n addRouter.use((req, res, next) => {\n void this.validateRemoteAddress(req).then((value) => {\n if (value === false) {\n return next(new HttpRemoteAddrForbiddenError());\n }\n return next();\n }).catch((err) => {\n return next(err);\n });\n });\n // insert router at the beginning of serviceRouter.stack\n serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);\n });\n }\n\n /**\n * Gets remote address from request\n * @param {import('express').Request} req \n * @returns \n */\n getRemoteAddress(req) {\n let remoteAddress;\n if (this.proxyAddressForwarding) {\n // get proxy headers or remote address\n remoteAddress = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n } else {\n remoteAddress = req.connection ? req.connection.remoteAddress : req.socket.remoteAddress;\n }\n return remoteAddress;\n }\n\n /**\n * Validates token remote address with request remote address\n * @param {import('express').Request} req \n * @returns {Promise<boolean>}\n */\n async validateRemoteAddress(req) {\n const authenticationToken = req.context?.user?.authenticationToken;\n if (authenticationToken != null) {\n const access_token = jwt.decode(authenticationToken);\n const remoteAddress = access_token[this.claim];\n if (remoteAddress == null) {\n TraceUtils.warn(`Remote address validation failed. Expected a valid remote address claimed by using \"${this.claim}\" attribute but got none.`);\n return false;\n }\n // get context remote address\n const requestRemoteAddress = this.getRemoteAddress(req);\n if (remoteAddress !== requestRemoteAddress) {\n TraceUtils.warn(`Remote address validation failed. Expected remote address is ${remoteAddress || 'Uknown'} but request remote address is ${requestRemoteAddress}`);\n return false;\n }\n return true;\n }\n TraceUtils.warn('Remote address validation cannot be completed because authentication token is not available.');\n return false;\n }\n\n}\n\nexport {\n HttpRemoteAddrForbiddenError,\n RemoteAddressValidator\n}\n"],"names":["RateLimitService","ApplicationService","constructor","app","serviceRouter","subscribe","addRouter","express","Router","serviceConfiguration","getConfiguration","getSourceAt","profiles","paths","extends","configurationPath","getConfigurationPath","extendsPath","path","resolve","TraceUtils","log","require","pathsArray","profilesArray","Map","size","warn","proxyAddressForwarding","forEach","value","profile","get","rateLimitOptions","Object","assign","windowMs","limit","legacyHeaders","keyGenerator","req","remoteAddress","headers","connection","socket","store","split","StoreClass","length","storeModule","prototype","hasOwnProperty","call","Error","use","rateLimit","stack","unshift","apply","err","error","SpeedLimitService","slowDownOptions","delayAfter","delayMs","maxDelayMs","Array","isArray","randomDelayMs","Math","floor","random","randomMaxDelayMs","slowDown","superLoadIncrementScript","superLoadGetScript","noLoadGetScript","noLoadIncrementScript","RedisStore","loadIncrementScript","name","loadGetScript","RedisClientStore","service","options","sendCommand","args","from","arguments","command","splice","self","connectOptions","getApplication","host","port","client","Redis","catch","TypeError","message","JSON","stringify","Promise","reject","finally","isOpen","disconnect","errDisconnect","incrementScriptSha","postInit","then","_defineProperty","init","debug","getScriptSha","sequence","HTTP_METHOD_REGEXP","ScopeString","str","toString","re","results","match","exec","push","ScopeAccessConfiguration","ConfigurationStrategy","configuration","elements","defineProperty","enumerable","verify","Args","notNull","context","user","authenticationScope","reqUrl","url","parse","originalUrl","pathname","reqScopes","reqAccess","test","method","result","find","x","RegExp","resource","scope","y","indexOf","access","DefaultScopeAccessConfiguration","defaults","code","EnableScopeAccessConfiguration","useStrategy","ExtendScopeAccessConfiguration","scopeAccessExtensions","settings","universis","janitor","scopeAccess","imports","container","getStrategy","scopeAccessExtension","validateScope","res","next","scopeAccessConfiguration","HttpForbiddenError","reason","responseHander","response","clientError","body","HttpError","status","OAuth2ClientService","writable","configurable","getServer","server_uri","getAdminRoot","admin_uri","getUserInfo","token","userinfo_uri","URL","Request","set","query","end","getContextTokenInfo","authenticationType","authenticationToken","getTokenInfo","_context","introspection_uri","auth","client_id","client_secret","type","send","authorize","authorizeUser","tokenURL","token_uri","getUserById","user_id","access_token","getUser","username","getUserByEmail","email","updateUser","id","DataError","request","createUser","$state","deleteUser","getWellKnownConfiguration","force","well_known_configuration","well_known_configuration_uri","HttpRemoteAddrForbiddenError","statusCode","RemoteAddressValidator","claim","validateRemoteAddress","getRemoteAddress","jwt","decode","requestRemoteAddress"],"mappings":";;;;;;;;;;;;;AAKO,MAAMA,gBAAgB,SAASC,kBAAkB,CAAC;AACrD;AACJ;AACA;EACIC,WAAWA,CAACC,GAAG,EAAE;IACb,KAAK,CAACA,GAAG,CAAC;AACVA,IAAAA,GAAG,CAACC,aAAa,CAACC,SAAS,CAAC,CAAAD,aAAa,KAAI;MACzC,IAAIA,aAAa,IAAI,IAAI,EAAE;AACvB,QAAA;AACJ;MACA,IAAI;AACA,QAAA,MAAME,SAAS,GAAGC,OAAO,CAACC,MAAM,EAAE;AAClC,QAAA,IAAIC,oBAAoB,GAAGN,GAAG,CAACO,gBAAgB,EAAE,CAACC,WAAW,CAAC,sCAAsC,CAAC,IAAI;AACrGC,UAAAA,QAAQ,EAAE,EAAE;AACZC,UAAAA,KAAK,EAAE;SACV;QACD,IAAIJ,oBAAoB,CAACK,OAAO,EAAE;AAC9B;UACA,MAAMC,iBAAiB,GAAGZ,GAAG,CAACO,gBAAgB,EAAE,CAACM,oBAAoB,EAAE;UACvE,MAAMC,WAAW,GAAGC,IAAI,CAACC,OAAO,CAACJ,iBAAiB,EAAEN,oBAAoB,CAACK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,MAAM/J,aAAa,GAAG8K,YAAY,CAAC,IAAI,CAACmB,KAAK,CAAC;MAC9C,IAAIjM,aAAa,IAAI,IAAI,EAAE;QACvBrB,UAAU,CAACO,IAAI,CAAC,CAAA,oFAAA,EAAuF,IAAI,CAAC+M,KAAK,2BAA2B,CAAC;AAC7I,QAAA,OAAO,KAAK;AAChB;AACA;AACA,MAAA,MAAMK,oBAAoB,GAAG,IAAI,CAACH,gBAAgB,CAACpM,GAAG,CAAC;MACvD,IAAIC,aAAa,KAAKsM,oBAAoB,EAAE;QACxC3N,UAAU,CAACO,IAAI,CAAC,CAAgEc,6DAAAA,EAAAA,aAAa,IAAI,QAAQ,CAAA,+BAAA,EAAkCsM,oBAAoB,CAAA,CAAE,CAAC;AAClK,QAAA,OAAO,KAAK;AAChB;AACA,MAAA,OAAO,IAAI;AACf;AACA3N,IAAAA,UAAU,CAACO,IAAI,CAAC,8FAA8F,CAAC;AAC/G,IAAA,OAAO,KAAK;AACd;;AAEF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/RateLimitService.js","../src/SpeedLimitService.js","../src/RedisClientStore.js","../src/ScopeAccessConfiguration.js","../src/validateScope.js","../src/OAuth2ClientService.js","../src/RemoteAddressValidator.js","../src/AppRateLimitService.js","../src/AppSpeedLimitService.js"],"sourcesContent":["import { ApplicationService, TraceUtils } from '@themost/common';\nimport { rateLimit } from 'express-rate-limit';\nimport express from 'express';\nimport path from 'path';\nimport { BehaviorSubject } from 'rxjs';\n\nexport class RateLimitService extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication} app \n */\n constructor(app) {\n super(app);\n\n // get proxy address forwarding option\n const proxyAddressForwarding = app.getConfiguration().getSourceAt('settings/universis/api/proxyAddressForwarding');\n this.proxyAddressForwarding = typeof proxyAddressForwarding !== 'boolean'? false : proxyAddressForwarding; \n\n /**\n * @type {BehaviorSubject<{ target: RateLimitService }>}\n */\n this.loaded = new BehaviorSubject(null);\n\n const serviceContainer = this.getServiceContainer();\n if (serviceContainer == null) {\n TraceUtils.warn(`${this.getServiceName()} is being started but the parent router seems to be unavailable.`);\n return;\n }\n serviceContainer.subscribe((router) => {\n if (router == null) {\n return;\n }\n try {\n // set router for further processing\n Object.defineProperty(this, 'router', {\n value: express.Router(),\n writable: false,\n enumerable: false,\n configurable: true\n });\n const serviceConfiguration = this.getServiceConfiguration();\n // create maps\n const paths = serviceConfiguration.paths;\n if (paths.size === 0) {\n TraceUtils.warn(`${this.getServiceName()} is being started but the collection of paths is empty.`);\n }\n paths.forEach((value, path) => {\n this.set(path, value);\n });\n if (router.stack) {\n router.stack.unshift.apply(router.stack, this.router.stack);\n } else {\n // use router\n router.use(this.router);\n // get router stack (use a workaround for express 4.x)\n const stack = router._router && router._router.stack;\n if (Array.isArray(stack)) {\n // stage #1 find logger middleware (for supporting request logging)\n let index = stack.findIndex((item) => {\n return item.name === 'logger';\n });\n if (index === -1) {\n // stage #2 find expressInit middleware\n index = stack.findIndex((item) => {\n return item.name === 'expressInit';\n });\n }\n // if found, move the last middleware to be after expressInit\n if (index > -1) {\n // move the last middleware to be after expressInit\n stack.splice(index + 1, 0, stack.pop());\n }\n } else {\n TraceUtils.warn(`${this.getServiceName()} is being started but the container stack is not available.`);\n }\n }\n // notify that the service is loaded\n this.loaded.next({ target: this });\n } catch (err) {\n TraceUtils.error('An error occurred while validating rate limit configuration.');\n TraceUtils.error(err);\n TraceUtils.warn('Rate limit service is inactive due to an error occured while loading configuration.')\n }\n });\n }\n\n /**\n * Returns the service router that is used to register rate limit middleware.\n * @returns {import('rxjs').BehaviorSubject<import('express').Router | import('express').Application>} The service router.\n */\n getServiceContainer() {\n return this.getApplication() && this.getApplication().serviceRouter;\n }\n\n /**\n * Returns the service name.\n * @returns {string} The service name.\n */\n getServiceName() {\n return '@universis/janitor#RateLimitService';\n }\n /**\n * Returns the service configuration.\n * @returns {{extends?: string, profiles?: Array, paths?: Array}} The service configuration.\n */\n getServiceConfiguration() {\n if (this.serviceConfiguration) {\n return this.serviceConfiguration;\n }\n let serviceConfiguration = {\n profiles: [],\n paths: []\n };\n // get service configuration\n const serviceConfigurationSource = this.getApplication().getConfiguration().getSourceAt('settings/universis/janitor/rateLimit');\n if (serviceConfigurationSource) {\n if (typeof serviceConfigurationSource.extends === 'string') {\n // get additional configuration\n const configurationPath = this.getApplication().getConfiguration().getConfigurationPath();\n const extendsPath = path.resolve(configurationPath, serviceConfigurationSource.extends);\n TraceUtils.log(`${this.getServiceName()} will try to extend service configuration using ${extendsPath}`);\n serviceConfiguration = Object.assign({}, {\n profiles: [],\n paths: []\n }, require(extendsPath));\n } else {\n TraceUtils.log(`${this.getServiceName()} will use service configuration from settings/universis/janitor/rateLimit`);\n serviceConfiguration = Object.assign({}, {\n profiles: [],\n paths: []\n }, serviceConfigurationSource);\n }\n }\n const pathsArray = serviceConfiguration.paths || [];\n const profilesArray = serviceConfiguration.profiles || [];\n // create maps\n serviceConfiguration.paths = new Map(pathsArray);\n serviceConfiguration.profiles = new Map(profilesArray);\n // set service configuration\n Object.defineProperty(this, 'serviceConfiguration', {\n value: serviceConfiguration,\n writable: false,\n enumerable: false,\n configurable: true\n });\n return this.serviceConfiguration;\n }\n\n /**\n * Sets the rate limit configuration for a specific path.\n * @param {string} path \n * @param {{ profile: string } | import('express-rate-limit').Options} options \n * @returns {RateLimitService} The service instance for chaining.\n */\n set(path, options) {\n let opts;\n // get profile\n if (options.profile) {\n opts = this.serviceConfiguration.profiles.get(options.profile);\n } else {\n // or options defined inline\n opts = options\n }\n /**\n * @type { import('express-rate-limit').Options }\n */\n const rateLimitOptions = Object.assign({\n windowMs: 5 * 60 * 1000, // 5 minutes\n limit: 50, // 50 requests\n legacyHeaders: true // send headers\n }, opts, {\n keyGenerator: (req) => {\n let remoteAddress;\n if (this.proxyAddressForwarding) {\n // get proxy headers or remote address\n remoteAddress = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n } else {\n // get remote address\n remoteAddress = (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n }\n return `${path}:${remoteAddress}`;\n }\n });\n if (typeof rateLimitOptions.store === 'undefined') {\n const StoreClass = this.getStoreType();\n if (typeof StoreClass === 'function') {\n rateLimitOptions.store = new StoreClass(this, rateLimitOptions);\n }\n }\n this.router.use(path, rateLimit(rateLimitOptions));\n return this;\n }\n\n /**\n * @returns {function} The type of store used for rate limiting.\n */\n getStoreType() {\n const serviceConfiguration = this.getServiceConfiguration();\n if (typeof serviceConfiguration.storeType !== 'string') {\n return;\n }\n let StoreClass;\n const store = serviceConfiguration.storeType.split('#');\n if (store.length === 2) {\n const storeModule = require(store[0]);\n if (Object.prototype.hasOwnProperty.call(storeModule, store[1])) {\n StoreClass = storeModule[store[1]];\n return StoreClass\n } else {\n throw new Error(`${store} cannot be found or is inaccessible`);\n }\n } else {\n StoreClass = require(store[0]);\n return StoreClass;\n }\n }\n\n /**\n * Unsets the rate limit configuration for a specific path.\n * @param {string} path \n * @returns {RateLimitService} The service instance for chaining.\n */\n unset(path) {\n const index =this.router.stack.findIndex((layer) => {\n return layer.route && layer.route.path === path;\n });\n if (index !== -1) {\n this.router.stack.splice(index, 1);\n }\n return this;\n }\n\n}","import { ApplicationService, TraceUtils } from '@themost/common';\nimport slowDown from 'express-slow-down';\nimport express from 'express';\nimport path from 'path';\nimport { BehaviorSubject } from 'rxjs';\n\nexport class SpeedLimitService extends ApplicationService {\n constructor(app) {\n super(app);\n\n // get proxy address forwarding option\n const proxyAddressForwarding = app.getConfiguration().getSourceAt('settings/universis/api/proxyAddressForwarding');\n this.proxyAddressForwarding = typeof proxyAddressForwarding !== 'boolean'? false : proxyAddressForwarding; \n\n /**\n * @type {BehaviorSubject<{ target: SpeedLimitService }>}\n */\n this.loaded = new BehaviorSubject(null);\n\n const serviceContainer = this.getServiceContainer();\n if (serviceContainer == null) {\n TraceUtils.warn(`${this.getServiceName()} is being started but the parent router seems to be unavailable.`);\n return;\n }\n\n serviceContainer.subscribe(router => {\n if (router == null) {\n return;\n }\n try {\n // set router for further processing\n Object.defineProperty(this, 'router', {\n value: express.Router(),\n writable: false,\n enumerable: false,\n configurable: true\n });\n const serviceConfiguration = this.getServiceConfiguration();\n // create maps\n const paths = serviceConfiguration.paths;\n if (paths.size === 0) {\n TraceUtils.warn(`${this.getServiceName()} is being started but the collection of paths is empty.`);\n }\n paths.forEach((value, path) => {\n this.set(path, value);\n });\n if (router.stack) {\n router.stack.unshift.apply(router.stack, this.router.stack);\n } else {\n // use router\n router.use(this.router);\n // get router stack (use a workaround for express 4.x)\n const stack = router._router && router._router.stack;\n if (Array.isArray(stack)) {\n // stage #1 find logger middleware (for supporting request logging)\n let index = stack.findIndex((item) => {\n return item.name === 'logger';\n });\n if (index === -1) {\n // stage #2 find expressInit middleware\n index = stack.findIndex((item) => {\n return item.name === 'expressInit';\n });\n }\n } else {\n TraceUtils.warn(`${this.getServiceName()} is being started but the container stack is not available.`);\n }\n }\n // notify that the service is loaded\n this.loaded.next({ target: this });\n } catch (err) {\n TraceUtils.error('An error occurred while validating speed limit configuration.');\n TraceUtils.error(err);\n TraceUtils.warn('Speed limit service is inactive due to an error occured while loading configuration.')\n }\n });\n }\n\n /**\n * @returns {function} The type of store used for rate limiting.\n */\n getStoreType() {\n const serviceConfiguration = this.getServiceConfiguration();\n if (typeof serviceConfiguration.storeType !== 'string') {\n return;\n }\n let StoreClass;\n const store = serviceConfiguration.storeType.split('#');\n if (store.length === 2) {\n const storeModule = require(store[0]);\n if (Object.prototype.hasOwnProperty.call(storeModule, store[1])) {\n StoreClass = storeModule[store[1]];\n return StoreClass\n } else {\n throw new Error(`${store} cannot be found or is inaccessible`);\n }\n } else {\n StoreClass = require(store[0]);\n return StoreClass;\n }\n }\n\n /**\n * Returns the service name.\n * @returns {string} The service name.\n */\n getServiceName() {\n return '@universis/janitor#SpeedLimitService';\n }\n\n /**\n * Returns the service router that is used to register speed limit middleware.\n * @returns {import('express').Router | import('express').Application} The service router.\n */\n getServiceContainer() {\n return this.getApplication() && this.getApplication().serviceRouter;\n }\n\n /**\n * Sets the speed limit configuration for a specific path.\n * @param {string} path \n * @param {{ profile: string } | import('express-slow-down').Options} options \n * @returns {SpeedLimitService} The service instance for chaining.\n */\n set(path, options) {\n let opts;\n // get profile\n if (options.profile) {\n opts = this.serviceConfiguration.profiles.get(options.profile);\n } else {\n // or options defined inline\n opts = options\n }\n const slowDownOptions = Object.assign({\n windowMs: 5 * 60 * 1000, // 5 minutes\n delayAfter: 20, // 20 requests\n delayMs: 500, // 500 ms\n maxDelayMs: 10000 // 10 seconds\n }, opts, {\n keyGenerator: (req) => {\n let remoteAddress;\n if (this.proxyAddressForwarding) {\n // get proxy headers or remote address\n remoteAddress = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n } else {\n // get remote address\n remoteAddress = (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n }\n return `${path}:${remoteAddress}`;\n }\n });\n if (Array.isArray(slowDownOptions.randomDelayMs)) {\n slowDownOptions.delayMs = () => {\n const delayMs = Math.floor(Math.random() * (slowDownOptions.randomDelayMs[1] - slowDownOptions.randomDelayMs[0] + 1) + slowDownOptions.randomDelayMs[0]);\n return delayMs;\n }\n }\n if (Array.isArray(slowDownOptions.randomMaxDelayMs)) {\n slowDownOptions.maxDelayMs = () => {\n const maxDelayMs = Math.floor(Math.random() * (slowDownOptions.randomMaxDelayMs[1] - slowDownOptions.randomMaxDelayMs[0] + 1) + slowDownOptions.randomMaxDelayMs[0]);\n return maxDelayMs;\n }\n }\n if (typeof slowDownOptions.store === 'undefined') {\n const StoreClass = this.getStoreType();\n if (typeof StoreClass === 'function') {\n slowDownOptions.store = new StoreClass(this, slowDownOptions);\n }\n }\n this.router.use(path, slowDown(slowDownOptions));\n return this;\n }\n \n\n /**\n * Unsets the speed limit configuration for a specific path.\n * @param {string} path \n * @return {SpeedLimitService} The service instance for chaining.\n */\n unset(path) {\n const index =this.router.stack.findIndex((layer) => {\n return layer.route && layer.route.path === path;\n });\n if (index !== -1) {\n this.router.stack.splice(index, 1);\n }\n return this;\n }\n\n /**\n * \n * @returns {{extends?: string, profiles?: Array, paths?: Array}} The service configuration.\n */\n getServiceConfiguration() {\n if (this.serviceConfiguration) {\n return this.serviceConfiguration;\n }\n let serviceConfiguration = {\n profiles: [],\n paths: []\n };\n // get service configuration\n const serviceConfigurationSource = this.getApplication().getConfiguration().getSourceAt('settings/universis/janitor/speedLimit');\n if (serviceConfigurationSource) {\n if (typeof serviceConfigurationSource.extends === 'string') {\n // get additional configuration\n const configurationPath = this.getApplication().getConfiguration().getConfigurationPath();\n const extendsPath = path.resolve(configurationPath, serviceConfigurationSource.extends);\n TraceUtils.log(`${this.getServiceName()} will try to extend service configuration using ${extendsPath}`);\n serviceConfiguration = Object.assign({}, {\n profiles: [],\n paths: []\n }, require(extendsPath));\n } else {\n TraceUtils.log(`${this.getServiceName()} will use service configuration from settings/universis/janitor/speedLimit`);\n serviceConfiguration = Object.assign({}, {\n profiles: [],\n paths: []\n }, serviceConfigurationSource);\n }\n }\n const profilesArray = serviceConfiguration.profiles || [];\n serviceConfiguration.profiles = new Map(profilesArray);\n const pathsArray = serviceConfiguration.paths || [];\n serviceConfiguration.paths = new Map(pathsArray);\n\n Object.defineProperty(this, 'serviceConfiguration', {\n value: serviceConfiguration,\n writable: false,\n enumerable: false,\n configurable: true\n });\n return this.serviceConfiguration;\n }\n\n}","import { TraceUtils } from '@themost/common';\nimport { RedisStore } from 'rate-limit-redis';\nimport { Redis } from 'ioredis';\nimport '@themost/promise-sequence';\n\nlet superLoadIncrementScript;\nlet superLoadGetScript;\n\nfunction noLoadGetScript() {\n //\n}\n\nfunction noLoadIncrementScript() {\n //\n}\n\nif (RedisStore.prototype.loadIncrementScript.name === 'loadIncrementScript') {\n // get super method for future use\n superLoadIncrementScript = RedisStore.prototype.loadIncrementScript;\n RedisStore.prototype.loadIncrementScript = noLoadIncrementScript;\n}\n\nif (RedisStore.prototype.loadGetScript.name === 'loadGetScript') {\n // get super method\n superLoadGetScript = RedisStore.prototype.loadGetScript;\n RedisStore.prototype.loadGetScript = noLoadGetScript;\n}\n\nclass RedisClientStore extends RedisStore {\n\n /**\n * @type {import('redis').RedisClientType}\n */\n client;\n\n /**\n * \n * @param {import('@themost/common').ApplicationService} service\n * @param {{windowMs: number}} options\n */\n constructor(service, options) {\n super({\n /**\n * @param {...string} args\n * @returns {Promise<*>}\n */\n sendCommand: function () {\n const args = Array.from(arguments);\n const [command] = args.splice(0, 1);\n const self = this;\n if (command === 'SCRIPT') {\n const connectOptions = service.getApplication().getConfiguration().getSourceAt('settings/redis/options') || {\n host: '127.0.0.1',\n port: 6379\n };\n const client = new Redis(connectOptions);\n return client.call(command, args).catch((error) => {\n if (error instanceof TypeError && error.message === 'Invalid argument type') {\n TraceUtils.warn('RedisClientStore: Invalid argument type: ' + JSON.stringify(args));\n }\n return Promise.reject(error);\n }).finally(() => {\n if (client.isOpen) {\n client.disconnect().catch((errDisconnect) => {\n TraceUtils.error(errDisconnect);\n });\n }\n });\n }\n if (self.client == null) {\n const connectOptions = service.getApplication().getConfiguration().getSourceAt('settings/redis/options') || {\n host: '127.0.0.1',\n port: 6379\n };\n self.client = new Redis(connectOptions);\n }\n if (self.client.isOpen) {\n return self.client.call(command, args).catch((error) => {\n if (error instanceof TypeError && error.message === 'Invalid argument type') {\n TraceUtils.warn('RedisClientStore: Invalid argument type: ' + JSON.stringify(args));\n }\n return Promise.reject(error);\n });\n }\n // send load script commands once\n return (() => {\n if (self.incrementScriptSha == null) {\n return this.postInit();\n }\n return Promise.resolve();\n })().then(() => {\n // send command \n args[0] = self.incrementScriptSha;\n return self.client.call(command, args).catch((error) => {\n if (error instanceof TypeError && error.message === 'Invalid argument type') {\n TraceUtils.warn('RedisClientStore: Invalid argument type: ' + JSON.stringify(args));\n }\n return Promise.reject(error);\n });\n });\n }\n });\n this.init(options);\n TraceUtils.debug('RedisClientStore: Starting up and loading increment and get scripts.');\n void this.postInit().then(() => {\n TraceUtils.debug('RedisClientStore: Successfully loaded increment and get scripts.');\n }).catch((err) => {\n TraceUtils.error('RedisClientStore: Failed to load increment and get scripts.');\n TraceUtils.error(err);\n });\n }\n async postInit() {\n const [incrementScriptSha, getScriptSha] = await Promise.sequence([\n () => superLoadIncrementScript.call(this),\n () => superLoadGetScript.call(this)\n ]);\n this.incrementScriptSha = incrementScriptSha;\n this.getScriptSha = getScriptSha;\n }\n\n}\n\nexport {\n RedisClientStore\n}","\nimport {ConfigurationStrategy, Args, ApplicationService} from '@themost/common';\nimport path from 'path';\nimport url from 'url';\n\nconst HTTP_METHOD_REGEXP = /^\\b(POST|PUT|PATCH|DELETE)\\b$/i;\n\nclass ScopeString {\n constructor(str) {\n this.value = str;\n }\n toString() {\n return this.value;\n }\n /**\n * Splits a comma-separated or space-separated scope string e.g. \"profile email\" or \"profile,email\"\n *\n * Important note: https://www.rfc-editor.org/rfc/rfc6749#section-3.3 defines the regular expression of access token scopes\n * which is a space separated string. Several OAuth2 servers use a comma-separated list instead.\n *\n * The operation will try to use both implementations by excluding comma ',' from access token regular expressions\n * @returns {Array<string>}\n */\n split() {\n // the default regular expression includes comma /([\\x21\\x23-\\x5B\\x5D-\\x7E]+)/g\n // the modified regular expression excludes comma /x2C /([\\x21\\x23-\\x2B\\x2D-\\x5B\\x5D-\\x7E]+)/g\n const re = /([\\x21\\x23-\\x2B\\x2D-\\x5B\\x5D-\\x7E]+)/g\n const results = [];\n let match = re.exec(this.value);\n while(match !== null) {\n results.push(match[0]);\n match = re.exec(this.value);\n }\n return results;\n }\n}\n\nclass ScopeAccessConfiguration extends ConfigurationStrategy {\n /**\n * @param {import('@themost/common').ConfigurationBase} configuration\n */\n constructor(configuration) {\n super(configuration);\n let elements = [];\n // define property\n Object.defineProperty(this, 'elements', {\n get: () => {\n return elements;\n },\n enumerable: true\n });\n }\n\n /**\n * @param {Request} req\n * @returns Promise<ScopeAccessConfigurationElement>\n */\n verify(req) {\n return new Promise((resolve, reject) => {\n try {\n // validate request context\n Args.notNull(req.context,'Context');\n // validate request context user\n Args.notNull(req.context.user,'User');\n if (req.context.user.authenticationScope && req.context.user.authenticationScope.length>0) {\n // get original url\n let reqUrl = url.parse(req.originalUrl).pathname;\n // get user context scopes as array e.g, ['students', 'students:read']\n let reqScopes = new ScopeString(req.context.user.authenticationScope).split();\n // get user access based on HTTP method e.g. GET -> read access\n let reqAccess = HTTP_METHOD_REGEXP.test(req.method) ? 'write' : 'read';\n // first phase: find element by resource and scope\n let result = this.elements.find(x => {\n // filter element by access level\n return new RegExp( \"^\" + x.resource, 'i').test(reqUrl)\n // and scopes\n && x.scope.find(y => {\n // search user scopes (validate wildcard scope)\n return y === \"*\" || reqScopes.indexOf(y)>=0;\n });\n });\n // second phase: check access level\n if (result == null) {\n return resolve();\n }\n // if access is missing or access is not an array\n if (Array.isArray(result.access) === false) {\n // the requested access is not allowed because the access is not defined\n return resolve();\n }\n // if the requested access is not in the access array\n if (result.access.indexOf(reqAccess) < 0) {\n // the requested access is not allowed because the access levels do not match\n return resolve();\n }\n // otherwise, return result\n return resolve(result);\n }\n return resolve();\n }\n catch(err) {\n return reject(err);\n }\n\n });\n }\n\n}\n\n/**\n * @class\n */\nclass DefaultScopeAccessConfiguration extends ScopeAccessConfiguration {\n /**\n * @param {import('@themost/common').ConfigurationBase} configuration\n */\n constructor(configuration) {\n super(configuration);\n let defaults = [];\n // load scope access from configuration resource\n try {\n /**\n * @type {Array<ScopeAccessConfigurationElement>}\n */\n defaults = require(path.resolve(configuration.getConfigurationPath(), 'scope.access.json'));\n }\n catch(err) {\n // if an error occurred other than module not found (there are no default access policies)\n if (err.code !== 'MODULE_NOT_FOUND') {\n // throw error\n throw err;\n }\n // otherwise continue\n }\n this.elements.push.apply(this.elements, defaults);\n }\n}\n\nclass EnableScopeAccessConfiguration extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase} app \n */\n constructor(app) {\n super(app);\n // register scope access configuration\n app.getConfiguration().useStrategy(ScopeAccessConfiguration, DefaultScopeAccessConfiguration);\n }\n}\n\n\n/**\n * @class\n */\nclass ExtendScopeAccessConfiguration extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase} app\n */\n constructor(app) {\n super(app);\n // Get the additional scope access extensions from the configuration\n const scopeAccessExtensions = app.getConfiguration().settings.universis?.janitor?.scopeAccess.imports;\n if (app && app.container && scopeAccessExtensions != null) {\n app.container.subscribe((container) => {\n if (container) {\n const scopeAccess = app.getConfiguration().getStrategy(function ScopeAccessConfiguration() { });\n if (scopeAccess != null) {\n for (const scopeAccessExtension of scopeAccessExtensions) {\n try {\n const elements = require(path.resolve(app.getConfiguration().getConfigurationPath(), scopeAccessExtension));\n if (elements) {\n // add extra scope access elements\n scopeAccess.elements.unshift(...elements);\n }\n }\n catch(err) {\n // if an error occurred other than module not found (there are no default access policies)\n if (err.code !== 'MODULE_NOT_FOUND') {\n // throw error\n throw err;\n }\n }\n }\n }\n }\n });\n }\n }\n}\n\nexport {\n ScopeString,\n ScopeAccessConfiguration,\n DefaultScopeAccessConfiguration,\n EnableScopeAccessConfiguration,\n ExtendScopeAccessConfiguration\n}\n","import { ScopeAccessConfiguration } from './ScopeAccessConfiguration';\nimport {HttpForbiddenError} from '@themost/common';\n\nfunction validateScope() {\n return (req, res, next) => {\n /**\n * @type {ScopeAccessConfiguration}\n */\n let scopeAccessConfiguration = req.context.getApplication().getConfiguration().getStrategy(ScopeAccessConfiguration);\n if (typeof scopeAccessConfiguration === 'undefined') {\n return next(new Error('Invalid application configuration. Scope access configuration strategy is missing or is in accessible.'));\n }\n scopeAccessConfiguration.verify(req).then(value => {\n if (value) {\n return next();\n }\n return next(new HttpForbiddenError('Access denied due to authorization scopes.'))\n }).catch(reason => {\n return next(reason);\n });\n };\n}\n\nexport {\n validateScope\n}\n","import {Request} from 'superagent'\nimport {URL} from 'url';\nimport {ApplicationService, DataError, HttpError} from '@themost/common';\n\nfunction responseHander(resolve, reject) {\n return function (err, response) {\n if (err) {\n /**\n * @type {import('superagent').Response}\n */\n const response = err.response\n if (response && response.headers['content-type'] === 'application/json') {\n // get body\n const clientError = response.body;\n const error = new HttpError(response.status);\n return reject(Object.assign(error, {\n clientError\n }));\n }\n return reject(err);\n }\n if (response.status === 204 && response.headers['content-type'] === 'application/json') {\n return resolve(null);\n }\n return resolve(response.body);\n };\n}\n\n/**\n * @class\n */\nclass OAuth2ClientService extends ApplicationService {\n /**\n * @param {import('@themost/express').ExpressDataApplication} app\n */\n constructor(app) {\n super(app);\n /**\n * @name OAuth2ClientService#settings\n * @type {{server_uri:string,token_uri?:string}}\n */\n Object.defineProperty(this, 'settings', {\n writable: false,\n value: app.getConfiguration().getSourceAt('settings/auth'),\n enumerable: false,\n configurable: false\n });\n }\n\n /**\n * Gets keycloak server root\n * @returns {string}\n */\n getServer() {\n return this.settings.server_uri;\n }\n\n /**\n * Gets keycloak server root\n * @returns {string}\n */\n getAdminRoot() {\n return this.settings.admin_uri;\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * Gets user's profile by calling OAuth2 server profile endpoint\n * @param {ExpressDataContext} context\n * @param {string} token\n */\n getUserInfo(token) {\n return new Promise((resolve, reject) => {\n const userinfo_uri = this.settings.userinfo_uri ? new URL(this.settings.userinfo_uri, this.getServer()) : new URL('me', this.getServer());\n return new Request('GET', userinfo_uri)\n .set({\n 'Authorization': `Bearer ${token}`,\n 'Accept': 'application/json'\n })\n .query({\n 'access_token':token\n }).end(responseHander(resolve, reject));\n });\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * Gets the token info of the current context\n * @param {ExpressDataContext} context\n */\n getContextTokenInfo(context) {\n if (context.user == null) {\n return Promise.reject(new Error('Context user may not be null'));\n }\n if (context.user.authenticationType !== 'Bearer') {\n return Promise.reject(new Error('Invalid context authentication type'));\n }\n if (context.user.authenticationToken == null) {\n return Promise.reject(new Error('Context authentication data may not be null'));\n }\n return this.getTokenInfo(context, context.user.authenticationToken);\n }\n /**\n * Gets token info by calling OAuth2 server endpoint\n * @param {ExpressDataContext} _context\n * @param {string} token\n */\n getTokenInfo(_context, token) {\n return new Promise((resolve, reject) => {\n const introspection_uri = this.settings.introspection_uri ? new URL(this.settings.introspection_uri, this.getServer()) : new URL('tokeninfo', this.getServer());\n return new Request('POST', introspection_uri)\n .auth(this.settings.client_id, this.settings.client_secret)\n .set('Accept', 'application/json')\n .type('form')\n .send({\n 'token_type_hint': 'access_token',\n 'token': token,\n }).end(responseHander(resolve, reject));\n });\n }\n\n /**\n * @param {AuthorizeUser} authorizeUser\n */\n authorize(authorizeUser) {\n const tokenURL = this.settings.token_uri ? new URL(this.settings.token_uri) : new URL('authorize', this.getServer());\n return new Promise((resolve, reject)=> {\n return new Request('POST', tokenURL)\n .type('form')\n .send(authorizeUser).end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Gets a user by name\n * @param {*} user_id \n * @param {AdminMethodOptions} options \n */\n getUserById(user_id, options) {\n return new Promise((resolve, reject) => {\n return new Request('GET', new URL(`users/${user_id}`, this.getAdminRoot()))\n .set('Authorization', `Bearer ${options.access_token}`)\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Gets a user by name\n * @param {string} username \n * @param {AdminMethodOptions} options \n */\n getUser(username, options) {\n return new Promise((resolve, reject)=> {\n return new Request('GET', new URL('users', this.getAdminRoot()))\n .set('Authorization', `Bearer ${options.access_token}`)\n .query({\n '$filter': `name eq '${username}'`\n })\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Gets a user by email address\n * @param {string} email \n * @param {AdminMethodOptions} options \n */\n getUserByEmail(email, options) {\n return new Promise((resolve, reject)=> {\n return new Request('GET', new URL('users', this.getAdminRoot()))\n .set('Authorization', `Bearer ${options.access_token}`)\n .query({\n '$filter': `alternateName eq '${email}'`\n })\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Updates an existing user\n * @param {*} user \n * @param {AdminMethodOptions} options \n */\n updateUser(user, options) {\n return new Promise((resolve, reject)=> {\n if (user.id == null) {\n return reject(new DataError('E_IDENTIFIER', 'User may not be empty at this context.', null, 'User', 'id'));\n }\n const request = new Request('PUT', new URL(`users/${user.id}`, this.getAdminRoot()));\n return request.set('Authorization', `Bearer ${options.access_token}`)\n .set('Content-Type', 'application/json')\n .send(user)\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Creates a new user\n * @param {*} user \n * @param {AdminMethodOptions} options \n */\n createUser(user, options) {\n return new Promise((resolve, reject)=> {\n const request = new Request('POST', new URL('users', this.getAdminRoot()));\n return request.set('Authorization', `Bearer ${options.access_token}`)\n .set('Content-Type', 'application/json')\n .send(Object.assign({}, user, {\n $state: 1 // for create\n }))\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * Deletes a user\n * @param {{id: any}} user \n * @param {AdminMethodOptions} options \n */\n deleteUser(user, options) {\n return new Promise((resolve, reject)=> {\n if (user.id == null) {\n return reject(new DataError('E_IDENTIFIER', 'User may not be empty at this context.', null, 'User', 'id'));\n }\n const request = new Request('DELETE', new URL(`users/${user.id}`, this.getAdminRoot()));\n return request.set('Authorization', `Bearer ${options.access_token}`)\n .end(responseHander(resolve, reject));\n });\n }\n\n /**\n * @param {boolean=} force \n * @returns {*}\n */\n getWellKnownConfiguration(force) {\n if (force) {\n this.well_known_configuration = null;\n }\n if (this.well_known_configuration) {\n return Promise.resolve(this.well_known_configuration);\n }\n return new Promise((resolve, reject) => {\n const well_known_configuration_uri = this.settings.well_known_configuration_uri ? new URL(this.settings.well_known_configuration_uri, this.getServer()) : new URL('.well-known/openid-configuration', this.getServer());\n return new Request('GET', well_known_configuration_uri)\n .end(responseHander(resolve, reject));\n }).then((configuration) => {\n this.well_known_configuration = configuration;\n return configuration;\n });\n }\n}\n\nexport {\n OAuth2ClientService\n}\n\n","import { ApplicationService, HttpForbiddenError, TraceUtils } from '@themost/common';\nimport express from 'express';\nimport jwt from 'jsonwebtoken';\n\nclass HttpRemoteAddrForbiddenError extends HttpForbiddenError {\n constructor() {\n super('Access is denied due to remote address conflict. The client network has been changed or cannot be determined.');\n this.statusCode = 403.6;\n }\n \n}\n\nclass RemoteAddressValidator extends ApplicationService {\n constructor(app) {\n super(app);\n\n // get proxy address forwarding option\n let proxyAddressForwarding = app.getConfiguration().getSourceAt('settings/universis/api/proxyAddressForwarding');\n if (typeof proxyAddressForwarding !== 'boolean') {\n proxyAddressForwarding = false;\n }\n this.proxyAddressForwarding = proxyAddressForwarding;\n // get token claim name\n this.claim = app.getConfiguration().getSourceAt('settings/universis/janitor/remoteAddress/claim') || 'remoteAddress';\n\n app.serviceRouter.subscribe((serviceRouter) => {\n if (serviceRouter == null) {\n return;\n }\n const addRouter = express.Router();\n addRouter.use((req, res, next) => {\n void this.validateRemoteAddress(req).then((value) => {\n if (value === false) {\n return next(new HttpRemoteAddrForbiddenError());\n }\n return next();\n }).catch((err) => {\n return next(err);\n });\n });\n // insert router at the beginning of serviceRouter.stack\n serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);\n });\n }\n\n /**\n * Gets remote address from request\n * @param {import('express').Request} req \n * @returns \n */\n getRemoteAddress(req) {\n let remoteAddress;\n if (this.proxyAddressForwarding) {\n // get proxy headers or remote address\n remoteAddress = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\n } else {\n remoteAddress = req.connection ? req.connection.remoteAddress : req.socket.remoteAddress;\n }\n return remoteAddress;\n }\n\n /**\n * Validates token remote address with request remote address\n * @param {import('express').Request} req \n * @returns {Promise<boolean>}\n */\n async validateRemoteAddress(req) {\n const authenticationToken = req.context?.user?.authenticationToken;\n if (authenticationToken != null) {\n const access_token = jwt.decode(authenticationToken);\n const remoteAddress = access_token[this.claim];\n if (remoteAddress == null) {\n TraceUtils.warn(`Remote address validation failed. Expected a valid remote address claimed by using \"${this.claim}\" attribute but got none.`);\n return false;\n }\n // get context remote address\n const requestRemoteAddress = this.getRemoteAddress(req);\n if (remoteAddress !== requestRemoteAddress) {\n TraceUtils.warn(`Remote address validation failed. Expected remote address is ${remoteAddress || 'Uknown'} but request remote address is ${requestRemoteAddress}`);\n return false;\n }\n return true;\n }\n TraceUtils.warn('Remote address validation cannot be completed because authentication token is not available.');\n return false;\n }\n\n}\n\nexport {\n HttpRemoteAddrForbiddenError,\n RemoteAddressValidator\n}\n","import { RateLimitService } from './RateLimitService';\n\nclass AppRateLimitService extends RateLimitService {\n /**\n * \n * @param {import('@themost/common').ApplicationBase} app \n */\n constructor(app) {\n super(app);\n }\n\n getServiceName() {\n return '@universis/janitor#AppRateLimitService';\n }\n\n getServiceContainer() {\n return this.getApplication() && this.getApplication().container;\n }\n}\n\nexport { AppRateLimitService };","import { SpeedLimitService } from './SpeedLimitService';\n\nclass AppSpeedLimitService extends SpeedLimitService {\n /**\n * \n * @param {import('@themost/common').ApplicationBase} app \n */\n constructor(app) {\n super(app);\n }\n\n getServiceName() {\n return '@universis/janitor#AppSpeedLimitService';\n }\n\n getServiceContainer() {\n return this.getApplication() && this.getApplication().container;\n }\n}\n\nexport { AppSpeedLimitService };"],"names":["RateLimitService","ApplicationService","constructor","app","proxyAddressForwarding","getConfiguration","getSourceAt","loaded","BehaviorSubject","serviceContainer","getServiceContainer","TraceUtils","warn","getServiceName","subscribe","router","Object","defineProperty","value","express","Router","writable","enumerable","configurable","serviceConfiguration","getServiceConfiguration","paths","size","forEach","path","set","stack","unshift","apply","use","_router","Array","isArray","index","findIndex","item","name","splice","pop","next","target","err","error","getApplication","serviceRouter","profiles","serviceConfigurationSource","extends","configurationPath","getConfigurationPath","extendsPath","resolve","log","assign","require","pathsArray","profilesArray","Map","options","opts","profile","get","rateLimitOptions","windowMs","limit","legacyHeaders","keyGenerator","req","remoteAddress","headers","connection","socket","store","StoreClass","getStoreType","rateLimit","storeType","split","length","storeModule","prototype","hasOwnProperty","call","Error","unset","layer","route","SpeedLimitService","slowDownOptions","delayAfter","delayMs","maxDelayMs","randomDelayMs","Math","floor","random","randomMaxDelayMs","slowDown","superLoadIncrementScript","superLoadGetScript","noLoadGetScript","noLoadIncrementScript","RedisStore","loadIncrementScript","loadGetScript","RedisClientStore","service","sendCommand","args","from","arguments","command","self","connectOptions","host","port","client","Redis","catch","TypeError","message","JSON","stringify","Promise","reject","finally","isOpen","disconnect","errDisconnect","incrementScriptSha","postInit","then","_defineProperty","init","debug","getScriptSha","sequence","HTTP_METHOD_REGEXP","ScopeString","str","toString","re","results","match","exec","push","ScopeAccessConfiguration","ConfigurationStrategy","configuration","elements","verify","Args","notNull","context","user","authenticationScope","reqUrl","url","parse","originalUrl","pathname","reqScopes","reqAccess","test","method","result","find","x","RegExp","resource","scope","y","indexOf","access","DefaultScopeAccessConfiguration","defaults","code","EnableScopeAccessConfiguration","useStrategy","ExtendScopeAccessConfiguration","scopeAccessExtensions","settings","universis","janitor","scopeAccess","imports","container","getStrategy","scopeAccessExtension","validateScope","res","scopeAccessConfiguration","HttpForbiddenError","reason","responseHander","response","clientError","body","HttpError","status","OAuth2ClientService","getServer","server_uri","getAdminRoot","admin_uri","getUserInfo","token","userinfo_uri","URL","Request","query","end","getContextTokenInfo","authenticationType","authenticationToken","getTokenInfo","_context","introspection_uri","auth","client_id","client_secret","type","send","authorize","authorizeUser","tokenURL","token_uri","getUserById","user_id","access_token","getUser","username","getUserByEmail","email","updateUser","id","DataError","request","createUser","$state","deleteUser","getWellKnownConfiguration","force","well_known_configuration","well_known_configuration_uri","HttpRemoteAddrForbiddenError","statusCode","RemoteAddressValidator","claim","addRouter","validateRemoteAddress","getRemoteAddress","jwt","decode","requestRemoteAddress","AppRateLimitService","AppSpeedLimitService"],"mappings":";;;;;;;;;;;;;;AAMO,MAAMA,gBAAgB,SAASC,kBAAkB,CAAC;AACrD;AACJ;AACA;EACIC,WAAWA,CAACC,GAAG,EAAE;IACb,KAAK,CAACA,GAAG,CAAC;;AAEV;IACA,MAAMC,sBAAsB,GAAGD,GA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