
Security News
Next.js Patches Critical Middleware Vulnerability (CVE-2025-29927)
Next.js has patched a critical vulnerability (CVE-2025-29927) that allowed attackers to bypass middleware-based authorization checks in self-hosted apps.
loopback4-ratelimiter
Advanced tools
A simple loopback-next extension for rate limiting in loopback applications. This extension uses express-rate-limit under the hood with redis, memcache and mongodDB used as store for rate limiting key storage using rate-limit-redis, rate-limit-memcached and rate-limit-mongo
npm install loopback4-ratelimiter
In order to use this component into your LoopBack application, please follow below steps.
this.component(RateLimiterComponent);
For redis datasource, you have to pass the name of a loopback4 datasource
this.bind(RateLimitSecurityBindings.CONFIG).to({
name: 'redis',
type: 'RedisStore',
});
For memcache datasource
this.bind(RateLimitSecurityBindings.CONFIG).to({
client: memoryClient,
type: 'MemcachedStore',
});
For mongoDB datasource
this.bind(RateLimitSecurityBindings.CONFIG).to({
name: 'mongo',
type:'MongoStore';
uri: 'mongodb://127.0.0.1:27017/test_db',
collectionName: 'expressRateRecords'
});
const rateLimitKeyGen = (req: Request) => {
const token =
(req.headers &&
req.headers.authorization &&
req.headers.authorization.replace(/bearer /i, '')) ||
'';
return token;
};
......
this.bind(RateLimitSecurityBindings.CONFIG).to({
name: 'redis',
type: 'RedisStore',
max: 60,
keyGenerator: rateLimitKeyGen,
});
enabledByDefault option in Config Binding will provide a configurable mode. When its enabled (default value is true),it will provide a way to ratelimit all API's except a few that are disabled using a decorator.
To disable ratelimiting for all APIs except those that are enabled using the decorator, you can set its value to false in config binding option.
this.bind(RateLimitSecurityBindings.CONFIG).to({
name: 'redis',
type: 'RedisStore',
max: 60,
keyGenerator: rateLimitKeyGen,
enabledByDefault:false
});
export class MySequence implements SequenceHandler {
constructor(
@inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
@inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
@inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
@inject(SequenceActions.SEND) public send: Send,
@inject(SequenceActions.REJECT) public reject: Reject,
@inject(RateLimitSecurityBindings.RATELIMIT_SECURITY_ACTION)
protected rateLimitAction: RateLimitAction,
) {}
async handle(context: RequestContext) {
const requestTime = Date.now();
try {
const {request, response} = context;
const route = this.findRoute(request);
const args = await this.parseParams(request, route);
// rate limit Action here
await this.rateLimitAction(request, response);
const result = await this.invoke(route, args);
this.send(response, result);
} catch (err) {
...
} finally {
...
}
}
}
const rateLimitKeyGen = (req: Request) => {
const token =
(req.headers &&
req.headers.authorization &&
req.headers.authorization.replace(/bearer /i, '')) ||
'';
return token;
};
.....
@ratelimit(true, {
max: 60,
keyGenerator: rateLimitKeyGen,
})
@patch(`/auth/change-password`, {
responses: {
[STATUS_CODE.OK]: {
description: 'If User password successfully changed.',
},
...ErrorCodes,
},
security: [
{
[STRATEGY.BEARER]: [],
},
],
})
async resetPassword(
@requestBody({
content: {
[CONTENT_TYPE.JSON]: {
schema: getModelSchemaRef(ResetPassword, {partial: true}),
},
},
})
req: ResetPassword,
@param.header.string('Authorization') auth: string,
): Promise<User> {
return this.authService.changepassword(req, auth);
}
@ratelimit(false)
@authenticate(STRATEGY.BEARER)
@authorize(['*'])
@get('/auth/me', {
description: ' To get the user details',
security: [
{
[STRATEGY.BEARER]: [],
},
],
responses: {
[STATUS_CODE.OK]: {
description: 'User Object',
content: {
[CONTENT_TYPE.JSON]: AuthUser,
},
},
...ErrorCodes,
},
})
async userDetails(
@inject(RestBindings.Http.REQUEST) req: Request,
): Promise<AuthUser> {
return this.authService.getme(req.headers.authorization);
}
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 :
this.bind(RateLimitSecurityBindings.RATELIMITCONFIG).to({
RatelimitActionMiddleware: true,
});
this.component(RateLimiterComponent);
This binding needs to be done before adding the RateLimiter component to your application. Apart from this all other steps will remain the same.
By default all the paths are rate limited based on the configuration provided, but can be skipped using the skip handler.
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.
const obfPath = process.env.OBF_PATH ?? '/obf';
this.bind(RateLimitSecurityBindings.CONFIG).to({
name: RedisDataSource.dataSourceName,
type: 'RedisStore',
+ skip: (request, response) => {
+ const isOBFSubpath = Boolean(
+ request.path.match(new RegExp(`^/$+{obfPath.replace(/^\//, '')}/.+`)),
+ );
+ return !!isOBFSubpath;
},
});
If you've noticed a bug or have a question or have a feature request, search the issue tracker to see if someone else in the community has already created a ticket. If not, go ahead and make one! All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can. If you think this extension is useful, please star it. Appreciation really helps in keeping this project alive.
Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.
Code of conduct guidelines here.
Release v7.0.6 December 17, 2024
Welcome to the December 17, 2024 release of loopback4-ratelimiter. There are many updates in this version that we hope you will like, the key highlights include:
:- chore(deps): node version update was commited on December 17, 2024 by Sunny Tyagi
node version update
gh-0
Clink on the above links to understand the changes in detail.
FAQs
A rate limiting extension for loopback-next APIs by ARC
The npm package loopback4-ratelimiter receives a total of 1,445 weekly downloads. As such, loopback4-ratelimiter popularity was classified as popular.
We found that loopback4-ratelimiter demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Next.js has patched a critical vulnerability (CVE-2025-29927) that allowed attackers to bypass middleware-based authorization checks in self-hosted apps.
Security News
A survey of 500 cybersecurity pros reveals high pay isn't enough—lack of growth and flexibility is driving attrition and risking organizational security.
Product
Socket, the leader in open source security, is now available on Google Cloud Marketplace for simplified procurement and enhanced protection against supply chain attacks.