trashposs/src/api/limitter.ts

81 lines
1.6 KiB
TypeScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
import * as Limiter from 'ratelimiter';
2017-01-23 10:25:52 +01:00
import * as debug from 'debug';
2016-12-28 23:49:51 +01:00
import limiterDB from '../db/redis';
import { IEndpoint } from './endpoints';
import { IAuthContext } from './authenticate';
2017-01-23 10:25:52 +01:00
const log = debug('misskey:limitter');
2016-12-28 23:49:51 +01:00
export default (endpoint: IEndpoint, ctx: IAuthContext) => new Promise((ok, reject) => {
const limitKey = endpoint.hasOwnProperty('limitKey')
? endpoint.limitKey
: endpoint.name;
const hasMinInterval =
endpoint.hasOwnProperty('minInterval');
const hasRateLimit =
endpoint.hasOwnProperty('limitDuration') &&
endpoint.hasOwnProperty('limitMax');
if (hasMinInterval) {
min();
} else if (hasRateLimit) {
max();
} else {
ok();
}
// Short-term limit
2017-01-23 10:25:52 +01:00
function min() {
2016-12-28 23:49:51 +01:00
const minIntervalLimiter = new Limiter({
id: `${ctx.user._id}:${limitKey}:min`,
duration: endpoint.minInterval,
max: 1,
db: limiterDB
});
2017-01-23 10:25:52 +01:00
minIntervalLimiter.get((err, info) => {
if (err) {
return reject('ERR');
}
log(`min remaining: ${info.remaining}`);
if (info.remaining === 0) {
2016-12-28 23:49:51 +01:00
reject('BRIEF_REQUEST_INTERVAL');
} else {
if (hasRateLimit) {
max();
} else {
ok();
}
}
});
}
// Long term limit
2017-01-23 10:25:52 +01:00
function max() {
2016-12-28 23:49:51 +01:00
const limiter = new Limiter({
id: `${ctx.user._id}:${limitKey}`,
duration: endpoint.limitDuration,
max: endpoint.limitMax,
db: limiterDB
});
2017-01-23 10:25:52 +01:00
limiter.get((err, info) => {
if (err) {
return reject('ERR');
}
log(`max remaining: ${info.remaining}`);
if (info.remaining === 0) {
2016-12-28 23:49:51 +01:00
reject('RATE_LIMIT_EXCEEDED');
} else {
ok();
}
});
}
});