npm package: @mega-apps/quick-proxy
Description: Proxy Agent for Mega apps
Author: sunzhifeng
Latest version: 0.11.10

# @mega-apps/quick-proxy

快速代理助手

## 特性

- 基于Koa框架的HTTP/HTTP2/HTTPS代理服务器
- 基于代理组件
  - [koa-better-http-proxy](https://www.npmjs.com/package/koa-better-http-proxy)
  - [express-http-proxy](https://www.npmjs.com/package/express-http-proxy)
  - [http-proxy-middleware](https://www.npmjs.com/package/http-proxy-middleware)
- 提供代码配置级别的处理. 参照: [config-json5](https://github.com/somewind/config-json5)
- 提供简单的配置文件
- 支持中间件的添加
- 支持代理的自定义添加; 参照：[koa-better-http-proxy](https://github.com/nsimmons/koa-better-http-proxy)
- 支持Web socket代理; 依赖[http-proxy-middleware](https://www.npmjs.com/package/http-proxy-middleware),
- （高级特性）所有基于代理组件，都支持对请求体(body) 的二次处理; 例如，加密解密，变更body内容

## 安装及使用

### 创建简单的Node项目

```
yarn init
```

``` txt 
# 目录结构如下：

│  index.js
│  package.json
│  yarn.lock
├─certs
│      default_rsa_private.pem
│      default_rsa_public.pem
├─config
│      default.js
└─node_modules


### 安装 @mega-apps/quick-proxy

```bash
yarn add @mega-apps/quick-proxy
```


### 编辑 index.js 文件

``` js
require("@mega-apps/quick-proxy");

```

### 配置 config

配置文件路径： config/default.js

```js
//  代码示例

/*
 * @Author       : sunzhifeng <ian.sun@auodigitech.com>
 * @Date         : 2022-01-10 14:27:45
 * @LastEditors  : sunzhifeng <ian.sun@auodigitech.com>
 * @LastEditTime : 2022-01-12 16:40:28
 * @Description  : Created by sunzhifeng, Please coding something here
 * 用于配置代理服务器
 */

const fs = require('fs');
const path = require('path');

const cfg = {
  prepare: 0,
  "port": 18080,

  // "offDefaultHTTPServer": false, 是否不开启默认的HTTP服务


  // 开启 HTTPS 服务, 主要参数参照：https://nodejs.org/docs/latest-v14.x/api/https.html， 
  // 更多内容：https://nodejs.org/docs/latest-v14.x/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
  "https": {
    "enable": false,
    "port": 18081,
    "key": fs.readFileSync(path.join(__dirname, "./ssl/key.pem")),
    "cert": fs.readFileSync(path.join(__dirname, "./ssl/cert.pem")),
  },
  // 开启 HTTP2 服务, 主要参数参照：https://nodejs.org/docs/latest-v14.x/api/http2.html
  // 更多内容：https://nodejs.org/docs/latest-v14.x/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
  "http2": {
    "enable": false,
    "port": "8443",
    "key": fs.readFileSync(path.join(__dirname, "./ssl/key.pem")),
    "cert": fs.readFileSync(path.join(__dirname, "./ssl/cert.pem")),
  },
  // 用于内部的加密解密
  "certs": {
    "default": {
      "public_key": "./certs/default_rsa_public.pem",
      "private_key": "./certs/default_rsa_private.pem",
    }
  },
  // Koa 扩展中间件
  "middlewares": {
    "enable": true,
    "list": [
      {
        "name": "proxy",
        "enable": true,
        "content": async (ctx) => {
          let url = ctx.url;
          let host = ctx.headers.host;
          console.log(url);
          console.log(host);
        }
      }
    ]
  },
  // 代理设置
  "proxy": {
    "enable": true,
    "table": [
      {
        "target": 'github.com',
        "koaOptions": {
          // filter
          filter: (ctx) => {
            console.log(ctx.url,typeof ctx.url);
            if (ctx.url.indexOf('/api') != 0) {
              return false;
            }
            return true;
          },
          // pathRewrite
          proxyReqPathResolver: (ctx) => {
            const urlPath = require('url').parse(ctx.url).path;
            console.log('proxyReqPathResolver:',ctx.url, urlPath);

            if (urlPath.indexOf('/api') == 0) {
              return '/nsimmons/koa-better-http-proxy'
            }

            return urlPath;
          },
          // proxyReqOptDecorator
          proxyReqOptDecorator: (proxyReqOpts, ctx) => {
            console.log('proxyReqOptDecorator: %c%s','color: #733d00',proxyReqOpts);
            // you can update headers
            proxyReqOpts.headers['content-type'] = 'text/html';
            // you can change the method
            proxyReqOpts.method = 'GET';

            // proxyReqOpts.headers['X-Forwarded-For'] = ctx.ip;
            // proxyReqOpts.headers['X-Forwarded-Host'] = ctx.host;
            // proxyReqOpts.headers['X-Forwarded-Port'] = ctx.port;
            // proxyReqOpts.headers['X-Forwarded-Proto'] = ctx.protocol;
            // proxyReqOpts.headers['X-Forwarded-Path'] = ctx.path;
            // proxyReqOpts.headers['X-Forwarded-Url'] = ctx.url;
            // proxyReqOpts.headers['X-Forwarded-Method'] = ctx.method;
            // proxyReqOpts.headers['X-Forwarded-User'] = ctx.user;
            // proxyReqOpts.headers['X-Forwarded-Password'] = ctx.password;
            // proxyReqOpts.headers['X-Forwarded-Auth'] = ctx.auth;
            // proxyReqOpts.headers['X-Forwarded-Referer'] = ctx.referer;
            // proxyReqOpts.headers['X-Forwarded-Cookie'] = ctx.cookie;
            // proxyReqOpts.headers['X-Forwarded-Headers'] = ctx.headers;
            // proxyReqOpts.headers['X-Forwarded-Body'] = ctx.body;
            // proxyReqOpts.headers['X-Forwarded-Query'] = ctx.query;
            // proxyReqOpts.headers['X-Forwarded-Querystring'] = ctx.querystring;
            // proxyReqOpts.headers['X-Forwarded-Cookies'] = ctx.cookies;
            // proxyReqOpts.headers['X-Forwarded-Session'] = ctx.session;
            // proxyReqOpts.headers['X-Forwarded-Session-Id'] = ctx.sessionId;
            // proxyReqOpts.headers['X-Forwarded-Session-Name'] = ctx.sessionName;
            // proxyReqOpts.headers['X-Forwarded-Session-Store'] = ctx.sessionStore;
            // proxyReqOpts.headers['X-Forwarded-Session-Options'] = ctx.sessionOptions;
            // proxyReqOpts.headers['X-Forwarded-Session-MaxAge'] = ctx.sessionMaxAge;
            // proxyReqOpts.headers['X-Forwarded-Session-Path'] = ctx.sessionPath;
            // proxyReqOpts.headers['X-Forwarded-Session-Domain'] = ctx.sessionDomain;
            // proxyReqOpts.headers['X-Forwarded-Session-Secure'] = ctx.sessionSecure;
            // proxyReqOpts.headers['X-Forwarded-Session-HttpOnly'] = ctx.sessionHttpOnly;
            // proxyReqOpts.headers['X-Forwarded-Session-SameSite'] = ctx.sessionSameSite;
            // proxyReqOpts.headers['X-Forwarded-Session-Expires'] = ctx.sessionExpires;

            return proxyReqOpts;
          },
          // proxyReqBodyDecorator
          proxyReqBodyDecorator: (bodyContent, ctx) => {
            console.log('proxyReqBodyDecorator: %c%s','color: #733d00',bodyContent);
            // you can update body
            // return bodyContent.split('').reverse().join('');
            return bodyContent;
          },
          // userResDecorator
          userResDecorator: (proxyRes, proxyResData, ctx) => {
            console.log('userResDecorator[proxyRes]: %c%s','color: #733d00',proxyRes);
            console.log('userResDecorator[proxyResData]: %c%s','color: #733d00',proxyResData);
            return proxyResData;
          },
        }
      }
    ]
  }
}



module.exports = () => {
  return cfg;
}
```

### 运行服务器

```bash
node index.js
```

## 变更日志

[CHANGELOG](./CHANGELOG.md)