@universis/janitor 1.0.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/.gitlab-ci.yml ADDED
@@ -0,0 +1,31 @@
1
+ image: node:14
2
+
3
+ stages:
4
+ - releases
5
+ - deploy
6
+
7
+ npm_publish:
8
+ stage: releases
9
+ only:
10
+ - /^(\d+\.)(\d+\.)(\d+)$/
11
+ except:
12
+ - branches
13
+ script:
14
+ - npm i
15
+ - npm run build
16
+ - echo //registry.npmjs.org/:_authToken=$NPM_TOKEN > .npmrc
17
+ - npm publish --access=public
18
+ - rm .npmrc
19
+
20
+ pages:
21
+ stage: deploy
22
+ script:
23
+ - mkdir .public
24
+ - cp -r * .public
25
+ - mv .public public
26
+ artifacts:
27
+ paths:
28
+ - public
29
+ rules:
30
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
31
+
package/LICENSE ADDED
@@ -0,0 +1,163 @@
1
+ GNU Lesser General Public License
2
+ =================================
3
+
4
+ _Version 3, 29 June 2007_
5
+ _Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies
8
+ of this license document, but changing it is not allowed.
9
+
10
+
11
+ This version of the GNU Lesser General Public License incorporates
12
+ the terms and conditions of version 3 of the GNU General Public
13
+ License, supplemented by the additional permissions listed below.
14
+
15
+ ### 0. Additional Definitions
16
+
17
+ As used herein, “this License” refers to version 3 of the GNU Lesser
18
+ General Public License, and the “GNU GPL” refers to version 3 of the GNU
19
+ General Public License.
20
+
21
+ “The Library” refers to a covered work governed by this License,
22
+ other than an Application or a Combined Work as defined below.
23
+
24
+ An “Application” is any work that makes use of an interface provided
25
+ by the Library, but which is not otherwise based on the Library.
26
+ Defining a subclass of a class defined by the Library is deemed a mode
27
+ of using an interface provided by the Library.
28
+
29
+ A “Combined Work” is a work produced by combining or linking an
30
+ Application with the Library. The particular version of the Library
31
+ with which the Combined Work was made is also called the “Linked
32
+ Version”.
33
+
34
+ The “Minimal Corresponding Source” for a Combined Work means the
35
+ Corresponding Source for the Combined Work, excluding any source code
36
+ for portions of the Combined Work that, considered in isolation, are
37
+ based on the Application, and not on the Linked Version.
38
+
39
+ The “Corresponding Application Code” for a Combined Work means the
40
+ object code and/or source code for the Application, including any data
41
+ and utility programs needed for reproducing the Combined Work from the
42
+ Application, but excluding the System Libraries of the Combined Work.
43
+
44
+ ### 1. Exception to Section 3 of the GNU GPL
45
+
46
+ You may convey a covered work under sections 3 and 4 of this License
47
+ without being bound by section 3 of the GNU GPL.
48
+
49
+ ### 2. Conveying Modified Versions
50
+
51
+ If you modify a copy of the Library, and, in your modifications, a
52
+ facility refers to a function or data to be supplied by an Application
53
+ that uses the facility (other than as an argument passed when the
54
+ facility is invoked), then you may convey a copy of the modified
55
+ version:
56
+
57
+ * **a)** under this License, provided that you make a good faith effort to
58
+ ensure that, in the event an Application does not supply the
59
+ function or data, the facility still operates, and performs
60
+ whatever part of its purpose remains meaningful, or
61
+
62
+ * **b)** under the GNU GPL, with none of the additional permissions of
63
+ this License applicable to that copy.
64
+
65
+ ### 3. Object Code Incorporating Material from Library Header Files
66
+
67
+ The object code form of an Application may incorporate material from
68
+ a header file that is part of the Library. You may convey such object
69
+ code under terms of your choice, provided that, if the incorporated
70
+ material is not limited to numerical parameters, data structure
71
+ layouts and accessors, or small macros, inline functions and templates
72
+ (ten or fewer lines in length), you do both of the following:
73
+
74
+ * **a)** Give prominent notice with each copy of the object code that the
75
+ Library is used in it and that the Library and its use are
76
+ covered by this License.
77
+ * **b)** Accompany the object code with a copy of the GNU GPL and this license
78
+ document.
79
+
80
+ ### 4. Combined Works
81
+
82
+ You may convey a Combined Work under terms of your choice that,
83
+ taken together, effectively do not restrict modification of the
84
+ portions of the Library contained in the Combined Work and reverse
85
+ engineering for debugging such modifications, if you also do each of
86
+ the following:
87
+
88
+ * **a)** Give prominent notice with each copy of the Combined Work that
89
+ the Library is used in it and that the Library and its use are
90
+ covered by this License.
91
+
92
+ * **b)** Accompany the Combined Work with a copy of the GNU GPL and this license
93
+ document.
94
+
95
+ * **c)** For a Combined Work that displays copyright notices during
96
+ execution, include the copyright notice for the Library among
97
+ these notices, as well as a reference directing the user to the
98
+ copies of the GNU GPL and this license document.
99
+
100
+ * **d)** Do one of the following:
101
+ - **0)** Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+ - **1)** Use a suitable shared library mechanism for linking with the
109
+ Library. A suitable mechanism is one that **(a)** uses at run time
110
+ a copy of the Library already present on the user's computer
111
+ system, and **(b)** will operate properly with a modified version
112
+ of the Library that is interface-compatible with the Linked
113
+ Version.
114
+
115
+ * **e)** Provide Installation Information, but only if you would otherwise
116
+ be required to provide such information under section 6 of the
117
+ GNU GPL, and only to the extent that such information is
118
+ necessary to install and execute a modified version of the
119
+ Combined Work produced by recombining or relinking the
120
+ Application with a modified version of the Linked Version. (If
121
+ you use option **4d0**, the Installation Information must accompany
122
+ the Minimal Corresponding Source and Corresponding Application
123
+ Code. If you use option **4d1**, you must provide the Installation
124
+ Information in the manner specified by section 6 of the GNU GPL
125
+ for conveying Corresponding Source.)
126
+
127
+ ### 5. Combined Libraries
128
+
129
+ You may place library facilities that are a work based on the
130
+ Library side by side in a single library together with other library
131
+ facilities that are not Applications and are not covered by this
132
+ License, and convey such a combined library under terms of your
133
+ choice, if you do both of the following:
134
+
135
+ * **a)** Accompany the combined library with a copy of the same work based
136
+ on the Library, uncombined with any other library facilities,
137
+ conveyed under the terms of this License.
138
+ * **b)** Give prominent notice with the combined library that part of it
139
+ is a work based on the Library, and explaining where to find the
140
+ accompanying uncombined form of the same work.
141
+
142
+ ### 6. Revised Versions of the GNU Lesser General Public License
143
+
144
+ The Free Software Foundation may publish revised and/or new versions
145
+ of the GNU Lesser General Public License from time to time. Such new
146
+ versions will be similar in spirit to the present version, but may
147
+ differ in detail to address new problems or concerns.
148
+
149
+ Each version is given a distinguishing version number. If the
150
+ Library as you received it specifies that a certain numbered version
151
+ of the GNU Lesser General Public License “or any later version”
152
+ applies to it, you have the option of following the terms and
153
+ conditions either of that published version or of any later version
154
+ published by the Free Software Foundation. If the Library as you
155
+ received it does not specify a version number of the GNU Lesser
156
+ General Public License, you may choose any version of the GNU Lesser
157
+ General Public License ever published by the Free Software Foundation.
158
+
159
+ If the Library as you received it specifies that a proxy can decide
160
+ whether future versions of the GNU Lesser General Public License shall
161
+ apply, that proxy's public statement of acceptance of any version is
162
+ permanent authorization for you to choose that version for the
163
+ Library.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # @universis/janitor
2
+
3
+ ![@universis/janitor logo](./public/janitor-logo-text.png)
4
+
5
+ Universis api plugin for rate limiting requests or slowing down service responses.
6
+
7
+ ## Usage
8
+
9
+ npm i @universis/janitor
10
+
11
+ ## RateLimitService
12
+
13
+ `RateLimitService` is a configurable extension of [express-rate-limit](https://www.npmjs.com/package/express-rate-limit) for limiting service requests.
14
+
15
+ Register service under application services:
16
+
17
+ ```json
18
+ {
19
+ "services": [
20
+ {
21
+ "serviceType": "@universis/janitor#RateLimitService"
22
+ }
23
+ ]
24
+ }
25
+ ```
26
+ and start configuring rate limited endpoints under `settings/universis/rateLimit`:
27
+
28
+ ```json
29
+ {
30
+ "settings": {
31
+ "universis": {
32
+ "rateLimit": {
33
+ "profiles": [
34
+ [
35
+ "userRateLimitProfile",
36
+ {
37
+ "windowMs": 300000,
38
+ "limit": 50,
39
+ "legacyHeaders": true
40
+ }
41
+ ]
42
+ ],
43
+ "paths": [
44
+ [
45
+ "/users/me",
46
+ {
47
+ "profile": "userRateLimitProfile"
48
+ }
49
+ ]
50
+ ]
51
+ }
52
+ }
53
+ }
54
+ }
55
+ ```
56
+
57
+ `RateLimitService` service configuration consists of a collection of rate limit `profiles` that are going to used as options during request validation and a collection of `paths` for defining rate limited route paths.
58
+
59
+ Read more about rate limit configuration at [express-rate-limit documentation](https://github.com/express-rate-limit/express-rate-limit#configuration)
60
+
61
+
62
+ ## SpeedLimitService
63
+
64
+ `SpeedLimitService` is a configurable extension of [express-slow-down](https://www.npmjs.com/package/express-slow-down) for slowing down service responses.
65
+
66
+ Register service under application services:
67
+
68
+ ```json
69
+ {
70
+ "services": [
71
+ {
72
+ "serviceType": "@universis/janitor#SpeedLimitService"
73
+ }
74
+ ]
75
+ }
76
+ ```
77
+ and start configuring speed limited endpoints under `settings/universis/speedLimit`:
78
+
79
+ ```json
80
+ {
81
+ "settings": {
82
+ "universis": {
83
+ "speedLimit": {
84
+ "profiles": [
85
+ [
86
+ "userSpeedLimitProfile",
87
+ {
88
+ "windowMs": 300000,
89
+ "delayAfter": 5,
90
+ "delayMs": 500,
91
+ "maxDelayMs": 20000,
92
+ "headers": true
93
+ }
94
+ ]
95
+ ],
96
+ "paths": [
97
+ [
98
+ "/users/me",
99
+ {
100
+ "profile": "userSpeedLimitProfile"
101
+ }
102
+ ]
103
+ ]
104
+ }
105
+ }
106
+ }
107
+ }
108
+ ```
109
+
110
+ `SpeedLimitService` configuration consists of a collection of speed limit `profiles` that are going to used as options during request validation and a collection of `paths` for defining speed limited route paths.
111
+
112
+ Read more about speed limit configuration at [express-slow-down documentation](https://github.com/express-rate-limit/express-slow-down#configuration)
113
+
@@ -0,0 +1,71 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.RateLimitService = void 0;var _common = require("@themost/common");
2
+ var _expressRateLimit = require("express-rate-limit");
3
+ var _express = _interopRequireDefault(require("express"));
4
+ var _path = _interopRequireDefault(require("path"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
5
+
6
+ class RateLimitService extends _common.ApplicationService {
7
+ /**
8
+ * @param {import('@themost/express').ExpressDataApplication} app
9
+ */
10
+ constructor(app) {
11
+ super(app);
12
+ app.serviceRouter.subscribe((serviceRouter) => {
13
+ if (serviceRouter == null) {
14
+ return;
15
+ }
16
+ try {
17
+ const addRouter = _express.default.Router();
18
+ let serviceConfiguration = app.getConfiguration().getSourceAt('settings/universis/janitor/rateLimit') || {
19
+ profiles: [],
20
+ paths: []
21
+ };
22
+ if (serviceConfiguration.extends) {
23
+ // get additional configuration
24
+ const configurationPath = app.getConfiguration().getConfigurationPath();
25
+ const extendsPath = _path.default.resolve(configurationPath, serviceConfiguration.extends);
26
+ _common.TraceUtils.log(`@universis/janitor#RateLimitService will try to extend service configuration from ${extendsPath}`);
27
+ serviceConfiguration = require(extendsPath);
28
+ }
29
+ const pathsArray = serviceConfiguration.paths || [];
30
+ const profilesArray = serviceConfiguration.profiles || [];
31
+ // create maps
32
+ const paths = new Map(pathsArray);
33
+ const profiles = new Map(profilesArray);
34
+ if (paths.size === 0) {
35
+ _common.TraceUtils.warn('@universis/janitor#RateLimitService is being started but the collection of paths is empty.');
36
+ }
37
+ paths.forEach((value, path) => {
38
+ let profile;
39
+ // get profile
40
+ if (value.profile) {
41
+ profile = profiles.get(value.profile);
42
+ } else {
43
+ // or options defined inline
44
+ profile = value;
45
+ }
46
+ if (profile != null) {
47
+ const rateLimitOptions = Object.assign({
48
+ windowMs: 5 * 60 * 1000, // 5 minutes
49
+ limit: 50, // 50 requests
50
+ legacyHeaders: true // send headers
51
+ }, profile, {
52
+ keyGenerator: (req) => {
53
+ return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);
54
+ }
55
+ });
56
+ addRouter.use(path, (0, _expressRateLimit.rateLimit)(rateLimitOptions));
57
+ }
58
+ });
59
+ if (addRouter.stack.length) {
60
+ serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);
61
+ }
62
+ } catch (err) {
63
+ _common.TraceUtils.error('An error occurred while validating rate limit configuration.');
64
+ _common.TraceUtils.error(err);
65
+ _common.TraceUtils.warn('Rate limit service is inactive due to an error occured while loading configuration.');
66
+ }
67
+ });
68
+ }
69
+
70
+ }exports.RateLimitService = RateLimitService;
71
+ //# sourceMappingURL=RateLimitService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RateLimitService.js","names":["_common","require","_expressRateLimit","_express","_interopRequireDefault","_path","obj","__esModule","default","RateLimitService","ApplicationService","constructor","app","serviceRouter","subscribe","addRouter","express","Router","serviceConfiguration","getConfiguration","getSourceAt","profiles","paths","extends","configurationPath","getConfigurationPath","extendsPath","path","resolve","TraceUtils","log","pathsArray","profilesArray","Map","size","warn","forEach","value","profile","get","rateLimitOptions","Object","assign","windowMs","limit","legacyHeaders","keyGenerator","req","headers","connection","remoteAddress","socket","use","rateLimit","stack","length","unshift","apply","err","error","exports"],"sources":["../src/RateLimitService.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 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 return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\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}"],"mappings":"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"}
@@ -0,0 +1,4 @@
1
+ import { ApplicationService } from '@themost/common';
2
+ export declare class RateLimitService extends ApplicationService {
3
+
4
+ }
@@ -0,0 +1,4 @@
1
+ import { ApplicationService } from '@themost/common';
2
+ export declare class SpeedLimitService extends ApplicationService {
3
+
4
+ }
@@ -0,0 +1,70 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.SpeedLimitService = void 0;var _common = require("@themost/common");
2
+ var _expressSlowDown = _interopRequireDefault(require("express-slow-down"));
3
+ var _express = _interopRequireDefault(require("express"));
4
+ var _path = _interopRequireDefault(require("path"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
5
+
6
+ class SpeedLimitService extends _common.ApplicationService {
7
+ constructor(app) {
8
+ super(app);
9
+
10
+ app.serviceRouter.subscribe((serviceRouter) => {
11
+ if (serviceRouter == null) {
12
+ return;
13
+ }
14
+ try {
15
+ const addRouter = _express.default.Router();
16
+ let serviceConfiguration = app.getConfiguration().getSourceAt('settings/universis/janitor/speedLimit') || {
17
+ profiles: [],
18
+ paths: []
19
+ };
20
+ if (serviceConfiguration.extends) {
21
+ // get additional configuration
22
+ const configurationPath = app.getConfiguration().getConfigurationPath();
23
+ const extendsPath = _path.default.resolve(configurationPath, serviceConfiguration.extends);
24
+ _common.TraceUtils.log(`@universis/janitor#SpeedLimitService will try to extend service configuration from ${extendsPath}`);
25
+ serviceConfiguration = require(extendsPath);
26
+ }
27
+ const pathsArray = serviceConfiguration.paths || [];
28
+ const profilesArray = serviceConfiguration.profiles || [];
29
+ // create maps
30
+ const paths = new Map(pathsArray);
31
+ const profiles = new Map(profilesArray);
32
+ if (paths.size === 0) {
33
+ _common.TraceUtils.warn('@universis/janitor#SpeedLimitService is being started but the collection of paths is empty.');
34
+ }
35
+ paths.forEach((value, path) => {
36
+ let profile;
37
+ // get profile
38
+ if (value.profile) {
39
+ profile = profiles.get(value.profile);
40
+ } else {
41
+ // or options defined inline
42
+ profile = value;
43
+ }
44
+ if (profile != null) {
45
+ const slowDownOptions = Object.assign({
46
+ windowMs: 5 * 60 * 1000, // 5 minutes
47
+ delayAfter: 5, // 5 requests
48
+ delayMs: 500, // 500 ms
49
+ maxDelayMs: 20000 // 20 seconds
50
+ }, profile, {
51
+ keyGenerator: (req) => {
52
+ return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);
53
+ }
54
+ });
55
+ addRouter.use(path, (0, _expressSlowDown.default)(slowDownOptions));
56
+ }
57
+ });
58
+ if (addRouter.stack.length) {
59
+ serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);
60
+ }
61
+ } catch (err) {
62
+ _common.TraceUtils.error('An error occurred while validating speed limit configuration.');
63
+ _common.TraceUtils.error(err);
64
+ _common.TraceUtils.warn('Speed limit service is inactive due to an error occured while loading configuration.');
65
+ }
66
+ });
67
+ }
68
+
69
+ }exports.SpeedLimitService = SpeedLimitService;
70
+ //# sourceMappingURL=SpeedLimitService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SpeedLimitService.js","names":["_common","require","_expressSlowDown","_interopRequireDefault","_express","_path","obj","__esModule","default","SpeedLimitService","ApplicationService","constructor","app","serviceRouter","subscribe","addRouter","express","Router","serviceConfiguration","getConfiguration","getSourceAt","profiles","paths","extends","configurationPath","getConfigurationPath","extendsPath","path","resolve","TraceUtils","log","pathsArray","profilesArray","Map","size","warn","forEach","value","profile","get","slowDownOptions","Object","assign","windowMs","delayAfter","delayMs","maxDelayMs","keyGenerator","req","headers","connection","remoteAddress","socket","use","slowDown","stack","length","unshift","apply","err","error","exports"],"sources":["../src/SpeedLimitService.js"],"sourcesContent":["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 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: 5, // 5 requests\n delayMs: 500, // 500 ms\n maxDelayMs: 20000 // 20 seconds\n }, profile, {\n keyGenerator: (req) => {\n return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);\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}"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ export * from './RateLimitService';
2
+ export * from './SpeedLimitService';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", { value: true });var _RateLimitService = require("./RateLimitService");Object.keys(_RateLimitService).forEach(function (key) {if (key === "default" || key === "__esModule") return;if (key in exports && exports[key] === _RateLimitService[key]) return;Object.defineProperty(exports, key, { enumerable: true, get: function () {return _RateLimitService[key];} });});
2
+ var _SpeedLimitService = require("./SpeedLimitService");Object.keys(_SpeedLimitService).forEach(function (key) {if (key === "default" || key === "__esModule") return;if (key in exports && exports[key] === _SpeedLimitService[key]) return;Object.defineProperty(exports, key, { enumerable: true, get: function () {return _SpeedLimitService[key];} });});
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_RateLimitService","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_SpeedLimitService"],"sources":["../src/index.js"],"sourcesContent":["export * from './RateLimitService';\nexport * from './SpeedLimitService';"],"mappings":"2EAAA,IAAAA,iBAAA,GAAAC,OAAA,uBAAAC,MAAA,CAAAC,IAAA,CAAAH,iBAAA,EAAAI,OAAA,WAAAC,GAAA,OAAAA,GAAA,kBAAAA,GAAA,8BAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,iBAAA,CAAAK,GAAA,UAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA,IAAAG,UAAA,QAAAC,GAAA,WAAAA,CAAA,UAAAT,iBAAA,CAAAK,GAAA;AACA,IAAAK,kBAAA,GAAAT,OAAA,wBAAAC,MAAA,CAAAC,IAAA,CAAAO,kBAAA,EAAAN,OAAA,WAAAC,GAAA,OAAAA,GAAA,kBAAAA,GAAA,8BAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,kBAAA,CAAAL,GAAA,UAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA,IAAAG,UAAA,QAAAC,GAAA,WAAAA,CAAA,UAAAC,kBAAA,CAAAL,GAAA"}
@@ -0,0 +1,5 @@
1
+ import { DataObject } from '@themost/data';
2
+
3
+ export declare class TestAction extends DataObject {
4
+
5
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.TestAction = void 0;var _data = require("@themost/data");var _dec, _class;let
2
+
3
+
4
+ TestAction = (_dec = _data.EdmMapping.entityType(), _dec(_class = class TestAction extends _data.DataObject {}) || _class);exports.TestAction = TestAction;
5
+ //# sourceMappingURL=TestAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TestAction.js","names":["_data","require","_dec","_class","TestAction","EdmMapping","entityType","DataObject","exports"],"sources":["../../src/models/TestAction.js"],"sourcesContent":["import { DataObject, EdmMapping } from \"@themost/data\";\n\n@EdmMapping.entityType()\nclass TestAction extends DataObject {\n\n}\n\nexport {\n TestAction\n}"],"mappings":"uGAAA,IAAAA,KAAA,GAAAC,OAAA,kBAAuD,IAAAC,IAAA,EAAAC,MAAA;;;AAGjDC,UAAU,IAAAF,IAAA,GADfG,gBAAU,CAACC,UAAU,EAAE,EAAAJ,IAAA,CAAAC,MAAA,GAAxB,MACMC,UAAU,SAASG,gBAAU,CAAC,EAEnC,KAAAJ,MAAA,EAAAK,OAAA,CAAAJ,UAAA,GAAAA,UAAA"}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@universis/janitor",
3
+ "version": "1.0.0",
4
+ "description": "Universis api plugin for rate limiting requests",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "engines": {
8
+ "node": ">=14"
9
+ },
10
+ "scripts": {
11
+ "test": "jasmine",
12
+ "build": "rimraf dist && babel src --out-dir dist --copy-files --source-maps"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://gitlab.com/universis/rate-limit.git"
17
+ },
18
+ "keywords": [
19
+ "universis",
20
+ "api",
21
+ "extension",
22
+ "plugin",
23
+ "library",
24
+ "microservice"
25
+ ],
26
+ "author": "",
27
+ "license": "LGPL-3.0-or-later",
28
+ "bugs": {
29
+ "url": "https://gitlab.com/universis/rate-limit/issues"
30
+ },
31
+ "dependencies": {
32
+ "express-rate-limit": "^7.1.1",
33
+ "express-slow-down": "^1.6.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@themost/common": "^2",
37
+ "@themost/data": "^2",
38
+ "@themost/query": "^2",
39
+ "@themost/xml": "^2",
40
+ "@themost/express": "^1"
41
+ },
42
+ "devDependencies": {
43
+ "@babel/cli": "^7.21.0",
44
+ "@babel/core": "^7.21.4",
45
+ "@babel/eslint-parser": "^7.21.3",
46
+ "@babel/plugin-proposal-decorators": "^7.21.0",
47
+ "@babel/preset-env": "^7.21.4",
48
+ "@babel/register": "^7.21.0",
49
+ "@rollup/plugin-babel": "^6.0.3",
50
+ "@types/express": "^4.17.6",
51
+ "@types/jasmine": "^3.5.10",
52
+ "dotenv": "^8.2.0",
53
+ "eslint": "^8.39.0",
54
+ "jasmine": "^4.6.0",
55
+ "jasmine-spec-reporter": "^5.0.2",
56
+ "rimraf": "3.0.2",
57
+ "typescript": "^5.0.4"
58
+ },
59
+ "homepage": "https://gitlab.com/universis/rate-limit#readme"
60
+ }
@@ -0,0 +1,42 @@
1
+ <html lang="en" data-bs-theme="dark">
2
+
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="description" content="">
7
+ <title>@universis/janitor</title>
8
+ <!-- Bootstrap core CSS -->
9
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
10
+ <link rel="preconnect" href="https://fonts.googleapis.com">
11
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
12
+ <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap" rel="stylesheet">
13
+ <style>
14
+ body {
15
+ font-family: 'Montserrat';
16
+ padding-top: 4.5rem;
17
+ }
18
+ </style>
19
+ </head>
20
+ <body >
21
+ <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-primary">
22
+ <div class="container-fluid">
23
+ <a class="navbar-brand" href="#">@universis/janitor</a>
24
+ </div>
25
+ </nav>
26
+ <main class="container">
27
+ <div class="p-5 rounded">
28
+ <h1>@universis/janitor</h1>
29
+ <p class="lead">Universis api plugin for rate limiting requests</p>
30
+ </div>
31
+ <div>
32
+ <script id="readme" type="text/markdown" src="https://gitlab.com/universis/janitor/-/raw/main/README.md?inline=false" ></script>
33
+ <div class="markdown">
34
+ </div>
35
+ </div>
36
+ </main>
37
+ <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
38
+ <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
39
+ <script src="https://cdn.jsdelivr.net/npm/showdown@2.1.0/dist/showdown.min.js" integrity="sha256-iOtvu+DCcN3zOEruDJYg0HDgkKJuB8Z0Ia42yQO11kk=" crossorigin="anonymous"></script>
40
+ </body>
41
+
42
+ </html>
Binary file
Binary file
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
+ <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
3
+ <!-- Created with Vectornator (http://vectornator.io/) -->
4
+ <svg height="1451.5199999999998mm" stroke-miterlimit="10" style="fill-rule:nonzero;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;" version="1.1" viewBox="0 0 4115.06 4115.06" width="1451.5199999999998mm" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
5
+ <defs/>
6
+ <g id="Layer-1">
7
+ <path d="M723.486 744.868L1942.84 744.767L3392.53 744.647" fill="none" opacity="1" stroke="#23b7cc" stroke-linecap="round" stroke-linejoin="round" stroke-width="283.5"/>
8
+ <path d="M735.141 1225.03L1408.88 1968.33L1629.62 2205.76L2290.13 2916.22" fill="none" opacity="1" stroke="#23b7cc" stroke-linecap="round" stroke-linejoin="round" stroke-width="283.5"/>
9
+ <path d="M2381.55 2272.88L2826.88 1797.13L3362.09 1218.8" fill="none" opacity="1" stroke="#23b7cc" stroke-linecap="round" stroke-linejoin="round" stroke-width="283.5"/>
10
+ <path d="M2806.2 3518.14L2806.83 3058.9L2806.03 2876.36L2804.41 2504.02" fill="none" opacity="1" stroke="#23b7cc" stroke-linecap="round" stroke-linejoin="round" stroke-width="283.5"/>
11
+ <path d="M817.89 2946.06L1633.75 2942.44" fill="none" opacity="1" stroke="#23b7cc" stroke-linecap="round" stroke-linejoin="round" stroke-width="283.5"/>
12
+ </g>
13
+ </svg>
@@ -0,0 +1,84 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-04/schema#",
3
+ "type": "object",
4
+ "id": "urn:universis:rate-limit-service:1",
5
+ "description": "@universis/janitor#RateLimitService configuration schema",
6
+ "properties": {
7
+ "profiles": {
8
+ "type": "array",
9
+ "description": "A named collection of rate limit configurations",
10
+ "items": [
11
+ {
12
+ "type": "array",
13
+ "items": [
14
+ {
15
+ "type": "string",
16
+ "description": "The name of current rate limit profile."
17
+ },
18
+ {
19
+ "type": "object",
20
+ "properties": {
21
+ "windowMs": {
22
+ "description": "Time frame for which requests are checked/remembered. Also used in the Retry-After header when the limit is reached.",
23
+ "type": "integer"
24
+ },
25
+ "limit": {
26
+ "description": "The maximum number of connections to allow during the window before rate limiting the client.",
27
+ "type": "integer"
28
+ },
29
+ "legacyHeaders": {
30
+ "description": "Whether to send the legacy rate limit headers for the limit (X-RateLimit-Limit), current usage (X-RateLimit-Remaining) and reset time (if the store provides it) (X-RateLimit-Reset) on all responses.",
31
+ "type": "boolean"
32
+ },
33
+ "skipFailedRequests": {
34
+ "description": "When set to true, failed requests won't be counted. Request considered failed when the requestWasSuccessful option returns false.",
35
+ "type": "boolean"
36
+ },
37
+ "skipSuccessfulRequests": {
38
+ "description": "If true, the library will (by default) skip all requests that are considered 'failed' by the requestWasSuccessful function.",
39
+ "type": "boolean"
40
+ },
41
+ "store": {
42
+ "description": "The storage to use when persisting rate limit attempts. By default, the MemoryStore is used.",
43
+ "type": "string"
44
+ }
45
+ },
46
+ "required": [
47
+ "windowMs",
48
+ "limit"
49
+ ]
50
+ }
51
+ ]
52
+ }
53
+ ]
54
+ },
55
+ "paths": {
56
+ "type": "array",
57
+ "items": [
58
+ {
59
+ "type": "array",
60
+ "items": [
61
+ {
62
+ "type": "string"
63
+ },
64
+ {
65
+ "type": "object",
66
+ "properties": {
67
+ "profile": {
68
+ "type": "string"
69
+ }
70
+ },
71
+ "required": [
72
+ "profile"
73
+ ]
74
+ }
75
+ ]
76
+ }
77
+ ]
78
+ }
79
+ },
80
+ "required": [
81
+ "profiles",
82
+ "paths"
83
+ ]
84
+ }
@@ -0,0 +1,93 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-04/schema#",
3
+ "type": "object",
4
+ "id": "urn:universis:speed-limit-service:1",
5
+ "description": "@universis/janitor#SpeedLimitService configuration schema",
6
+ "properties": {
7
+ "profiles": {
8
+ "description": "A named collection of speed limit configurations",
9
+ "type": "array",
10
+ "items": [
11
+ {
12
+ "type": "array",
13
+ "items": [
14
+ {
15
+ "type": "string",
16
+ "description": "The name of current speed limit profile."
17
+ },
18
+ {
19
+ "type": "object",
20
+ "properties": {
21
+ "windowMs": {
22
+ "description": "milliseconds - how long to keep records of requests in memory. Defaults to 60000 (1 minute)",
23
+ "type": "integer"
24
+ },
25
+ "delayMs": {
26
+ "description": "milliseconds - how long to delay the response, multiplied by (number of recent hits - delayAfter). Defaults to 1000 (1 second). Set to 0 to disable delaying.",
27
+ "type": "integer"
28
+ },
29
+ "delayAfter": {
30
+ "description": "max number of connections during windowMs before starting to delay responses. Number or function that returns a number. Defaults to 1.",
31
+ "type": "integer"
32
+ },
33
+ "maxDelayMs": {
34
+ "description": "milliseconds - maximum value for delayMs after many consecutive attempts, that is, after the n-th request, the delay will be always maxDelayMs. Important when your application is running behind a load balancer or reverse proxy that has a request timeout. Defaults to Infinity.",
35
+ "type": "integer"
36
+ },
37
+ "skipFailedRequests": {
38
+ "description": "when true failed requests (response status >= 400) won't be counted. Defaults to false.",
39
+ "type": "boolean"
40
+ },
41
+ "skipSuccessfulRequests": {
42
+ "description": "when true successful requests (response status < 400) won't be counted. Defaults to false.",
43
+ "type": "boolean"
44
+ },
45
+ "store": {
46
+ "description": "The storage to use when persisting rate limit attempts. By default, the MemoryStore is used.",
47
+ "type": "string"
48
+ },
49
+ "headers": {
50
+ "description": "Add X-SlowDown-Limit, X-SlowDown-Remaining, and if the store supports it, X-SlowDown-Reset headers to all responses. Modeled after the equivalent headers in express-rate-limit. Default: false",
51
+ "type": "boolean"
52
+ }
53
+ },
54
+ "required": [
55
+ "windowMs",
56
+ "delayAfter",
57
+ "delayMs"
58
+ ]
59
+ }
60
+ ]
61
+ }
62
+ ]
63
+ },
64
+ "paths": {
65
+ "type": "array",
66
+ "items": [
67
+ {
68
+ "type": "array",
69
+ "items": [
70
+ {
71
+ "type": "string"
72
+ },
73
+ {
74
+ "type": "object",
75
+ "properties": {
76
+ "profile": {
77
+ "type": "string"
78
+ }
79
+ },
80
+ "required": [
81
+ "profile"
82
+ ]
83
+ }
84
+ ]
85
+ }
86
+ ]
87
+ }
88
+ },
89
+ "required": [
90
+ "profiles",
91
+ "paths"
92
+ ]
93
+ }
@@ -0,0 +1,70 @@
1
+ import { ApplicationService, TraceUtils } from '@themost/common';
2
+ import { rateLimit } from 'express-rate-limit';
3
+ import express from 'express';
4
+ import path from 'path';
5
+
6
+ export class RateLimitService extends ApplicationService {
7
+ /**
8
+ * @param {import('@themost/express').ExpressDataApplication} app
9
+ */
10
+ constructor(app) {
11
+ super(app);
12
+ app.serviceRouter.subscribe(serviceRouter => {
13
+ if (serviceRouter == null) {
14
+ return;
15
+ }
16
+ try {
17
+ const addRouter = express.Router();
18
+ let serviceConfiguration = app.getConfiguration().getSourceAt('settings/universis/janitor/rateLimit') || {
19
+ profiles: [],
20
+ paths: []
21
+ };
22
+ if (serviceConfiguration.extends) {
23
+ // get additional configuration
24
+ const configurationPath = app.getConfiguration().getConfigurationPath();
25
+ const extendsPath = path.resolve(configurationPath, serviceConfiguration.extends);
26
+ TraceUtils.log(`@universis/janitor#RateLimitService will try to extend service configuration from ${extendsPath}`);
27
+ serviceConfiguration = require(extendsPath);
28
+ }
29
+ const pathsArray = serviceConfiguration.paths || [];
30
+ const profilesArray = serviceConfiguration.profiles || [];
31
+ // create maps
32
+ const paths = new Map(pathsArray);
33
+ const profiles = new Map(profilesArray);
34
+ if (paths.size === 0) {
35
+ TraceUtils.warn('@universis/janitor#RateLimitService is being started but the collection of paths is empty.');
36
+ }
37
+ paths.forEach((value, path) => {
38
+ let profile;
39
+ // get profile
40
+ if (value.profile) {
41
+ profile = profiles.get(value.profile);
42
+ } else {
43
+ // or options defined inline
44
+ profile = value
45
+ }
46
+ if (profile != null) {
47
+ const rateLimitOptions = Object.assign({
48
+ windowMs: 5 * 60 * 1000, // 5 minutes
49
+ limit: 50, // 50 requests
50
+ legacyHeaders: true // send headers
51
+ }, profile, {
52
+ keyGenerator: (req) => {
53
+ return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);
54
+ }
55
+ });
56
+ addRouter.use(path, rateLimit(rateLimitOptions));
57
+ }
58
+ });
59
+ if (addRouter.stack.length) {
60
+ serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);
61
+ }
62
+ } catch (err) {
63
+ TraceUtils.error('An error occurred while validating rate limit configuration.');
64
+ TraceUtils.error(err);
65
+ TraceUtils.warn('Rate limit service is inactive due to an error occured while loading configuration.')
66
+ }
67
+ });
68
+ }
69
+
70
+ }
@@ -0,0 +1,4 @@
1
+ import { ApplicationService } from '@themost/common';
2
+ export declare class RateLimitService extends ApplicationService {
3
+
4
+ }
@@ -0,0 +1,4 @@
1
+ import { ApplicationService } from '@themost/common';
2
+ export declare class SpeedLimitService extends ApplicationService {
3
+
4
+ }
@@ -0,0 +1,69 @@
1
+ import { ApplicationService, TraceUtils } from '@themost/common';
2
+ import slowDown from 'express-slow-down';
3
+ import express from 'express';
4
+ import path from 'path';
5
+
6
+ export class SpeedLimitService extends ApplicationService {
7
+ constructor(app) {
8
+ super(app);
9
+
10
+ app.serviceRouter.subscribe(serviceRouter => {
11
+ if (serviceRouter == null) {
12
+ return;
13
+ }
14
+ try {
15
+ const addRouter = express.Router();
16
+ let serviceConfiguration = app.getConfiguration().getSourceAt('settings/universis/janitor/speedLimit') || {
17
+ profiles: [],
18
+ paths: []
19
+ };
20
+ if (serviceConfiguration.extends) {
21
+ // get additional configuration
22
+ const configurationPath = app.getConfiguration().getConfigurationPath();
23
+ const extendsPath = path.resolve(configurationPath, serviceConfiguration.extends);
24
+ TraceUtils.log(`@universis/janitor#SpeedLimitService will try to extend service configuration from ${extendsPath}`);
25
+ serviceConfiguration = require(extendsPath);
26
+ }
27
+ const pathsArray = serviceConfiguration.paths || [];
28
+ const profilesArray = serviceConfiguration.profiles || [];
29
+ // create maps
30
+ const paths = new Map(pathsArray);
31
+ const profiles = new Map(profilesArray);
32
+ if (paths.size === 0) {
33
+ TraceUtils.warn('@universis/janitor#SpeedLimitService is being started but the collection of paths is empty.');
34
+ }
35
+ paths.forEach((value, path) => {
36
+ let profile;
37
+ // get profile
38
+ if (value.profile) {
39
+ profile = profiles.get(value.profile);
40
+ } else {
41
+ // or options defined inline
42
+ profile = value
43
+ }
44
+ if (profile != null) {
45
+ const slowDownOptions = Object.assign({
46
+ windowMs: 5 * 60 * 1000, // 5 minutes
47
+ delayAfter: 5, // 5 requests
48
+ delayMs: 500, // 500 ms
49
+ maxDelayMs: 20000 // 20 seconds
50
+ }, profile, {
51
+ keyGenerator: (req) => {
52
+ return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || (req.connection ? req.connection.remoteAddress : req.socket.remoteAddress);
53
+ }
54
+ });
55
+ addRouter.use(path, slowDown(slowDownOptions));
56
+ }
57
+ });
58
+ if (addRouter.stack.length) {
59
+ serviceRouter.stack.unshift.apply(serviceRouter.stack, addRouter.stack);
60
+ }
61
+ } catch (err) {
62
+ TraceUtils.error('An error occurred while validating speed limit configuration.');
63
+ TraceUtils.error(err);
64
+ TraceUtils.warn('Speed limit service is inactive due to an error occured while loading configuration.')
65
+ }
66
+ });
67
+ }
68
+
69
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './RateLimitService';
2
+ export * from './SpeedLimitService';
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './RateLimitService';
2
+ export * from './SpeedLimitService';
@@ -0,0 +1,5 @@
1
+ import { DataObject } from '@themost/data';
2
+
3
+ export declare class TestAction extends DataObject {
4
+
5
+ }
@@ -0,0 +1,10 @@
1
+ import { DataObject, EdmMapping } from "@themost/data";
2
+
3
+ @EdmMapping.entityType()
4
+ class TestAction extends DataObject {
5
+
6
+ }
7
+
8
+ export {
9
+ TestAction
10
+ }