misskey/src/server/api/limitter.ts

90 lines
1.8 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';
2018-03-28 18:20:40 +02:00
import limiterDB from '../../db/redis';
2018-07-15 20:43:36 +02:00
import { IEndpoint } from './endpoints';
2018-07-07 12:19:00 +02:00
import getAcct from '../../misc/acct/render';
import { IUser } from '../../models/user';
2016-12-28 23:49:51 +01:00
2017-01-23 10:25:52 +01:00
const log = debug('misskey:limitter');
2018-07-15 20:43:36 +02:00
export default (endpoint: IEndpoint, user: IUser) => new Promise((ok, reject) => {
2018-10-11 08:50:27 +02:00
// Redisがインストールされてない場合は常に許可
if (limiterDB == null) {
ok();
return;
}
2018-07-15 20:43:36 +02:00
const limitation = endpoint.meta.limit;
2017-03-01 14:33:43 +01:00
const key = limitation.hasOwnProperty('key')
? limitation.key
2016-12-28 23:49:51 +01:00
: endpoint.name;
2017-03-01 14:33:43 +01:00
const hasShortTermLimit =
limitation.hasOwnProperty('minInterval');
2016-12-28 23:49:51 +01:00
2017-03-01 14:33:43 +01:00
const hasLongTermLimit =
limitation.hasOwnProperty('duration') &&
limitation.hasOwnProperty('max');
2016-12-28 23:49:51 +01:00
2017-03-01 14:33:43 +01:00
if (hasShortTermLimit) {
2016-12-28 23:49:51 +01:00
min();
2017-03-01 14:33:43 +01:00
} else if (hasLongTermLimit) {
2016-12-28 23:49:51 +01:00
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: `${user._id}:${key}:min`,
2017-03-01 14:33:43 +01:00
duration: limitation.minInterval,
2016-12-28 23:49:51 +01:00
max: 1,
db: limiterDB
});
2017-01-23 10:25:52 +01:00
minIntervalLimiter.get((err, info) => {
if (err) {
return reject('ERR');
}
log(`@${getAcct(user)} ${endpoint.name} min remaining: ${info.remaining}`);
2017-01-23 10:25:52 +01:00
if (info.remaining === 0) {
2016-12-28 23:49:51 +01:00
reject('BRIEF_REQUEST_INTERVAL');
} else {
2017-03-01 14:33:43 +01:00
if (hasLongTermLimit) {
2016-12-28 23:49:51 +01:00
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: `${user._id}:${key}`,
2017-03-01 14:33:43 +01:00
duration: limitation.duration,
max: limitation.max,
2016-12-28 23:49:51 +01:00
db: limiterDB
});
2017-01-23 10:25:52 +01:00
limiter.get((err, info) => {
if (err) {
return reject('ERR');
}
log(`@${getAcct(user)} ${endpoint.name} max remaining: ${info.remaining}`);
2017-01-23 10:25:52 +01:00
if (info.remaining === 0) {
2016-12-28 23:49:51 +01:00
reject('RATE_LIMIT_EXCEEDED');
} else {
ok();
}
});
}
});