Selaa lähdekoodia

增加域名校验,优化一些代码

zhusiqing 4 vuotta sitten
vanhempi
commit
286bc1f45a
6 muutettua tiedostoa jossa 16 lisäystä ja 4 poistoa
  1. 1 1
      package.json
  2. 1 1
      pm2.config.js
  3. 4 0
      src/app.ts
  4. 1 0
      src/config.ts
  5. 8 1
      src/middlewares/limit.ts
  6. 1 1
      tsconfig.json

+ 1 - 1
package.json

@@ -12,7 +12,7 @@
   "license": "MIT",
   "scripts": {
     "dev": "cross-env NODE_ENV=dev nodemon -e ts --exec ts-node src/app.ts",
-    "start": "cross-env NODE_ENV=prod tsc"
+    "start": "rm -rf ./dist && cross-env NODE_ENV=prod tsc --inlineSourceMap false"
   },
   "dependencies": {
     "consola": "^2.15.0",

+ 1 - 1
pm2.config.js

@@ -3,7 +3,7 @@ module.exports = {
   apps: [
     {
       name: 'demo',
-      script: './app.js',
+      script: 'dist/app.js',
       exec_mode: 'cluster',
       watch: false,
       instances: 2,

+ 4 - 0
src/app.ts

@@ -20,6 +20,10 @@ import authMiddleware from './middlewares/auth';
 
 const app = new Koa<DefaultState, Context>();
 
+// 为了获取到真实的ip
+// https://github.com/koajs/koa/issues/599
+app.proxy = true;
+
 /* 中间件 */
 // 安全防护
 app.use(helmet());

+ 1 - 0
src/config.ts

@@ -3,6 +3,7 @@ const env = process.env.NODE_ENV;
 
 export = {
   port: 9900,
+  checkHost: ['localhost', '127.0.0.1'],
   redis: {
     host: '10.203.169.158',
     port: 1843,

+ 8 - 1
src/middlewares/limit.ts

@@ -2,8 +2,15 @@ import { Context, Next } from 'koa';
 import config from '../config';
 export = () => {
   return async (ctx: Context, next: Next) => {
+    const host: string = ctx.host
+    const isMatch = config.checkHost.find(el => host.match(el))
+    console.log(host, isMatch);
+    if (!isMatch) {
+      // 域名不对
+      ctx.throw(403, '请求出错')
+    }
     const ip: string = ctx.ip;
-    const key :string = `client_ip_limit_${ip}`;
+    const key: string = `client_ip_limit_${ip}`;
     const limit: number = Number(await ctx.$redis.get(key)) || 0;
     if (limit > config.limit.times) {
       ctx.throw(403, '请求频次过高');

+ 1 - 1
tsconfig.json

@@ -14,7 +14,7 @@
     "allowUnusedLabels": true, // 未执行标签
     "strictNullChecks": true, // 空检查
     "checkJs": true, // 检查js错误
-    "declaration": true, // 生成相应的 '.d.ts' 文件
+    "declaration": false, // 生成相应的 '.d.ts' 文件
     "removeComments": true, // 删除编译后的所有的注释
     "importHelpers": true, // 从 tslib 导入辅助工具函数
     "moduleResolution": "node", // 选择模块解析策略