Skip to content

Commit 1dab03f

Browse files
docs(chore): copy the Readme to root as well (#171)
copy the Readme to root as well GH-170
1 parent 87b65e1 commit 1dab03f

File tree

1 file changed

+286
-0
lines changed

1 file changed

+286
-0
lines changed

README.md

Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
<a href="https://sourcefuse.github.io/arc-docs/arc-api-docs" target="_blank"><img src="https://github.com/sourcefuse/loopback4-microservice-catalog/blob/master/docs/assets/logo-dark-bg.png?raw=true" alt="ARC By SourceFuse logo" title="ARC By SourceFuse" align="right" width="150" /></a>
2+
3+
# [loopback4-ratelimiter](https://github.com/sourcefuse/loopback4-ratelimiter)
4+
5+
<p align="left">
6+
<a href="https://www.npmjs.com/package/loopback4-ratelimiter">
7+
<img src="https://img.shields.io/npm/v/loopback4-ratelimiter.svg" alt="npm version" />
8+
</a>
9+
<a href="https://sonarcloud.io/summary/new_code?id=sourcefuse_loopback4-ratelimiter" target="_blank">
10+
<img alt="Sonar Quality Gate" src="https://img.shields.io/sonar/quality_gate/sourcefuse_loopback4-ratelimiter?server=https%3A%2F%2Fsonarcloud.io">
11+
</a>
12+
<a href="https://app.snyk.io/org/ashishkaushik/reporting?context[page]=issues-detail&project_target=%255B%2522sourcefuse%252Floopback4-ratelimiter%2522%255D&project_origin=%255B%2522github%2522%255D&issue_status=%255B%2522Open%2522%255D&issue_by=Severity&table_issues_detail_cols=SCORE%257CCVE%257CCWE%257CPROJECT%257CEXPLOIT%2520MATURITY%257CAUTO%2520FIXABLE%257CINTRODUCED%257CSNYK%2520PRODUCT&v=1">
13+
<img alt="Synk Status" src="https://img.shields.io/badge/SYNK_SECURITY-MONITORED-GREEN">
14+
</a>
15+
<a href="https://github.com/sourcefuse/loopback4-ratelimiter/graphs/contributors" target="_blank">
16+
<img alt="GitHub contributors" src="https://img.shields.io/github/contributors/sourcefuse/loopback4-ratelimiter">
17+
</a>
18+
<a href="https://www.npmjs.com/package/loopback4-ratelimiter" target="_blank">
19+
<img alt="downloads" src="https://img.shields.io/npm/dw/loopback4-ratelimiter.svg">
20+
</a>
21+
<a href="https://github.com/sourcefuse/loopback4-ratelimiter/blob/master/LICENSE">
22+
<img src="https://img.shields.io/github/license/sourcefuse/loopback4-ratelimiter" alt="License" />
23+
</a>
24+
<a href="https://loopback.io/" target="_blank">
25+
<img alt="Powered By LoopBack 4" src="https://img.shields.io/badge/Powered%20by-LoopBack 4-brightgreen" />
26+
</a>
27+
</p>
28+
29+
## Overview
30+
31+
A simple loopback-next extension for rate limiting in loopback applications. This extension uses [express-rate-limit](https://github.com/nfriedly/express-rate-limit) under the hood with redis, memcache and mongodDB used as store for rate limiting key storage using [rate-limit-redis](https://github.com/wyattjoh/rate-limit-redis), [rate-limit-memcached](https://github.com/linyows/rate-limit-memcached) and [rate-limit-mongo](https://github.com/2do2go/rate-limit-mongo)
32+
33+
## Install
34+
35+
```sh
36+
npm install loopback4-ratelimiter
37+
```
38+
39+
## Usage
40+
41+
In order to use this component into your LoopBack application, please follow below steps.
42+
43+
- Add component to application.
44+
45+
```ts
46+
this.component(RateLimiterComponent);
47+
```
48+
49+
- Minimum configuration required for this component is given below.
50+
51+
For redis datasource, you have to pass the name of a loopback4 datasource
52+
53+
```ts
54+
this.bind(RateLimitSecurityBindings.CONFIG).to({
55+
name: 'redis',
56+
type: 'RedisStore',
57+
});
58+
```
59+
60+
For memcache datasource
61+
62+
```ts
63+
this.bind(RateLimitSecurityBindings.CONFIG).to({
64+
client: memoryClient,
65+
type: 'MemcachedStore',
66+
});
67+
```
68+
69+
For mongoDB datasource
70+
71+
```ts
72+
this.bind(RateLimitSecurityBindings.CONFIG).to({
73+
name: 'mongo',
74+
type:'MongoStore';
75+
uri: 'mongodb://127.0.0.1:27017/test_db',
76+
collectionName: 'expressRateRecords'
77+
});
78+
```
79+
80+
- By default, ratelimiter will be initialized with default options as mentioned [here](https://github.com/nfriedly/express-rate-limit#configuration-options). However, you can override any of the options using the Config Binding. Below is an example of how to do it with the redis datasource, you can also do it with other two datasources similarly.
81+
82+
```ts
83+
const rateLimitKeyGen = (req: Request) => {
84+
const token =
85+
(req.headers &&
86+
req.headers.authorization &&
87+
req.headers.authorization.replace(/bearer /i, '')) ||
88+
'';
89+
return token;
90+
};
91+
92+
......
93+
94+
95+
this.bind(RateLimitSecurityBindings.CONFIG).to({
96+
name: 'redis',
97+
type: 'RedisStore',
98+
max: 60,
99+
keyGenerator: rateLimitKeyGen,
100+
});
101+
```
102+
103+
## EnabledbyDefault
104+
105+
enabledByDefault option in Config Binding will provide a configurable mode.
106+
When its enabled (default value is true),it will provide a way to
107+
ratelimit all API's except a few that are disabled using a decorator.
108+
109+
To disable ratelimiting for all APIs except those that are enabled using the decorator,
110+
you can set its value to false in config binding option.
111+
112+
```
113+
this.bind(RateLimitSecurityBindings.CONFIG).to({
114+
name: 'redis',
115+
type: 'RedisStore',
116+
max: 60,
117+
keyGenerator: rateLimitKeyGen,
118+
enabledByDefault:false
119+
});
120+
```
121+
122+
- The component exposes a sequence action which can be added to your server sequence class. Adding this will trigger ratelimiter middleware for all the requests passing through.
123+
124+
```ts
125+
export class MySequence implements SequenceHandler {
126+
constructor(
127+
@inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
128+
@inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
129+
@inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
130+
@inject(SequenceActions.SEND) public send: Send,
131+
@inject(SequenceActions.REJECT) public reject: Reject,
132+
@inject(RateLimitSecurityBindings.RATELIMIT_SECURITY_ACTION)
133+
protected rateLimitAction: RateLimitAction,
134+
) {}
135+
136+
async handle(context: RequestContext) {
137+
const requestTime = Date.now();
138+
try {
139+
const {request, response} = context;
140+
const route = this.findRoute(request);
141+
const args = await this.parseParams(request, route);
142+
143+
// rate limit Action here
144+
await this.rateLimitAction(request, response);
145+
146+
const result = await this.invoke(route, args);
147+
this.send(response, result);
148+
} catch (err) {
149+
...
150+
} finally {
151+
...
152+
}
153+
}
154+
}
155+
```
156+
157+
- This component also exposes a method decorator for cases where you want tp specify different rate limiting options at API method level. For example, you want to keep hard rate limit for unauthorized API requests and want to keep it softer for other API requests. In this case, the global config will be overwritten by the method decoration. Refer below.
158+
159+
```ts
160+
const rateLimitKeyGen = (req: Request) => {
161+
const token =
162+
(req.headers &&
163+
req.headers.authorization &&
164+
req.headers.authorization.replace(/bearer /i, '')) ||
165+
'';
166+
return token;
167+
};
168+
169+
.....
170+
171+
@ratelimit(true, {
172+
max: 60,
173+
keyGenerator: rateLimitKeyGen,
174+
})
175+
@patch(`/auth/change-password`, {
176+
responses: {
177+
[STATUS_CODE.OK]: {
178+
description: 'If User password successfully changed.',
179+
},
180+
...ErrorCodes,
181+
},
182+
security: [
183+
{
184+
[STRATEGY.BEARER]: [],
185+
},
186+
],
187+
})
188+
async resetPassword(
189+
@requestBody({
190+
content: {
191+
[CONTENT_TYPE.JSON]: {
192+
schema: getModelSchemaRef(ResetPassword, {partial: true}),
193+
},
194+
},
195+
})
196+
req: ResetPassword,
197+
@param.header.string('Authorization') auth: string,
198+
): Promise<User> {
199+
return this.authService.changepassword(req, auth);
200+
}
201+
```
202+
203+
- You can also disable rate limiting for specific API methods using the decorator like below or use the [skip handler](#skip-handler)
204+
205+
```ts
206+
@ratelimit(false)
207+
@authenticate(STRATEGY.BEARER)
208+
@authorize(['*'])
209+
@get('/auth/me', {
210+
description: ' To get the user details',
211+
security: [
212+
{
213+
[STRATEGY.BEARER]: [],
214+
},
215+
],
216+
responses: {
217+
[STATUS_CODE.OK]: {
218+
description: 'User Object',
219+
content: {
220+
[CONTENT_TYPE.JSON]: AuthUser,
221+
},
222+
},
223+
...ErrorCodes,
224+
},
225+
})
226+
async userDetails(
227+
@inject(RestBindings.Http.REQUEST) req: Request,
228+
): Promise<AuthUser> {
229+
return this.authService.getme(req.headers.authorization);
230+
}
231+
```
232+
233+
## Middleware Sequence Support
234+
235+
As action based sequence will be deprecated soon, we have provided support for middleware based sequences. If you are using middleware sequence you can add ratelimit to your application by enabling ratelimit action middleware. This can be done by binding the RateLimitSecurityBindings.CONFIG in application.ts :
236+
237+
```ts
238+
this.bind(RateLimitSecurityBindings.RATELIMITCONFIG).to({
239+
RatelimitActionMiddleware: true,
240+
});
241+
242+
this.component(RateLimiterComponent);
243+
```
244+
245+
This binding needs to be done before adding the RateLimiter component to your application.
246+
Apart from this all other steps will remain the same.
247+
248+
## Skip Handler
249+
250+
By default all the paths are rate limited based on the configuration provided, but can be skipped using the skip handler.
251+
252+
Following is the example of an handler that returns true if the path starts with `/obf/` such as `/obf/css/style.css`, `/obf/fonts`, `/obf/stats` etc.
253+
254+
```diff
255+
const obfPath = process.env.OBF_PATH ?? '/obf';
256+
257+
this.bind(RateLimitSecurityBindings.CONFIG).to({
258+
name: RedisDataSource.dataSourceName,
259+
type: 'RedisStore',
260+
+ skip: (request, response) => {
261+
+ const isOBFSubpath = Boolean(
262+
+ request.path.match(new RegExp(`^/$+{obfPath.replace(/^\//, '')}/.+`)),
263+
+ );
264+
+ return !!isOBFSubpath;
265+
},
266+
});
267+
```
268+
269+
## Feedback
270+
271+
If you've noticed a bug or have a question or have a feature request, [search the issue tracker](https://github.com/sourcefuse/loopback4-ratelimiter/issues) to see if someone else in the community has already created a ticket.
272+
If not, go ahead and [make one](https://github.com/sourcefuse/loopback4-ratelimiter/issues/new/choose)!
273+
All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can.
274+
If you think this extension is useful, please [star](https://help.github.com/en/articles/about-stars) it. Appreciation really helps in keeping this project alive.
275+
276+
## Contributing
277+
278+
Please read [CONTRIBUTING.md](https://github.com/sourcefuse/loopback4-ratelimiter/blob/master/.github/CONTRIBUTING.md) for details on the process for submitting pull requests to us.
279+
280+
## Code of conduct
281+
282+
Code of conduct guidelines [here](https://github.com/sourcefuse/loopback4-ratelimiter/blob/master/.github/CODE_OF_CONDUCT.md).
283+
284+
## License
285+
286+
[MIT](https://github.com/sourcefuse/loopback4-ratelimiter/blob/master/LICENSE)

0 commit comments

Comments
 (0)