Skip to content

Commit

Permalink
feat: auto generate root cert.
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangbin committed Nov 20, 2018
1 parent e4090a6 commit 65ea483
Show file tree
Hide file tree
Showing 16 changed files with 266 additions and 1,200 deletions.
5 changes: 4 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"type": "node",
"request": "launch",
"name": "启动程序",
"program": "${workspaceFolder}\\lib\\anymock.js"
"program": "${workspaceFolder}\\lib\\anymock.js",
"args": [
"init"
],
}
]
}
18 changes: 4 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,6 @@ English | [简体中文](./docs/README-zh_CN.md)

## Getting Started

### Prerequisites

```bash
npm install anyproxy -g
anyproxy-ca
```

trust the root cert

### Installation

```bash
Expand All @@ -48,12 +39,11 @@ run command below anywhere
[AnyProxy Log][2018-11-15 12:35:52]: Active rule is: a rule to hack response
```

* first run with 'init' will create a directory 'mock' contains *.config.json and mocks.json template
(default api.config.json and file.config.json)

* first run with 'init' will create a directory 'mock' contains *.config.json and mocks.json template(default api.config.json and file.config.json), and generate root cert

* trust the root cert
* configure chrome's proxy to http://127.0.0.1:8001 via [Proxy SwitchyOmega](https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif)

* then you can browse
* then you can browse
* https://api.github.com/repos/temberature/anymock/branches?protected=0
* https://suggest.taobao.com/sug?code=utf-8&callback=KISSY.Suggest.callback&q=apple
* https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
Expand Down
13 changes: 2 additions & 11 deletions docs/README-zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,6 @@

## 起步

### 前提

```bash
npm install anyproxy -g
anyproxy-ca
```

信任生成的根证书

### 安装

```bash
Expand All @@ -47,8 +38,8 @@ npm install @tiandatong/anymock -g
```

* 自动创建一个名为mock 的目录, 其中包含*.config.json 和 mocks.json 配置模板
(默认 api.config.json 和 file.config.json)

(默认 api.config.json 和 file.config.json), 也会生成一个根证书
* 信任根证书
* 通过[Proxy SwitchyOmega](https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif)把Chrome 的代理配置为http://127.0.0.1:8001
* 然后分别访问
* https://api.github.com/repos/temberature/anymock/branches?protected=0
Expand Down
37 changes: 34 additions & 3 deletions lib/anymock.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,40 @@
#!/usr/bin/env node
const AnyProxy = require('anyproxy');
const fs = require('fs-extra')
const glob = require("glob")
const loadJsonFile = require('load-json-file');
const validator = require('is-my-json-valid')
const exec = require('child_process').exec;


if (process.argv[2] === 'init') {
fs.copy(__dirname + '/../mock', process.cwd() + '/mock')
if (!AnyProxy.utils.certMgr.ifRootCAFileExists()) {
AnyProxy.utils.certMgr.generateRootCA((error, keyPath) => {
// let users to trust this CA before using proxy
if (!error) {
const certDir = require('path').dirname(keyPath);
console.log('The cert is generated at', certDir);
const isWin = /^win/.test(process.platform);
if (isWin) {
exec('start .', { cwd: certDir });
} else {
exec('open .', { cwd: certDir });
}
} else {
console.error('error when generating rootCA', error);
}
});
}
}

glob.sync('./mock/*.json').some(filePath => {
const FILE_CONFIG = loadJsonFile.sync(filePath);
if (!validator(FILE_CONFIG)) {
throw new Error('invalid ' + filePath)
}
})

const options = {
port: 8001,
rule: require('./anyproxy.config')(),
Expand All @@ -13,9 +47,6 @@ const options = {
wsIntercept: false, // 不开启websocket代理
silent: false
};
if (process.argv[2] === 'init') {
fs.copy(__dirname + '/../mock', process.cwd() + '/mock')
}
const proxyServer = new AnyProxy.ProxyServer(options);

proxyServer.on('ready', () => { /* */ });
Expand Down
3 changes: 1 addition & 2 deletions lib/anyproxy.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const {
URL,
URLSearchParams
} = require('url');
const removeProtocol = require('./removeProtocol')
const mock = require('./mock');

module.exports = function () {
Expand All @@ -14,7 +13,7 @@ module.exports = function () {
const searchParams = url.searchParams;
const callback = searchParams.get('callback') || new URLSearchParams(requestDetail.requestData.toString()).get('callback');

const rt = mock(removeProtocol(url.href), searchParams, callback)
const rt = mock(url.href, searchParams, callback)
if (rt && rt.match) {
return {
response: rt.response
Expand Down
10 changes: 10 additions & 0 deletions lib/customNormalizeUrl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const normalizeUrl = require('normalize-url');

function customNormalizeUrl(url) {
return normalizeUrl(url, {
stripProtocol: true,
stripWWW: false
});
}

module.exports = customNormalizeUrl
9 changes: 0 additions & 9 deletions lib/getJSON.js

This file was deleted.

12 changes: 6 additions & 6 deletions lib/mock.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const getJSON = require('./getJSON')
const createRes = require('./createRes')
const startsWith = require('./startsWith')
const removeProtocol = require('./removeProtocol')
const is = require('is-type-of');
const path = require('path');
const fs = require("fs");
const glob = require("glob")
const loadJsonFile = require('load-json-file');
const normalizeUrl = require('./customNormalizeUrl');

const contentTypeMap = {
'.js': 'application/javascript',
Expand All @@ -15,7 +15,7 @@ const contentTypeMap = {
function mock(url, searchParams, callbackName) {
let match, response;
const mocks = glob.sync('./mock/*.config.json').reduce((mocks, filePath) => {
const FILE_CONFIG = getJSON(filePath);
const FILE_CONFIG = loadJsonFile.sync(filePath);
if (!FILE_CONFIG.disabled) {
return mocks.concat(FILE_CONFIG.mocks)
} else {
Expand All @@ -32,7 +32,7 @@ function mock(url, searchParams, callbackName) {
if (!matchMock || matchMock.enabled === 0) {
return;
}
const matchURL = removeProtocol(matchMock.URL || matchMock.url);
const matchURL = normalizeUrl(matchMock.URL || matchMock.url);
if (is.string(matchMock.enabled)) {
const local = matchMock.enabled
if (fs.existsSync(local)) {
Expand All @@ -50,9 +50,9 @@ function mock(url, searchParams, callbackName) {
throw new Error('local file not exists ' + local)
}
} else {
const MOCKS = getJSON("./mock/mocks.json");
const MOCKS = loadJsonFile.sync("./mock/mocks.json");
match = MOCKS.some(MOCK => {
if (matchURL === removeProtocol(MOCK.url || MOCK.URL)) {
if (matchURL === normalizeUrl(MOCK.url || MOCK.URL)) {
// console.log(MOCK);
if (Array.isArray(matchMock.enabled)) {
const choice = matchMock.enabled.filter(choice => isQueryMatch(MOCK[choice], searchParams))[0];
Expand Down
5 changes: 0 additions & 5 deletions lib/removeProtocol.js

This file was deleted.

4 changes: 2 additions & 2 deletions lib/startsWith.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const removeProtocol = require('./removeProtocol')
const normalizeUrl = require('./customNormalizeUrl');

function startsWith(url, pattern) {
return removeProtocol(url).startsWith(removeProtocol(pattern));
return normalizeUrl(url).startsWith(normalizeUrl(pattern));
}

module.exports = startsWith
Loading

0 comments on commit 65ea483

Please sign in to comment.