diff --git a/docs/install/README.md b/docs/install/README.md index 2b283dda5..410321d4f 100644 --- a/docs/install/README.md +++ b/docs/install/README.md @@ -372,3 +372,13 @@ gcloud app deploy - `github`: [申请地址](https://github.com/settings/tokens) - `GITHUB_ACCESS_TOKEN`: GitHub Access Token + +### 黑名单 & 白名单 + +可以通过修改 `middleware/access-control.js` 或者设置环境变量来配置黑名单和白名单。 + +支持 IP 和路由,设置多项时用英文逗号 `,` 隔开。同时设置黑名单和白名单时仅白名单有效。 + +- `BLACKLIST`: 黑名单 + +- `WHITELIST`: 白名单,设置白名单后黑名单无效 diff --git a/index.js b/index.js index c79ec17a0..a45ce92e3 100644 --- a/index.js +++ b/index.js @@ -12,6 +12,7 @@ const filter = require('./middleware/filter.js'); const template = require('./middleware/template.js'); const favicon = require('koa-favicon'); const debug = require('./middleware/debug.js'); +const accessControl = require('./middleware/access-control.js'); const router = require('./router'); @@ -33,6 +34,8 @@ app.use(onerror); // 1 set header app.use(header); +app.use(accessControl); + // 6 debug app.context.debug = { hitCache: 0, diff --git a/middleware/access-control.js b/middleware/access-control.js new file mode 100644 index 000000000..c86540af5 --- /dev/null +++ b/middleware/access-control.js @@ -0,0 +1,32 @@ +const art = require('art-template'); +const path = require('path'); + +module.exports = async (ctx, next) => { + const blacklist = (process.env.BLACKLIST && process.env.BLACKLIST.split(',')) || []; + const whitelist = process.env.WHITELIST && process.env.WHITELIST.split(','); + + const ip = ctx.ips[0] || ctx.ip; + const requestPath = ctx.request.path; + + const pathAllowed = (whitelist && whitelist.indexOf(requestPath) !== -1) || blacklist.indexOf(requestPath) === -1; + const ipAllowed = (whitelist && whitelist.indexOf(ip) !== -1) || blacklist.indexOf(ip) === -1; + + if (pathAllowed && ipAllowed) { + await next(); + } else { + ctx.response.status = 403; + ctx.body = art(path.resolve(__dirname, '../views/rss.art'), { + lastBuildDate: new Date().toUTCString(), + updated: new Date().toISOString(), + ttl: 24 * 60 * 60, + title: `没有访问权限: ${!pathAllowed ? '该路由' : '你的 IP '}已被列为黑名单`, + link: 'https://docs.rsshub.app/install/#%E9%BB%91%E5%90%8D%E5%8D%95', + item: [ + { + title: `没有访问权限: ${!pathAllowed ? '该路由' : '你的 IP '}已被列为黑名单`, + link: 'https://docs.rsshub.app/install/#%E9%BB%91%E5%90%8D%E5%8D%95', + }, + ], + }); + } +};